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

PullRequestRouteScreen.tsx

1,413 lines60.4 KB

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 { AppBar } from "../../components/ui/AppBar";
69import { useAndroidControlSizing } from "../../components/ui/useAndroidControlSizing";
70import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
71import { useWorkspaceSidebarHeaderItem } from "../layout/useWorkspaceSidebarHeaderItem";
72import { useAndroidWorkspaceBack } from "../workspace/useAndroidWorkspaceNavigation";
73import { EmptyState } from "../../components/ui/EmptyState";
74import { SegmentedControl } from "../../components/ui/SegmentedControl";
75import { SymbolView } from "../../components/ui/AppSymbol";
76import { ScreenContent } from "../../components/ui/ScreenContent";
77import { RelativeTime } from "../../components/RelativeTime";
78import { 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 );
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 };
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 );
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 );
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 );
333​
334function usePullRequestToolbarHeight(bottomInset: number) {
335 const { buttonSize } = useAndroidControlSizing();
336 return useState(() => (Platform.OS === "android" ? bottomInset + buttonSize + 40 : 0));
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 stateAction = action.available("close")
427 ? "close"
428 : action.available("reopen")
429 ? "reopen"
430 : null;
431 const runStateAction = () =>
432 stateAction === "close" ? action.confirmClose() : void action.perform("reopen");
433 const confirmDeleteBranch = () =>
434 pr &&
435 action.confirm(
436 "delete-branch",
437 pullRequestActionLabel("delete-branch", terminology),
438 `Delete ${pr.headBranch} from ${pr.headRepositoryNameWithOwner ?? pr.repository}? Local branches and worktrees are not changed.`,
439 );
440 const stack = usePullRequestStack(params, pr);
441 const refreshActivity = useAtomRefresh(composerPullRequests.activity(requestTarget(params)));
442 const refreshGuide = useAtomRefresh(composerPullRequests.reviewGuide(requestTarget(params)));
443 const registry = use(RegistryContext);
444 const refresh = () =>
445 pullRefresh.onRefresh(async (signal) => {
446 const target = requestTarget(params);
447 await composerPullRequests.invalidate
448 .run(registry, {
449 environmentId: target.environmentId,
450 input: { reference: target.input },
451 })
452 .catch(() => undefined);
453 if (signal.aborted) return;
454 if (guidesEnabled) refreshGuide();
455 stack.refresh();
456 refreshActivity();
457 filesContent.refresh();
458 });
459 const jumpToFiles = () => {
460 scrollViews.current.overview?.scrollToOffset({
461 offset: bodyY.current + filesY.current - barInsets.top,
462 animated: true,
463 });
464 pendingFilesJump.current = false;
465 };
466 const openFiles = () => {
467 if (section === "overview") jumpToFiles();
468 else {
469 pendingFilesJump.current = true;
470 selectSection("overview");
471 if (filesY.current > 0) requestAnimationFrame(jumpToFiles);
472 }
473 };
474 return (
475 <PullRequestMarkdownRepository params={params} changeRequest={pr}>
476 <View className={Platform.OS === "android" ? "flex-1 bg-header" : "flex-1 bg-screen"}>
477 <NativeStackScreenOptions
478 options={{
479 title: `#${params.number}`,
480 headerTitle: `#${params.number}`,
481 unstable_headerSubtitle: connected
482 ? params.repository
483 : `${params.repository} · Offline`,
484 unstable_headerLeftItems: sidebarHeaderItem ? () => [sidebarHeaderItem] : undefined,
485 }}
486 optionsVersion={[sidebarHeaderItem]}
487 />
488 {Platform.OS === "android" ? (
489 <AppBar
490 embedded
491 title={`#${params.number}${connected ? "" : " · Offline"}`}
492 subtitle={params.repository}
493 onBack={layout.usesSplitView ? undefined : returnToList}
494 actions={[
495 ...(permissions.verdicts.length
496 ? [
497 {
498 accessibilityLabel: "Submit review",
499 icon: "text.bubble" as const,
500 onPress: () =>
501 navigation.navigate("PullRequestReview", { ...params, mode: "review" }),
502 },
503 ]
504 : []),
505 ...(permissions.canComment
506 ? [
507 {
508 accessibilityLabel: "Add comment",
509 icon: "plus.bubble" as const,
510 onPress: () =>
511 navigation.navigate("PullRequestReview", { ...params, mode: "comment" }),
512 },
513 ]
514 : []),
515 ...(permissions.canEditChangeRequest
516 ? [
517 {
518 accessibilityLabel: "Edit title",
519 icon: "pencil" as const,
520 overflowOnly: true,
521 onPress: () =>
522 navigation.navigate("PullRequestEdit", { ...params, field: "title" }),
523 },
524 {
525 accessibilityLabel: "Edit description",
526 icon: "doc.text" as const,
527 overflowOnly: true,
528 onPress: () =>
529 navigation.navigate("PullRequestEdit", { ...params, field: "body" }),
530 },
531 ]
532 : []),
533 ...(maintainerEdits.visible
534 ? [
535 {
536 accessibilityLabel: "Allow edits from maintainers",
537 icon: "pencil" as const,
538 selected: maintainerEdits.value,
539 disabled: maintainerEdits.saving,
540 subtitle: maintainerEdits.subtitle,
541 overflowOnly: true,
542 onPress: maintainerEdits.toggle,
543 },
544 ]
545 : []),
546 ...(identity
547 ? [
548 {
549 accessibilityLabel: openOnProviderLabel(identity.provider),
550 icon: "arrow.up.right" as const,
551 onPress: () => void Linking.openURL(identity.url),
552 },
553 {
554 accessibilityLabel: "Copy link",
555 icon: "link" as const,
556 overflowOnly: true,
557 onPress: () => copyPullRequestLink(identity),
558 },
559 {
560 accessibilityLabel: "Share…",
561 icon: "square.and.arrow.up" as const,
562 overflowOnly: true,
563 onPress: () => sharePullRequestLink(identity),
564 },
565 ]
566 : []),
567 ...(stateAction
568 ? [
569 {
570 accessibilityLabel: pullRequestActionLabel(stateAction, terminology),
571 icon: PR_ACTION_ICONS[stateAction],
572 destructive: stateAction === "close",
573 overflowOnly: true,
574 onPress: runStateAction,
575 },
576 ]
577 : []),
578 ...(showsDeleteBranch
579 ? [
580 {
581 accessibilityLabel: pullRequestActionLabel("delete-branch", terminology),
582 icon: PR_ACTION_ICONS["delete-branch"],
583 disabled: !action.available("delete-branch"),
584 destructive: true,
585 overflowOnly: true,
586 onPress: confirmDeleteBranch,
587 },
588 ]
589 : []),
590 ]}
591 />
592 ) : null}
593 <Toolbar placement="right">
594 <Toolbar.Menu
595 title={capitalizeTerm(terminology.singular)}
596 accessibilityLabel={`${capitalizeTerm(terminology.singular)} actions`}
597 icon="ellipsis"
598 >
599 {permissions.verdicts.length ? (
600 <Toolbar.MenuAction
601 icon="text.bubble"
602 onPress={() =>
603 navigation.navigate("PullRequestReview", { ...params, mode: "review" })
604 }
605 >
606 <Toolbar.Label>Submit review</Toolbar.Label>
607 </Toolbar.MenuAction>
608 ) : null}
609 {permissions.canComment ? (
610 <Toolbar.MenuAction
611 icon="plus.bubble"
612 onPress={() =>
613 navigation.navigate("PullRequestReview", { ...params, mode: "comment" })
614 }
615 >
616 <Toolbar.Label>Add comment</Toolbar.Label>
617 </Toolbar.MenuAction>
618 ) : null}
619 {permissions.canEditChangeRequest ? (
620 <Toolbar.MenuAction
621 icon="pencil"
622 onPress={() =>
623 navigation.navigate("PullRequestEdit", { ...params, field: "title" })
624 }
625 >
626 <Toolbar.Label>Edit title</Toolbar.Label>
627 </Toolbar.MenuAction>
628 ) : null}
629 {permissions.canEditChangeRequest ? (
630 <Toolbar.MenuAction
631 icon="doc.text"
632 onPress={() => navigation.navigate("PullRequestEdit", { ...params, field: "body" })}
633 >
634 <Toolbar.Label>Edit description</Toolbar.Label>
635 </Toolbar.MenuAction>
636 ) : null}
637 {maintainerEdits.visible ? (
638 <Toolbar.MenuAction
639 icon="pencil"
640 isOn={maintainerEdits.value}
641 disabled={maintainerEdits.saving}
642 subtitle={maintainerEdits.subtitle}
643 onPress={maintainerEdits.toggle}
644 >
645 <Toolbar.Label>Allow edits from maintainers</Toolbar.Label>
646 </Toolbar.MenuAction>
647 ) : null}
648 {identity ? (
649 <Toolbar.MenuAction
650 icon="arrow.up.right"
651 onPress={() => void Linking.openURL(identity.url)}
652 >
653 <Toolbar.Label>{openOnProviderLabel(identity.provider)}</Toolbar.Label>
654 </Toolbar.MenuAction>
655 ) : null}
656 {identity ? (
657 <Toolbar.MenuAction icon="link" onPress={() => copyPullRequestLink(identity)}>
658 <Toolbar.Label>Copy link</Toolbar.Label>
659 </Toolbar.MenuAction>
660 ) : null}
661 {identity ? (
662 <Toolbar.MenuAction
663 icon="square.and.arrow.up"
664 onPress={() => sharePullRequestLink(identity)}
665 >
666 <Toolbar.Label>Share…</Toolbar.Label>
667 </Toolbar.MenuAction>
668 ) : null}
669 {stateAction ? (
670 <Toolbar.MenuAction
671 icon={PR_ACTION_ICONS[stateAction]}
672 destructive={stateAction === "close"}
673 onPress={runStateAction}
674 >
675 <Toolbar.Label>{pullRequestActionLabel(stateAction, terminology)}</Toolbar.Label>
676 </Toolbar.MenuAction>
677 ) : null}
678 {showsDeleteBranch ? (
679 <Toolbar.MenuAction
680 icon={PR_ACTION_ICONS["delete-branch"]}
681 destructive
682 disabled={!action.available("delete-branch")}
683 subtitle={
684 action.busy
685 ? "Deleting…"
686 : connected
687 ? pr.headBranch
688 : "Reconnect to delete this branch."
689 }
690 onPress={confirmDeleteBranch}
691 >
692 <Toolbar.Label>
693 {pullRequestActionLabel("delete-branch", terminology)}
694 </Toolbar.Label>
695 </Toolbar.MenuAction>
696 ) : null}
697 </Toolbar.Menu>
698 </Toolbar>
699 <ScreenContent
700 insetHorizontal={layout.usesSplitView}
701 onLayout={(event) => setViewportHeight(event.nativeEvent.layout.height)}
702 >
703 {(["overview", "guide", "activity"] as const)
704 .filter((tab) => tab !== "guide" || guidesEnabled)
705 .map((tab) => (
706 <View
707 key={tab}
708 style={[StyleSheet.absoluteFill, { opacity: section === tab ? 1 : 0 }]}
709 pointerEvents={section === tab ? "auto" : "none"}
710 accessibilityElementsHidden={section !== tab}
711 importantForAccessibility={section === tab ? "auto" : "no-hide-descendants"}
712 >
713 <AnimatedLegendList
714 ref={listRefs[tab]}
715 // The scroll view owns its resting offset. LegendList keeps the first
716 // initialScrollOffset it gets, and the first render has the window's top
717 // inset (0 on the folded iPhone Duo), not the header's.
718 onScroll={(event) => {
719 const offset = event.nativeEvent.contentOffset.y;
720 scrollOffsets.current[tab] = offset;
721 if (shown(requestedSection.current) === tab)
722 currentScrollOffset.current = { tab, offset };
723 }}
724 className="flex-1"
725 renderScrollComponent={
726 Platform.OS === "ios" ? PullRequestTabScrollView : undefined
727 }
728 // UIKit owns the bar's inset, so a minimizing bar and a resized column
729 // move the list in the same frame as the bar.
730 contentInsetAdjustmentBehavior="automatic"
731 contentInsetStartAdjustment={barInsets.top}
732 // RN scrollTo clamps against raw insets and ignores the automatic bar inset.
733 scrollToOverflowEnabled
734 refreshControl={
735 <RefreshControl
736 refreshing={section === tab && pullRefresh.refreshing}
737 onRefresh={refresh}
738 />
739 }
740 alwaysBounceVertical
741 scrollsToTop={section === tab}
742 onContentSizeChange={() => {
743 if (
744 tab !== "overview" ||
745 section !== "overview" ||
746 !pendingDescriptionJump.current
747 )
748 return;
749 pendingDescriptionJump.current = false;
750 // Collapse changes the scroll range; restore the heading after that layout commits.
751 scrollViews.current.overview?.scrollToOffset({
752 offset: bodyY.current + descriptionY.current - barInsets.top,
753 animated: false,
754 });
755 }}
756 contentContainerStyle={{
757 paddingHorizontal: 16,
758 paddingTop: 8,
759 paddingBottom: 24 + (Platform.OS === "android" ? toolbarHeight : 0),
760 // Short tabs must still be tall enough to preserve the collapsed header.
761 minHeight: Math.max(
762 0,
763 viewportHeight + headerHeight - barInsets.top - barInsets.bottom,
764 ),
765 }}
766 data={[
767 {
768 key: `${tab}:body`,
769 content: (
770 <View>
771 {tab === "overview" && identity ? (
772 <View>
773 <SourceControlAppAccessNotice
774 environmentId={params.environmentId}
775 provider={identity.provider}
776 host={params.host}
777 repository={params.repository}
778 />
779 {pr ? (
780 <PullRequestOverview
781 pr={pr}
782 params={params}
783 stack={stack}
784 descriptionExpanded={descriptionExpanded}
785 onDescriptionExpandedChange={setDescriptionExpanded}
786 onDescriptionLayout={(y) => {
787 descriptionY.current = y;
788 }}
789 onDescriptionCollapse={() => {
790 pendingDescriptionJump.current = true;
791 }}
792 />
793 ) : summary ? (
794 <PullRequestOverviewLoading
795 summary={summary}
796 params={params}
797 stack={stack}
798 />
799 ) : null}
800 <View
801 className="mt-8 border-t border-border-subtle pt-3"
802 onLayout={(event) => {
803 filesY.current = event.nativeEvent.layout.y;
804 if (pendingFilesJump.current) {
805 requestAnimationFrame(() => {
806 if (shown(requestedSection.current) === "overview")
807 jumpToFiles();
808 });
809 }
810 }}
811 >
812 {filesContent.header}
813 </View>
814 </View>
815 ) : null}
816 {tab === "guide" ? (
817 <PullRequestGuideContent
818 params={params}
819 visible={section === "guide"}
820 />
821 ) : null}
822 {tab === "activity" ? (
823 <PullRequestActivityFilters
824 value={activityFilter}
825 onChange={setActivityFilter}
826 hiddenCount={tabContent.hiddenCount}
827 />
828 ) : null}
829 {tab === "activity" ? (
830 <PullRequestReadStatus
831 pending={tabContent.pending}
832 error={tabContent.error}
833 terminology={terminology}
834 />
835 ) : null}
836 </View>
837 ),
838 },
839 ...(tab === "overview"
840 ? identity
841 ? filesContent.rows
842 : []
843 : tab === "activity"
844 ? tabContent.rows
845 : []
846 ).map((row) => ({
847 ...row,
848 key: `${tab}:${row.key}`,
849 content: row.content,
850 })),
851 ]}
852 keyExtractor={(row) => row.key}
853 getItemType={(row) =>
854 row.key.endsWith(":body") ? row.key : row.key.split(":")[0]
855 }
856 // Animating overview fights clipped markdown and collapse scroll correction; file rows can still fade.
857 itemLayoutAnimation={tab === "overview" ? undefined : PR_ROW_LAYOUT}
858 onLoad={() => setListAnimationsReady(true)}
859 renderItem={({ item }) => (
860 <Animated.View
861 key={item.key}
862 entering={
863 listAnimationsReady && !item.key.endsWith(":body")
864 ? PR_ROW_ENTER
865 : undefined
866 }
867 exiting={
868 listAnimationsReady && !item.key.endsWith(":body") ? PR_ROW_EXIT : undefined
869 }
870 >
871 <PullRequestMediaVisibleContext value={section === tab}>
872 {item.content}
873 </PullRequestMediaVisibleContext>
874 </Animated.View>
875 )}
876 recycleItems={false}
877 estimatedItemSize={tab === "overview" ? 64 : 220}
878 maintainVisibleContentPosition={false}
879 ListHeaderComponent={
880 <>
881 <PullRequestReadStatus
882 pending={result.isPending && !identity}
883 error={result.error}
884 terminology={terminology}
885 />
886 {identity ? (
887 <View
888 className="gap-5 pb-5"
889 onLayout={(event) => {
890 bodyY.current = event.nativeEvent.layout.height;
891 setHeaderHeight(event.nativeEvent.layout.height);
892 }}
893 >
894 <PullRequestIdentity pr={identity} params={params} />
895 {/* UIKit draws the tapped control's glass lens outside the hidden
896 tab's opacity, so only the visible tab mounts the control. */}
897 {Platform.OS !== "ios" || section === tab ? (
898 <SegmentedControl
899 options={[
900 { value: "overview", label: "Overview" },
901 ...(guidesEnabled
902 ? [{ value: "guide" as const, label: "Guide" }]
903 : []),
904 { value: "activity", label: "Activity" },
905 ]}
906 selected={section}
907 onSelect={selectSection}
908 role="tab"
909 size="compact"
910 />
911 ) : (
912 <View style={{ height: 32 }} />
913 )}
914 </View>
915 ) : null}
916 </>
917 }
918 ListFooterComponent={tab === "overview" ? filesContent.footer : null}
919 />
920 </View>
921 ))}
922 </ScreenContent>
923 <PullRequestActionToolbar
924 pr={pr}
925 params={params}
926 onOpenFiles={openFiles}
927 onHeightChange={setToolbarHeight}
928 />
929 </View>
930 </PullRequestMarkdownRepository>
931 );
933​
934type PullRequestFileRouteProps = StaticScreenProps<
935 PullRequestDiffParams & {
936 readonly path: string;
937 readonly replacingDraftId?: string;
938 readonly focus?: GuideDiffFocus;
939 }
940>;
941​
942export function PullRequestFileRouteScreen(props: PullRequestFileRouteProps) {
943 const navigation =
944 useNavigation<NativeStackNavigationProp<ReactNavigation.RootParamList, "PullRequestFile">>();
945 const ready = usePullRequestDiffEntry(navigation);
946 if (ready) return <PullRequestFileRouteContent {...props} />;
947 const title = props.route.params.commit ? "Commit changes" : "Changes";
948 return (
949 <View className="flex-1 bg-screen">
950 <NativeStackScreenOptions options={{ title, headerTitle: title }} />
951 {Platform.OS === "android" ? (
952 <AppBar embedded title={title} onBack={() => navigation.goBack()} />
953 ) : null}
954 <View className="flex-1 items-center justify-center">
955 <AppActivityIndicator accessibilityLabel="Loading changes" />
956 </View>
957 </View>
958 );
960​
961function PullRequestFileRouteContent({ route }: PullRequestFileRouteProps) {
962 const { layout } = useAdaptiveWorkspaceLayout();
963 const navigation = useNavigation();
964 const insets = useSafeAreaInsets();
965 const [toolbarHeight, setToolbarHeight] = usePullRequestToolbarHeight(insets.bottom);
966 const commit = route.params.commit;
967 const detail = useEnvironmentQuery(composerPullRequests.detail(requestTarget(route.params)));
968 const terminology = sourceControlClients.get(
969 (detail.data ?? route.params.initialSummary)?.provider,
970 ).changeRequest;
971 const result = usePullRequestDiff(route.params, terminology);
972 const filter = usePullRequestFileFilter(
973 result.parsed,
974 route.params.focus ? route.params.path : undefined,
975 );
976 const { refresh: refreshDetail } = detail;
977 useFocusEffect(refreshDetail);
978 const { loadMore } = result;
979 const parsed = filter.parsed;
980 const reviewDraft = usePullRequestReviewDraft(route.params);
981 const viewed = usePullRequestFilesViewed(route.params, commit ? null : detail.data);
982 const [commitViewedPaths, setCommitViewedPaths] = useState<ReadonlySet<string>>(() => new Set());
983 const permissions = usePullRequestPermissions(route.params, detail.data);
984 const scopeKey = pullRequestReviewKey(route.params);
985 const [diffHead, setDiffHead] = useState({ scopeKey, sha: detail.data?.headSha ?? null });
986 if (diffHead.scopeKey !== scopeKey || (!diffHead.sha && detail.data?.headSha))
987 setDiffHead({ scopeKey, sha: detail.data?.headSha ?? null });
988 const staleDiff = Boolean(
989 !commit && diffHead.sha && detail.data?.headSha && diffHead.sha !== detail.data.headSha,
990 );
991 const canCommentOnDiff =
992 permissions.canInlineComment &&
993 !commit &&
994 !staleDiff &&
995 !detail.isPending &&
996 !result.isPending &&
997 !result.error;
998 const activity = useEnvironmentQuery(composerPullRequests.activity(requestTarget(route.params)));
999 const baseData = useMemo(() => getCachedNativeReviewDiffData({ parsedDiff: parsed }), [parsed]);
1000 const highlightFiles = usePullRequestDiffHighlightFiles(route.params, parsed, baseData.files);
1001 const data = useMemo(
1002 () =>
1003 annotatePullRequestDiff(
1004 { ...baseData, files: highlightFiles },
1005 staleDiff || commit ? [] : (activity.data?.reviewThreads ?? []),
1006 commit ? [] : reviewDraft.draft.comments,
1007 diffHead.sha ?? undefined,
1008 ),
1010 baseData,
1011 highlightFiles,
1012 staleDiff,
1013 commit,
1014 activity.data?.reviewThreads,
1015 reviewDraft.draft.comments,
1016 diffHead.sha,
1017 ],
1018 );
1019 const viewedIds = data.files
1020 .filter((file) => (commit ? commitViewedPaths.has(file.path) : viewed.isViewed(file.path)))
1021 .map((file) => file.id);
1022 const [selectedRowId, setSelectedRowId] = useState<string | null>(null);
1023 const selectedRow = data.rows.find((row) => row.id === selectedRowId);
1024 const selectedFile = data.files.find((file) => file.id === selectedRow?.fileId);
1025 const commentOnLine = (rowId = selectedRowId) => {
1026 const row = data.rows.find((row) => row.id === rowId);
1027 const file = data.files.find((file) => file.id === row?.fileId);
1028 if (!row || !file || !diffHead.sha || !canCommentOnDiff) return;
1029 const position = reviewPosition(row);
1030 if (!position) return;
1031 const oldPath =
1032 parsed.kind === "files"
1033 ? parsed.files.find((entry) => entry.id === file.id)?.previousPath
1034 : null;
1035 if (route.params.replacingDraftId) navigation.setParams({ replacingDraftId: undefined });
1036 navigation.navigate("PullRequestInlineComment", {
1037 ...route.params,
1038 ...(route.params.replacingDraftId ? { draftId: route.params.replacingDraftId } : {}),
1039 path: file.path,
1040 ...(oldPath ? { oldPath } : {}),
1041 position,
1042 headSha: diffHead.sha,
1043 code: row.content ?? "",
1044 });
1045 };
1046 const [jumpPath, setJumpPath] = useState(route.params.path);
1047 const requestedFile =
1048 result.parsed.kind === "files"
1049 ? result.parsed.files.find((file) => file.path === jumpPath)
1050 : undefined;
1051 const targetFile =
1052 data.files.find((file) => file.path === jumpPath) ??
1053 (!jumpPath || requestedFile ? data.files[0] : undefined);
1054 const focus = route.params.focus;
1055 const focusedRows = guideFocusedRows(data.rows, targetFile?.id, focus);
1056 const focusIndex = focusedRows.length
1057 ? data.rows.findIndex((row) => row.id === focusedRows[0]?.id)
1058 : -1;
1059 const [collapsedIds, setCollapsedIds] = useState<readonly string[]>(EMPTY_IDS);
1060 const [visibleFileId, setVisibleFileId] = useState<string | null>(null);
1061 const nativeView = useRef<NativeReviewDiffViewHandle>(null);
1062 // The filter the current jump was made under. Hiding or showing test files replaces the rows,
1063 // so a jump made under the other filter has to run again. Native applies the entry
1064 // destination before its first viewport, so the first one counts as made.
1065 const jumpedUnder = useRef<boolean | null>(filter.hideTestFiles);
1066 const hasTestFiles =
1067 result.parsed.kind === "files" &&
1068 result.parsed.files.some((file) => isTestChangedFile(file.path));
1069 const jumpStarted = () =>
1070 jumpedUnder.current !== null && (!hasTestFiles || jumpedUnder.current === filter.hideTestFiles);
1071 const scrollToFile = (fileId: string) => {
1072 if (!nativeView.current) return;
1073 jumpedUnder.current = filter.hideTestFiles;
1074 void nativeView.current.scrollToFile(fileId, false).catch(() => {
1075 jumpedUnder.current = null;
1076 });
1077 };
1078 const jumpScope = pullRequestFileJumpScope(route.params);
1079 const jumpToFile = useEffectEvent((path: string) => {
1080 setJumpPath(path);
1081 setSelectedRowId(null);
1082 jumpedUnder.current = null;
1083 const file = data.files.find((entry) => entry.path === path);
1084 if (!file) return;
1085 setCollapsedIds((ids) => ids.filter((id) => id !== file.id));
1086 scrollToFile(file.id);
1087 });
1088 // Subscribed for the whole screen, so a pick made while the diff is still loading is kept for
1089 // the first draw.
1090 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to pull request file jump requests for the screen's lifetime
1091 useEffect(() => subscribePullRequestFileJump(jumpScope, (path) => jumpToFile(path)), [jumpScope]);
1092 const { nativeReviewDiffStyle } = useAppearanceCodeSurface();
1093 const { themeAppearance, appearance, setCodeWordBreak } = useAppearancePreferences();
1094 const bridge = useNativeReviewDiffBridge({
1095 threadKey: null,
1096 sectionId: `pull-request:${route.params.repository}:${route.params.number}:${commit ?? "all"}`,
1097 diff: result.patch,
1098 data,
1099 collapsedFileIds: collapsedIds,
1100 viewedFileIds: viewedIds,
1101 selectedRowIds: selectedRowId ? [selectedRowId] : focusedRows.map((row) => row.id),
1102 canHighlight: true,
1103 });
1104 const [NativeDiffView] = useState(() => resolveNativeReviewDiffView());
1105 // 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
1106 useEffect(() => {
1107 if (!targetFile) loadMore();
1108 }, [targetFile, loadMore]);
1109 const onDebug: NonNullable<NativeReviewDiffViewProps["onDebug"]> = (event) =>
1110 handlePullRequestDiffDebugEvent(event, {
1111 rowCount: data.rows.length,
1112 targetFileId: targetFile?.id,
1113 focusIndex,
1114 isIos: Platform.OS === "ios",
1115 nativeView,
1116 jumpStarted,
1117 setJumpStarted: (started) => {
1118 jumpedUnder.current = started ? filter.hideTestFiles : null;
1119 },
1120 onDebug: bridge.onDebug,
1121 loadMore,
1122 });
1123 const onToggleFile: NonNullable<NativeReviewDiffViewProps["onToggleFile"]> = (event) => {
1124 const id = event.nativeEvent.fileId;
1125 if (!id) return;
1126 setCollapsedIds((ids) =>
1127 ids.includes(id) ? ids.filter((value) => value !== id) : [...ids, id],
1128 );
1129 };
1130 const visibleFile = data.files.find((file) => file.id === visibleFileId) ?? targetFile;
1131 const toggleTestFiles = () => {
1132 setJumpPath(visibleFile?.path ?? route.params.path);
1133 setSelectedRowId(null);
1134 filter.toggle();
1135 };
1136 const title = commit ? "Commit changes" : "Changes";
1137 const seekingFile = !targetFile && result.nextCursor !== null;
1138 const loadingDiff = (result.isPending && !data.rows.length) || (seekingFile && !result.error);
1139 return (
1140 <View className={Platform.OS === "android" ? "flex-1 bg-header" : "flex-1 bg-screen"}>
1141 <NativeStackScreenOptions
1142 options={{
1143 title,
1144 headerTitle: title,
1145 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` : ""}`,
1146 }}
1147 />
1148 {Platform.OS === "android" ? (
1149 <AppBar
1150 embedded
1151 title={title}
1152 onBack={() => navigation.goBack()}
1153 trailing={
1154 <Menu
1155 actions={[
1157 id: "word-wrap",
1158 title: "Word wrap",
1159 image: "text.alignleft",
1160 state: appearance.codeWordBreak ? "on" : "off",
1161 },
1163 id: "hide-tests",
1164 title: "Hide test files",
1165 image: "line.3.horizontal.decrease",
1166 state: filter.hideTestFiles ? "on" : "off",
1167 },
1168 ...(permissions.verdicts.length
1169 ? [{ id: "submit-review", title: "Submit review", image: "text.bubble" }]
1170 : []),
1171 ...(permissions.canComment
1172 ? [{ id: "comment-on-pr", title: "Add comment", image: "plus.bubble" }]
1173 : []),
1174 ...(selectedRow && selectedFile
1175 ? [
1176 ...(canCommentOnDiff ? [{ id: "comment", title: "Add review comment" }] : []),
1177 { id: "copy", title: "Copy line" },
1179 : []),
1180 ]}
1181 onPressAction={({ nativeEvent }) => {
1182 if (nativeEvent.event === "word-wrap") setCodeWordBreak(!appearance.codeWordBreak);
1183 else if (nativeEvent.event === "hide-tests") toggleTestFiles();
1184 else if (
1185 nativeEvent.event === "submit-review" ||
1186 nativeEvent.event === "comment-on-pr"
1188 navigation.navigate("PullRequestReview", {
1189 ...route.params,
1190 mode: nativeEvent.event === "submit-review" ? "review" : "comment",
1191 });
1192 else if (nativeEvent.event === "comment") commentOnLine();
1193 else void Clipboard.setStringAsync(selectedRow?.content ?? "");
1194 }}
1196 <View pointerEvents="none">
1197 <IconButton icon="ellipsis" accessibilityLabel="Diff options" />
1198 </View>
1199 </Menu>
1201 />
1202 ) : null}
1203 <Toolbar placement="right">
1204 <Toolbar.Menu title="Diff options" accessibilityLabel="Diff options" icon="ellipsis">
1205 {permissions.verdicts.length ? (
1206 <Toolbar.MenuAction
1207 icon="text.bubble"
1208 onPress={() =>
1209 navigation.navigate("PullRequestReview", { ...route.params, mode: "review" })
1212 <Toolbar.Label>Submit review</Toolbar.Label>
1213 </Toolbar.MenuAction>
1214 ) : null}
1215 {permissions.canComment ? (
1216 <Toolbar.MenuAction
1217 icon="plus.bubble"
1218 onPress={() =>
1219 navigation.navigate("PullRequestReview", { ...route.params, mode: "comment" })
1222 <Toolbar.Label>Add comment</Toolbar.Label>
1223 </Toolbar.MenuAction>
1224 ) : null}
1225 <Toolbar.MenuAction
1226 icon="text.alignleft"
1227 isOn={appearance.codeWordBreak}
1228 onPress={() => setCodeWordBreak(!appearance.codeWordBreak)}
1230 <Toolbar.Label>Word wrap</Toolbar.Label>
1231 </Toolbar.MenuAction>
1232 <Toolbar.MenuAction
1233 icon="line.3.horizontal.decrease"
1234 isOn={filter.hideTestFiles}
1235 onPress={toggleTestFiles}
1237 <Toolbar.Label>Hide test files</Toolbar.Label>
1238 </Toolbar.MenuAction>
1239 {selectedRow && selectedFile && canCommentOnDiff ? (
1240 <Toolbar.MenuAction icon="bubble.left" onPress={() => commentOnLine()}>
1241 <Toolbar.Label>
1242 {route.params.replacingDraftId ? "Move draft to this line" : "Add review comment"}
1243 </Toolbar.Label>
1244 </Toolbar.MenuAction>
1245 ) : null}
1246 {selectedRow && selectedFile ? (
1247 <Toolbar.MenuAction
1248 icon="document.on.document"
1249 onPress={() => void Clipboard.setStringAsync(selectedRow.content ?? "")}
1251 <Toolbar.Label>Copy line</Toolbar.Label>
1252 </Toolbar.MenuAction>
1253 ) : null}
1254 </Toolbar.Menu>
1255 </Toolbar>
1256 {route.params.replacingDraftId ? (
1257 <Text className="px-4 py-2 text-xs text-foreground-muted">
1258 Select a current line, then choose “Move draft to this line” from its menu.
1259 </Text>
1260 ) : null}
1261 {viewed.error ? (
1262 <Text className="px-4 py-2 text-xs text-danger-foreground">{viewed.error}</Text>
1263 ) : null}
1264 {staleDiff ? (
1265 <View
1266 className="flex-row items-center gap-2 px-4 py-2"
1267 style={{ paddingTop: Platform.OS === "ios" ? insets.top + 8 : 8 }}
1269 <Text className="min-w-0 flex-1 text-xs text-foreground-muted">
1270 The branch changed. Reload before adding line comments.
1271 </Text>
1272 <Button
1273 label="Reload changes"
1274 onPress={() => {
1275 result.refresh();
1276 setDiffHead({ scopeKey, sha: detail.data?.headSha ?? null });
1277 jumpedUnder.current = null;
1278 setSelectedRowId(null);
1279 setCollapsedIds(EMPTY_IDS);
1280 }}
1281 />
1282 </View>
1283 ) : null}
1284 <ScreenContent insetHorizontal={layout.usesSplitView}>
1285 <View className="flex-1" collapsable={false}>
1286 {loadingDiff || result.error ? (
1287 <View style={{ paddingTop: Platform.OS === "ios" && !staleDiff ? insets.top : 0 }}>
1288 <PullRequestReadStatus
1289 pending={loadingDiff}
1290 error={result.error}
1291 terminology={terminology}
1292 />
1293 </View>
1294 ) : null}
1295 {NativeDiffView && data.rows.length && !seekingFile ? (
1296 <View className="flex-1" collapsable={false}>
1297 <NativeDiffView
1298 {...pullRequestDiffInitialPosition(targetFile?.id, focusIndex)}
1299 nativeViewRef={nativeView}
1300 refreshing={result.refreshing}
1301 onPullToRefresh={result.onPullRefresh}
1302 style={StyleSheet.absoluteFill}
1303 rowsJson={bridge.rowsJson}
1304 themeJson={bridge.themeJson}
1305 styleJson={bridge.styleJson}
1306 tokensPatchJson={bridge.tokensPatchJson}
1307 tokensResetKey={bridge.tokensResetKey}
1308 collapsedFileIdsJson={bridge.collapsedFileIdsJson}
1309 onDebug={onDebug}
1310 viewedFileIdsJson={bridge.viewedFileIdsJson}
1311 selectedRowIdsJson={bridge.selectedRowIdsJson}
1312 onPressLine={(event) => {
1313 const rowId = event.nativeEvent.rowId ?? null;
1314 setSelectedRowId(rowId);
1315 if (event.nativeEvent.gesture !== "longPress") commentOnLine(rowId);
1316 }}
1317 onToggleViewedFile={(event) => {
1318 const file = data.files.find((file) => file.id === event.nativeEvent.fileId);
1319 if (!file || (!commit && !viewed.canToggle)) return;
1320 const wasViewed = commit
1321 ? commitViewedPaths.has(file.path)
1322 : viewed.isViewed(file.path);
1323 setCollapsedIds((ids) =>
1324 wasViewed
1325 ? ids.filter((id) => id !== file.id)
1326 : ids.includes(file.id)
1327 ? ids
1328 : [...ids, file.id],
1329 );
1330 if (commit)
1331 setCommitViewedPaths((current) => {
1332 const next = new Set(current);
1333 if (next.has(file.path)) next.delete(file.path);
1334 else next.add(file.path);
1335 return next;
1336 });
1337 else void viewed.toggle(file.path);
1338 }}
1339 onToggleComment={(event) => {
1340 const id = event.nativeEvent.commentId;
1341 if (id?.startsWith("discussion:"))
1342 navigation.navigate("PullRequestDiscussion", {
1343 ...route.params,
1344 discussionId: id.slice("discussion:".length),
1345 });
1346 if (id?.startsWith("draft:")) {
1347 const draft = reviewDraft.draft.comments.find(
1348 (draft) => draft.id === id.slice("draft:".length),
1349 );
1350 if (draft)
1351 navigation.navigate("PullRequestInlineComment", {
1352 ...route.params,
1353 ...draft,
1354 draftId: draft.id,
1355 });
1357 }}
1358 onToggleFile={onToggleFile}
1359 onVisibleFileChange={(event) => setVisibleFileId(event.nativeEvent.fileId ?? null)}
1360 appearanceScheme={themeAppearance}
1361 rowHeight={nativeReviewDiffStyle.rowHeight}
1362 contentWidth={NATIVE_REVIEW_DIFF_CONTENT_WIDTH}
1363 contentInsetTop={Platform.OS === "ios" ? (staleDiff ? 0 : insets.top) : undefined}
1364 contentInsetBottom={Platform.OS === "android" ? toolbarHeight : insets.bottom}
1365 contentResetKey={`pull-request:${route.params.environmentId}:${route.params.repository}:${route.params.number}:${commit ?? "all"}`}
1366 />
1367 </View>
1368 ) : filter.hiddenCount > 0 &&
1369 !data.rows.length &&
1370 !result.isPending &&
1371 !result.error &&
1372 !seekingFile ? (
1373 <View style={{ paddingTop: Platform.OS === "ios" ? insets.top : 0 }}>
1374 <EmptyState
1375 title="Only test files changed"
1376 detail="Test files are hidden from this review."
1377 action={<Button label="Show test files" tone="contrast" onPress={filter.showAll} />}
1378 variant="plain"
1379 />
1380 </View>
1381 ) : !result.isPending && !result.error && !seekingFile ? (
1382 <EmptyState
1383 title="Diff unavailable"
1384 detail={`Open this ${terminology.singular} on its provider to view the changes.`}
1385 variant="plain"
1386 />
1387 ) : null}
1388 {result.nextCursor && result.isPending && data.rows.length && !seekingFile ? (
1389 <View className="flex-row items-center justify-center gap-2 py-2">
1390 <AppActivityIndicator size="small" />
1391 <Text className="text-xs text-foreground-muted">Loading more files…</Text>
1392 </View>
1393 ) : null}
1394 {result.error && result.nextCursor ? (
1395 <View className="self-center">
1396 <Button label="Retry loading remaining files" tone="text" onPress={result.refresh} />
1397 </View>
1398 ) : null}
1399 {parsed.kind === "files" && parsed.notice ? (
1400 <Text className="px-4 py-2 text-2xs text-foreground-muted">{parsed.notice}</Text>
1401 ) : null}
1402 </View>
1403 </ScreenContent>
1404 <PullRequestActionToolbar
1405 pr={detail.data}
1406 params={route.params}
1407 filePath={visibleFile?.path}
1408 onOpenFiles={() => navigation.navigate("PullRequestFiles", route.params)}
1409 onHeightChange={setToolbarHeight}
1410 />
1411 </View>
1412 );