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