ui / src / components / agent-chat / use-ticking-now-ms.tsmain at d68d7e1
// A ticking clock: a wall-clock subscribed via `useSyncExternalStore`, not `useState` + `setInterval`
// in an effect — the snapshot is a stable scalar between ticks, and the interval only runs while
// something is subscribed.
import { useCallback, useState, useSyncExternalStore } from "react";
function createTickingClock(intervalMs: number) {
let now = Date.now();
const listeners = new Set<() => void>();
let timer: ReturnType<typeof setInterval> | undefined;
function ensureTimer() {
if (timer || listeners.size === 0) return;
timer = setInterval(() => {
now = Date.now();
for (const listener of listeners) listener();
}, intervalMs);
}
function maybeStopTimer() {
if (!timer || listeners.size > 0) return;
clearInterval(timer);
timer = undefined;
}
return {
subscribe(onStoreChange: () => void) {
listeners.add(onStoreChange);
now = Date.now();
ensureTimer();
// Notify after subscribe returns so a remount re-reads getSnapshot. Skip if
// already unsubscribed (Strict Mode remount).
queueMicrotask(() => {
if (listeners.has(onStoreChange)) onStoreChange();
});
return () => {
listeners.delete(onStoreChange);
maybeStopTimer();
};
},
getSnapshot() {
return now;
},
};
}
/** One shared clock per interval so many components do not each own a timer. */
const clocks = new Map<number, ReturnType<typeof createTickingClock>>();
function clockFor(intervalMs: number) {
let clock = clocks.get(intervalMs);
if (!clock) {
clock = createTickingClock(intervalMs);
clocks.set(intervalMs, clock);
}
return clock;
}
const boundary = (stopAtMs: number | null) =>
typeof stopAtMs === "number" ? stopAtMs : Number.POSITIVE_INFINITY;
/**
* Live wall-clock milliseconds, ticking every `intervalMs`. When `stopAtMs` is reached, the
* returned value freezes at that boundary and this subscriber detaches from the shared timer.
*/
export function useTickingNowMs(intervalMs: number, stopAtMs: number | null = null): number {
const clock = clockFor(intervalMs);
const snapshot = useCallback(
() => Math.min(clock.getSnapshot(), boundary(stopAtMs)),
[clock, stopAtMs],
);
// Server rendering never subscribes, so it needs a snapshot from this render rather than the
// shared clock's last browser tick. A lazy immutable state value is render-pure and remains
// Object.is-stable for hydration.
const [initialNowMs] = useState(Date.now);
const serverSnapshot = useCallback(
() => Math.min(initialNowMs, boundary(stopAtMs)),
[initialNowMs, stopAtMs],
);
const subscribe = useCallback(
(onStoreChange: () => void) => {
const pastBoundary = () => typeof stopAtMs === "number" && clock.getSnapshot() >= stopAtMs;
const unsubscribe = clock.subscribe(() => {
onStoreChange();
if (pastBoundary()) unsubscribe();
});
if (pastBoundary()) unsubscribe();
return unsubscribe;
},
[clock, stopAtMs],
);
// The clock snapshot is mutated only by the external store. With no live subscription it
// remains stable, so a consumer past its boundary freezes without a render-time ref write.
return useSyncExternalStore(subscribe, snapshot, serverSnapshot);
}