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

PullRequestRouteScreen.tsx

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