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

GuideTour.tsx

177 lines6.6 KB

1import type { EnvironmentId, PullRequestRef, PullRequestReviewGuide } from "@t3tools/contracts";
2import { T, Var } from "gt-react";
3import { useEffect, useEffectEvent, useRef, useState, type ReactNode } from "react";
4​
5import { createPullRequestDiffFileContentsLoader } from "~/lib/diffFileContents";
6import { isEditableFocused } from "~/lib/editableFocus";
7import { isInSideChatPane } from "~/lib/sideChatPane";
8import { pullRequestEnvironment } from "~/state/pullRequests";
9import { useAtomCommand } from "~/state/use-atom-command";
10​
11import { isCommandPaletteOpen } from "~/commandPaletteBus";
12​
13import { GuideRail } from "./GuideRail";
14import { GuideStop } from "./GuideStop";
15import type { ExcerptCommenting } from "./GuideExcerpt";
16import {
17 guideProgressKey,
18 guideRunKey,
19 useGuideProgress,
20 useGuideRunStore,
21 type GuideProgress,
22} from "./guideRunStore";
23import { stepTourPosition, stopFilePaths } from "@t3tools/client-runtime/review-guide-tour";
24import { useGuideDiffFiles } from "./useGuideDiffFiles";
25​
26export function GuideTour({
27 environmentId,
28 reference,
29 guide,
30 banner,
31 active,
32 commenting,
33 onAsk,
34 onFinish,
35 onOpenFile,
36}: {
37 environmentId: EnvironmentId;
38 reference: PullRequestRef;
39 guide: PullRequestReviewGuide;
40 banner: ReactNode;
41 active: boolean;
42 commenting: ExcerptCommenting | null;
43 onAsk: ((stop: number, question: string) => void) | null;
44 onFinish: (() => void) | null;
45 onOpenFile: (path: string) => void;
46}) {
47 const key = guideProgressKey(guideRunKey(environmentId, reference), guide.headSha);
48 const tour = useGuideProgress(key);
49 const update = (change: (current: GuideProgress) => Partial<GuideProgress>) =>
50 useGuideRunStore.getState().setProgress(key, (current) => ({ ...current, ...change(current) }));
51 const [railOpen, setRailOpen] = useState(false);
52​
53 const stopCount = guide.stops.length;
54 const position = Math.max(Math.min(tour.position, stopCount - 1), 0);
55 const stop = guide.stops[position] ?? null;
56​
57 const wantedPaths = stop === null ? [] : stopFilePaths(stop);
58 const diff = useGuideDiffFiles({
59 environmentId,
60 reference,
61 headSha: guide.headSha,
62 wantedPaths,
63 });
64 const getDiffFileContents = useAtomCommand(pullRequestEnvironment.diffFileContents);
65 const loadDiffFiles = createPullRequestDiffFileContentsLoader(getDiffFileContents, {
66 environmentId,
67 reference,
68 commit: null,
69 cacheKey: `pull-request-guide:${key}`,
70 });
71​
72 const scrollRef = useRef<HTMLDivElement>(null);
73 const railRef = useRef<HTMLElement>(null);
74 const goTo = (next: number) => {
75 const focused = document.activeElement;
76 if (scrollRef.current?.contains(focused) && !railRef.current?.contains(focused)) {
77 // Keeps focus off the unmounting stop; it is not navigation, so no workspace ring.
78 scrollRef.current.focus({ preventScroll: true, focusVisible: false });
79 }
80 update((current) => ({
81 position: next,
82 seen: next > position ? new Set(current.seen).add(position) : current.seen,
83 }));
84 setRailOpen(false);
85 scrollRef.current?.scrollTo({ top: 0 });
86 };
87 const step = (delta: 1 | -1) => goTo(stepTourPosition(position, delta, stopCount));
88​
89 const stepFromKey = useEffectEvent((event: KeyboardEvent) => {
90 if (event.defaultPrevented || event.isComposing || event.keyCode === 229) return;
91 if (isCommandPaletteOpen()) return;
92 if (event.metaKey || event.ctrlKey || event.altKey || event.shiftKey) return;
93 const key = event.key.toLowerCase();
94 if (key !== "j" && key !== "k") return;
95 if (isEditableFocused(event.target) || isInSideChatPane(event.target)) return;
96 const floatingLayer =
97 event.target instanceof Element
98 ? event.target.closest(
99 '[role="dialog"], [role="alertdialog"], [aria-modal="true"], [role="menu"], [role="combobox"], [data-slot$="popup"]',
100 )
101 : null;
102 if (floatingLayer !== null && !floatingLayer.contains(scrollRef.current)) return;
103 event.preventDefault();
104 step(key === "j" ? 1 : -1);
105 });
106 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- document keydown listener for j/k tour stepping while the guide is active
107 useEffect(() => {
108 if (!active) return;
109 const onKeyDown = (event: KeyboardEvent) => stepFromKey(event);
110 document.addEventListener("keydown", onKeyDown);
111 return () => document.removeEventListener("keydown", onKeyDown);
112 }, [active]);
113​
114 return (
115 <div
116 ref={scrollRef}
117 tabIndex={-1}
118 data-workspace-focus-default
119 aria-keyshortcuts="J K"
120 className="@container/guide h-full overflow-y-auto scrollbar-gutter-both outline-none"
121 >
122 <div className="mx-auto grid max-w-[100rem] gap-6 px-4 py-4 @min-[56rem]/guide:grid-cols-[16rem_minmax(0,1fr)] @min-[90rem]/guide:gap-8 @min-[90rem]/guide:px-6">
123 <aside ref={railRef} className="sticky top-4 self-start @max-[56rem]/guide:hidden">
124 <GuideRail stops={guide.stops} position={position} seen={tour.seen} onSelect={goTo} />
125 </aside>
126 <main className="flex min-w-0 flex-col gap-4">
127 {banner}
128 {diff.error !== null ? (
129 <p className="text-xs text-muted-foreground">
130 <T>
131 The diff could not be loaded, so excerpts are missing: <Var>{diff.error}</Var>
132 </T>
133 </p>
134 ) : null}
135 {stop === null ? (
136 <p className="text-sm text-muted-foreground">
137 <T>This change has no files to tour.</T>
138 </p>
139 ) : (
140 <GuideStop
141 key={position}
142 stop={stop}
143 index={position}
144 stopCount={stopCount}
145 railOpen={railOpen}
146 onRailOpenChange={setRailOpen}
147 stopList={
148 <GuideRail
149 stops={guide.stops}
150 position={position}
151 seen={tour.seen}
152 onSelect={goTo}
153 />
154 }
155 nextTitle={guide.stops[position + 1]?.title ?? null}
156 files={diff.files}
157 loadDiffFiles={loadDiffFiles}
158 diffLoading={diff.loading}
159 commenting={commenting}
160 onStep={step}
161 onAsk={onAsk === null ? null : (question) => onAsk(position, question)}
162 onFinish={
163 onFinish === null
164 ? null
165 : () => {
166 update((current) => ({ seen: new Set(current.seen).add(position) }));
167 onFinish();
168 }
169 }
170 onOpenFile={onOpenFile}
171 />
172 )}
173 </main>
174 </div>
175 </div>
176 );