Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PullRequestRouteScreen.tsx

1,405 lines60.3 KB

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