taiga-family/ng-web-apis

[FEATURE] window focus/blur events

Closed this issue ยท 3 comments

๐Ÿš€ Feature request

Is your feature request related to a problem?

Similar to the already available PAGE_VISIBILITY token for the document visibility state changed events, I also have a need for the focus and blur events on the window object. Since the page visibility might not change state when the user switches to another application or space (the macOs terminology for virtual desktops). When that happens, the window blur/focus events do get triggered

Describe the solution you'd like

Similar to the page visibility token, a token that is created from the two events on the window object (blur and focus) emitting true upon focus and false upon blur

Describe alternatives you've considered

Currently, I have this stream created in my a project, but realise this might be very useful for other to also have available.

Additional context

Be aware when developing this token, that if you have the browser's devtools open, the devtools most probably have focus. This means, the actual window object will never receive the focus (or blur) event when you switch to another app or space to test the behaviour. It took me a while to find out/realise this.

Example implementation

factory: () => {
  const windowRef = inject(WINDOW);

  return merge(
    fromEvent(windowRef, 'focus'),
    fromEvent(windowRef, 'blur'),
  ).pipe(
    startWith({ type: 'focus' }),
    map(({ type }) => type === 'focus'),
    distinctUntilChanged(),
    share(),
  );
}

Don't think you need distinctUntilChanged here, I don't think it can fire same event twice. Also you can rewrite it a little better:

factory: () => {
  const windowRef = inject(WINDOW);
  const documentRef = inject(DOCUMENT);

  return merge(
    fromEvent(windowRef, 'focus'),
    fromEvent(windowRef, 'blur'),
  ).pipe(
    startWith(null),
    map(() => documentRef.hasFocus()),
    share(),
  );
}

Otherwise each resubscription might get a wrong initial value. Not sure if document.hasFocus() is what you are after and if it's already updated upon focus and blur events from window. You would need to test that :)

While this seems like a handy snippet I'm not sure it is something that should go into this library. We focus on Web APIs and while it looks a lot like Page Visibility API it is more of a helper function. I'll keep it open for a while see if anybody else has their thoughts on the subject.

While this seems like a handy snippet I'm not sure it is something that should go into this library. We focus on Web APIs and while it looks a lot like Page Visibility API it is more of a helper function

I see, thanks for the explanation, makes sense.

And also thanks for the suggested improvement. I'll have to do some testing indeed, to see if document.hasFocus() indeed provides the right values.

Ok, so I guess let's close this and if anybody needs it, the snipped shared above can help.