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

PullRequestFiles.tsx

520 lines18.6 KB

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