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