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