Open History to see the last commit
1import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
2import { Toolbar } from "../../../components/ui/Toolbar";
3import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles";
4import type { FileDiffMetadata } from "@pierre/diffs";
5import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
6import { useEffect } from "react";
7import { Platform, Pressable, View } from "react-native";
8import { AppBar } from "../../../components/ui/AppBar";
9import { useSafeAreaInsets } from "react-native-safe-area-context";
10import {
11 letterStopNotes,
12 stepTourPosition,
13 stopFilePaths,
14} from "@t3tools/client-runtime/review-guide-tour";
15import { SymbolView } from "../../../components/ui/AppSymbol";
16import { GuideOutline } from "./GuideOutline";
17import { AppText as Text } from "../../../components/ui/AppText";
18import { ScreenScrollView } from "../../../components/ui/ScreenScrollView";
19import { Menu } from "../../../components/ui/Menu";
20import { IconButton } from "../../../components/ui/IconButton";
21import { useAppearancePreferences } from "../../settings/appearance/AppearancePreferencesProvider";
22import { NativeStackScreenOptions } from "../../../native/StackHeader";
23import { PullRequestCardGroup, PullRequestCardRow } from "../PullRequestControls";
24import { PullRequestMarkdown, PullRequestMarkdownRepository } from "../PullRequestMarkdown";
25import { usePullRequestDiff, type PullRequestParams } from "../usePullRequestDiff";
26import { ReviewGuideExcerpt } from "./ReviewGuideExcerpt";
27import { reviewGuideState } from "./reviewGuideState";
28import { GuideNotice } from "./GuideNotice";
29import Animated from "react-native-reanimated";
30import { PR_ROW_ENTER, PR_ROW_EXIT, PR_ROW_LAYOUT } from "../pullRequestAnimations";
31import { useEnvironmentQuery } from "../../../state/query";
32import { composerPullRequests } from "../../../state/pull-requests";
33import { usePullRequestPermissions } from "../usePullRequestPermissions";
34import { pullRequestTarget } from "../usePullRequestDiff";
35import { useReviewGuide } from "./useReviewGuide";
36
37export type GuideStopParams = PullRequestParams & {
38 readonly position: number;
39 readonly guideHeadSha: string;
40 readonly guideGeneratedAt: string;
41};
42
43const attentionLabels = {
44 tradeoff: "A tradeoff to weigh",
45 contract: "A contract to check",
46 product: "A product call",
47 risk: "A risk to judge",
48 accessibility: "An accessibility call",
49};
50
51export function PullRequestGuideContent({
52 params,
53 visible = true,
54}: {
55 readonly params: PullRequestParams;
56 readonly visible?: boolean;
57}) {
58 const navigation = useNavigation();
59 const state = useReviewGuide(params, visible);
60 const { guide, stale } = reviewGuideState(state.data);
61 return (
62 <Animated.View layout={PR_ROW_LAYOUT} className="w-full max-w-[760px] self-center">
63 {!state.enabled ? (
64 <Text>Review guides are disabled for this server.</Text>
65 ) : (
66 <>
67 <GuideNotice state={state} />
68 {guide ? (
69 <Animated.View
70 key={`outline:${guide.headSha}:${guide.generatedAt}`}
71 layout={PR_ROW_LAYOUT}
72 entering={PR_ROW_ENTER}
73 exiting={PR_ROW_EXIT}
74 >
75 <GuideOutline
76 guide={guide}
77 onOpen={(position) =>
78 navigation.dispatch(
79 StackActions.push("PullRequestGuideStop", {
80 ...params,
81 position,
82 guideHeadSha: guide.headSha,
83 guideGeneratedAt: guide.generatedAt,
84 }),
85 )
86 }
87 onRewrite={
88 state.canWrite && !state.running && !stale && !state.startError && !state.error
89 ? () => void state.write()
90 : undefined
91 }
92 />
93 </Animated.View>
94 ) : null}
95 </>
96 )}
97 </Animated.View>
98 );
99}
100
101export function PullRequestGuideStopScreen({ route }: StaticScreenProps<GuideStopParams>) {
102 const navigation = useNavigation();
103 const state = useReviewGuide(route.params);
104 const detail = useEnvironmentQuery(composerPullRequests.detail(pullRequestTarget(route.params)));
105 const permissions = usePullRequestPermissions(route.params, detail.data);
106 const canReview =
107 permissions.verdicts.length > 0 && detail.data?.headSha === route.params.guideHeadSha;
108 const { guide, stale } = reviewGuideState(state.data);
109 const position = Math.max(0, Math.min(route.params.position, (guide?.stops.length ?? 1) - 1));
110 const stop = guide?.stops[Math.max(0, position)];
111 const diff = usePullRequestDiff(
112 route.params,
113 sourceControlClients.get((detail.data ?? route.params.initialSummary)?.provider).changeRequest,
114 );
115 const excerptFiles = diffFilesByPath(diff.patch);
116 const wanted = stop ? stopFilePaths(stop) : [];
117 const loadedPaths = new Set(
118 diff.parsed.kind === "files" ? diff.parsed.files.map((file) => file.path) : [],
119 );
120 const missing = wanted.some((path) => !loadedPaths.has(path));
121 const { error: diffError, loadMore } = diff;
122 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- requests the next page of the paged diff query until the stop's files have loaded
123 useEffect(() => {
124 if (state.enabled && missing && !diffError) loadMore();
125 }, [state.enabled, missing, diffError, loadMore]);
126 const insets = useSafeAreaInsets();
127 const changedGuide =
128 guide !== null &&
129 (guide.headSha !== route.params.guideHeadSha ||
130 guide.generatedAt !== route.params.guideGeneratedAt);
131 const { appearance, setCodeWordBreak } = useAppearancePreferences();
132 const notes = stop ? letterStopNotes(stop).lettered : [];
133 return (
134 <View className="flex-1 bg-screen">
135 <NativeStackScreenOptions
136 options={{
137 title: `Stop ${route.params.position + 1}`,
138 headerTitle: `Stop ${route.params.position + 1} of ${guide?.stops.length ?? "…"}`,
139 }}
140 />
141 {Platform.OS === "android" ? (
142 <AppBar
143 embedded
144 title={`Stop ${route.params.position + 1}`}
145 onBack={() => navigation.goBack()}
146 trailing={
147 <Menu
148 actions={[
149 {
150 id: "word-wrap",
151 title: "Word wrap",
152 image: "text.alignleft",
153 state: appearance.codeWordBreak ? "on" : "off",
154 },
155 ]}
156 onPressAction={() => setCodeWordBreak(!appearance.codeWordBreak)}
157 >
158 <View pointerEvents="none">
159 <IconButton icon="ellipsis" accessibilityLabel="Guide options" />
160 </View>
161 </Menu>
162 }
163 />
164 ) : null}
165 <Toolbar placement="right">
166 <Toolbar.Menu title="Guide options" accessibilityLabel="Guide options" icon="ellipsis">
167 <Toolbar.MenuAction
168 icon="text.alignleft"
169 isOn={appearance.codeWordBreak}
170 onPress={() => setCodeWordBreak(!appearance.codeWordBreak)}
171 >
172 <Toolbar.Label>Word wrap</Toolbar.Label>
173 </Toolbar.MenuAction>
174 </Toolbar.Menu>
175 </Toolbar>
176 <PullRequestMarkdownRepository params={route.params} changeRequest={detail.data}>
177 <ScreenScrollView
178 contentInsetAdjustmentBehavior="automatic"
179 contentContainerStyle={{ padding: 16, paddingBottom: insets.bottom + 24, gap: 20 }}
180 >
181 <View className="w-full max-w-[760px] self-center gap-5">
182 {!state.enabled ? (
183 <Text>Review guides are disabled for this server.</Text>
184 ) : changedGuide ? (
185 <Text>This guide was rewritten. Go back to start the new tour.</Text>
186 ) : !stop ? (
187 <Text>{state.error ?? "Loading stop…"}</Text>
188 ) : (
189 <>
190 <GuideNotice state={state} />
191 <Text className="text-2xl leading-8 font-t3-semibold">{stop.title}</Text>
192 <PullRequestMarkdown lineBreaks={false} markdown={stop.summary} />
193 {stop.attention ? (
194 <View className="gap-3 rounded-xl border border-border bg-grouped-card p-4">
195 <View className="flex-row items-center gap-2">
196 <SymbolView name="eye" size={17} tintColorClassName="accent-icon-muted" />
197 <Text className="text-sm font-t3-semibold">
198 {attentionLabels[stop.attention.kind]}
199 </Text>
200 </View>
201 <PullRequestMarkdown lineBreaks={false} markdown={stop.attention.note} />
202 </View>
203 ) : null}
204 {stale ? (
205 <Text className="text-sm text-foreground-muted">
206 Excerpts are hidden until the guide is rewritten for the current head.
207 </Text>
208 ) : (
209 stop.excerpts.map((excerpt) => (
210 <ReviewGuideExcerpt
211 key={`${guide?.headSha}:${JSON.stringify(excerpt)}`}
212 onOpen={() =>
213 navigation.dispatch(
214 StackActions.push("PullRequestFile", {
215 ...route.params,
216 path: excerpt.path,
217 focus: { side: excerpt.side, start: excerpt.start, end: excerpt.end },
218 }),
219 )
220 }
221 excerpt={excerpt}
222 file={excerptFiles.get(excerpt.path)}
223 loading={diff.isPending || (missing && diff.nextCursor !== null)}
224 />
225 ))
226 )}
227 {diff.error ? <Text className="text-danger-foreground">{diff.error}</Text> : null}
228 {notes.length ? (
229 <View className="gap-4">
230 <Text className="font-t3-semibold">Notes on this stop</Text>
231 {notes.map(({ marker, note }) => (
232 <View key={marker} className="flex-row gap-3">
233 <View className="h-7 w-7 items-center justify-center rounded-lg bg-grouped-card">
234 <Text className="text-xs font-t3-semibold">{marker}</Text>
235 </View>
236 <View className="min-w-0 flex-1 gap-2">
237 <Text className="font-t3-semibold">{note.title}</Text>
238 <Text className="text-xs text-foreground-muted">
239 {note.path.split("/").at(-1)}:{note.line}
240 </Text>
241 <PullRequestMarkdown lineBreaks={false} markdown={note.body} />
242 </View>
243 </View>
244 ))}
245 </View>
246 ) : null}
247 {stop.files.length ? (
248 <PullRequestCardGroup>
249 {stop.files.map((file, index) => (
250 <PullRequestCardRow
251 key={file.path}
252 title={file.path}
253 detail={file.note}
254 icon="doc"
255 last={index === stop.files.length - 1}
256 onPress={() =>
257 navigation.navigate("PullRequestFile", {
258 ...route.params,
259 path: file.path,
260 })
261 }
262 />
263 ))}
264 </PullRequestCardGroup>
265 ) : null}
266 {stop.questions.length ? (
267 <View className="gap-3">
268 <Text className="font-t3-semibold">Questions to consider</Text>
269 {stop.questions.map((question) => (
270 <PullRequestMarkdown key={question} lineBreaks={false} markdown={question} />
271 ))}
272 </View>
273 ) : null}
274 <Pressable
275 accessibilityRole="button"
276 accessibilityLabel={
277 guide && position < guide.stops.length - 1
278 ? "Next stop"
279 : canReview
280 ? "Finish review"
281 : "Finish tour"
282 }
283 className="mt-2 flex-row items-center gap-4 border-t border-border-subtle pt-5 pb-2 active:opacity-60"
284 onPress={() =>
285 guide && position < guide.stops.length - 1
286 ? navigation.dispatch(
287 StackActions.push("PullRequestGuideStop", {
288 ...route.params,
289 position: stepTourPosition(position, 1, guide.stops.length),
290 }),
291 )
292 : canReview
293 ? navigation.navigate("PullRequestReview", {
294 ...route.params,
295 mode: "review",
296 })
297 : navigation.dispatch(StackActions.popTo("PullRequest", route.params))
298 }
299 >
300 <View className="min-w-0 flex-1 gap-1">
301 <Text className="text-xs text-foreground-muted">
302 {guide && position < guide.stops.length - 1
303 ? `Next · ${position + 2} of ${guide.stops.length}`
304 : "End of guide"}
305 </Text>
306 <Text className="text-base font-t3-semibold">
307 {guide && position < guide.stops.length - 1
308 ? guide.stops[position + 1]?.title
309 : canReview
310 ? "Finish review"
311 : "Finish tour"}
312 </Text>
313 </View>
314 <View className="h-11 w-11 items-center justify-center rounded-full bg-foreground">
315 <SymbolView
316 name={
317 guide && position < guide.stops.length - 1 ? "arrow.right" : "checkmark"
318 }
319 size={20}
320 tintColorClassName="accent-screen"
321 />
322 </View>
323 </Pressable>
324 </>
325 )}
326 </View>
327 </ScreenScrollView>
328 </PullRequestMarkdownRepository>
329 </View>
330 );
331}
332
333function diffFilesByPath(patchText: string): Map<string, FileDiffMetadata> {
334 const files = new Map<string, FileDiffMetadata>();
335 try {
336 for (const patch of parsePatchFiles(patchText)) {
337 for (const file of patch.files) {
338 files.set(file.name, file);
339 if (file.prevName) files.set(file.prevName, file);
340 }
341 }
342 } catch {}
343 return files;
344}