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