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

PullRequestGuideScreen.tsx

332 lines14.1 KB

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