@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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