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

usePermissionStatus.ts

84 lines2.8 KB

1import { useState, useSyncExternalStore } from "react";
2​
3import { useStableCallback } from "~/hooks/useStableCallback";
4import { getDocumentActivity, subscribeDocumentActivity } from "~/lib/documentActivity";
5​
6const POLL_INTERVAL_MS = 1500;
7const CHECK_FAILED_MESSAGE = "Could not check permissions. We'll try again automatically.";
8​
9interface PermissionSnapshot<Id extends string> {
10 readonly status: Record<Id, boolean>;
11 readonly error: string | null;
13​
14/**
15 * Holds the last permission check result and polls while subscribed: on
16 * subscribe, every interval, and when the window regains focus or visibility.
17 * Checks are skipped while the tab is hidden and never overlap.
18 */
19export function createPermissionPoller<Id extends string>(
20 check: () => Promise<Record<Id, boolean>>,
21 initialStatus: Record<Id, boolean>,
22) {
23 let snapshot: PermissionSnapshot<Id> = { status: initialStatus, error: null };
24 return {
25 getSnapshot: () => snapshot,
26 subscribe(onChange: () => void): () => void {
27 let disposed = false;
28 let checking = false;
29 const publish = (next: PermissionSnapshot<Id>) => {
30 if (disposed) return;
31 snapshot = next;
32 onChange();
33 };
34 const refresh = async () => {
35 if (disposed || checking || !getDocumentActivity().visible) return;
36 checking = true;
37 try {
38 publish({ status: await check(), error: null });
39 } catch {
40 publish({ status: snapshot.status, error: CHECK_FAILED_MESSAGE });
41 }
42 checking = false;
43 };
44 void refresh();
45 const timer = setInterval(() => void refresh(), POLL_INTERVAL_MS);
46 let previous = getDocumentActivity();
47 const stopActivity = subscribeDocumentActivity(() => {
48 const next = getDocumentActivity();
49 const regained = (next.focused && !previous.focused) || next.visible !== previous.visible;
50 previous = next;
51 if (regained) void refresh();
52 });
53 return () => {
54 disposed = true;
55 clearInterval(timer);
56 stopActivity();
57 };
58 },
59 };
61​
62const noopSubscribe = () => () => {};
63​
64/**
65 * Each check calls the latest `check`, since callers close over props. `initialStatus` is
66 * read once, when the component mounts, and the subscription only restarts when `enabled` flips.
67 */
68export function usePermissionStatus<Id extends string>(
69 check: () => Promise<Record<Id, boolean>>,
70 initialStatus: Record<Id, boolean>,
71 enabled = true,
72) {
73 const checkLatest = useStableCallback(check);
74 const [poller] = useState(() => createPermissionPoller(checkLatest, initialStatus));
75 const { status, error } = useSyncExternalStore(
76 enabled ? poller.subscribe : noopSubscribe,
77 poller.getSnapshot,
78 );
79 return {
80 status,
81 error,
82 isReady: (required: readonly Id[]) => error === null && required.every((id) => status[id]),
83 };