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

useThreadIntentPrefetch.ts

52 lines1.9 KB

1import type { ScopedThreadRef } from "@t3tools/contracts";
2import { useEffect, useRef } from "react";
3​
4import { appAtomRegistry } from "~/rpc/atomRegistry";
5import { environmentThreadStateAtom } from "~/state/threads";
6​
7const INTENT_DELAY_MS = 150;
8// A tap leaves the row before its click opens the thread, so the hold outlives the pointer.
9const RELEASE_DELAY_MS = 1_000;
10​
11/**
12 * Loads a thread's detail once the pointer rests on its row, or at pointerdown, so the click
13 * renders the timeline in its first frame instead of an empty one. The opened thread holds its own
14 * subscription, so the row lets go soon after the pointer leaves.
15 */
16export function useThreadIntentPrefetch(threadRef: ScopedThreadRef) {
17 const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
18 const release = useRef<(() => void) | null>(null);
19 const stop = () => {
20 clearTimeout(timer.current);
21 release.current?.();
22 release.current = null;
23 };
24 const start = () => {
25 clearTimeout(timer.current);
26 if (release.current !== null) return;
27 release.current = appAtomRegistry.mount(
28 environmentThreadStateAtom(threadRef.environmentId, threadRef.threadId),
29 );
30 };
31 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- releases a held thread subscription when the row unmounts
32 useEffect(
33 () => () => {
34 clearTimeout(timer.current);
35 release.current?.();
36 release.current = null;
37 },
38 [],
39 );
40 return {
41 onPointerEnter: (event: React.PointerEvent) => {
42 if (event.pointerType !== "mouse") return;
43 clearTimeout(timer.current);
44 timer.current = setTimeout(start, release.current === null ? INTENT_DELAY_MS : 0);
45 },
46 onPointerLeave: () => {
47 clearTimeout(timer.current);
48 if (release.current !== null) timer.current = setTimeout(stop, RELEASE_DELAY_MS);
49 },
50 onPointerDown: start,
51 };