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