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