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