Open History to see the last commit
1import { useEffect } from "react";
2
3import { getCachedNativeReviewDiffData } from "./nativeReviewDiffAdapter";
4import type { ReviewSectionItem } from "./reviewModel";
5import { getCachedReviewParsedDiff } from "./reviewState";
6
7interface IdleDeadlineLike {
8 readonly didTimeout: boolean;
9 timeRemaining(): number;
10}
11
12type IdleCallback = (deadline: IdleDeadlineLike) => void;
13
14function scheduleIdle(callback: IdleCallback): number {
15 if (typeof globalThis.requestIdleCallback === "function") {
16 return globalThis.requestIdleCallback(callback, { timeout: 2_000 });
17 }
18
19 return setTimeout(
20 () => callback({ didTimeout: true, timeRemaining: () => 0 }),
21 100,
22 ) as unknown as number;
23}
24
25function cancelIdle(handle: number): void {
26 if (typeof globalThis.cancelIdleCallback === "function") {
27 globalThis.cancelIdleCallback(handle);
28 return;
29 }
30 clearTimeout(handle);
31}
32
33export function prewarmReviewDiffSection(input: {
34 readonly threadKey: string;
35 readonly section: ReviewSectionItem;
36}): void {
37 const { section, threadKey } = input;
38 if (section.diff === null) {
39 return;
40 }
41
42 const parsedDiff = getCachedReviewParsedDiff({
43 threadKey,
44 sectionId: section.id,
45 diff: section.diff,
46 });
47 getCachedNativeReviewDiffData({ parsedDiff, comments: [] });
48}
49
50/** Warms one cached section per idle period, after navigation animations finish. */
51export function useReviewDiffPrewarming(input: {
52 readonly threadKey: string | null;
53 readonly sections: ReadonlyArray<ReviewSectionItem>;
54 readonly selectedSectionId: string | null;
55}): void {
56 const { sections, selectedSectionId, threadKey } = input;
57
58 useEffect(() => {
59 if (!threadKey) {
60 return;
61 }
62
63 const pendingSections = sections.filter(
64 (section) => section.id !== selectedSectionId && section.diff !== null,
65 );
66 if (pendingSections.length === 0) {
67 return;
68 }
69
70 let cancelled = false;
71 let idleHandle: number | null = null;
72 let nextSectionIndex = 0;
73
74 const scheduleNext = () => {
75 idleHandle = scheduleIdle(() => {
76 if (cancelled) {
77 return;
78 }
79
80 const section = pendingSections[nextSectionIndex];
81 if (!section) {
82 return;
83 }
84 nextSectionIndex += 1;
85 prewarmReviewDiffSection({ threadKey, section });
86
87 if (nextSectionIndex < pendingSections.length) {
88 scheduleNext();
89 }
90 });
91 };
92
93 scheduleNext();
94 return () => {
95 cancelled = true;
96 if (idleHandle !== null) {
97 cancelIdle(idleHandle);
98 }
99 };
100 }, [sections, selectedSectionId, threadKey]);
101}