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

delayedStatus.ts

75 lines2.4 KB

1const STATUS_SHOW_DELAY_MS = 400;
2const STATUS_MIN_VISIBLE_MS = 400;
3​
4/**
5 * A status shows only after it has stayed set for a moment, then stays shown
6 * for a minimum time so a quick flicker never flashes on screen.
7 * `deadlinePassed` tells whether `delayedStatusDeadline(state)` has been reached.
8 */
9export type DelayedStatusState<A> =
10 | { readonly phase: "idle"; readonly key: string }
11 | { readonly phase: "pending"; readonly key: string; readonly showAt: number }
12 | {
13 readonly phase: "shown";
14 readonly key: string;
15 readonly value: A;
16 readonly holdUntil: number;
17 };
18​
19export interface DelayedStatusInput<A> {
20 readonly key: string;
21 /** Compared by identity, so use strings or other stable values. */
22 readonly value: A | null;
23 readonly deadlinePassed: boolean;
25​
26/**
27 * Returns `state` itself when nothing changes, so it can run on every render.
28 * `now` is read only to stamp a new deadline; it is a function so a memoizing
29 * caller (the React Compiler) cannot cache a stale clock reading.
30 */
31export function stepDelayedStatus<A>(
32 state: DelayedStatusState<A> | null,
33 { key, value, deadlinePassed }: DelayedStatusInput<A>,
34 now: () => number,
35): DelayedStatusState<A> {
36 const idle = (): DelayedStatusState<A> => ({ phase: "idle", key });
37 const pending = (): DelayedStatusState<A> => ({
38 phase: "pending",
39 key,
40 showAt: now() + STATUS_SHOW_DELAY_MS,
41 });
42 const shown = (shownValue: A): DelayedStatusState<A> => ({
43 phase: "shown",
44 key,
45 value: shownValue,
46 holdUntil: now() + STATUS_MIN_VISIBLE_MS,
47 });
48​
49 if (state === null || state.key !== key) return value === null ? idle() : pending();
50 switch (state.phase) {
51 case "idle":
52 return value === null ? state : pending();
53 case "pending":
54 if (value === null) return idle();
55 return deadlinePassed ? shown(value) : state;
56 case "shown":
57 if (value === null) return deadlinePassed ? idle() : state;
58 return value === state.value ? state : shown(value);
59 }
61​
62export function delayedStatusDeadline<A>(state: DelayedStatusState<A>): number | null {
63 switch (state.phase) {
64 case "idle":
65 return null;
66 case "pending":
67 return state.showAt;
68 case "shown":
69 return state.holdUntil;
70 }
72​
73export function shownDelayedStatus<A>(state: DelayedStatusState<A>, key: string): A | null {
74 return state.phase === "shown" && state.key === key ? state.value : null;