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