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 { AndroidScreenHeader } from "../../../components/ui/AndroidScreenHeader";
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 <AndroidScreenHeader
143 title={`Stop ${route.params.position + 1}`}
144 onBack={() => navigation.goBack()}
145 trailing={
146 <Menu
147 actions={[
148 {
149 id: "word-wrap",
150 title: "Word wrap",
151 image: "text.alignleft",
152 state: appearance.codeWordBreak ? "on" : "off",
153 },
154 ]}
155 onPressAction={() => setCodeWordBreak(!appearance.codeWordBreak)}
156 >
157 <View pointerEvents="none">
158 <IconButton icon="ellipsis" accessibilityLabel="Guide options" />
159 </View>
160 </Menu>
161 }
162 />
163 ) : null}
164 <Toolbar placement="right">
165 <Toolbar.Menu title="Guide options" accessibilityLabel="Guide options" icon="ellipsis">
166 <Toolbar.MenuAction
167 icon="text.alignleft"
168 isOn={appearance.codeWordBreak}
169 onPress={() => setCodeWordBreak(!appearance.codeWordBreak)}
170 >
171 <Toolbar.Label>Word wrap</Toolbar.Label>
172 </Toolbar.MenuAction>
173 </Toolbar.Menu>
174 </Toolbar>
175 <PullRequestMarkdownRepository params={route.params} changeRequest={detail.data}>
176 <ScreenScrollView
177 contentInsetAdjustmentBehavior="automatic"
178 contentContainerStyle={{ padding: 16, paddingBottom: insets.bottom + 24, gap: 20 }}
179 >
180 <View className="w-full max-w-[760px] self-center gap-5">
181 {!state.enabled ? (
182 <Text>Review guides are disabled for this server.</Text>
183 ) : changedGuide ? (
184 <Text>This guide was rewritten. Go back to start the new tour.</Text>
185 ) : !stop ? (
186 <Text>{state.error ?? "Loading stop…"}</Text>
187 ) : (
188 <>
189 <GuideNotice state={state} />
190 <Text className="text-2xl leading-8 font-t3-semibold">{stop.title}</Text>
191 <PullRequestMarkdown lineBreaks={false} markdown={stop.summary} />
192 {stop.attention ? (
193 <View className="gap-3 rounded-xl border border-border bg-grouped-card p-4">
194 <View className="flex-row items-center gap-2">
195 <SymbolView name="eye" size={17} tintColorClassName="accent-icon-muted" />
196 <Text className="text-sm font-t3-semibold">
197 {attentionLabels[stop.attention.kind]}
198 </Text>
199 </View>
200 <PullRequestMarkdown lineBreaks={false} markdown={stop.attention.note} />
201 </View>
202 ) : null}
203 {stale ? (
204 <Text className="text-sm text-foreground-muted">
205 Excerpts are hidden until the guide is rewritten for the current head.
206 </Text>
207 ) : (
208 stop.excerpts.map((excerpt) => (
209 <ReviewGuideExcerpt
210 key={`${guide?.headSha}:${JSON.stringify(excerpt)}`}
211 onOpen={() =>
212 navigation.dispatch(
213 StackActions.push("PullRequestFile", {
214 ...route.params,
215 path: excerpt.path,
216 focus: { side: excerpt.side, start: excerpt.start, end: excerpt.end },
217 }),
218 )
219 }
220 excerpt={excerpt}
221 file={excerptFiles.get(excerpt.path)}
222 loading={diff.isPending || (missing && diff.nextCursor !== null)}
223 />
224 ))
225 )}
226 {diff.error ? <Text className="text-danger-foreground">{diff.error}</Text> : null}
227 {notes.length ? (
228 <View className="gap-4">
229 <Text className="font-t3-semibold">Notes on this stop</Text>
230 {notes.map(({ marker, note }) => (
231 <View key={marker} className="flex-row gap-3">
232 <View className="h-7 w-7 items-center justify-center rounded-lg bg-grouped-card">
233 <Text className="text-xs font-t3-semibold">{marker}</Text>
234 </View>
235 <View className="min-w-0 flex-1 gap-2">
236 <Text className="font-t3-semibold">{note.title}</Text>
237 <Text className="text-xs text-foreground-muted">
238 {note.path.split("/").at(-1)}:{note.line}
239 </Text>
240 <PullRequestMarkdown lineBreaks={false} markdown={note.body} />
241 </View>
242 </View>
243 ))}
244 </View>
245 ) : null}
246 {stop.files.length ? (
247 <PullRequestCardGroup>
248 {stop.files.map((file, index) => (
249 <PullRequestCardRow
250 key={file.path}
251 title={file.path}
252 detail={file.note}
253 icon="doc"
254 last={index === stop.files.length - 1}
255 onPress={() =>
256 navigation.navigate("PullRequestFile", {
257 ...route.params,
258 path: file.path,
259 })
260 }
261 />
262 ))}
263 </PullRequestCardGroup>
264 ) : null}
265 {stop.questions.length ? (
266 <View className="gap-3">
267 <Text className="font-t3-semibold">Questions to consider</Text>
268 {stop.questions.map((question) => (
269 <PullRequestMarkdown key={question} lineBreaks={false} markdown={question} />
270 ))}
271 </View>
272 ) : null}
273 <Pressable
274 accessibilityRole="button"
275 accessibilityLabel={
276 guide && position < guide.stops.length - 1
277 ? "Next stop"
278 : canReview
279 ? "Finish review"
280 : "Finish tour"
281 }
282 className="mt-2 flex-row items-center gap-4 border-t border-border-subtle pt-5 pb-2 active:opacity-60"
283 onPress={() =>
284 guide && position < guide.stops.length - 1
285 ? navigation.dispatch(
286 StackActions.push("PullRequestGuideStop", {
287 ...route.params,
288 position: stepTourPosition(position, 1, guide.stops.length),
289 }),
290 )
291 : canReview
292 ? navigation.navigate("PullRequestReview", {
293 ...route.params,
294 mode: "review",
295 })
296 : navigation.dispatch(StackActions.popTo("PullRequest", route.params))
297 }
298 >
299 <View className="min-w-0 flex-1 gap-1">
300 <Text className="text-xs text-foreground-muted">
301 {guide && position < guide.stops.length - 1
302 ? `Next · ${position + 2} of ${guide.stops.length}`
303 : "End of guide"}
304 </Text>
305 <Text className="text-base font-t3-semibold">
306 {guide && position < guide.stops.length - 1
307 ? guide.stops[position + 1]?.title
308 : canReview
309 ? "Finish review"
310 : "Finish tour"}
311 </Text>
312 </View>
313 <View className="h-11 w-11 items-center justify-center rounded-full bg-foreground">
314 <SymbolView
315 name={
316 guide && position < guide.stops.length - 1 ? "arrow.right" : "checkmark"
317 }
318 size={20}
319 tintColorClassName="accent-screen"
320 />
321 </View>
322 </Pressable>
323 </>
324 )}
325 </View>
326 </ScreenScrollView>
327 </PullRequestMarkdownRepository>
328 </View>
329 );
330}
331
332function diffFilesByPath(patchText: string): Map<string, FileDiffMetadata> {
333 const files = new Map<string, FileDiffMetadata>();
334 try {
335 for (const patch of parsePatchFiles(patchText)) {
336 for (const file of patch.files) {
337 files.set(file.name, file);
338 if (file.prevName) files.set(file.prevName, file);
339 }
340 }
341 } catch {}
342 return files;
343}