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