@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 522 lines 18.6 KB
Raw
1 import { NativeScrollView } from "../../native/NativeScrollViewMarker";
2 import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
3 import { AnimatedLegendList } from "@legendapp/list/reanimated";
4 import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
5 import type { PullRequestChangeBreakdown } from "@t3tools/contracts";
6 import { msg, T, useGT, useMessages, Var } from "gt-react-native";
7 import { useState } from "react";
8 import { View } from "react-native";
9 import Animated from "react-native-reanimated";
10 import { PierreEntryIcon } from "../../components/PierreEntryIcon";
11 import { AppText as Text } from "../../components/ui/AppText";
12 import { SymbolView } from "../../components/ui/AppSymbol";
13 import { Button } from "../../components/ui/Button";
14 import { EmptyState } from "../../components/ui/EmptyState";
15 import { IconButton } from "../../components/ui/IconButton";
16 import { Menu } from "../../components/ui/Menu";
17 import { RowPressable } from "../../components/ui/RowPressable";
18 import { ScreenContent } from "../../components/ui/ScreenContent";
19 import { SheetHeader } from "../../components/ui/SheetHeader";
20 import { composerPullRequests } from "../../state/pull-requests";
21 import { useEnvironmentQuery } from "../../state/query";
22 import type { ReviewParsedDiff, ReviewRenderableFile } from "../review/reviewModel";
23 import { PR_ROW_ENTER, PR_ROW_EXIT, PR_ROW_LAYOUT } from "./pullRequestAnimations";
24 import { PullRequestDiffStats, PullRequestReadStatus } from "./PullRequestPresentation";
25 import { PullRequestSectionHeading } from "./PullRequestSectionHeading";
26 import {
27 pullRequestTarget,
28 usePullRequestDiff,
29 type PullRequestDiffParams,
30 type PullRequestParams,
31 } from "./usePullRequestDiff";
32 import { usePullRequestFileFilter } from "./usePullRequestFileFilter";
33 import { usePullRequestFilesViewed } from "./usePullRequestFilesViewed";
34 import { requestPullRequestFileJump } from "./pullRequestFileJump";
35 import { fileDirectory, groupByDirectory } from "./pullRequestFileSections";
36 import type { MessageResolver } from "../../i18n/messages";
37
38 const BREAKDOWN_LABELS = {
39 code: msg("Code", { $context: "kind of changed file" }),
40 tests: msg("Tests", { $context: "kind of changed file" }),
41 mocks: msg("Mocks", { $context: "kind of changed file" }),
42 generated: msg("Generated", { $context: "kind of changed file" }),
43 docs: msg("Docs", { $context: "kind of changed file" }),
44 } satisfies Record<keyof NonNullable<PullRequestChangeBreakdown>, string>;
45
46 function useChangedFiles(params: PullRequestDiffParams) {
47 const detail = useEnvironmentQuery(composerPullRequests.detail(pullRequestTarget(params)));
48 // A commit's diff is part of the pull request, so the PR's file counts and viewed state don't apply.
49 const pr = params.commit ? null : detail.data;
50 const terminology = sourceControlClients.get(
51 (detail.data ?? params.initialSummary)?.provider,
52 ).changeRequest;
53 const diff = usePullRequestDiff(params, terminology);
54 const viewed = usePullRequestFilesViewed(params, pr);
55 const filter = usePullRequestFileFilter(diff.parsed);
56 const parsed = filter.parsed;
57 return {
58 diff,
59 filter,
60 viewed,
61 pr,
62 terminology,
63 parsed,
64 loading: diff.isPending && parsed.kind === "empty" && !diff.error,
65 };
66 }
67
68 type ChangedFiles = ReturnType<typeof useChangedFiles>;
69
70 function loadingRowCount(files: ChangedFiles) {
71 return Math.min(files.pr?.changedFiles ?? 4, 6);
72 }
73
74 function describeFiles(
75 parsed: Extract<ReviewParsedDiff, { readonly kind: "files" }>,
76 { filter, viewed }: ChangedFiles,
77 resolve: MessageResolver,
78 ) {
79 const count = parsed.fileCount;
80 return [
81 filter.hiddenCount
82 ? resolve(
83 msg("{count, plural, one {{count} visible file} other {{count} visible files}}", {
84 count,
85 }),
86 )
87 : resolve(
88 msg("{count, plural, one {{count} changed file} other {{count} changed files}}", {
89 count,
90 }),
91 ),
92 viewed.supported
93 ? resolve(
94 msg("{count, plural, one {{count} viewed} other {{count} viewed}}", {
95 count: parsed.files.filter((file) => viewed.isViewed(file.path)).length,
96 }),
97 )
98 : null,
99 filter.hideTestFiles
100 ? resolve(
101 msg("{count, plural, one {{count} test file hidden} other {{count} test files hidden}}", {
102 count: filter.hiddenCount,
103 }),
104 )
105 : resolve(msg("Test files included")),
106 ]
107 .filter(Boolean)
108 .join(" · ");
109 }
110
111 function FileRow(props: {
112 readonly file: ReviewRenderableFile;
113 readonly viewed: boolean;
114 /** Shown under the file name where files aren't grouped by directory. */
115 readonly directory?: string;
116 readonly onPress: () => void;
117 }) {
118 const { file } = props;
119 const gt = useGT();
120 const values = { path: file.path, additions: file.additions, deletions: file.deletions };
121 return (
122 <RowPressable
123 accessibilityRole="button"
124 accessibilityLabel={
125 props.viewed
126 ? gt("View diff for {path}, {additions} additions, {deletions} deletions, viewed", values)
127 : gt("View diff for {path}, {additions} additions, {deletions} deletions", values)
128 }
129 onPress={props.onPress}
130 className="min-h-14 flex-row items-center gap-3 border-b border-border-subtle py-3 active:opacity-70"
131 >
132 <PierreEntryIcon kind="file" path={file.path} size={20} />
133 <View className="min-w-0 flex-1 gap-0.5">
134 <Text textRole="footnote" className="font-t3-medium" numberOfLines={2}>
135 {file.path.split("/").at(-1)}
136 </Text>
137 {props.directory ? (
138 <Text textRole="caption" className="text-foreground-muted" numberOfLines={1}>
139 {props.directory}
140 </Text>
141 ) : null}
142 {file.previousPath ? (
143 <Text textRole="caption" className="text-foreground-muted" numberOfLines={1}>
144 <T>
145 Renamed from <Var>{file.previousPath}</Var>
146 </T>
147 </Text>
148 ) : null}
149 </View>
150 <PullRequestDiffStats additions={file.additions} deletions={file.deletions} compact />
151 {props.viewed ? (
152 <SymbolView
153 name="checkmark.circle.fill"
154 size={18}
155 tintColorClassName="accent-adaptive-emerald-600-400"
156 />
157 ) : null}
158 <SymbolView name="chevron.right" size={12} tintColorClassName="accent-icon-muted" />
159 </RowPressable>
160 );
161 }
162
163 function FileRowSkeleton(props: { readonly index: number }) {
164 return (
165 <View
166 accessible={false}
167 importantForAccessibility="no-hide-descendants"
168 className="min-h-14 flex-row items-center gap-3 border-b border-border-subtle py-3"
169 >
170 <View className="size-5 rounded-md bg-subtle-strong" />
171 <View className="flex-1 gap-2">
172 <View
173 className="h-3.5 rounded bg-subtle-strong"
174 style={{ width: props.index % 2 ? "65%" : "80%" }}
175 />
176 <View className="h-2.5 w-2/5 rounded bg-subtle-strong" />
177 </View>
178 <View className="h-3 w-7 rounded bg-subtle-strong" />
179 </View>
180 );
181 }
182
183 function FileFilterMenu({ filter }: { readonly filter: ChangedFiles["filter"] }) {
184 const gt = useGT();
185 return (
186 <Menu
187 title={gt("Review files")}
188 actions={[
189 {
190 id: "hide-tests",
191 title: gt("Hide test files"),
192 image: "line.3.horizontal.decrease",
193 state: filter.hideTestFiles ? "on" : "off",
194 },
195 ]}
196 onPressAction={filter.toggle}
197 >
198 <View pointerEvents="none">
199 <IconButton
200 icon="line.3.horizontal.decrease"
201 accessibilityLabel={gt("Filter review files")}
202 selected={filter.hideTestFiles}
203 />
204 </View>
205 </Menu>
206 );
207 }
208
209 function NoVisibleFiles({ files }: { readonly files: ChangedFiles }) {
210 const { diff, filter, parsed } = files;
211 const gt = useGT();
212 if (parsed.kind === "files") {
213 return parsed.files.length === 0 && filter.hiddenCount > 0 ? (
214 <EmptyState
215 title={diff.nextCursor ? gt("No non-test files loaded yet") : gt("Only test files changed")}
216 detail={gt("Test files are hidden from this review.")}
217 action={<Button label={gt("Show test files")} tone="contrast" onPress={filter.showAll} />}
218 variant="plain"
219 />
220 ) : null;
221 }
222 return !diff.isPending && !diff.error ? (
223 <Text textRole="footnote" className="py-6 text-foreground-muted">
224 <T>No text changes available.</T>
225 </Text>
226 ) : null;
227 }
228
229 function FilesFooter({ files }: { readonly files: ChangedFiles }) {
230 const { diff, viewed, parsed } = files;
231 const gt = useGT();
232 return (
233 <>
234 {diff.nextCursor ? (
235 <Button
236 label={diff.error ? gt("Retry loading files") : gt("Load more files")}
237 tone="secondary"
238 onPress={diff.error ? diff.refresh : diff.loadMore}
239 loading={diff.isPending}
240 fullWidth
241 />
242 ) : null}
243 {viewed.error ? (
244 <Text textRole="label" className="py-2 text-danger-foreground">
245 {viewed.error}
246 </Text>
247 ) : null}
248 {parsed.kind === "files" && parsed.notice ? (
249 <Text textRole="label" className="py-4 text-foreground-muted">
250 {parsed.notice}
251 </Text>
252 ) : null}
253 </>
254 );
255 }
256
257 function ChangeBreakdownLine(props: {
258 readonly breakdown: NonNullable<PullRequestChangeBreakdown>;
259 }) {
260 const m = useMessages();
261 const parts = (Object.keys(BREAKDOWN_LABELS) as Array<keyof typeof BREAKDOWN_LABELS>).flatMap(
262 (kind) => {
263 const { additions, deletions } = props.breakdown[kind];
264 return additions === 0 && deletions === 0
265 ? []
266 : [
267 `${m(BREAKDOWN_LABELS[kind])} +${additions.toLocaleString()} −${deletions.toLocaleString()}`,
268 ];
269 },
270 );
271 return (
272 <Text textRole="caption" className="tabular-nums text-foreground-muted" numberOfLines={2}>
273 {parts.join(" · ")}
274 </Text>
275 );
276 }
277
278 /**
279 * The changed-files section of the pull request overview. The overview tab is a single list,
280 * so the section supplies its header, rows, and footer instead of rendering a list of its own.
281 */
282 export function usePullRequestFilesSection(params: PullRequestParams) {
283 const navigation = useNavigation();
284 const gt = useGT();
285 const m = useMessages();
286 const files = useChangedFiles(params);
287 const { diff, filter, viewed, pr, parsed, loading } = files;
288 const breakdown = useEnvironmentQuery(
289 composerPullRequests.changeBreakdown(pullRequestTarget(params)),
290 ).data;
291 const expected = pr ?? params.initialSummary;
292 return {
293 refresh: diff.refresh,
294 header: (
295 <>
296 <PullRequestReadStatus pending={false} error={diff.error} terminology={files.terminology} />
297 {loading ? (
298 <View
299 accessibilityLabel={gt("Loading changed files")}
300 accessibilityState={{ busy: true }}
301 className="min-h-17 flex-row items-center gap-2 py-3"
302 >
303 <View className="min-w-0 flex-1 gap-1">
304 <PullRequestSectionHeading>
305 <T>Changed files</T>
306 </PullRequestSectionHeading>
307 {pr ? (
308 <Text textRole="caption" className="text-foreground-muted">
309 {gt("{count, plural, one {{count} file} other {{count} files}}", {
310 count: pr.changedFiles,
311 })}
312 </Text>
313 ) : (
314 <View className="h-2.5 w-28 rounded bg-subtle-strong" />
315 )}
316 </View>
317 {expected?.additions !== undefined && expected.deletions !== undefined ? (
318 <PullRequestDiffStats
319 additions={expected.additions}
320 deletions={expected.deletions}
321 compact
322 />
323 ) : null}
324 <View className="size-11 items-center justify-center opacity-40">
325 <SymbolView
326 name="line.3.horizontal.decrease"
327 size={20}
328 tintColorClassName="accent-icon-muted"
329 />
330 </View>
331 </View>
332 ) : parsed.kind === "files" ? (
333 <View className="min-h-17 flex-row items-center gap-2 py-3">
334 <View className="min-w-0 flex-1 gap-1">
335 <PullRequestSectionHeading>
336 <T>Changed files</T>
337 </PullRequestSectionHeading>
338 <Text textRole="caption" className="text-foreground-muted">
339 {describeFiles(parsed, files, m)}
340 </Text>
341 {breakdown ? <ChangeBreakdownLine breakdown={breakdown} /> : null}
342 </View>
343 <PullRequestDiffStats
344 additions={parsed.additions}
345 deletions={parsed.deletions}
346 compact
347 />
348 <FileFilterMenu filter={filter} />
349 </View>
350 ) : null}
351 <NoVisibleFiles files={files} />
352 </>
353 ),
354 rows: loading
355 ? Array.from({ length: loadingRowCount(files) }, (_, index) => ({
356 key: `loading-file:${index}`,
357 content: <FileRowSkeleton index={index} />,
358 }))
359 : (parsed.kind === "files" ? parsed.files : []).map((file) => ({
360 key: file.id,
361 content: (
362 <FileRow
363 file={file}
364 directory={fileDirectory(file.path)}
365 viewed={viewed.isViewed(file.path)}
366 onPress={() => navigation.navigate("PullRequestFile", { ...params, path: file.path })}
367 />
368 ),
369 })),
370 footer: <FilesFooter files={files} />,
371 };
372 }
373
374 function DirectoryRow(props: {
375 readonly directory: string;
376 readonly collapsed: boolean;
377 readonly onPress: () => void;
378 }) {
379 const gt = useGT();
380 const label = props.directory || gt("Repository root");
381 return (
382 <RowPressable
383 accessibilityRole="button"
384 accessibilityLabel={label}
385 accessibilityState={{ expanded: !props.collapsed }}
386 onPress={props.onPress}
387 className="min-h-11 flex-row items-center gap-2 pt-4 pb-2 active:opacity-70"
388 >
389 <SymbolView
390 name={props.collapsed ? "chevron.right" : "chevron.down"}
391 size={11}
392 tintColorClassName="accent-icon-muted"
393 />
394 <SymbolView name="folder" size={16} tintColorClassName="accent-icon-muted" />
395 <Text textRole="label" className="min-w-0 flex-1 text-foreground-muted" numberOfLines={2}>
396 {label}
397 </Text>
398 </RowPressable>
399 );
400 }
401
402 /** The `PullRequestFiles` sheet: a changed-file picker presented over a file diff. */
403 export function PullRequestFilesSheet({ route }: StaticScreenProps<PullRequestDiffParams>) {
404 const params = route.params;
405 const navigation = useNavigation();
406 const gt = useGT();
407 const m = useMessages();
408 const files = useChangedFiles(params);
409 const { diff, filter, viewed, parsed, loading } = files;
410 const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(() => new Set());
411 const [animationsReady, setAnimationsReady] = useState(false);
412 const toggleDirectory = (directory: string) =>
413 setCollapsed((current) => {
414 const next = new Set(current);
415 if (!next.delete(directory)) next.add(directory);
416 return next;
417 });
418 return (
419 <View collapsable={false} className="flex-1 bg-sheet">
420 <SheetHeader
421 title={gt("Changed files")}
422 subtitle={`#${params.number} · ${params.commit?.slice(0, 7) ?? params.repository}`}
423 onClose={() => navigation.goBack()}
424 menus={[
425 {
426 title: gt("Filter review files"),
427 icon: "line.3.horizontal.decrease",
428 items: [
429 {
430 id: "hide-tests",
431 title: gt("Hide test files"),
432 icon: "line.3.horizontal.decrease",
433 selected: filter.hideTestFiles,
434 onPress: filter.toggle,
435 },
436 ],
437 },
438 ]}
439 />
440 <ScreenContent>
441 <AnimatedLegendList
442 renderScrollComponent={NativeScrollView}
443 className="flex-1"
444 data={parsed.kind === "files" ? groupByDirectory(parsed.files, collapsed) : []}
445 keyExtractor={(item) => item.key}
446 getItemType={(item) => item.kind}
447 itemLayoutAnimation={PR_ROW_LAYOUT}
448 onLoad={() => setAnimationsReady(true)}
449 renderItem={({ item }) => (
450 <Animated.View
451 entering={animationsReady ? PR_ROW_ENTER : undefined}
452 exiting={animationsReady ? PR_ROW_EXIT : undefined}
453 >
454 {item.kind === "directory" ? (
455 <DirectoryRow
456 directory={item.directory}
457 collapsed={item.collapsed}
458 onPress={() => toggleDirectory(item.directory)}
459 />
460 ) : (
461 <FileRow
462 file={item.file}
463 viewed={viewed.isViewed(item.file.path)}
464 onPress={() => {
465 requestPullRequestFileJump(navigation.getState()?.routes ?? [], item.file.path);
466 navigation.dispatch(
467 StackActions.popTo("PullRequestFile", {
468 ...params,
469 path: item.file.path,
470 focus: undefined,
471 }),
472 );
473 }}
474 />
475 )}
476 </Animated.View>
477 )}
478 contentInsetAdjustmentBehavior="automatic"
479 recycleItems={false}
480 estimatedItemSize={64}
481 ListHeaderComponent={
482 <>
483 <PullRequestReadStatus
484 pending={false}
485 error={diff.error}
486 terminology={files.terminology}
487 />
488 {parsed.kind === "files" ? (
489 <View className="flex-row items-center gap-2 py-2">
490 <Text textRole="caption" className="min-w-0 flex-1 text-foreground-muted">
491 {describeFiles(parsed, files, m)}
492 </Text>
493 <PullRequestDiffStats
494 additions={parsed.additions}
495 deletions={parsed.deletions}
496 compact
497 />
498 </View>
499 ) : null}
500 <NoVisibleFiles files={files} />
501 </>
502 }
503 ListEmptyComponent={
504 loading ? (
505 <View
506 accessible
507 accessibilityLabel={gt("Loading changed files")}
508 accessibilityState={{ busy: true }}
509 >
510 {Array.from({ length: loadingRowCount(files) }, (_, index) => (
511 <FileRowSkeleton key={index} index={index} />
512 ))}
513 </View>
514 ) : null
515 }
516 ListFooterComponent={<FilesFooter files={files} />}
517 contentContainerStyle={{ paddingHorizontal: 16, paddingBottom: 20 }}
518 />
519 </ScreenContent>
520 </View>
521 );
522 }