Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PullRequestFiles.tsx

512 lines18.0 KB

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