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