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