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

PullRequestRouteScreen.tsx

1,495 lines62.1 KB

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