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

useNowMinute.ts

69 lines2.1 KB

1import { useSyncExternalStore } from "react";
2​
3/** Minute-quantized clock ("YYYY-MM-DDTHH:MM") for settled-state resolution.
4 One module-level timer feeds every consumer through useSyncExternalStore,
5 so all surfaces resolving effectiveSettled against it (sidebar partition,
6 composer banner) share a single value by construction and tick on UTC
7 minute boundaries together. */
8​
9function currentMinute(): string {
10 return new Date().toISOString().slice(0, 16);
12​
13let nowMinute = currentMinute();
14let timerId: number | null = null;
15let timerIsInterval = false;
16const listeners = new Set<() => void>();
17​
18function tick(): void {
19 const next = currentMinute();
20 if (next !== nowMinute) {
21 nowMinute = next;
22 for (const listener of listeners) listener();
23 }
25​
26function startTimer(): void {
27 // Align to the next UTC minute boundary, then tick every 60s. Ticks re-read
28 // the clock, so a throttled or late timer self-corrects when it fires.
29 timerIsInterval = false;
30 timerId = window.setTimeout(
31 () => {
32 tick();
33 timerIsInterval = true;
34 timerId = window.setInterval(tick, 60_000);
35 },
36 60_000 - (Date.now() % 60_000),
37 );
39​
40function subscribe(listener: () => void): () => void {
41 if (listeners.size === 0) {
42 startTimer();
43 }
44 listeners.add(listener);
45 return () => {
46 listeners.delete(listener);
47 if (listeners.size === 0 && timerId !== null) {
48 if (timerIsInterval) window.clearInterval(timerId);
49 else window.clearTimeout(timerId);
50 timerId = null;
51 }
52 };
54​
55function getSnapshot(): string {
56 // With no timer running (no subscribers yet — e.g. the first render after
57 // a full unmount), the stored minute may be stale; re-read it so a fresh
58 // mount renders the current minute instead of waiting for the first tick.
59 // While the timer runs the cached value is returned untouched, as
60 // useSyncExternalStore requires between change notifications.
61 if (timerId === null) {
62 nowMinute = currentMinute();
63 }
64 return nowMinute;
66​
67export function useNowMinute(): string {
68 return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);