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

PullRequestGuideScreen.tsx

336 lines14.5 KB

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