@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
tsx 337 lines 14.2 KB
Raw
1 import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
2 import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles";
3 import type { FileDiffMetadata } from "@pierre/diffs";
4 import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
5 import { msg, T, useGT, useMessages } from "gt-react-native";
6 import { useEffect } from "react";
7 import { Pressable, View } from "react-native";
8 import { AppBar } from "../../../components/ui/AppBar";
9 import { useSafeAreaInsets } from "react-native-safe-area-context";
10 import {
11 letterStopNotes,
12 stepTourPosition,
13 stopFilePaths,
14 } from "@t3tools/client-runtime/review-guide-tour";
15 import { SymbolView } from "../../../components/ui/AppSymbol";
16 import { GuideOutline } from "./GuideOutline";
17 import { AppText as Text } from "../../../components/ui/AppText";
18 import { ScreenScrollView } from "../../../components/ui/ScreenScrollView";
19 import { useAppearancePreferences } from "../../settings/appearance/AppearancePreferencesProvider";
20 import { PullRequestCardGroup, PullRequestCardRow } from "../PullRequestControls";
21 import { PullRequestMarkdown, PullRequestMarkdownRepository } from "../PullRequestMarkdown";
22 import { usePullRequestDiff, type PullRequestParams } from "../usePullRequestDiff";
23 import { ReviewGuideExcerpt } from "./ReviewGuideExcerpt";
24 import { reviewGuideState } from "./reviewGuideState";
25 import { GuideNotice } from "./GuideNotice";
26 import Animated from "react-native-reanimated";
27 import { PR_ROW_ENTER, PR_ROW_EXIT, PR_ROW_LAYOUT } from "../pullRequestAnimations";
28 import { useEnvironmentQuery } from "../../../state/query";
29 import { composerPullRequests } from "../../../state/pull-requests";
30 import { usePullRequestPermissions } from "../usePullRequestPermissions";
31 import { pullRequestTarget } from "../usePullRequestDiff";
32 import { useReviewGuide } from "./useReviewGuide";
33
34 export type GuideStopParams = PullRequestParams & {
35 readonly position: number;
36 readonly guideHeadSha: string;
37 readonly guideGeneratedAt: string;
38 };
39
40 const 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
48 export 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 );
98 }
99
100 export 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} of {total}", {
138 position: route.params.position + 1,
139 total: guide?.stops.length ?? "…",
140 })}
141 onBack={() => navigation.goBack()}
142 menus={[
143 {
144 title: gt("Guide options"),
145 icon: "ellipsis",
146 items: [
147 {
148 id: "word-wrap",
149 title: gt("Word wrap"),
150 icon: "text.alignleft",
151 selected: appearance.codeWordBreak,
152 onPress: () => setCodeWordBreak(!appearance.codeWordBreak),
153 },
154 ],
155 },
156 ]}
157 />
158 <PullRequestMarkdownRepository params={route.params} changeRequest={detail.data}>
159 <ScreenScrollView
160 contentInsetAdjustmentBehavior="automatic"
161 contentContainerStyle={{ padding: 16, paddingBottom: insets.bottom + 24, gap: 20 }}
162 >
163 <View className="w-full max-w-[760px] self-center gap-5">
164 {!state.enabled ? (
165 <Text>
166 <T>Review guides are disabled for this server.</T>
167 </Text>
168 ) : changedGuide ? (
169 <Text>
170 <T>This guide was rewritten. Go back to start the new tour.</T>
171 </Text>
172 ) : !stop ? (
173 <Text>{state.error ?? gt("Loading stop…")}</Text>
174 ) : (
175 <>
176 <GuideNotice state={state} />
177 <Text className="text-2xl leading-8 font-t3-semibold">{stop.title}</Text>
178 <PullRequestMarkdown lineBreaks={false} markdown={stop.summary} />
179 {stop.attention ? (
180 <View className="gap-3 rounded-xl border border-border bg-grouped-card p-4">
181 <View className="flex-row items-center gap-2">
182 <SymbolView name="eye" size={17} tintColorClassName="accent-icon-muted" />
183 <Text className="text-sm font-t3-semibold">
184 {m(attentionLabels[stop.attention.kind])}
185 </Text>
186 </View>
187 <PullRequestMarkdown lineBreaks={false} markdown={stop.attention.note} />
188 </View>
189 ) : null}
190 {stale ? (
191 <Text className="text-sm text-foreground-muted">
192 <T>Excerpts are hidden until the guide is rewritten for the current head.</T>
193 </Text>
194 ) : (
195 stop.excerpts.map((excerpt) => (
196 <ReviewGuideExcerpt
197 key={`${guide?.headSha}:${JSON.stringify(excerpt)}`}
198 onOpen={() =>
199 navigation.dispatch(
200 StackActions.push("PullRequestFile", {
201 ...route.params,
202 path: excerpt.path,
203 focus: { side: excerpt.side, start: excerpt.start, end: excerpt.end },
204 }),
205 )
206 }
207 excerpt={excerpt}
208 file={excerptFiles.get(excerpt.path)}
209 loading={diff.isPending || (missing && diff.nextCursor !== null)}
210 />
211 ))
212 )}
213 {diff.error ? <Text className="text-danger-foreground">{diff.error}</Text> : null}
214 {notes.length ? (
215 <View className="gap-4">
216 <Text className="font-t3-semibold">
217 <T>Notes on this stop</T>
218 </Text>
219 {notes.map(({ marker, note }) => (
220 <View key={marker} className="flex-row gap-3">
221 <View className="h-7 w-7 items-center justify-center rounded-lg bg-grouped-card">
222 <Text className="text-xs font-t3-semibold">{marker}</Text>
223 </View>
224 <View className="min-w-0 flex-1 gap-2">
225 <Text className="font-t3-semibold">{note.title}</Text>
226 <Text className="text-xs text-foreground-muted">
227 {note.path.split("/").at(-1)}:{note.line}
228 </Text>
229 <PullRequestMarkdown lineBreaks={false} markdown={note.body} />
230 </View>
231 </View>
232 ))}
233 </View>
234 ) : null}
235 {stop.files.length ? (
236 <PullRequestCardGroup>
237 {stop.files.map((file, index) => (
238 <PullRequestCardRow
239 key={file.path}
240 title={file.path}
241 detail={file.note}
242 icon="doc"
243 last={index === stop.files.length - 1}
244 onPress={() =>
245 navigation.navigate("PullRequestFile", {
246 ...route.params,
247 path: file.path,
248 })
249 }
250 />
251 ))}
252 </PullRequestCardGroup>
253 ) : null}
254 {stop.questions.length ? (
255 <View className="gap-3">
256 <Text className="font-t3-semibold">
257 <T>Questions to consider</T>
258 </Text>
259 {stop.questions.map((question) => (
260 <PullRequestMarkdown key={question} lineBreaks={false} markdown={question} />
261 ))}
262 </View>
263 ) : null}
264 <Pressable
265 accessibilityRole="button"
266 accessibilityLabel={
267 guide && position < guide.stops.length - 1
268 ? gt("Next stop")
269 : canReview
270 ? gt("Finish review")
271 : gt("Finish tour")
272 }
273 className="mt-2 flex-row items-center gap-4 border-t border-border-subtle pt-5 pb-2 active:opacity-60"
274 onPress={() =>
275 guide && position < guide.stops.length - 1
276 ? navigation.dispatch(
277 StackActions.push("PullRequestGuideStop", {
278 ...route.params,
279 position: stepTourPosition(position, 1, guide.stops.length),
280 }),
281 )
282 : canReview
283 ? navigation.navigate("PullRequestReview", {
284 ...route.params,
285 mode: "review",
286 })
287 : navigation.dispatch(StackActions.popTo("PullRequest", route.params))
288 }
289 >
290 <View className="min-w-0 flex-1 gap-1">
291 <Text className="text-xs text-foreground-muted">
292 {guide && position < guide.stops.length - 1
293 ? gt("Next · {position} of {total}", {
294 position: position + 2,
295 total: guide.stops.length,
296 })
297 : gt("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 ? gt("Finish review")
304 : gt("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
326 function 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 }