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

usePullRequestIntentPrefetch.ts

51 lines1.7 KB

1import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
2import { useRef, useState } from "react";
3​
4import { useStableCallback } from "~/hooks/useStableCallback";
5import { pullRequestEnvironment } from "~/state/pullRequests";
6import { useEnvironmentQuery } from "~/state/query";
7​
8import { pullRequestPanelReference } from "./usePullRequestDetail";
9​
10const INTENT_DELAY_MS = 150;
11​
12interface PullRequestIntentTarget {
13 readonly environmentId: EnvironmentId;
14 readonly projectId: ProjectId;
15 readonly host: string;
16 readonly repository: string;
17 readonly number: number;
19​
20/**
21 * Reads the detail a row's panel will ask for once the pointer or focus rests on it, so the
22 * click paints from it. Passing over rows asks the host nothing, and leaving a row stops reading it.
23 */
24export function usePullRequestIntentPrefetch(
25 isListed: (target: PullRequestIntentTarget) => boolean,
26) {
27 const [target, setTarget] = useState<PullRequestIntentTarget | null>(null);
28 const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
29 // A removed row fires no leave event.
30 const listed = target !== null && isListed(target);
31 if (target !== null && !listed) setTarget(null);
32 useEnvironmentQuery(
33 target === null || !listed
34 ? null
35 : pullRequestEnvironment.detail({
36 environmentId: target.environmentId,
37 input: {
38 ...pullRequestPanelReference({ ...target, host: target.host.toLowerCase() }),
39 allowStale: false,
40 },
41 }),
42 );
43 return useStableCallback((next: PullRequestIntentTarget | null) => {
44 clearTimeout(timer.current);
45 if (next === null) {
46 setTarget(null);
47 return;
48 }
49 timer.current = setTimeout(() => setTarget(next), INTENT_DELAY_MS);
50 });