Open History to see the last commit
1import type { PullRequestChangeBreakdown } from "@t3tools/contracts";
2import { PullRequestSectionHeading } from "./PullRequestSectionHeading";
3import { AnimatedLegendList } from "@legendapp/list/reanimated";
4import Animated from "react-native-reanimated";
5import { PR_ROW_LAYOUT, PR_ROW_ENTER, PR_ROW_EXIT } from "./pullRequestAnimations";
6import { useNavigation } from "@react-navigation/native";
7import { useState } from "react";
8import { Pressable, View } from "react-native";
9import { AppText as Text } from "../../components/ui/AppText";
10import { EmptyState } from "../../components/ui/EmptyState";
11import { Menu } from "../../components/ui/Menu";
12import { Button } from "../../components/ui/Button";
13import { IconButton } from "../../components/ui/IconButton";
14import { SymbolView } from "../../components/ui/AppSymbol";
15import { PierreEntryIcon } from "../../components/PierreEntryIcon";
16import { composerPullRequests } from "../../state/pull-requests";
17import { useEnvironmentQuery } from "../../state/query";
18import { PullRequestDiffStats, PullRequestReadStatus } from "./PullRequestPresentation";
19import {
20 pullRequestTarget as requestTarget,
21 usePullRequestDiff,
22 type PullRequestDiffParams,
23} from "./usePullRequestDiff";
24import { usePullRequestFilesViewed } from "./usePullRequestFilesViewed";
25import { usePullRequestFileFilter } from "./usePullRequestFileFilter";
26
27const BREAKDOWN_LABELS = {
28 code: "Code",
29 tests: "Tests",
30 mocks: "Mocks",
31 generated: "Generated",
32 docs: "Docs",
33} satisfies Record<keyof NonNullable<PullRequestChangeBreakdown>, string>;
34
35function PullRequestChangeBreakdownLine(props: {
36 readonly breakdown: NonNullable<PullRequestChangeBreakdown>;
37}) {
38 const parts = (Object.keys(BREAKDOWN_LABELS) as Array<keyof typeof BREAKDOWN_LABELS>).flatMap(
39 (kind) => {
40 const { additions, deletions } = props.breakdown[kind];
41 return additions === 0 && deletions === 0
42 ? []
43 : [
44 `${BREAKDOWN_LABELS[kind]} +${additions.toLocaleString()} −${deletions.toLocaleString()}`,
45 ];
46 },
47 );
48 return (
49 <Text className="text-2xs tabular-nums text-foreground-muted" numberOfLines={2}>
50 {parts.join(" · ")}
51 </Text>
52 );
53}
54
55function fileDirectory(path: string) {
56 const separator = path.lastIndexOf("/");
57 return separator < 0 ? "" : path.slice(0, separator);
58}
59
60export function usePullRequestFilesContent(props: {
61 readonly params: PullRequestDiffParams;
62 readonly onSelectFile?: (path: string) => void;
63 readonly groupByDirectory?: boolean;
64}) {
65 const navigation = useNavigation();
66 const result = usePullRequestDiff(props.params);
67 const detail = useEnvironmentQuery(composerPullRequests.detail(requestTarget(props.params)));
68 const viewed = usePullRequestFilesViewed(props.params, props.params.commit ? null : detail.data);
69 const breakdown = useEnvironmentQuery(
70 props.params.commit ? null : composerPullRequests.changeBreakdown(requestTarget(props.params)),
71 ).data;
72 const filter = usePullRequestFileFilter(result.parsed);
73 const parsed = filter.parsed;
74 const loading = result.isPending && parsed.kind === "empty" && !result.error;
75 const fileCount = props.params.commit ? undefined : detail.data?.changedFiles;
76 const summary = props.params.commit ? undefined : (detail.data ?? props.params.initialSummary);
77 const [collapsedDirectories, setCollapsedDirectories] = useState<ReadonlySet<string>>(
78 () => new Set(),
79 );
80 const files = parsed.kind === "files" ? parsed.files : [];
81 const orderedFiles = props.groupByDirectory
82 ? [...files].sort(
83 (a, b) =>
84 fileDirectory(a.path).localeCompare(fileDirectory(b.path)) ||
85 a.path.localeCompare(b.path),
86 )
87 : files;
88 const rows = orderedFiles.map((file, index) => {
89 const directory = fileDirectory(file.path);
90 const previousDirectory = fileDirectory(orderedFiles[index - 1]?.path ?? "");
91 const showDirectory =
92 props.groupByDirectory && (index === 0 || directory !== previousDirectory);
93 const collapsed = props.groupByDirectory && collapsedDirectories.has(directory);
94 if (collapsed && !showDirectory) return null;
95 return {
96 key: file.id,
97 content: (
98 <View>
99 {showDirectory ? (
100 <Pressable
101 accessibilityRole="button"
102 accessibilityLabel={directory || "Repository root"}
103 accessibilityState={{ expanded: !collapsed }}
104 onPress={() =>
105 setCollapsedDirectories((current) => {
106 const next = new Set(current);
107 if (next.has(directory)) next.delete(directory);
108 else next.add(directory);
109 return next;
110 })
111 }
112 className="min-h-11 flex-row items-center gap-2 pt-4 pb-2 active:opacity-70"
113 >
114 <SymbolView
115 name={collapsed ? "chevron.right" : "chevron.down"}
116 size={11}
117 tintColorClassName="accent-icon-muted"
118 />
119 <SymbolView name="folder" size={16} tintColorClassName="accent-icon-muted" />
120 <Text className="min-w-0 flex-1 text-xs text-foreground-muted" numberOfLines={2}>
121 {directory || "Repository root"}
122 </Text>
123 </Pressable>
124 ) : null}
125 {!collapsed ? (
126 <Pressable
127 accessibilityRole="button"
128 accessibilityLabel={`View diff for ${file.path}, ${file.additions} additions, ${file.deletions} deletions`}
129 onPress={() => {
130 if (props.onSelectFile) props.onSelectFile(file.path);
131 else
132 navigation.navigate("PullRequestFile", {
133 ...props.params,
134 path: file.path,
135 });
136 }}
137 className="min-h-14 flex-row items-center gap-3 border-b border-border-subtle py-3 active:opacity-70"
138 >
139 <PierreEntryIcon kind="file" path={file.path} size={20} />
140 <View className="min-w-0 flex-1">
141 <Text className="text-sm font-t3-medium text-foreground" numberOfLines={2}>
142 {file.path.split("/").at(-1)}
143 </Text>
144 {directory && !props.groupByDirectory ? (
145 <Text className="mt-0.5 text-2xs text-foreground-muted" numberOfLines={1}>
146 {directory}
147 </Text>
148 ) : null}
149 {file.previousPath ? (
150 <Text className="mt-0.5 text-2xs text-foreground-muted" numberOfLines={1}>
151 Renamed from {file.previousPath}
152 </Text>
153 ) : null}
154 </View>
155 <PullRequestDiffStats additions={file.additions} deletions={file.deletions} compact />
156 {viewed.isViewed(file.path) ? (
157 <SymbolView
158 name="checkmark.circle.fill"
159 size={18}
160 tintColorClassName="accent-adaptive-emerald-600-400"
161 />
162 ) : null}
163 <SymbolView name="chevron.right" size={12} tintColorClassName="accent-icon-muted" />
164 </Pressable>
165 ) : null}
166 </View>
167 ),
168 };
169 });
170 return {
171 refresh: result.refresh,
172 rows: loading
173 ? Array.from({ length: Math.min(fileCount ?? 4, 6) }, (_, index) => ({
174 key: `loading-file:${index}`,
175 content: (
176 <View
177 accessible={false}
178 importantForAccessibility="no-hide-descendants"
179 className="min-h-14 flex-row items-center gap-3 border-b border-border-subtle py-3"
180 >
181 <View className="size-5 rounded-md bg-subtle-strong" />
182 <View className="flex-1 gap-2">
183 <View
184 className="h-3.5 rounded bg-subtle-strong"
185 style={{ width: index % 2 ? "65%" : "80%" }}
186 />
187 <View className="h-2.5 w-2/5 rounded bg-subtle-strong" />
188 </View>
189 <View className="h-3 w-7 rounded bg-subtle-strong" />
190 </View>
191 ),
192 }))
193 : rows.filter((row) => row !== null),
194 header: (
195 <>
196 <PullRequestReadStatus pending={false} error={result.error} />
197 {loading ? (
198 <View
199 accessibilityLabel="Loading changed files"
200 accessibilityState={{ busy: true }}
201 className="min-h-17 flex-row items-center gap-2 py-3"
202 >
203 <View className="min-w-0 flex-1 gap-1">
204 <PullRequestSectionHeading>Changed files</PullRequestSectionHeading>
205 {fileCount !== undefined ? (
206 <Text className="text-2xs text-foreground-muted">
207 {fileCount} {fileCount === 1 ? "file" : "files"}
208 </Text>
209 ) : (
210 <View className="h-2.5 w-28 rounded bg-subtle-strong" />
211 )}
212 </View>
213 {summary?.additions !== undefined && summary.deletions !== undefined ? (
214 <PullRequestDiffStats
215 additions={summary.additions}
216 deletions={summary.deletions}
217 compact
218 />
219 ) : null}
220 <View className="size-11 items-center justify-center opacity-40">
221 <SymbolView
222 name="line.3.horizontal.decrease"
223 size={20}
224 tintColorClassName="accent-icon-muted"
225 />
226 </View>
227 </View>
228 ) : parsed.kind === "files" ? (
229 <>
230 <View className="min-h-17 flex-row items-center gap-2 py-3">
231 <View className="min-w-0 flex-1 gap-1">
232 <PullRequestSectionHeading>Changed files</PullRequestSectionHeading>
233 <Text className="text-2xs text-foreground-muted">
234 {parsed.fileCount} {filter.hiddenCount ? "visible" : "changed"}{" "}
235 {parsed.fileCount === 1 ? "file" : "files"}
236 {viewed.supported
237 ? ` · ${parsed.files.filter((file) => viewed.isViewed(file.path)).length} viewed`
238 : ""}
239 {" · "}
240 {filter.hideTestFiles
241 ? `${filter.hiddenCount} test ${filter.hiddenCount === 1 ? "file" : "files"} hidden`
242 : "Test files included"}
243 </Text>
244 {breakdown ? <PullRequestChangeBreakdownLine breakdown={breakdown} /> : null}
245 </View>
246 <PullRequestDiffStats
247 additions={parsed.additions}
248 deletions={parsed.deletions}
249 compact
250 />
251 <Menu
252 title="Review files"
253 actions={[
254 {
255 id: "hide-tests",
256 title: "Hide test files",
257 image: "line.3.horizontal.decrease",
258 state: filter.hideTestFiles ? "on" : "off",
259 },
260 ]}
261 onPressAction={filter.toggle}
262 >
263 <View pointerEvents="none">
264 <IconButton
265 icon="line.3.horizontal.decrease"
266 accessibilityLabel="Filter review files"
267 selected={filter.hideTestFiles}
268 />
269 </View>
270 </Menu>
271 </View>
272 {parsed.files.length === 0 && filter.hiddenCount > 0 ? (
273 <EmptyState
274 title={
275 result.nextCursor ? "No non-test files loaded yet" : "Only test files changed"
276 }
277 detail="Test files are hidden from this review."
278 action={<Button label="Show test files" tone="contrast" onPress={filter.showAll} />}
279 variant="plain"
280 />
281 ) : null}
282 </>
283 ) : !result.isPending && !result.error ? (
284 <Text className="py-6 text-sm text-foreground-muted">No text changes available.</Text>
285 ) : null}
286 </>
287 ),
288 footer: (
289 <>
290 {result.nextCursor ? (
291 <Button
292 label={result.error ? "Retry loading files" : "Load more files"}
293 tone="secondary"
294 onPress={result.error ? result.refresh : result.loadMore}
295 loading={result.isPending}
296 fullWidth
297 />
298 ) : null}
299 {viewed.error ? (
300 <Text className="py-2 text-xs text-danger-foreground">{viewed.error}</Text>
301 ) : null}
302 {parsed.kind === "files" && parsed.notice ? (
303 <Text className="py-4 text-xs text-foreground-muted">{parsed.notice}</Text>
304 ) : null}
305 </>
306 ),
307 };
308}
309
310export function PullRequestFiles(props: Parameters<typeof usePullRequestFilesContent>[0]) {
311 const content = usePullRequestFilesContent(props);
312 const [animationsReady, setAnimationsReady] = useState(false);
313 return (
314 <AnimatedLegendList
315 data={content.rows}
316 keyExtractor={(row) => row.key}
317 itemLayoutAnimation={PR_ROW_LAYOUT}
318 onLoad={() => setAnimationsReady(true)}
319 renderItem={({ item }) => (
320 <Animated.View
321 key={item.key}
322 entering={animationsReady ? PR_ROW_ENTER : undefined}
323 exiting={animationsReady ? PR_ROW_EXIT : undefined}
324 >
325 {item.content}
326 </Animated.View>
327 )}
328 recycleItems={false}
329 estimatedItemSize={64}
330 ListHeaderComponent={content.header}
331 ListFooterComponent={content.footer}
332 contentContainerStyle={{ paddingHorizontal: 16, paddingBottom: 20 }}
333 />
334 );
335}