Open History to see the last commit
1// @effect-diagnostics globalTimers:off - Display timing for React hooks, outside an Effect runtime.
2
3export const STATUS_SHOW_DELAY_MS = 400;
4export const STATUS_MIN_VISIBLE_MS = 400;
5
6export interface ShownStatus<A> {
7 readonly key: string;
8 readonly value: A;
9}
10
11export interface DelayedStatus<A> {
12 readonly update: (key: string, value: A | null) => void;
13 readonly dispose: () => void;
14}
15
16/**
17 * Values compare by identity, so use strings or other stable values.
18 */
19export function createDelayedStatus<A>(
20 onChange: (shown: ShownStatus<A> | null) => void,
21): DelayedStatus<A> {
22 let key = "";
23 let latest: A | null = null;
24 let shown: A | null = null;
25 let timer: ReturnType<typeof setTimeout> | undefined;
26
27 const clearTimer = () => {
28 clearTimeout(timer);
29 timer = undefined;
30 };
31 const hide = () => {
32 shown = null;
33 onChange(null);
34 };
35 const show = (value: A) => {
36 shown = value;
37 onChange({ key, value });
38 clearTimer();
39 timer = setTimeout(() => {
40 timer = undefined;
41 if (latest === null) hide();
42 }, STATUS_MIN_VISIBLE_MS);
43 };
44
45 return {
46 update: (nextKey, value) => {
47 if (nextKey !== key) {
48 key = nextKey;
49 clearTimer();
50 if (shown !== null) hide();
51 }
52 latest = value;
53
54 if (shown === null) {
55 if (value === null) {
56 clearTimer();
57 } else if (timer === undefined) {
58 timer = setTimeout(() => {
59 timer = undefined;
60 if (latest !== null) show(latest);
61 }, STATUS_SHOW_DELAY_MS);
62 }
63 return;
64 }
65
66 if (value !== null) {
67 if (value !== shown) show(value);
68 } else if (timer === undefined) {
69 hide();
70 }
71 },
72 dispose: clearTimer,
73 };
74}