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

PullRequestFiles.tsx

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