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

PullRequestRouteScreen.tsx

1,316 lines55.0 KB

1import { Toolbar } from "../../components/ui/Toolbar";
2import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
3import { Chip } from "../../components/ui/Chip";
4import { pullRequestTabOffset } from "./pullRequestTabScroll";
5import { guideFocusedRows, type GuideDiffFocus } from "./guide/guideDiffFocus";
6import { PullRequestGuideContent } from "./guide/PullRequestGuideScreen";
7import { useReviewGuidesEnabled } from "./guide/useReviewGuide";
8import {
9 filterPullRequestActivity,
10 DEFAULT_ACTIVITY_FILTER,
11 type ActivityFilter,
12} from "./pullRequestActivityFilter";
13import { PullRequestActivityFilters } from "./PullRequestActivityFilters";
14import type { LegendListRef } from "@legendapp/list/react-native";
15import { AnimatedLegendList } from "@legendapp/list/reanimated";
16import Animated from "react-native-reanimated";
17import {
18 PR_ROW_LAYOUT,
19 PR_ROW_ENTER,
20 PR_ROW_EXIT,
21 PR_POSITION_LAYOUT,
22} from "./pullRequestAnimations";
23import {
24 canPerformPullRequestAction,
25 openOnProviderLabel,
26 PR_ACTION_ICONS,
27 pullRequestActionLabel,
28} from "./pullRequestActions";
29import * as Clipboard from "expo-clipboard";
30import { Menu } from "../../components/ui/Menu";
31import { IconButton } from "../../components/ui/IconButton";
32import { Button } from "../../components/ui/Button";
33import { usePullRequestReviewDraft } from "./usePullRequestReviewDraft";
34import { usePullRequestFilesViewed } from "./usePullRequestFilesViewed";
35import { usePullRequestPermissions } from "./usePullRequestPermissions";
36import { usePullRequestAction } from "./usePullRequestAction";
37import { annotatePullRequestDiff, reviewPosition } from "./pullRequestDiffComments";
38import { usePullRequestFileFilter } from "./usePullRequestFileFilter";
39import {
40 handlePullRequestDiffDebugEvent,
41 pullRequestDiffInitialPosition,
42} from "./pullRequestDiffDebug";
43import { usePullRequestDiffHighlightFiles } from "./usePullRequestDiffHighlightFiles";
44import { isPullRequestTestFile } from "./pullRequestFileFilters";
45import { useFocusEffect, useNavigation, type StaticScreenProps } from "@react-navigation/native";
46import { RegistryContext, useAtomRefresh, useAtomValue } from "@effect/atom-react";
47import { pullRequestReviewKey } from "./pullRequestReviewDrafts";
48import { type PullRequestDetail, type PullRequestListEntry } from "@t3tools/contracts";
49import { PullRequestOverviewLoading } from "./PullRequestOverviewLoading";
50import { copyPullRequestLink, sharePullRequestLink } from "./pullRequestLink";
51import { pullRequestStatus } from "./pullRequestStatus";
52import { use, useEffect, useMemo, useRef, useState } from "react";
53import {
54 Linking,
55 Platform,
56 Pressable,
57 RefreshControl,
58 ScrollView,
59 type ScrollViewProps,
60 StyleSheet,
61 View,
62} from "react-native";
63import { NativeScrollViewMarker as ScrollViewMarker } from "../../native/NativeScrollViewMarker";
64import { useSafeAreaInsets } from "react-native-safe-area-context";
65​
66import { AppText as Text } from "../../components/ui/AppText";
67import { AndroidScreenHeader } from "../../components/ui/AndroidScreenHeader";
68import { useAndroidControlSizing } from "../../components/ui/useAndroidControlSizing";
69import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
70import { AndroidWorkspaceSidebarButton } from "../layout/workspace-sidebar-toolbar";
71import { useWorkspaceSidebarHeaderItem } from "../layout/useWorkspaceSidebarHeaderItem";
72import { useAndroidWorkspaceBack } from "../workspace/useAndroidWorkspaceNavigation";
73import { EmptyState } from "../../components/ui/EmptyState";
74import { SegmentedControl } from "../../components/ui/SegmentedControl";
75import { SymbolView } from "../../components/ui/AppSymbol";
76import { relativeTime } from "../../lib/time";
77import { NativeStackScreenOptions } from "../../native/StackHeader";
78import { usePullRequestConnected } from "./usePullRequestConnected";
79import { usePullRequestLiveChecks } from "./usePullRequestLiveChecks";
80import { pullRequestLabelColor } from "./pullRequestList";
81import { PullRequestReactions } from "./PullRequestReactions";
82import { composerPullRequests } from "../../state/pull-requests";
83import { useEnvironmentQuery } from "../../state/query";
84import { usePullToRefresh } from "../../state/use-pull-to-refresh";
85import {
86 resolveNativeReviewDiffView,
87 type NativeReviewDiffViewHandle,
88 type NativeReviewDiffViewProps,
89} from "../diffs/nativeReviewDiffSurface";
90import {
91 buildNativeReviewDiffData,
92 NATIVE_REVIEW_DIFF_CONTENT_WIDTH,
93} from "../review/nativeReviewDiffAdapter";
94import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
95import { useAppearanceCodeSurface } from "../settings/appearance/useAppearanceCodeSurface";
96import { useNativeReviewDiffBridge } from "../review/useNativeReviewDiffBridge";
97import { pullRequestTimelineRows } from "./PullRequestTimeline";
98import { PullRequestActionToolbar, PullRequestCardGroup } from "./PullRequestControls";
99import {
100 pullRequestTarget as requestTarget,
101 usePullRequestDiff,
102 type PullRequestDiffParams,
103 type PullRequestParams,
104} from "./usePullRequestDiff";
105import {
106 PullRequestAvatar,
107 PullRequestDiffStats,
108 PullRequestReadStatus,
109} from "./PullRequestPresentation";
110import { usePullRequestFilesSection } from "./PullRequestFiles";
111import { PullRequestDescription } from "./PullRequestDescription";
112import { PullRequestMarkdownRepository } from "./PullRequestMarkdown";
113import {
114 PullRequestStatusMenu,
115 PullRequestChecksRow,
116 PullRequestBranchRow,
117 PullRequestReviewersRow,
118} from "./PullRequestStatusRows";
119import { PullRequestMergeControls } from "./PullRequestMergeControls";
120import { PullRequestStackCard } from "./PullRequestStackCard";
121import { usePullRequestStack, type PullRequestStackState } from "./usePullRequestStack";
122import { usePullRequestEnvironmentFallback } from "./usePullRequestEnvironmentFallback";
123import {
124 capitalizeTerm,
125 sourceControlClients,
126} from "@t3tools/client-runtime/source-control-clients";
127​
128const EMPTY_IDS: readonly string[] = [];
129​
130function PullRequestTabScrollView(props: ScrollViewProps) {
131 return (
132 <ScrollViewMarker style={{ flex: 1 }}>
133 <ScrollView {...props} />
134 </ScrollViewMarker>
135 );
137​
138function usePullRequestActivityRows(params: PullRequestParams, filter: ActivityFilter) {
139 const navigation = useNavigation();
140 const result = useEnvironmentQuery(composerPullRequests.activity(requestTarget(params)));
141 const detail = useEnvironmentQuery(composerPullRequests.detail(requestTarget(params)));
142 const permissions = usePullRequestPermissions(params, detail.data);
143 const filtered = result.data ? filterPullRequestActivity(result.data, filter) : null;
144 const rows = (() => {
145 if (!filtered) return [];
146 const rows = pullRequestTimelineRows(filtered.activity, params, navigation, {
147 permissions,
148 onChanged: result.refresh,
149 });
150 if (filter.newestFirst) {
151 const notice = rows.at(-1)?.key === "truncated" ? rows.pop() : undefined;
152 rows.reverse();
153 if (notice) rows.push(notice);
154 }
155 if (!rows.length)
156 rows.push({
157 key: "empty",
158 date: "",
159 content: (
160 <Text className="py-6 text-sm text-foreground-muted">
161 No activity matches these filters.
162 </Text>
163 ),
164 });
165 return rows;
166 })();
167 return {
168 rows,
169 hiddenCount: filtered?.hiddenCount ?? 0,
170 pending: result.isPending && !result.data,
171 error: result.error,
172 };
174​
175function PullRequestIdentity(props: {
176 readonly pr: PullRequestDetail | PullRequestListEntry;
177 readonly params: PullRequestParams;
178}) {
179 const { pr } = props;
180 const status = pullRequestStatus(pr);
181 return (
182 <View className="gap-3">
183 <View className="flex-row flex-wrap items-center gap-2">
184 {"capabilities" in pr ? (
185 <PullRequestStatusMenu pr={pr} params={props.params} />
186 ) : (
187 <View className="min-h-8 flex-row items-center gap-1.5">
188 <SymbolView name={status.icon} size={14} tintColorClassName={status.tint} />
189 <Text className={`text-xs font-t3-medium ${status.text}`}>{status.label}</Text>
190 </View>
191 )}
192 <PullRequestDiffStats additions={pr.additions} deletions={pr.deletions} compact />
193 {"changedFiles" in pr ? (
194 <Text className="text-2xs text-foreground-muted">
195 {pr.changedFiles} {pr.changedFiles === 1 ? "file" : "files"}
196 </Text>
197 ) : (
198 <View className="h-3 w-12 rounded bg-subtle-strong" />
199 )}
200 </View>
201 <Text selectable className="text-xl font-t3-bold leading-7">
202 {pr.title}
203 </Text>
204 <View className="flex-row items-center gap-2">
205 <PullRequestAvatar actor={pr.author} size={20} />
206 <Text className="min-w-0 flex-1 text-xs font-t3-medium" numberOfLines={1}>
207 {pr.author?.login ?? "Unknown author"}
208 </Text>
209 <Text className="shrink text-right text-2xs text-foreground-muted" numberOfLines={1}>
210 Updated {relativeTime(pr.updatedAt)} ago
211 </Text>
212 </View>
213 <View className="flex-row items-start gap-1.5">
214 <Pressable
215 accessibilityRole="button"
216 accessibilityLabel={`Copy base branch ${pr.baseBranch}`}
217 onPress={() => void Clipboard.setStringAsync(pr.baseBranch)}
218 className="min-w-0 shrink active:opacity-70"
219 hitSlop={8}
220 >
221 <Text className="font-mono text-2xs text-foreground-muted">{pr.baseBranch}</Text>
222 </Pressable>
223 <View className="pt-0.5">
224 <SymbolView name="arrow.left" size={11} tintColorClassName="accent-icon-muted" />
225 </View>
226 <Pressable
227 accessibilityRole="button"
228 accessibilityLabel={`Copy head branch ${pr.headBranch}`}
229 onPress={() => void Clipboard.setStringAsync(pr.headBranch)}
230 className="min-w-0 shrink active:opacity-70"
231 hitSlop={8}
232 >
233 <Text className="font-mono text-2xs text-foreground-muted">{pr.headBranch}</Text>
234 </Pressable>
235 </View>
236 </View>
237 );
239​
240function PullRequestLabels(props: {
241 readonly pr: PullRequestDetail;
242 readonly params: PullRequestParams;
243}) {
244 const navigation = useNavigation();
245 const connected = usePullRequestConnected(props.params.environmentId);
246 const canWrite = useAtomValue(
247 composerPullRequests.setLabels.permissionAtom(requestTarget(props.params).environmentId),
248 );
249 const editable =
250 connected &&
251 canWrite &&
252 props.pr.capabilities.labels === true &&
253 props.pr.viewerPermissions.labels !== false;
254 if (!props.pr.labels.length && !editable) return null;
255 return (
256 <Animated.View layout={PR_ROW_LAYOUT} className="flex-row flex-wrap gap-2">
257 {props.pr.labels.map((label) => {
258 const color = pullRequestLabelColor(label.color);
259 // Tinted like the list row's label pills, at the overview's chip size.
260 return (
261 <View
262 key={label.name}
263 className="max-w-full flex-row items-center gap-1.5 rounded-2xl bg-grouped-card px-3 py-1"
264 style={color ? { backgroundColor: `${color}20` } : undefined}
265 >
266 {color ? (
267 <View style={{ width: 6, height: 6, borderRadius: 3, backgroundColor: color }} />
268 ) : null}
269 <Text textRole="caption" className="shrink text-foreground-muted" numberOfLines={1}>
270 {label.name}
271 </Text>
272 </View>
273 );
274 })}
275 {editable ? (
276 <Chip
277 label={props.pr.labels.length ? "Edit" : "Add labels"}
278 icon="tag"
279 size="small"
280 accessibilityLabel="Edit labels"
281 onPress={() => navigation.navigate("PullRequestLabels", props.params)}
282 />
283 ) : null}
284 </Animated.View>
285 );
287​
288function PullRequestOverview(props: {
289 readonly pr: PullRequestDetail;
290 readonly params: PullRequestParams;
291 readonly stack: PullRequestStackState;
292 readonly onDescriptionLayout: (y: number) => void;
293 readonly onDescriptionCollapse: () => void;
294 readonly descriptionExpanded: boolean;
295 readonly onDescriptionExpandedChange: (expanded: boolean) => void;
296}) {
297 const { pr } = props;
298 return (
299 <View className="gap-5">
300 <PullRequestStackCard params={props.params} state={props.stack} />
301 <PullRequestCardGroup>
302 <PullRequestChecksRow pr={pr} params={props.params} />
303 <PullRequestReviewersRow pr={pr} params={props.params} />
304 <Animated.View layout={PR_ROW_LAYOUT}>
305 <PullRequestBranchRow pr={pr} params={props.params} />
306 </Animated.View>
307 <Animated.View layout={PR_ROW_LAYOUT}>
308 <PullRequestMergeControls pr={pr} params={props.params} stack={props.stack} />
309 </Animated.View>
310 </PullRequestCardGroup>
311 <PullRequestLabels pr={pr} params={props.params} />
312 <Animated.View
313 layout={PR_POSITION_LAYOUT}
314 onLayout={(event) => props.onDescriptionLayout(event.nativeEvent.layout.y)}
315 >
316 <PullRequestDescription
317 markdown={pr.body}
318 onCollapse={props.onDescriptionCollapse}
319 expanded={props.descriptionExpanded}
320 onExpandedChange={props.onDescriptionExpandedChange}
321 footer={<PullRequestReactions params={props.params} />}
322 />
323 </Animated.View>
324 </View>
325 );
327​
328function usePullRequestToolbarHeight(bottomInset: number) {
329 const { buttonSize } = useAndroidControlSizing();
330 return useState(() => (Platform.OS === "android" ? bottomInset + buttonSize + 40 : 0));
332​
333export function PullRequestRouteScreen({ route }: StaticScreenProps<PullRequestParams>) {
334 const returnToList = useAndroidWorkspaceBack("pullRequests");
335 const { layout } = useAdaptiveWorkspaceLayout();
336 const sidebarHeaderItem = useWorkspaceSidebarHeaderItem();
337 const navigation = useNavigation();
338 const insets = useSafeAreaInsets();
339 const [toolbarHeight, setToolbarHeight] = usePullRequestToolbarHeight(insets.bottom);
340 const params = route.params;
341 usePullRequestEnvironmentFallback(params);
342 const connected = usePullRequestConnected(params.environmentId);
343 const [section, setSection] = useState<"overview" | "activity" | "guide">("overview");
344 const requestedSection = useRef(section);
345 const [listAnimationsReady, setListAnimationsReady] = useState(false);
346 const [descriptionExpanded, setDescriptionExpanded] = useState(false);
347 const filesContent = usePullRequestFilesSection(params);
348 const guidesEnabled = useReviewGuidesEnabled(params);
349 const [activityFilter, setActivityFilter] = useState<ActivityFilter>(DEFAULT_ACTIVITY_FILTER);
350 const activityContent = usePullRequestActivityRows(params, activityFilter);
351 const scrollOffsets = useRef<Record<string, number>>({});
352 const currentScrollOffset = useRef(-insets.top);
353 const bodyY = useRef(0);
354 const [headerHeight, setHeaderHeight] = useState(0);
355 const [viewportHeight, setViewportHeight] = useState(0);
356 const scrollViews = useRef<Partial<Record<typeof section, LegendListRef | null>>>({});
357 // AnimatedLegendList re-attaches its handle and sets state whenever its ref changes,
358 // so an inline ref in the tab map loops the screen into "Maximum update depth exceeded".
359 const [listRefs] = useState(() => {
360 const listRef = (tab: typeof section) => (list: LegendListRef | null) => {
361 scrollViews.current[tab] = list;
362 };
363 return {
364 overview: listRef("overview"),
365 guide: listRef("guide"),
366 activity: listRef("activity"),
367 };
368 });
369 const selectSection = (next: typeof section) => {
370 if (next === section) return;
371 scrollOffsets.current[section] = currentScrollOffset.current;
372 const headerEnd = Math.max(-insets.top, bodyY.current - insets.top);
373 const offset = pullRequestTabOffset(
374 currentScrollOffset.current,
375 scrollOffsets.current[next],
376 headerEnd,
377 );
378 requestedSection.current = next;
379 scrollOffsets.current[next] = offset;
380 currentScrollOffset.current = offset;
381 scrollViews.current[next]?.scrollToOffset({ offset, animated: false });
382 setSection(next);
383 };
384 useEffect(() => {
385 if (!guidesEnabled && section === "guide") {
386 requestedSection.current = "overview";
387 currentScrollOffset.current = scrollOffsets.current.overview ?? -insets.top;
388 setSection("overview");
389 }
390 }, [guidesEnabled, section, insets.top]);
391 const tabContent = activityContent;
392 const filesY = useRef(0);
393 const descriptionY = useRef(0);
394 const pendingDescriptionJump = useRef(false);
395 const pendingFilesJump = useRef(false);
396 const detailAtom = composerPullRequests.detail(requestTarget(params));
397 const result = useEnvironmentQuery(detailAtom);
398 const pullRefresh = usePullToRefresh(detailAtom);
399 const { refresh: refreshDetail } = result;
400 useFocusEffect(() => refreshDetail());
401 const pr = usePullRequestLiveChecks(params, result.data);
402 const summary = params.initialSummary;
403 const identity = pr ?? summary;
404 const terminology = sourceControlClients.get(identity?.provider).changeRequest;
405 const permissions = usePullRequestPermissions(params, pr);
406 const action = usePullRequestAction(params, pr);
407 const showsDeleteBranch = pr !== null && canPerformPullRequestAction(pr, "delete-branch");
408 const confirmDeleteBranch = () =>
409 pr &&
410 action.confirm(
411 "delete-branch",
412 pullRequestActionLabel("delete-branch", terminology),
413 `Delete ${pr.headBranch} from ${pr.headRepositoryNameWithOwner ?? pr.repository}? Local branches and worktrees are not changed.`,
414 );
415 const stack = usePullRequestStack(params, pr);
416 const refreshActivity = useAtomRefresh(composerPullRequests.activity(requestTarget(params)));
417 const refreshGuide = useAtomRefresh(composerPullRequests.reviewGuide(requestTarget(params)));
418 const registry = use(RegistryContext);
419 const refresh = () =>
420 pullRefresh.onRefresh(async (signal) => {
421 const target = requestTarget(params);
422 await composerPullRequests.invalidate
423 .run(registry, {
424 environmentId: target.environmentId,
425 input: { reference: target.input },
426 })
427 .catch(() => undefined);
428 if (signal.aborted) return;
429 if (guidesEnabled) refreshGuide();
430 stack.refresh();
431 refreshActivity();
432 filesContent.refresh();
433 });
434 const jumpToFiles = () => {
435 scrollViews.current.overview?.scrollToOffset({
436 offset: bodyY.current + filesY.current - insets.top,
437 animated: true,
438 });
439 pendingFilesJump.current = false;
440 };
441 const openFiles = () => {
442 if (section === "overview") jumpToFiles();
443 else {
444 pendingFilesJump.current = true;
445 selectSection("overview");
446 if (filesY.current > 0) requestAnimationFrame(jumpToFiles);
447 }
448 };
449 return (
450 <PullRequestMarkdownRepository params={params} changeRequest={pr}>
451 <View className={Platform.OS === "android" ? "flex-1 bg-header" : "flex-1 bg-screen"}>
452 <NativeStackScreenOptions
453 options={{
454 title: `#${params.number}`,
455 headerTitle: `#${params.number}`,
456 unstable_headerSubtitle: connected
457 ? params.repository
458 : `${params.repository} · Offline`,
459 unstable_headerLeftItems: layout.usesSplitView ? () => [sidebarHeaderItem] : undefined,
460 }}
461 optionsVersion={[layout.usesSplitView, sidebarHeaderItem]}
462 />
463 {Platform.OS === "android" ? (
464 <AndroidScreenHeader
465 title={`#${params.number}${connected ? "" : " · Offline"}`}
466 subtitle={params.repository}
467 onBack={layout.usesSplitView ? undefined : returnToList}
468 leading={layout.usesSplitView ? <AndroidWorkspaceSidebarButton /> : undefined}
469 actions={[
470 ...(permissions.verdicts.length
471 ? [
472 {
473 accessibilityLabel: "Submit review",
474 icon: "text.bubble" as const,
475 onPress: () =>
476 navigation.navigate("PullRequestReview", { ...params, mode: "review" }),
477 },
478 ]
479 : []),
480 ...(permissions.canComment
481 ? [
482 {
483 accessibilityLabel: "Add comment",
484 icon: "plus.bubble" as const,
485 onPress: () =>
486 navigation.navigate("PullRequestReview", { ...params, mode: "comment" }),
487 },
488 ]
489 : []),
490 ...(permissions.canEditChangeRequest
491 ? [
492 {
493 accessibilityLabel: "Edit title",
494 icon: "pencil" as const,
495 overflowOnly: true,
496 onPress: () =>
497 navigation.navigate("PullRequestEdit", { ...params, field: "title" }),
498 },
499 {
500 accessibilityLabel: "Edit description",
501 icon: "doc.text" as const,
502 overflowOnly: true,
503 onPress: () =>
504 navigation.navigate("PullRequestEdit", { ...params, field: "body" }),
505 },
506 ]
507 : []),
508 ...(identity
509 ? [
510 {
511 accessibilityLabel: openOnProviderLabel(identity.provider),
512 icon: "arrow.up.right" as const,
513 onPress: () => void Linking.openURL(identity.url),
514 },
515 {
516 accessibilityLabel: "Copy link",
517 icon: "link" as const,
518 overflowOnly: true,
519 onPress: () => copyPullRequestLink(identity),
520 },
521 {
522 accessibilityLabel: "Share…",
523 icon: "square.and.arrow.up" as const,
524 overflowOnly: true,
525 onPress: () => sharePullRequestLink(identity),
526 },
527 ]
528 : []),
529 ...(showsDeleteBranch
530 ? [
531 {
532 accessibilityLabel: pullRequestActionLabel("delete-branch", terminology),
533 icon: PR_ACTION_ICONS["delete-branch"],
534 disabled: !action.available("delete-branch"),
535 destructive: true,
536 overflowOnly: true,
537 onPress: confirmDeleteBranch,
538 },
539 ]
540 : []),
541 ]}
542 />
543 ) : null}
544 <Toolbar placement="right">
545 <Toolbar.Menu
546 title={capitalizeTerm(terminology.singular)}
547 accessibilityLabel={`${capitalizeTerm(terminology.singular)} actions`}
548 icon="ellipsis"
549 >
550 {permissions.verdicts.length ? (
551 <Toolbar.MenuAction
552 icon="text.bubble"
553 onPress={() =>
554 navigation.navigate("PullRequestReview", { ...params, mode: "review" })
555 }
556 >
557 <Toolbar.Label>Submit review</Toolbar.Label>
558 </Toolbar.MenuAction>
559 ) : null}
560 {permissions.canComment ? (
561 <Toolbar.MenuAction
562 icon="plus.bubble"
563 onPress={() =>
564 navigation.navigate("PullRequestReview", { ...params, mode: "comment" })
565 }
566 >
567 <Toolbar.Label>Add comment</Toolbar.Label>
568 </Toolbar.MenuAction>
569 ) : null}
570 {permissions.canEditChangeRequest ? (
571 <Toolbar.MenuAction
572 icon="pencil"
573 onPress={() =>
574 navigation.navigate("PullRequestEdit", { ...params, field: "title" })
575 }
576 >
577 <Toolbar.Label>Edit title</Toolbar.Label>
578 </Toolbar.MenuAction>
579 ) : null}
580 {permissions.canEditChangeRequest ? (
581 <Toolbar.MenuAction
582 icon="doc.text"
583 onPress={() => navigation.navigate("PullRequestEdit", { ...params, field: "body" })}
584 >
585 <Toolbar.Label>Edit description</Toolbar.Label>
586 </Toolbar.MenuAction>
587 ) : null}
588 {identity ? (
589 <Toolbar.MenuAction
590 icon="arrow.up.right"
591 onPress={() => void Linking.openURL(identity.url)}
592 >
593 <Toolbar.Label>{openOnProviderLabel(identity.provider)}</Toolbar.Label>
594 </Toolbar.MenuAction>
595 ) : null}
596 {identity ? (
597 <Toolbar.MenuAction icon="link" onPress={() => copyPullRequestLink(identity)}>
598 <Toolbar.Label>Copy link</Toolbar.Label>
599 </Toolbar.MenuAction>
600 ) : null}
601 {identity ? (
602 <Toolbar.MenuAction
603 icon="square.and.arrow.up"
604 onPress={() => sharePullRequestLink(identity)}
605 >
606 <Toolbar.Label>Share…</Toolbar.Label>
607 </Toolbar.MenuAction>
608 ) : null}
609 {showsDeleteBranch ? (
610 <Toolbar.MenuAction
611 icon={PR_ACTION_ICONS["delete-branch"]}
612 destructive
613 disabled={!action.available("delete-branch")}
614 subtitle={
615 action.busy
616 ? "Deleting…"
617 : connected
618 ? pr.headBranch
619 : "Reconnect to delete this branch."
620 }
621 onPress={confirmDeleteBranch}
622 >
623 <Toolbar.Label>
624 {pullRequestActionLabel("delete-branch", terminology)}
625 </Toolbar.Label>
626 </Toolbar.MenuAction>
627 ) : null}
628 </Toolbar.Menu>
629 </Toolbar>
630 <View
631 style={{
632 flex: 1,
633 marginHorizontal: Platform.OS === "android" && layout.usesSplitView ? 4 : 0,
634 }}
635 className={
636 Platform.OS === "android"
637 ? "overflow-hidden rounded-t-[28px] bg-sheet-solid"
638 : undefined
639 }
640 onLayout={(event) => setViewportHeight(event.nativeEvent.layout.height)}
641 >
642 {(["overview", "guide", "activity"] as const)
643 .filter((tab) => tab !== "guide" || guidesEnabled)
644 .map((tab) => (
645 <View
646 key={tab}
647 style={[StyleSheet.absoluteFill, { opacity: section === tab ? 1 : 0 }]}
648 pointerEvents={section === tab ? "auto" : "none"}
649 accessibilityElementsHidden={section !== tab}
650 importantForAccessibility={section === tab ? "auto" : "no-hide-descendants"}
651 >
652 <AnimatedLegendList
653 ref={listRefs[tab]}
654 // The scroll view owns its resting offset. LegendList keeps the first
655 // initialScrollOffset it gets, and the first render has the window's top
656 // inset (0 on the folded iPhone Duo), not the header's.
657 onScroll={(event) => {
658 const offset = event.nativeEvent.contentOffset.y;
659 scrollOffsets.current[tab] = offset;
660 if (requestedSection.current === tab) currentScrollOffset.current = offset;
661 }}
662 className="flex-1"
663 renderScrollComponent={
664 Platform.OS === "ios" ? PullRequestTabScrollView : undefined
665 }
666 // UIKit owns the bar's inset, so a minimizing bar and a resized column
667 // move the list in the same frame as the bar.
668 contentInsetAdjustmentBehavior="automatic"
669 contentInsetStartAdjustment={Platform.OS === "ios" ? insets.top : 0}
670 refreshControl={
671 <RefreshControl
672 refreshing={section === tab && pullRefresh.refreshing}
673 onRefresh={refresh}
674 />
675 }
676 alwaysBounceVertical
677 scrollsToTop={section === tab}
678 onContentSizeChange={() => {
679 if (
680 tab !== "overview" ||
681 section !== "overview" ||
682 !pendingDescriptionJump.current
683 )
684 return;
685 pendingDescriptionJump.current = false;
686 // Collapse changes the scroll range; restore the heading after that layout commits.
687 scrollViews.current.overview?.scrollToOffset({
688 offset: bodyY.current + descriptionY.current - insets.top,
689 animated: false,
690 });
691 }}
692 contentContainerStyle={{
693 paddingHorizontal: 16,
694 paddingTop: 8,
695 paddingBottom: 24 + (Platform.OS === "android" ? toolbarHeight : 0),
696 // Short tabs must still be tall enough to preserve the collapsed header.
697 minHeight: Math.max(
698 0,
699 viewportHeight + headerHeight - insets.top - insets.bottom,
700 ),
701 }}
702 data={[
703 {
704 key: `${tab}:body`,
705 content: (
706 <View>
707 {tab === "overview" && identity ? (
708 <View>
709 {pr ? (
710 <PullRequestOverview
711 pr={pr}
712 params={params}
713 stack={stack}
714 descriptionExpanded={descriptionExpanded}
715 onDescriptionExpandedChange={setDescriptionExpanded}
716 onDescriptionLayout={(y) => {
717 descriptionY.current = y;
718 }}
719 onDescriptionCollapse={() => {
720 pendingDescriptionJump.current = true;
721 }}
722 />
723 ) : summary ? (
724 <PullRequestOverviewLoading
725 summary={summary}
726 params={params}
727 stack={stack}
728 />
729 ) : null}
730 <View
731 className="mt-8 border-t border-border-subtle pt-3"
732 onLayout={(event) => {
733 filesY.current = event.nativeEvent.layout.y;
734 if (pendingFilesJump.current) {
735 requestAnimationFrame(() => {
736 if (requestedSection.current === "overview") jumpToFiles();
737 });
738 }
739 }}
740 >
741 {filesContent.header}
742 </View>
743 </View>
744 ) : null}
745 {tab === "guide" ? <PullRequestGuideContent params={params} /> : null}
746 {tab === "activity" ? (
747 <PullRequestActivityFilters
748 value={activityFilter}
749 onChange={setActivityFilter}
750 hiddenCount={tabContent.hiddenCount}
751 />
752 ) : null}
753 {tab === "activity" ? (
754 <PullRequestReadStatus
755 pending={tabContent.pending}
756 error={tabContent.error}
757 terminology={terminology}
758 />
759 ) : null}
760 </View>
761 ),
762 },
763 ...(tab === "overview"
764 ? identity
765 ? filesContent.rows
766 : []
767 : tab === "activity"
768 ? tabContent.rows
769 : []
770 ).map((row) => ({
771 ...row,
772 key: `${tab}:${row.key}`,
773 content: row.content,
774 })),
775 ]}
776 keyExtractor={(row) => row.key}
777 getItemType={(row) =>
778 row.key.endsWith(":body") ? row.key : row.key.split(":")[0]
779 }
780 // Animating overview fights clipped markdown and collapse scroll correction; file rows can still fade.
781 itemLayoutAnimation={tab === "overview" ? undefined : PR_ROW_LAYOUT}
782 onLoad={() => setListAnimationsReady(true)}
783 renderItem={({ item }) => (
784 <Animated.View
785 key={item.key}
786 entering={
787 listAnimationsReady && !item.key.endsWith(":body")
788 ? PR_ROW_ENTER
789 : undefined
790 }
791 exiting={
792 listAnimationsReady && !item.key.endsWith(":body") ? PR_ROW_EXIT : undefined
793 }
794 >
795 {item.content}
796 </Animated.View>
797 )}
798 recycleItems={false}
799 estimatedItemSize={tab === "overview" ? 64 : 220}
800 maintainVisibleContentPosition={false}
801 ListHeaderComponent={
802 <>
803 <PullRequestReadStatus
804 pending={result.isPending && !identity}
805 error={result.error}
806 terminology={terminology}
807 />
808 {identity ? (
809 <View
810 className="gap-5 pb-5"
811 onLayout={(event) => {
812 bodyY.current = event.nativeEvent.layout.height;
813 setHeaderHeight(event.nativeEvent.layout.height);
814 }}
815 >
816 <PullRequestIdentity pr={identity} params={params} />
817 <SegmentedControl
818 options={[
819 { value: "overview", label: "Overview" },
820 ...(guidesEnabled
821 ? [{ value: "guide" as const, label: "Guide" }]
822 : []),
823 { value: "activity", label: "Activity" },
824 ]}
825 selected={section}
826 onSelect={selectSection}
827 role="tab"
828 size="compact"
829 />
830 </View>
831 ) : null}
832 </>
833 }
834 ListFooterComponent={tab === "overview" ? filesContent.footer : null}
835 />
836 </View>
837 ))}
838 </View>
839 <PullRequestActionToolbar
840 pr={pr}
841 params={params}
842 onOpenFiles={openFiles}
843 onHeightChange={setToolbarHeight}
844 />
845 </View>
846 </PullRequestMarkdownRepository>
847 );
849​
850export function PullRequestFileRouteScreen({
851 route,
852}: StaticScreenProps<
853 PullRequestDiffParams & {
854 readonly path: string;
855 readonly fileSelectionId?: string;
856 readonly replacingDraftId?: string;
857 readonly focus?: GuideDiffFocus;
858 }
859>) {
860 const { layout } = useAdaptiveWorkspaceLayout();
861 const navigation = useNavigation();
862 const insets = useSafeAreaInsets();
863 const [toolbarHeight, setToolbarHeight] = usePullRequestToolbarHeight(insets.bottom);
864 const commit = route.params.commit;
865 const detail = useEnvironmentQuery(composerPullRequests.detail(requestTarget(route.params)));
866 const terminology = sourceControlClients.get(
867 (detail.data ?? route.params.initialSummary)?.provider,
868 ).changeRequest;
869 const result = usePullRequestDiff(route.params, terminology);
870 const filter = usePullRequestFileFilter(
871 result.parsed,
872 route.params.focus ? route.params.path : undefined,
873 );
874 const { refresh: refreshDetail } = detail;
875 useFocusEffect(() => refreshDetail());
876 const { loadMore } = result;
877 const parsed = filter.parsed;
878 const reviewDraft = usePullRequestReviewDraft(route.params);
879 const viewed = usePullRequestFilesViewed(route.params, commit ? null : detail.data);
880 const [commitViewedPaths, setCommitViewedPaths] = useState<ReadonlySet<string>>(() => new Set());
881 const permissions = usePullRequestPermissions(route.params, detail.data);
882 const scopeKey = pullRequestReviewKey(route.params);
883 const [diffHead, setDiffHead] = useState({ scopeKey, sha: detail.data?.headSha ?? null });
884 if (diffHead.scopeKey !== scopeKey || (!diffHead.sha && detail.data?.headSha))
885 setDiffHead({ scopeKey, sha: detail.data?.headSha ?? null });
886 const staleDiff = Boolean(
887 !commit && diffHead.sha && detail.data?.headSha && diffHead.sha !== detail.data.headSha,
888 );
889 const canCommentOnDiff =
890 permissions.canInlineComment &&
891 !commit &&
892 !staleDiff &&
893 !detail.isPending &&
894 !result.isPending &&
895 !result.error;
896 const activity = useEnvironmentQuery(composerPullRequests.activity(requestTarget(route.params)));
897 const baseData = useMemo(() => buildNativeReviewDiffData(parsed), [parsed]);
898 const highlightFiles = usePullRequestDiffHighlightFiles(route.params, parsed, baseData.files);
899 const data = useMemo(
900 () =>
901 annotatePullRequestDiff(
902 { ...baseData, files: highlightFiles },
903 staleDiff || commit ? [] : (activity.data?.reviewThreads ?? []),
904 commit ? [] : reviewDraft.draft.comments,
905 diffHead.sha ?? undefined,
906 ),
907 [
908 baseData,
909 highlightFiles,
910 staleDiff,
911 commit,
912 activity.data?.reviewThreads,
913 reviewDraft.draft.comments,
914 diffHead.sha,
915 ],
916 );
917 const viewedIds = data.files
918 .filter((file) => (commit ? commitViewedPaths.has(file.path) : viewed.isViewed(file.path)))
919 .map((file) => file.id);
920 const [selectedRowId, setSelectedRowId] = useState<string | null>(null);
921 const selectedRow = data.rows.find((row) => row.id === selectedRowId);
922 const selectedFile = data.files.find((file) => file.id === selectedRow?.fileId);
923 const commentOnLine = (rowId = selectedRowId) => {
924 const row = data.rows.find((row) => row.id === rowId);
925 const file = data.files.find((file) => file.id === row?.fileId);
926 if (!row || !file || !diffHead.sha || !canCommentOnDiff) return;
927 const position = reviewPosition(row);
928 if (!position) return;
929 const oldPath =
930 parsed.kind === "files"
931 ? parsed.files.find((entry) => entry.id === file.id)?.previousPath
932 : null;
933 if (route.params.replacingDraftId) navigation.setParams({ replacingDraftId: undefined });
934 navigation.navigate("PullRequestInlineComment", {
935 ...route.params,
936 ...(route.params.replacingDraftId ? { draftId: route.params.replacingDraftId } : {}),
937 path: file.path,
938 ...(oldPath ? { oldPath } : {}),
939 position,
940 headSha: diffHead.sha,
941 code: row.content ?? "",
942 });
943 };
944 const [jumpPath, setJumpPath] = useState(route.params.path);
945 const requestedFile =
946 result.parsed.kind === "files"
947 ? result.parsed.files.find((file) => file.path === jumpPath)
948 : undefined;
949 const targetFile =
950 data.files.find((file) => file.path === jumpPath) ??
951 (!jumpPath || requestedFile ? data.files[0] : undefined);
952 const focus = route.params.focus;
953 const focusedRows = guideFocusedRows(data.rows, targetFile?.id, focus);
954 const focusIndex = focusedRows.length
955 ? data.rows.findIndex((row) => row.id === focusedRows[0]?.id)
956 : -1;
957 const [collapsedIds, setCollapsedIds] = useState<readonly string[]>(EMPTY_IDS);
958 const [visibleFileId, setVisibleFileId] = useState<string | null>(null);
959 const nativeView = useRef<NativeReviewDiffViewHandle>(null);
960 // Native applies the entry destination before its first viewport. Imperative
961 // jumps below are for subsequent selections and filter changes only.
962 const jumpStarted = useRef(true);
963 const lastSelection = useRef({ path: route.params.path, id: route.params.fileSelectionId });
964 useEffect(() => {
965 if (
966 lastSelection.current.path === route.params.path &&
967 lastSelection.current.id === route.params.fileSelectionId
968 )
969 return;
970 lastSelection.current = { path: route.params.path, id: route.params.fileSelectionId };
971 if (route.params.focus) navigation.setParams({ focus: undefined });
972 setJumpPath(route.params.path);
973 setSelectedRowId(null);
974 jumpStarted.current = false;
975 const file = data.files.find((entry) => entry.path === route.params.path);
976 if (!file || !nativeView.current) return;
977 setCollapsedIds((ids) => ids.filter((id) => id !== file.id));
978 jumpStarted.current = true;
979 void nativeView.current.scrollToFile(file.id, false).catch(() => {
980 jumpStarted.current = false;
981 });
982 }, [route.params.path, route.params.fileSelectionId, route.params.focus, data.files, navigation]);
983 const appliedFilter = useRef(filter.hideTestFiles);
984 useEffect(() => {
985 if (appliedFilter.current === filter.hideTestFiles) return;
986 appliedFilter.current = filter.hideTestFiles;
987 if (
988 result.parsed.kind === "files" &&
989 result.parsed.files.some((file) => isPullRequestTestFile(file.path))
990 ) {
991 jumpStarted.current = false;
992 }
993 }, [filter.hideTestFiles, result.parsed]);
994 const { nativeReviewDiffStyle } = useAppearanceCodeSurface();
995 const { themeAppearance, appearance, setCodeWordBreak } = useAppearancePreferences();
996 const bridge = useNativeReviewDiffBridge({
997 threadKey: null,
998 sectionId: `pull-request:${route.params.repository}:${route.params.number}:${commit ?? "all"}`,
999 diff: result.patch,
1000 data,
1001 collapsedFileIds: collapsedIds,
1002 viewedFileIds: viewedIds,
1003 selectedRowIds: selectedRowId ? [selectedRowId] : focusedRows.map((row) => row.id),
1004 canHighlight: true,
1005 });
1006 const [NativeDiffView] = useState(() => resolveNativeReviewDiffView());
1007 useEffect(() => {
1008 if (!targetFile) loadMore();
1009 }, [targetFile, loadMore]);
1010 const onDebug: NonNullable<NativeReviewDiffViewProps["onDebug"]> = (event) =>
1011 handlePullRequestDiffDebugEvent(event, {
1012 rowCount: data.rows.length,
1013 targetFileId: targetFile?.id,
1014 focusIndex,
1015 isIos: Platform.OS === "ios",
1016 nativeView,
1017 jumpStarted,
1018 onDebug: bridge.onDebug,
1019 loadMore,
1020 });
1021 const onToggleFile: NonNullable<NativeReviewDiffViewProps["onToggleFile"]> = (event) => {
1022 const id = event.nativeEvent.fileId;
1023 if (!id) return;
1024 setCollapsedIds((ids) =>
1025 ids.includes(id) ? ids.filter((value) => value !== id) : [...ids, id],
1026 );
1027 };
1028 const visibleFile = data.files.find((file) => file.id === visibleFileId) ?? targetFile;
1029 const toggleTestFiles = () => {
1030 setJumpPath(visibleFile?.path ?? route.params.path);
1031 setSelectedRowId(null);
1032 filter.toggle();
1033 };
1034 const title = commit ? "Commit changes" : "Changes";
1035 const seekingFile = !targetFile && result.nextCursor !== null;
1036 const loadingDiff = (result.isPending && !data.rows.length) || (seekingFile && !result.error);
1037 return (
1038 <View className={Platform.OS === "android" ? "flex-1 bg-header" : "flex-1 bg-screen"}>
1039 <NativeStackScreenOptions
1040 options={{
1041 title,
1042 headerTitle: title,
1043 unstable_headerSubtitle: `${commit ? commit.slice(0, 7) : `#${route.params.number}`} · ${data.files.length} ${data.files.length === 1 ? "file" : "files"}${filter.hideTestFiles && filter.hiddenCount ? ` · ${filter.hiddenCount} ${filter.hiddenCount === 1 ? "test" : "tests"} hidden` : ""}`,
1044 }}
1045 />
1046 {Platform.OS === "android" ? (
1047 <AndroidScreenHeader
1048 title={title}
1049 onBack={() => navigation.goBack()}
1050 trailing={
1051 <Menu
1052 actions={[
1054 id: "word-wrap",
1055 title: "Word wrap",
1056 image: "text.alignleft",
1057 state: appearance.codeWordBreak ? "on" : "off",
1058 },
1060 id: "hide-tests",
1061 title: "Hide test files",
1062 image: "line.3.horizontal.decrease",
1063 state: filter.hideTestFiles ? "on" : "off",
1064 },
1065 ...(permissions.verdicts.length
1066 ? [{ id: "submit-review", title: "Submit review", image: "text.bubble" }]
1067 : []),
1068 ...(permissions.canComment
1069 ? [{ id: "comment-on-pr", title: "Add comment", image: "plus.bubble" }]
1070 : []),
1071 ...(selectedRow && selectedFile
1072 ? [
1073 ...(canCommentOnDiff ? [{ id: "comment", title: "Add review comment" }] : []),
1074 { id: "copy", title: "Copy line" },
1076 : []),
1077 ]}
1078 onPressAction={({ nativeEvent }) => {
1079 if (nativeEvent.event === "word-wrap") setCodeWordBreak(!appearance.codeWordBreak);
1080 else if (nativeEvent.event === "hide-tests") toggleTestFiles();
1081 else if (
1082 nativeEvent.event === "submit-review" ||
1083 nativeEvent.event === "comment-on-pr"
1085 navigation.navigate("PullRequestReview", {
1086 ...route.params,
1087 mode: nativeEvent.event === "submit-review" ? "review" : "comment",
1088 });
1089 else if (nativeEvent.event === "comment") commentOnLine();
1090 else void Clipboard.setStringAsync(selectedRow?.content ?? "");
1091 }}
1093 <View pointerEvents="none">
1094 <IconButton icon="ellipsis" accessibilityLabel="Diff options" />
1095 </View>
1096 </Menu>
1098 />
1099 ) : null}
1100 <Toolbar placement="right">
1101 <Toolbar.Menu title="Diff options" accessibilityLabel="Diff options" icon="ellipsis">
1102 {permissions.verdicts.length ? (
1103 <Toolbar.MenuAction
1104 icon="text.bubble"
1105 onPress={() =>
1106 navigation.navigate("PullRequestReview", { ...route.params, mode: "review" })
1109 <Toolbar.Label>Submit review</Toolbar.Label>
1110 </Toolbar.MenuAction>
1111 ) : null}
1112 {permissions.canComment ? (
1113 <Toolbar.MenuAction
1114 icon="plus.bubble"
1115 onPress={() =>
1116 navigation.navigate("PullRequestReview", { ...route.params, mode: "comment" })
1119 <Toolbar.Label>Add comment</Toolbar.Label>
1120 </Toolbar.MenuAction>
1121 ) : null}
1122 <Toolbar.MenuAction
1123 icon="text.alignleft"
1124 isOn={appearance.codeWordBreak}
1125 onPress={() => setCodeWordBreak(!appearance.codeWordBreak)}
1127 <Toolbar.Label>Word wrap</Toolbar.Label>
1128 </Toolbar.MenuAction>
1129 <Toolbar.MenuAction
1130 icon="line.3.horizontal.decrease"
1131 isOn={filter.hideTestFiles}
1132 onPress={toggleTestFiles}
1134 <Toolbar.Label>Hide test files</Toolbar.Label>
1135 </Toolbar.MenuAction>
1136 {selectedRow && selectedFile && canCommentOnDiff ? (
1137 <Toolbar.MenuAction icon="bubble.left" onPress={() => commentOnLine()}>
1138 <Toolbar.Label>
1139 {route.params.replacingDraftId ? "Move draft to this line" : "Add review comment"}
1140 </Toolbar.Label>
1141 </Toolbar.MenuAction>
1142 ) : null}
1143 {selectedRow && selectedFile ? (
1144 <Toolbar.MenuAction
1145 icon="document.on.document"
1146 onPress={() => void Clipboard.setStringAsync(selectedRow.content ?? "")}
1148 <Toolbar.Label>Copy line</Toolbar.Label>
1149 </Toolbar.MenuAction>
1150 ) : null}
1151 </Toolbar.Menu>
1152 </Toolbar>
1153 {route.params.replacingDraftId ? (
1154 <Text className="px-4 py-2 text-xs text-foreground-muted">
1155 Select a current line, then choose “Move draft to this line” from its menu.
1156 </Text>
1157 ) : null}
1158 {viewed.error ? (
1159 <Text className="px-4 py-2 text-xs text-danger-foreground">{viewed.error}</Text>
1160 ) : null}
1161 {staleDiff ? (
1162 <View
1163 className="flex-row items-center gap-2 px-4 py-2"
1164 style={{ paddingTop: Platform.OS === "ios" ? insets.top + 8 : 8 }}
1166 <Text className="min-w-0 flex-1 text-xs text-foreground-muted">
1167 The branch changed. Reload before adding line comments.
1168 </Text>
1169 <Button
1170 label="Reload changes"
1171 onPress={() => {
1172 result.refresh();
1173 setDiffHead({ scopeKey, sha: detail.data?.headSha ?? null });
1174 jumpStarted.current = false;
1175 setSelectedRowId(null);
1176 setCollapsedIds(EMPTY_IDS);
1177 }}
1178 />
1179 </View>
1180 ) : null}
1181 <View
1182 className={
1183 Platform.OS === "android"
1184 ? "flex-1 overflow-hidden rounded-t-[28px] bg-sheet-solid"
1185 : "flex-1"
1187 collapsable={false}
1188 style={{ marginHorizontal: Platform.OS === "android" && layout.usesSplitView ? 4 : 0 }}
1190 {loadingDiff || result.error ? (
1191 <View style={{ paddingTop: Platform.OS === "ios" && !staleDiff ? insets.top : 0 }}>
1192 <PullRequestReadStatus
1193 pending={loadingDiff}
1194 error={result.error}
1195 terminology={terminology}
1196 />
1197 </View>
1198 ) : null}
1199 {NativeDiffView && data.rows.length && !seekingFile ? (
1200 <View className="flex-1" collapsable={false}>
1201 <NativeDiffView
1202 {...pullRequestDiffInitialPosition(targetFile?.id, focusIndex)}
1203 nativeViewRef={nativeView}
1204 refreshing={result.refreshing}
1205 onPullToRefresh={result.onPullRefresh}
1206 style={StyleSheet.absoluteFill}
1207 rowsJson={bridge.rowsJson}
1208 themeJson={bridge.themeJson}
1209 styleJson={bridge.styleJson}
1210 tokensPatchJson={bridge.tokensPatchJson}
1211 tokensResetKey={bridge.tokensResetKey}
1212 collapsedFileIdsJson={bridge.collapsedFileIdsJson}
1213 onDebug={onDebug}
1214 viewedFileIdsJson={bridge.viewedFileIdsJson}
1215 selectedRowIdsJson={bridge.selectedRowIdsJson}
1216 onPressLine={(event) => {
1217 const rowId = event.nativeEvent.rowId ?? null;
1218 setSelectedRowId(rowId);
1219 if (event.nativeEvent.gesture !== "longPress") commentOnLine(rowId);
1220 }}
1221 onToggleViewedFile={(event) => {
1222 const file = data.files.find((file) => file.id === event.nativeEvent.fileId);
1223 if (!file || (!commit && !viewed.canToggle)) return;
1224 const wasViewed = commit
1225 ? commitViewedPaths.has(file.path)
1226 : viewed.isViewed(file.path);
1227 setCollapsedIds((ids) =>
1228 wasViewed
1229 ? ids.filter((id) => id !== file.id)
1230 : ids.includes(file.id)
1231 ? ids
1232 : [...ids, file.id],
1233 );
1234 if (commit)
1235 setCommitViewedPaths((current) => {
1236 const next = new Set(current);
1237 if (next.has(file.path)) next.delete(file.path);
1238 else next.add(file.path);
1239 return next;
1240 });
1241 else void viewed.toggle(file.path);
1242 }}
1243 onToggleComment={(event) => {
1244 const id = event.nativeEvent.commentId;
1245 if (id?.startsWith("discussion:"))
1246 navigation.navigate("PullRequestDiscussion", {
1247 ...route.params,
1248 discussionId: id.slice("discussion:".length),
1249 });
1250 if (id?.startsWith("draft:")) {
1251 const draft = reviewDraft.draft.comments.find(
1252 (draft) => draft.id === id.slice("draft:".length),
1253 );
1254 if (draft)
1255 navigation.navigate("PullRequestInlineComment", {
1256 ...route.params,
1257 ...draft,
1258 draftId: draft.id,
1259 });
1261 }}
1262 onToggleFile={onToggleFile}
1263 onVisibleFileChange={(event) => setVisibleFileId(event.nativeEvent.fileId ?? null)}
1264 appearanceScheme={themeAppearance}
1265 rowHeight={nativeReviewDiffStyle.rowHeight}
1266 contentWidth={NATIVE_REVIEW_DIFF_CONTENT_WIDTH}
1267 contentInsetTop={Platform.OS === "ios" ? (staleDiff ? 0 : insets.top) : undefined}
1268 contentInsetBottom={Platform.OS === "android" ? toolbarHeight : insets.bottom}
1269 contentResetKey={`pull-request:${route.params.environmentId}:${route.params.repository}:${route.params.number}:${commit ?? "all"}`}
1270 />
1271 </View>
1272 ) : filter.hiddenCount > 0 &&
1273 !data.rows.length &&
1274 !result.isPending &&
1275 !result.error &&
1276 !seekingFile ? (
1277 <View style={{ paddingTop: Platform.OS === "ios" ? insets.top : 0 }}>
1278 <EmptyState
1279 title="Only test files changed"
1280 detail="Test files are hidden from this review."
1281 action={<Button label="Show test files" tone="contrast" onPress={filter.showAll} />}
1282 variant="plain"
1283 />
1284 </View>
1285 ) : !result.isPending && !result.error && !seekingFile ? (
1286 <EmptyState
1287 title="Diff unavailable"
1288 detail={`Open this ${terminology.singular} on its provider to view the changes.`}
1289 variant="plain"
1290 />
1291 ) : null}
1292 {result.nextCursor && result.isPending && data.rows.length && !seekingFile ? (
1293 <View className="flex-row items-center justify-center gap-2 py-2">
1294 <AppActivityIndicator size="small" />
1295 <Text className="text-xs text-foreground-muted">Loading more files…</Text>
1296 </View>
1297 ) : null}
1298 {result.error && result.nextCursor ? (
1299 <View className="self-center">
1300 <Button label="Retry loading remaining files" tone="text" onPress={result.refresh} />
1301 </View>
1302 ) : null}
1303 {parsed.kind === "files" && parsed.notice ? (
1304 <Text className="px-4 py-2 text-2xs text-foreground-muted">{parsed.notice}</Text>
1305 ) : null}
1306 </View>
1307 <PullRequestActionToolbar
1308 pr={detail.data}
1309 params={route.params}
1310 filePath={visibleFile?.path}
1311 onOpenFiles={() => navigation.navigate("PullRequestFiles", route.params)}
1312 onHeightChange={setToolbarHeight}
1313 />
1314 </View>
1315 );