@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 69 lines 2.54 KB
Raw
1 export interface DocumentActivity {
2 readonly visible: boolean;
3 readonly focused: boolean;
4 }
5
6 const ALWAYS_ACTIVE: DocumentActivity = { visible: true, focused: true };
7
8 const listeners = new Set<() => void>();
9 let snapshot: DocumentActivity = ALWAYS_ACTIVE;
10
11 function 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 };
18 }
19
20 function handleActivityEvent() {
21 const next = readActivity();
22 if (next === snapshot) return;
23 snapshot = next;
24 for (const listener of listeners) listener();
25 }
26
27 /** Whether the user is looking at this window: the tab is visible and the window has focus. */
28 export function getDocumentActivity(): DocumentActivity {
29 // Without listeners the cached snapshot is not kept current.
30 if (listeners.size === 0) snapshot = readActivity();
31 return snapshot;
32 }
33
34 /** One visibilitychange/focus/blur listener set shared by every subscriber. */
35 export 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 };
50 }
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 */
58 export 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 };
69 }