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