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

PullRequestGuideScreen.tsx

336 lines14.5 KB

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