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