Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

documentActivity.ts

69 lines2.5 KB

1export interface DocumentActivity {
2 readonly visible: boolean;
3 readonly focused: boolean;
4}
5​
6const ALWAYS_ACTIVE: DocumentActivity = { visible: true, focused: true };
7​
8const listeners = new Set<() => void>();
9let snapshot: DocumentActivity = ALWAYS_ACTIVE;
10​
11function readActivity(): DocumentActivity {
12 if (typeof document === "undefined") return ALWAYS_ACTIVE;
13 const visible = document.visibilityState === "visible";
14 const focused = document.hasFocus();
15 return snapshot.visible === visible && snapshot.focused === focused
16 ? snapshot
17 : { visible, focused };
19​
20function handleActivityEvent() {
21 const next = readActivity();
22 if (next === snapshot) return;
23 snapshot = next;
24 for (const listener of listeners) listener();
26​
27/** Whether the user is looking at this window: the tab is visible and the window has focus. */
28export function getDocumentActivity(): DocumentActivity {
29 // Without listeners the cached snapshot is not kept current.
30 if (listeners.size === 0) snapshot = readActivity();
31 return snapshot;
33​
34/** One visibilitychange/focus/blur listener set shared by every subscriber. */
35export function subscribeDocumentActivity(listener: () => void): () => void {
36 if (typeof document === "undefined") return () => {};
37 if (listeners.size === 0) {
38 snapshot = readActivity();
39 document.addEventListener("visibilitychange", handleActivityEvent);
40 window.addEventListener("focus", handleActivityEvent);
41 window.addEventListener("blur", handleActivityEvent);
42 }
43 listeners.add(listener);
44 return () => {
45 if (!listeners.delete(listener) || listeners.size > 0) return;
46 document.removeEventListener("visibilitychange", handleActivityEvent);
47 window.removeEventListener("focus", handleActivityEvent);
48 window.removeEventListener("blur", handleActivityEvent);
49 };
51​
52/**
53 * Fires on every window focus and every switch to a visible tab. Unlike
54 * `subscribeDocumentActivity` it does not wait for the cached activity to flip:
55 * focus coming back from an iframe, or an alt-tab whose blur was missed, still
56 * counts as a return.
57 */
58export function subscribeDocumentReturn(listener: () => void): () => void {
59 if (typeof document === "undefined") return () => {};
60 const handleVisibilityChange = () => {
61 if (document.visibilityState === "visible") listener();
62 };
63 window.addEventListener("focus", listener);
64 document.addEventListener("visibilitychange", handleVisibilityChange);
65 return () => {
66 window.removeEventListener("focus", listener);
67 document.removeEventListener("visibilitychange", handleVisibilityChange);
68 };