Open History to see the last commit
1import { pullRequestTabOffset } from "./pullRequestTabScroll";
2import { guideFocusedRows, type GuideDiffFocus } from "./guide/guideDiffFocus";
3import { PullRequestGuideContent } from "./guide/PullRequestGuideScreen";
4import { useReviewGuidesEnabled } from "./guide/useReviewGuide";
5import {
6 filterPullRequestActivity,
7 DEFAULT_ACTIVITY_FILTER,
8 type ActivityFilter,
9} from "./pullRequestActivityFilter";
10import { PullRequestActivityFilters } from "./PullRequestActivityFilters";
11import type { LegendListRef } from "@legendapp/list/react-native";
12import { AnimatedLegendList } from "@legendapp/list/reanimated";
13import Animated from "react-native-reanimated";
14import {
15 PR_ROW_LAYOUT,
16 PR_ROW_ENTER,
17 PR_ROW_EXIT,
18 PR_POSITION_LAYOUT,
19} from "./pullRequestAnimations";
20import { openOnProviderLabel } from "./pullRequestActions";
21import * as Clipboard from "expo-clipboard";
22import { ControlPillMenu } from "../../components/ControlPillMenu";
23import { MaterialIconButton } from "../../components/MaterialIconButton";
24import { MaterialButton } from "../../components/MaterialButton";
25import { usePullRequestReviewDraft } from "./usePullRequestReviewDraft";
26import { usePullRequestFilesViewed } from "./usePullRequestFilesViewed";
27import { usePullRequestPermissions } from "./usePullRequestPermissions";
28import { annotatePullRequestDiff, reviewPosition } from "./pullRequestDiffComments";
29import { usePullRequestFileFilter } from "./usePullRequestFileFilter";
30import { isPullRequestTestFile } from "./pullRequestFileFilters";
31import {
32 StackActions,
33 useFocusEffect,
34 useNavigation,
35 useRoute,
36 type StaticScreenProps,
37} from "@react-navigation/native";
38import { useAtomRefresh } from "@effect/atom-react";
39import { pullRequestReviewKey } from "./pullRequestReviewDrafts";
40import { type PullRequestDetail, type PullRequestListEntry } from "@t3tools/contracts";
41import { PullRequestOverviewLoading } from "./PullRequestOverviewLoading";
42import { pullRequestStatus } from "./pullRequestStatus";
43import { useCallback, useEffect, useMemo, useRef, useState } from "react";
44import {
45 ActivityIndicator,
46 Linking,
47 Platform,
48 Pressable,
49 RefreshControl,
50 ScrollView,
51 type ScrollViewProps,
52 StyleSheet,
53 View,
54} from "react-native";
55import { NativeScrollViewMarker as ScrollViewMarker } from "../../native/NativeScrollViewMarker";
56import { useSafeAreaInsets } from "react-native-safe-area-context";
57
58import { AppText as Text } from "../../components/AppText";
59import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
60import { useAndroidControlSizing } from "../../components/useAndroidControlSizing";
61import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
62import { AndroidWorkspaceSidebarButton } from "../layout/workspace-sidebar-toolbar";
63import { useAndroidWorkspaceBack } from "../workspace/useAndroidWorkspaceNavigation";
64import { EmptyState } from "../../components/EmptyState";
65import { SegmentedControl } from "../../components/SegmentedControl";
66import { SymbolView } from "../../components/AppSymbol";
67import { relativeTime } from "../../lib/time";
68import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
69import { usePullRequestConnected } from "./usePullRequestConnected";
70import { composerPullRequests } from "../../state/pull-requests";
71import { useEnvironmentQuery } from "../../state/query";
72import { usePullToRefresh } from "../../state/use-pull-to-refresh";
73import {
74 isNativeReviewDiffDrawEvent,
75 resolveNativeReviewDiffView,
76 type NativeReviewDiffViewHandle,
77 type NativeReviewDiffViewProps,
78} from "../diffs/nativeReviewDiffSurface";
79import {
80 buildNativeReviewDiffData,
81 NATIVE_REVIEW_DIFF_CONTENT_WIDTH,
82} from "../review/nativeReviewDiffAdapter";
83import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
84import { useAppearanceCodeSurface } from "../settings/appearance/useAppearanceCodeSurface";
85import { useNativeReviewDiffBridge } from "../review/useNativeReviewDiffBridge";
86import { pullRequestTimelineRows } from "./PullRequestTimeline";
87import { PullRequestActionToolbar, PullRequestCardGroup } from "./PullRequestControls";
88import {
89 pullRequestTarget as requestTarget,
90 usePullRequestDiff,
91 type PullRequestDiffParams,
92 type PullRequestParams,
93} from "./usePullRequestDiff";
94import {
95 PullRequestAvatar,
96 PullRequestDiffStats,
97 PullRequestReadStatus,
98} from "./PullRequestPresentation";
99import { PullRequestFiles, usePullRequestFilesContent } from "./PullRequestFiles";
100import { PullRequestSheetContent } from "./PullRequestSheetContent";
101import { PullRequestDescription } from "./PullRequestDescription";
102import { PullRequestMarkdownRepository } from "./PullRequestMarkdown";
103import {
104 PullRequestStatusMenu,
105 PullRequestChecksRow,
106 PullRequestBranchRow,
107 PullRequestReviewersRow,
108} from "./PullRequestStatusRows";
109import { PullRequestMergeControls } from "./PullRequestMergeControls";
110import { PullRequestStackCard } from "./PullRequestStackCard";
111import { usePullRequestStack, type PullRequestStackState } from "./usePullRequestStack";
112
113const EMPTY_IDS: readonly string[] = [];
114
115function PullRequestTabScrollView(props: ScrollViewProps) {
116 const insets = useSafeAreaInsets();
117 return (
118 <ScrollViewMarker style={{ flex: 1 }}>
119 <ScrollView
120 {...props}
121 automaticallyAdjustContentInsets={false}
122 contentInsetAdjustmentBehavior="never"
123 contentOffset={props.contentOffset ?? { x: 0, y: -insets.top }}
124 />
125 </ScrollViewMarker>
126 );
127}
128
129function usePullRequestActivityRows(params: PullRequestParams, filter: ActivityFilter) {
130 const navigation = useNavigation();
131 const result = useEnvironmentQuery(composerPullRequests.activity(requestTarget(params)));
132 const filtered = useMemo(
133 () => (result.data ? filterPullRequestActivity(result.data, filter) : null),
134 [result.data, filter],
135 );
136 const rows = useMemo(() => {
137 if (!filtered) return [];
138 const rows = pullRequestTimelineRows(filtered.activity, params, navigation);
139 if (filter.newestFirst) {
140 const notice = rows.at(-1)?.key === "truncated" ? rows.pop() : undefined;
141 rows.reverse();
142 if (notice) rows.push(notice);
143 }
144 if (!rows.length)
145 rows.push({
146 key: "empty",
147 date: "",
148 content: (
149 <Text className="py-6 text-sm text-foreground-muted">
150 No activity matches these filters.
151 </Text>
152 ),
153 });
154 return rows;
155 }, [filtered, filter.newestFirst, params, navigation]);
156 return {
157 rows,
158 hiddenCount: filtered?.hiddenCount ?? 0,
159 pending: result.isPending,
160 error: result.error,
161 };
162}
163
164function PullRequestIdentity(props: {
165 readonly pr: PullRequestDetail | PullRequestListEntry;
166 readonly params: PullRequestParams;
167}) {
168 const { pr } = props;
169 const status = pullRequestStatus(pr);
170 return (
171 <View className="gap-3">
172 <View className="flex-row flex-wrap items-center gap-2">
173 {"capabilities" in pr ? (
174 <PullRequestStatusMenu pr={pr} params={props.params} />
175 ) : (
176 <View className="min-h-8 flex-row items-center gap-1.5">
177 <SymbolView name={status.icon} size={14} tintColorClassName={status.tint} />
178 <Text className={`text-xs font-t3-medium ${status.text}`}>{status.label}</Text>
179 </View>
180 )}
181 <PullRequestDiffStats additions={pr.additions} deletions={pr.deletions} compact />
182 {"changedFiles" in pr ? (
183 <Text className="text-2xs text-foreground-muted">
184 {pr.changedFiles} {pr.changedFiles === 1 ? "file" : "files"}
185 </Text>
186 ) : (
187 <View className="h-3 w-12 rounded bg-subtle-strong" />
188 )}
189 </View>
190 <Text selectable className="text-xl font-t3-bold leading-7">
191 {pr.title}
192 </Text>
193 <View className="flex-row items-center gap-2">
194 <PullRequestAvatar actor={pr.author} size={20} />
195 <Text className="min-w-0 flex-1 text-xs font-t3-medium" numberOfLines={1}>
196 {pr.author?.login ?? "Unknown author"}
197 </Text>
198 <Text className="shrink text-right text-2xs text-foreground-muted" numberOfLines={1}>
199 Updated {relativeTime(pr.updatedAt)} ago
200 </Text>
201 </View>
202 <View className="flex-row items-start gap-1.5">
203 <Pressable
204 accessibilityRole="button"
205 accessibilityLabel={`Copy base branch ${pr.baseBranch}`}
206 onPress={() => void Clipboard.setStringAsync(pr.baseBranch)}
207 className="min-w-0 shrink active:opacity-70"
208 hitSlop={8}
209 >
210 <Text className="font-mono text-2xs text-foreground-muted">{pr.baseBranch}</Text>
211 </Pressable>
212 <View className="pt-0.5">
213 <SymbolView name="arrow.left" size={11} tintColorClassName="accent-icon-muted" />
214 </View>
215 <Pressable
216 accessibilityRole="button"
217 accessibilityLabel={`Copy head branch ${pr.headBranch}`}
218 onPress={() => void Clipboard.setStringAsync(pr.headBranch)}
219 className="min-w-0 shrink active:opacity-70"
220 hitSlop={8}
221 >
222 <Text className="font-mono text-2xs text-foreground-muted">{pr.headBranch}</Text>
223 </Pressable>
224 </View>
225 </View>
226 );
227}
228
229function PullRequestOverview(props: {
230 readonly pr: PullRequestDetail;
231 readonly params: PullRequestParams;
232 readonly stack: PullRequestStackState;
233 readonly onDescriptionLayout: (y: number) => void;
234 readonly onDescriptionCollapse: () => void;
235 readonly descriptionExpanded: boolean;
236 readonly onDescriptionExpandedChange: (expanded: boolean) => void;
237}) {
238 const { pr } = props;
239 return (
240 <View className="gap-5">
241 <PullRequestStackCard params={props.params} state={props.stack} />
242 <PullRequestCardGroup>
243 <PullRequestChecksRow pr={pr} params={props.params} />
244 <PullRequestReviewersRow pr={pr} params={props.params} />
245 <Animated.View layout={PR_ROW_LAYOUT}>
246 <PullRequestBranchRow pr={pr} params={props.params} />
247 </Animated.View>
248 <Animated.View layout={PR_ROW_LAYOUT}>
249 <PullRequestMergeControls pr={pr} params={props.params} stack={props.stack} />
250 </Animated.View>
251 </PullRequestCardGroup>
252 {pr.labels.length ? (
253 <Animated.View layout={PR_ROW_LAYOUT} className="flex-row flex-wrap gap-2">
254 {pr.labels.map((label) => (
255 <View key={label.name} className="rounded-full bg-grouped-card px-3 py-1">
256 <Text className="text-2xs text-foreground-muted">{label.name}</Text>
257 </View>
258 ))}
259 </Animated.View>
260 ) : null}
261 <Animated.View
262 layout={PR_POSITION_LAYOUT}
263 onLayout={(event) => props.onDescriptionLayout(event.nativeEvent.layout.y)}
264 >
265 <PullRequestDescription
266 markdown={pr.body}
267 onCollapse={props.onDescriptionCollapse}
268 expanded={props.descriptionExpanded}
269 onExpandedChange={props.onDescriptionExpandedChange}
270 />
271 </Animated.View>
272 </View>
273 );
274}
275
276function usePullRequestToolbarHeight(bottomInset: number) {
277 const { buttonSize } = useAndroidControlSizing();
278 // Reserve the controls, native toolbar padding, and outer gaps before onLayout measures them.
279 return useState(() => (Platform.OS === "android" ? bottomInset + buttonSize + 40 : 0));
280}
281
282export function PullRequestRouteScreen({ route }: StaticScreenProps<PullRequestParams>) {
283 const returnToList = useAndroidWorkspaceBack("pullRequests");
284 const { layout } = useAdaptiveWorkspaceLayout();
285 const navigation = useNavigation();
286 const insets = useSafeAreaInsets();
287 const [toolbarHeight, setToolbarHeight] = usePullRequestToolbarHeight(insets.bottom);
288 const params = route.params;
289 const connected = usePullRequestConnected(params.environmentId);
290 const [section, setSection] = useState<"overview" | "activity" | "guide">("overview");
291 // Keep each tab's native list and measured rows alive when it is hidden.
292 const requestedSection = useRef(section);
293 const [listAnimationsReady, setListAnimationsReady] = useState(false);
294 const [descriptionExpanded, setDescriptionExpanded] = useState(false);
295 const filesContent = usePullRequestFilesContent({ params });
296 const guidesEnabled = useReviewGuidesEnabled(params);
297 const [activityFilter, setActivityFilter] = useState<ActivityFilter>(DEFAULT_ACTIVITY_FILTER);
298 const activityContent = usePullRequestActivityRows(params, activityFilter);
299 const scrollOffsets = useRef<Record<string, number>>({});
300 const currentScrollOffset = useRef(-insets.top);
301 const bodyY = useRef(0);
302 const [headerHeight, setHeaderHeight] = useState(0);
303 const [viewportHeight, setViewportHeight] = useState(0);
304 const scrollViews = useRef<Partial<Record<typeof section, LegendListRef | null>>>({});
305 const selectSection = (next: typeof section) => {
306 if (next === section) return;
307 scrollOffsets.current[section] = currentScrollOffset.current;
308 const headerEnd = Math.max(-insets.top, bodyY.current - insets.top);
309 // The shared header stays in place. Once collapsed, retain each tab's own reading position.
310 const offset = pullRequestTabOffset(
311 currentScrollOffset.current,
312 scrollOffsets.current[next],
313 headerEnd,
314 );
315 requestedSection.current = next;
316 scrollOffsets.current[next] = offset;
317 currentScrollOffset.current = offset;
318 scrollViews.current[next]?.scrollToOffset({ offset, animated: false });
319 setSection(next);
320 };
321 useEffect(() => {
322 if (!guidesEnabled && section === "guide") {
323 requestedSection.current = "overview";
324 currentScrollOffset.current = scrollOffsets.current.overview ?? -insets.top;
325 setSection("overview");
326 }
327 }, [guidesEnabled, section, insets.top]);
328 const tabContent = activityContent;
329 const filesY = useRef(0);
330 const descriptionY = useRef(0);
331 const pendingDescriptionJump = useRef(false);
332 const pendingFilesJump = useRef(false);
333 const detailAtom = composerPullRequests.detail(requestTarget(params));
334 const result = useEnvironmentQuery(detailAtom);
335 const pullRefresh = usePullToRefresh(detailAtom);
336 const { refresh: refreshDetail } = result;
337 useFocusEffect(useCallback(() => refreshDetail(), [refreshDetail]));
338 const pr = result.data;
339 const summary = params.initialSummary;
340 const identity = pr ?? summary;
341 const permissions = usePullRequestPermissions(params, pr);
342 const stack = usePullRequestStack(params, pr);
343 const refreshActivity = useAtomRefresh(composerPullRequests.activity(requestTarget(params)));
344 const refreshGuide = useAtomRefresh(composerPullRequests.reviewGuide(requestTarget(params)));
345 const refresh = () => {
346 pullRefresh.onRefresh();
347 if (guidesEnabled) refreshGuide();
348 stack.refresh();
349 refreshActivity();
350 filesContent.refresh();
351 };
352 const jumpToFiles = () => {
353 scrollViews.current.overview?.scrollToOffset({
354 offset: bodyY.current + filesY.current - insets.top,
355 animated: true,
356 });
357 pendingFilesJump.current = false;
358 };
359 const openFiles = () => {
360 if (section === "overview") jumpToFiles();
361 else {
362 pendingFilesJump.current = true;
363 selectSection("overview");
364 if (filesY.current > 0) requestAnimationFrame(jumpToFiles);
365 }
366 };
367 return (
368 <PullRequestMarkdownRepository
369 params={params}
370 value={pr?.provider === "github" ? pr.url : null}
371 >
372 <View className={Platform.OS === "android" ? "flex-1 bg-header" : "flex-1 bg-screen"}>
373 <NativeStackScreenOptions
374 options={{
375 title: `#${params.number}`,
376 headerTitle: `#${params.number}`,
377 unstable_headerSubtitle: connected
378 ? params.repository
379 : `${params.repository} · Offline`,
380 }}
381 />
382 {Platform.OS === "android" ? (
383 <AndroidScreenHeader
384 title={`#${params.number}${connected ? "" : " · Offline"}`}
385 subtitle={params.repository}
386 onBack={layout.usesSplitView ? undefined : returnToList}
387 leading={layout.usesSplitView ? <AndroidWorkspaceSidebarButton /> : undefined}
388 actions={[
389 ...(permissions.verdicts.length
390 ? [
391 {
392 accessibilityLabel: "Submit review",
393 icon: "text.bubble" as const,
394 onPress: () =>
395 navigation.navigate("PullRequestReview", { ...params, mode: "review" }),
396 },
397 ]
398 : []),
399 ...(permissions.canComment
400 ? [
401 {
402 accessibilityLabel: "Add comment",
403 icon: "plus.bubble" as const,
404 onPress: () =>
405 navigation.navigate("PullRequestReview", { ...params, mode: "comment" }),
406 },
407 ]
408 : []),
409 ...(pr
410 ? [
411 {
412 accessibilityLabel: openOnProviderLabel(pr.provider),
413 icon: "arrow.up.right" as const,
414 onPress: () => void Linking.openURL(pr.url),
415 },
416 ]
417 : []),
418 ]}
419 />
420 ) : null}
421 <NativeHeaderToolbar placement="right">
422 <NativeHeaderToolbar.Menu
423 title="Pull request"
424 accessibilityLabel="Pull request actions"
425 icon="ellipsis"
426 >
427 {permissions.verdicts.length ? (
428 <NativeHeaderToolbar.MenuAction
429 icon="text.bubble"
430 onPress={() =>
431 navigation.navigate("PullRequestReview", { ...params, mode: "review" })
432 }
433 >
434 <NativeHeaderToolbar.Label>Submit review</NativeHeaderToolbar.Label>
435 </NativeHeaderToolbar.MenuAction>
436 ) : null}
437 {permissions.canComment ? (
438 <NativeHeaderToolbar.MenuAction
439 icon="plus.bubble"
440 onPress={() =>
441 navigation.navigate("PullRequestReview", { ...params, mode: "comment" })
442 }
443 >
444 <NativeHeaderToolbar.Label>Add comment</NativeHeaderToolbar.Label>
445 </NativeHeaderToolbar.MenuAction>
446 ) : null}
447 {pr ? (
448 <NativeHeaderToolbar.MenuAction
449 icon="arrow.up.right"
450 onPress={() => void Linking.openURL(pr.url)}
451 >
452 <NativeHeaderToolbar.Label>
453 {openOnProviderLabel(pr.provider)}
454 </NativeHeaderToolbar.Label>
455 </NativeHeaderToolbar.MenuAction>
456 ) : null}
457 </NativeHeaderToolbar.Menu>
458 </NativeHeaderToolbar>
459 <View
460 style={{
461 flex: 1,
462 marginHorizontal: Platform.OS === "android" && layout.usesSplitView ? 4 : 0,
463 }}
464 className={
465 Platform.OS === "android"
466 ? "overflow-hidden rounded-t-[28px] bg-sheet-solid"
467 : undefined
468 }
469 onLayout={(event) => setViewportHeight(event.nativeEvent.layout.height)}
470 >
471 {(["overview", "guide", "activity"] as const)
472 .filter((tab) => tab !== "guide" || guidesEnabled)
473 .map((tab) => (
474 <View
475 key={tab}
476 style={[StyleSheet.absoluteFill, { opacity: section === tab ? 1 : 0 }]}
477 pointerEvents={section === tab ? "auto" : "none"}
478 accessibilityElementsHidden={section !== tab}
479 importantForAccessibility={section === tab ? "auto" : "no-hide-descendants"}
480 >
481 <AnimatedLegendList
482 ref={(list) => {
483 scrollViews.current[tab] = list;
484 }}
485 initialScrollOffset={-insets.top}
486 onScroll={(event) => {
487 const offset = event.nativeEvent.contentOffset.y;
488 scrollOffsets.current[tab] = offset;
489 if (requestedSection.current === tab) currentScrollOffset.current = offset;
490 }}
491 className="flex-1"
492 renderScrollComponent={
493 Platform.OS === "ios" ? PullRequestTabScrollView : undefined
494 }
495 contentInsetAdjustmentBehavior="never"
496 contentInset={
497 Platform.OS === "ios" ? { top: insets.top, bottom: insets.bottom } : undefined
498 }
499 contentInsetStartAdjustment={Platform.OS === "ios" ? insets.top : 0}
500 refreshControl={
501 <RefreshControl
502 refreshing={section === tab && pullRefresh.refreshing}
503 onRefresh={refresh}
504 />
505 }
506 alwaysBounceVertical
507 scrollsToTop={section === tab}
508 onContentSizeChange={() => {
509 if (
510 tab !== "overview" ||
511 section !== "overview" ||
512 !pendingDescriptionJump.current
513 )
514 return;
515 pendingDescriptionJump.current = false;
516 // Collapse changes the scroll range; restore the heading after that layout commits.
517 scrollViews.current.overview?.scrollToOffset({
518 offset: bodyY.current + descriptionY.current - insets.top,
519 animated: false,
520 });
521 }}
522 contentContainerStyle={{
523 paddingHorizontal: 16,
524 paddingTop: 8,
525 paddingBottom: 24 + (Platform.OS === "android" ? toolbarHeight : 0),
526 // Short tabs must still be tall enough to preserve the collapsed header.
527 minHeight: Math.max(
528 0,
529 viewportHeight + headerHeight - insets.top - insets.bottom,
530 ),
531 }}
532 data={[
533 {
534 key: `${tab}:body`,
535 content: (
536 <View>
537 {tab === "overview" && identity ? (
538 <View>
539 {pr ? (
540 <PullRequestOverview
541 pr={pr}
542 params={params}
543 stack={stack}
544 descriptionExpanded={descriptionExpanded}
545 onDescriptionExpandedChange={setDescriptionExpanded}
546 onDescriptionLayout={(y) => {
547 descriptionY.current = y;
548 }}
549 onDescriptionCollapse={() => {
550 pendingDescriptionJump.current = true;
551 }}
552 />
553 ) : summary ? (
554 <PullRequestOverviewLoading
555 summary={summary}
556 params={params}
557 stack={stack}
558 />
559 ) : null}
560 <View
561 className="mt-8 border-t border-border-subtle pt-3"
562 onLayout={(event) => {
563 filesY.current = event.nativeEvent.layout.y;
564 if (pendingFilesJump.current) {
565 requestAnimationFrame(() => {
566 if (requestedSection.current === "overview") jumpToFiles();
567 });
568 }
569 }}
570 >
571 {filesContent.header}
572 </View>
573 </View>
574 ) : null}
575 {tab === "guide" ? <PullRequestGuideContent params={params} /> : null}
576 {tab === "activity" ? (
577 <PullRequestActivityFilters
578 value={activityFilter}
579 onChange={setActivityFilter}
580 hiddenCount={tabContent.hiddenCount}
581 />
582 ) : null}
583 {tab === "activity" ? (
584 <PullRequestReadStatus
585 pending={tabContent.pending}
586 error={tabContent.error}
587 />
588 ) : null}
589 </View>
590 ),
591 },
592 ...(tab === "overview"
593 ? identity
594 ? filesContent.rows
595 : []
596 : tab === "activity"
597 ? tabContent.rows
598 : []
599 ).map((row) => ({
600 ...row,
601 key: `${tab}:${row.key}`,
602 content: row.content,
603 })),
604 ]}
605 keyExtractor={(row) => row.key}
606 getItemType={(row) =>
607 row.key.endsWith(":body") ? row.key : row.key.split(":")[0]
608 }
609 // The overview body contains the clipped description and owns collapse scroll
610 // correction. Animating that cell fights both; file rows still fade individually.
611 itemLayoutAnimation={tab === "overview" ? undefined : PR_ROW_LAYOUT}
612 onLoad={() => setListAnimationsReady(true)}
613 renderItem={({ item }) => (
614 <Animated.View
615 key={item.key}
616 entering={
617 listAnimationsReady && !item.key.endsWith(":body")
618 ? PR_ROW_ENTER
619 : undefined
620 }
621 exiting={
622 listAnimationsReady && !item.key.endsWith(":body") ? PR_ROW_EXIT : undefined
623 }
624 >
625 {item.content}
626 </Animated.View>
627 )}
628 recycleItems={false}
629 estimatedItemSize={tab === "overview" ? 64 : 220}
630 maintainVisibleContentPosition={false}
631 ListHeaderComponent={
632 <>
633 <PullRequestReadStatus
634 pending={result.isPending && !identity}
635 error={result.error}
636 />
637 {identity ? (
638 <View
639 className="gap-5 pb-5"
640 onLayout={(event) => {
641 bodyY.current = event.nativeEvent.layout.height;
642 setHeaderHeight(event.nativeEvent.layout.height);
643 }}
644 >
645 <PullRequestIdentity pr={identity} params={params} />
646 <SegmentedControl
647 className={Platform.OS === "android" ? undefined : "bg-grouped-card"}
648 options={[
649 { value: "overview", label: "Overview" },
650 ...(guidesEnabled
651 ? [{ value: "guide" as const, label: "Guide" }]
652 : []),
653 { value: "activity", label: "Activity" },
654 ]}
655 selected={section}
656 onSelect={selectSection}
657 role="tab"
658 size="compact"
659 />
660 </View>
661 ) : null}
662 </>
663 }
664 ListFooterComponent={tab === "overview" ? filesContent.footer : null}
665 />
666 </View>
667 ))}
668 </View>
669 <PullRequestActionToolbar
670 pr={pr}
671 params={params}
672 onOpenFiles={openFiles}
673 onHeightChange={setToolbarHeight}
674 />
675 </View>
676 </PullRequestMarkdownRepository>
677 );
678}
679
680export function PullRequestFilesRouteScreen({ route }: StaticScreenProps<PullRequestDiffParams>) {
681 const navigation = useNavigation();
682 const fileSelectionId = useRoute().key;
683 return (
684 <PullRequestSheetContent
685 title="Changed files"
686 scrollable={false}
687 subtitle={`#${route.params.number}${route.params.commit ? ` · ${route.params.commit.slice(0, 7)}` : ` · ${route.params.repository}`}`}
688 >
689 <PullRequestFiles
690 params={route.params}
691 groupByDirectory
692 onSelectFile={(path) =>
693 navigation.dispatch(
694 StackActions.popTo("PullRequestFile", {
695 ...route.params,
696 path,
697 fileSelectionId,
698 }),
699 )
700 }
701 />
702 </PullRequestSheetContent>
703 );
704}
705
706export function PullRequestFileRouteScreen({
707 route,
708}: StaticScreenProps<
709 PullRequestDiffParams & {
710 readonly path: string;
711 readonly fileSelectionId?: string;
712 readonly replacingDraftId?: string;
713 readonly focus?: GuideDiffFocus;
714 }
715>) {
716 const { layout } = useAdaptiveWorkspaceLayout();
717 const navigation = useNavigation();
718 const insets = useSafeAreaInsets();
719 const [toolbarHeight, setToolbarHeight] = usePullRequestToolbarHeight(insets.bottom);
720 const commit = route.params.commit;
721 const result = usePullRequestDiff(route.params);
722 const filter = usePullRequestFileFilter(
723 result.parsed,
724 route.params.focus ? route.params.path : undefined,
725 );
726 const detail = useEnvironmentQuery(composerPullRequests.detail(requestTarget(route.params)));
727 const { refresh: refreshDetail } = detail;
728 useFocusEffect(useCallback(() => refreshDetail(), [refreshDetail]));
729 const { loadMore } = result;
730 const parsed = filter.parsed;
731 const reviewDraft = usePullRequestReviewDraft(route.params);
732 const viewed = usePullRequestFilesViewed(route.params, commit ? null : detail.data);
733 const [commitViewedPaths, setCommitViewedPaths] = useState<ReadonlySet<string>>(() => new Set());
734 const permissions = usePullRequestPermissions(route.params, detail.data);
735 const scopeKey = pullRequestReviewKey(route.params);
736 const [diffHead, setDiffHead] = useState({ scopeKey, sha: detail.data?.headSha ?? null });
737 if (diffHead.scopeKey !== scopeKey || (!diffHead.sha && detail.data?.headSha))
738 setDiffHead({ scopeKey, sha: detail.data?.headSha ?? null });
739 const staleDiff = Boolean(
740 !commit && diffHead.sha && detail.data?.headSha && diffHead.sha !== detail.data.headSha,
741 );
742 const canCommentOnDiff =
743 permissions.canInlineComment &&
744 !commit &&
745 !staleDiff &&
746 !detail.isPending &&
747 !result.isPending &&
748 !result.error;
749 const activity = useEnvironmentQuery(composerPullRequests.activity(requestTarget(route.params)));
750 const baseData = useMemo(() => buildNativeReviewDiffData(parsed), [parsed]);
751 const data = useMemo(
752 () =>
753 annotatePullRequestDiff(
754 baseData,
755 staleDiff || commit ? [] : (activity.data?.reviewThreads ?? []),
756 commit ? [] : reviewDraft.draft.comments,
757 diffHead.sha ?? undefined,
758 ),
759 [baseData, activity.data, reviewDraft.draft.comments, diffHead.sha, staleDiff, commit],
760 );
761 const viewedIds = data.files
762 .filter((file) => (commit ? commitViewedPaths.has(file.path) : viewed.isViewed(file.path)))
763 .map((file) => file.id);
764 const [selectedRowId, setSelectedRowId] = useState<string | null>(null);
765 const selectedRow = data.rows.find((row) => row.id === selectedRowId);
766 const selectedFile = data.files.find((file) => file.id === selectedRow?.fileId);
767 const commentOnLine = (rowId = selectedRowId) => {
768 const row = data.rows.find((row) => row.id === rowId);
769 const file = data.files.find((file) => file.id === row?.fileId);
770 if (!row || !file || !diffHead.sha || !canCommentOnDiff) return;
771 const position = reviewPosition(row);
772 if (!position) return;
773 const oldPath =
774 parsed.kind === "files"
775 ? parsed.files.find((entry) => entry.id === file.id)?.previousPath
776 : null;
777 if (route.params.replacingDraftId) navigation.setParams({ replacingDraftId: undefined });
778 navigation.navigate("PullRequestInlineComment", {
779 ...route.params,
780 ...(route.params.replacingDraftId ? { draftId: route.params.replacingDraftId } : {}),
781 path: file.path,
782 ...(oldPath ? { oldPath } : {}),
783 position,
784 headSha: diffHead.sha,
785 code: row.content ?? "",
786 });
787 };
788 const [jumpPath, setJumpPath] = useState(route.params.path);
789 const requestedFile =
790 result.parsed.kind === "files"
791 ? result.parsed.files.find((file) => file.path === jumpPath)
792 : undefined;
793 const targetFile =
794 data.files.find((file) => file.path === jumpPath) ??
795 (!jumpPath || requestedFile ? data.files[0] : undefined);
796 const focus = route.params.focus;
797 const focusedRows = guideFocusedRows(data.rows, targetFile?.id, focus);
798 const focusIndex = focusedRows.length
799 ? data.rows.findIndex((row) => row.id === focusedRows[0]?.id)
800 : -1;
801 const [collapsedIds, setCollapsedIds] = useState<readonly string[]>(EMPTY_IDS);
802 const [visibleFileId, setVisibleFileId] = useState<string | null>(null);
803 const nativeView = useRef<NativeReviewDiffViewHandle>(null);
804 const jumpStarted = useRef(false);
805 const lastSelection = useRef({ path: route.params.path, id: route.params.fileSelectionId });
806 // Each sheet selection jumps in this reader, including reselecting its original file.
807 useEffect(() => {
808 if (
809 lastSelection.current.path === route.params.path &&
810 lastSelection.current.id === route.params.fileSelectionId
811 )
812 return;
813 lastSelection.current = { path: route.params.path, id: route.params.fileSelectionId };
814 if (route.params.focus) navigation.setParams({ focus: undefined });
815 setJumpPath(route.params.path);
816 setSelectedRowId(null);
817 jumpStarted.current = false;
818 const file = data.files.find((entry) => entry.path === route.params.path);
819 if (!file || !nativeView.current) return;
820 setCollapsedIds((ids) => ids.filter((id) => id !== file.id));
821 jumpStarted.current = true;
822 void nativeView.current.scrollToFile(file.id, false).catch(() => {
823 jumpStarted.current = false;
824 });
825 }, [route.params.path, route.params.fileSelectionId, route.params.focus, data.files, navigation]);
826 const appliedFilter = useRef(filter.hideTestFiles);
827 useEffect(() => {
828 if (appliedFilter.current === filter.hideTestFiles) return;
829 appliedFilter.current = filter.hideTestFiles;
830 if (
831 result.parsed.kind === "files" &&
832 result.parsed.files.some((file) => isPullRequestTestFile(file.path))
833 ) {
834 jumpStarted.current = false;
835 }
836 }, [filter.hideTestFiles, result.parsed]);
837 const { nativeReviewDiffStyle } = useAppearanceCodeSurface();
838 const { themeAppearance, appearance, setCodeWordBreak } = useAppearancePreferences();
839 const bridge = useNativeReviewDiffBridge({
840 threadKey: null,
841 sectionId: `pull-request:${route.params.repository}:${route.params.number}:${commit ?? "all"}`,
842 diff: result.patch,
843 data,
844 collapsedFileIds: collapsedIds,
845 viewedFileIds: viewedIds,
846 selectedRowIds: selectedRowId ? [selectedRowId] : focusedRows.map((row) => row.id),
847 canHighlight: true,
848 });
849 const [NativeDiffView] = useState(() => resolveNativeReviewDiffView());
850 // A file picked from a later page must be fetched before we can jump to its header.
851 useEffect(() => {
852 if (!targetFile) loadMore();
853 }, [targetFile, loadMore]);
854 const { onDebug: updateVisibleRange } = bridge;
855 const onDebug = useCallback<NonNullable<NativeReviewDiffViewProps["onDebug"]>>(
856 (event) => {
857 const drawn = isNativeReviewDiffDrawEvent(event.nativeEvent);
858 const decoded =
859 event.nativeEvent.message === "rows-decoded" && event.nativeEvent.rows === data.rows.length;
860 if (!drawn && !decoded) return;
861 // Filtering replaces the native row payload asynchronously. Old draw events
862 // must not consume the file jump or highlight the new payload's row indices.
863 if (
864 typeof event.nativeEvent.totalRows === "number" &&
865 event.nativeEvent.totalRows !== data.rows.length
866 )
867 return;
868 if (drawn) updateVisibleRange(event);
869 if (
870 targetFile &&
871 !jumpStarted.current &&
872 nativeView.current &&
873 (Platform.OS !== "ios" || decoded)
874 ) {
875 jumpStarted.current = true;
876 if (focusIndex >= 0) return;
877 void nativeView.current.scrollToFile(targetFile.id, false).catch(() => {
878 jumpStarted.current = false;
879 });
880 return;
881 }
882 if (!drawn) return;
883 const lastRow = event.nativeEvent.lastRowIndex;
884 if (typeof lastRow === "number" && lastRow >= data.rows.length - 40) loadMore();
885 },
886 [updateVisibleRange, data.rows.length, loadMore, targetFile, focusIndex],
887 );
888 const onToggleFile = useCallback<NonNullable<NativeReviewDiffViewProps["onToggleFile"]>>(
889 (event) => {
890 const id = event.nativeEvent.fileId;
891 if (!id) return;
892 setCollapsedIds((ids) =>
893 ids.includes(id) ? ids.filter((value) => value !== id) : [...ids, id],
894 );
895 },
896 [],
897 );
898 const visibleFile = data.files.find((file) => file.id === visibleFileId) ?? targetFile;
899 const toggleTestFiles = () => {
900 setJumpPath(visibleFile?.path ?? route.params.path);
901 setSelectedRowId(null);
902 filter.toggle();
903 };
904 const title = commit ? "Commit changes" : "Changes";
905 const seekingFile = !targetFile && result.nextCursor !== null;
906 const loadingDiff = (result.isPending && !data.rows.length) || (seekingFile && !result.error);
907 return (
908 <View className={Platform.OS === "android" ? "flex-1 bg-header" : "flex-1 bg-screen"}>
909 <NativeStackScreenOptions
910 options={{
911 title,
912 headerTitle: title,
913 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` : ""}`,
914 }}
915 />
916 {Platform.OS === "android" ? (
917 <AndroidScreenHeader
918 title={title}
919 onBack={() => navigation.goBack()}
920 trailing={
921 <ControlPillMenu
922 actions={[
923 {
924 id: "word-wrap",
925 title: "Word wrap",
926 image: "text.alignleft",
927 state: appearance.codeWordBreak ? "on" : "off",
928 },
929 {
930 id: "hide-tests",
931 title: "Hide test files",
932 image: "line.3.horizontal.decrease",
933 state: filter.hideTestFiles ? "on" : "off",
934 },
935 ...(permissions.verdicts.length
936 ? [{ id: "submit-review", title: "Submit review", image: "text.bubble" }]
937 : []),
938 ...(permissions.canComment
939 ? [{ id: "comment-on-pr", title: "Add comment", image: "plus.bubble" }]
940 : []),
941 ...(selectedRow && selectedFile
942 ? [
943 ...(canCommentOnDiff ? [{ id: "comment", title: "Add review comment" }] : []),
944 { id: "copy", title: "Copy line" },
945 ]
946 : []),
947 ]}
948 onPressAction={({ nativeEvent }) => {
949 if (nativeEvent.event === "word-wrap") setCodeWordBreak(!appearance.codeWordBreak);
950 else if (nativeEvent.event === "hide-tests") toggleTestFiles();
951 else if (
952 nativeEvent.event === "submit-review" ||
953 nativeEvent.event === "comment-on-pr"
954 )
955 navigation.navigate("PullRequestReview", {
956 ...route.params,
957 mode: nativeEvent.event === "submit-review" ? "review" : "comment",
958 });
959 else if (nativeEvent.event === "comment") commentOnLine();
960 else void Clipboard.setStringAsync(selectedRow?.content ?? "");
961 }}
962 >
963 <View pointerEvents="none">
964 <MaterialIconButton icon="ellipsis" accessibilityLabel="Diff options" />
965 </View>
966 </ControlPillMenu>
967 }
968 />
969 ) : null}
970 <NativeHeaderToolbar placement="right">
971 <NativeHeaderToolbar.Menu
972 title="Diff options"
973 accessibilityLabel="Diff options"
974 icon="ellipsis"
975 >
976 {permissions.verdicts.length ? (
977 <NativeHeaderToolbar.MenuAction
978 icon="text.bubble"
979 onPress={() =>
980 navigation.navigate("PullRequestReview", { ...route.params, mode: "review" })
981 }
982 >
983 <NativeHeaderToolbar.Label>Submit review</NativeHeaderToolbar.Label>
984 </NativeHeaderToolbar.MenuAction>
985 ) : null}
986 {permissions.canComment ? (
987 <NativeHeaderToolbar.MenuAction
988 icon="plus.bubble"
989 onPress={() =>
990 navigation.navigate("PullRequestReview", { ...route.params, mode: "comment" })
991 }
992 >
993 <NativeHeaderToolbar.Label>Add comment</NativeHeaderToolbar.Label>
994 </NativeHeaderToolbar.MenuAction>
995 ) : null}
996 <NativeHeaderToolbar.MenuAction
997 icon="text.alignleft"
998 isOn={appearance.codeWordBreak}
999 onPress={() => setCodeWordBreak(!appearance.codeWordBreak)}
1000 >
1001 <NativeHeaderToolbar.Label>Word wrap</NativeHeaderToolbar.Label>
1002 </NativeHeaderToolbar.MenuAction>
1003 <NativeHeaderToolbar.MenuAction
1004 icon="line.3.horizontal.decrease"
1005 isOn={filter.hideTestFiles}
1006 onPress={toggleTestFiles}
1007 >
1008 <NativeHeaderToolbar.Label>Hide test files</NativeHeaderToolbar.Label>
1009 </NativeHeaderToolbar.MenuAction>
1010 {selectedRow && selectedFile && canCommentOnDiff ? (
1011 <NativeHeaderToolbar.MenuAction icon="bubble.left" onPress={() => commentOnLine()}>
1012 <NativeHeaderToolbar.Label>
1013 {route.params.replacingDraftId ? "Move draft to this line" : "Add review comment"}
1014 </NativeHeaderToolbar.Label>
1015 </NativeHeaderToolbar.MenuAction>
1016 ) : null}
1017 {selectedRow && selectedFile ? (
1018 <NativeHeaderToolbar.MenuAction
1019 icon="document.on.document"
1020 onPress={() => void Clipboard.setStringAsync(selectedRow.content ?? "")}
1021 >
1022 <NativeHeaderToolbar.Label>Copy line</NativeHeaderToolbar.Label>
1023 </NativeHeaderToolbar.MenuAction>
1024 ) : null}
1025 </NativeHeaderToolbar.Menu>
1026 </NativeHeaderToolbar>
1027 {route.params.replacingDraftId ? (
1028 <Text className="px-4 py-2 text-xs text-foreground-muted">
1029 Select a current line, then choose “Move draft to this line” from its menu.
1030 </Text>
1031 ) : null}
1032 {viewed.error ? (
1033 <Text className="px-4 py-2 text-xs text-danger-foreground">{viewed.error}</Text>
1034 ) : null}
1035 {staleDiff ? (
1036 <View
1037 className="flex-row items-center gap-2 px-4 py-2"
1038 style={{ paddingTop: Platform.OS === "ios" ? insets.top + 8 : 8 }}
1039 >
1040 <Text className="min-w-0 flex-1 text-xs text-foreground-muted">
1041 The branch changed. Reload before adding line comments.
1042 </Text>
1043 <MaterialButton
1044 label="Reload changes"
1045 onPress={() => {
1046 result.refresh();
1047 setDiffHead({ scopeKey, sha: detail.data?.headSha ?? null });
1048 jumpStarted.current = false;
1049 setSelectedRowId(null);
1050 setCollapsedIds(EMPTY_IDS);
1051 }}
1052 />
1053 </View>
1054 ) : null}
1055 <View
1056 className={
1057 Platform.OS === "android"
1058 ? "flex-1 overflow-hidden rounded-t-[28px] bg-sheet-solid"
1059 : "flex-1"
1060 }
1061 collapsable={false}
1062 style={{ marginHorizontal: Platform.OS === "android" && layout.usesSplitView ? 4 : 0 }}
1063 >
1064 {loadingDiff || result.error ? (
1065 <View style={{ paddingTop: Platform.OS === "ios" && !staleDiff ? insets.top : 0 }}>
1066 <PullRequestReadStatus pending={loadingDiff} error={result.error} />
1067 </View>
1068 ) : null}
1069 {NativeDiffView && data.rows.length && !seekingFile ? (
1070 <View className="flex-1" collapsable={false}>
1071 <NativeDiffView
1072 initialRowIndex={focusIndex >= 0 ? Math.max(0, focusIndex - 3) : undefined}
1073 nativeViewRef={nativeView}
1074 refreshing={result.refreshing}
1075 onPullToRefresh={result.onPullRefresh}
1076 style={StyleSheet.absoluteFill}
1077 rowsJson={bridge.rowsJson}
1078 themeJson={bridge.themeJson}
1079 styleJson={bridge.styleJson}
1080 tokensPatchJson={bridge.tokensPatchJson}
1081 tokensResetKey={bridge.tokensResetKey}
1082 collapsedFileIdsJson={bridge.collapsedFileIdsJson}
1083 onDebug={onDebug}
1084 viewedFileIdsJson={bridge.viewedFileIdsJson}
1085 selectedRowIdsJson={bridge.selectedRowIdsJson}
1086 onPressLine={(event) => {
1087 const rowId = event.nativeEvent.rowId ?? null;
1088 setSelectedRowId(rowId);
1089 if (event.nativeEvent.gesture !== "longPress") commentOnLine(rowId);
1090 }}
1091 onToggleViewedFile={(event) => {
1092 const file = data.files.find((file) => file.id === event.nativeEvent.fileId);
1093 if (!file || (!commit && !viewed.canToggle)) return;
1094 const wasViewed = commit
1095 ? commitViewedPaths.has(file.path)
1096 : viewed.isViewed(file.path);
1097 setCollapsedIds((ids) =>
1098 wasViewed
1099 ? ids.filter((id) => id !== file.id)
1100 : ids.includes(file.id)
1101 ? ids
1102 : [...ids, file.id],
1103 );
1104 if (commit)
1105 setCommitViewedPaths((current) => {
1106 const next = new Set(current);
1107 if (next.has(file.path)) next.delete(file.path);
1108 else next.add(file.path);
1109 return next;
1110 });
1111 else void viewed.toggle(file.path);
1112 }}
1113 onToggleComment={(event) => {
1114 const id = event.nativeEvent.commentId;
1115 if (id?.startsWith("discussion:"))
1116 navigation.navigate("PullRequestDiscussion", {
1117 ...route.params,
1118 discussionId: id.slice("discussion:".length),
1119 });
1120 if (id?.startsWith("draft:")) {
1121 const draft = reviewDraft.draft.comments.find(
1122 (draft) => draft.id === id.slice("draft:".length),
1123 );
1124 if (draft)
1125 navigation.navigate("PullRequestInlineComment", {
1126 ...route.params,
1127 ...draft,
1128 draftId: draft.id,
1129 });
1130 }
1131 }}
1132 onToggleFile={onToggleFile}
1133 onVisibleFileChange={(event) => setVisibleFileId(event.nativeEvent.fileId ?? null)}
1134 appearanceScheme={themeAppearance}
1135 rowHeight={nativeReviewDiffStyle.rowHeight}
1136 contentWidth={NATIVE_REVIEW_DIFF_CONTENT_WIDTH}
1137 contentInsetTop={Platform.OS === "ios" ? (staleDiff ? 0 : insets.top) : undefined}
1138 contentInsetBottom={Platform.OS === "android" ? toolbarHeight : insets.bottom}
1139 contentResetKey={`pull-request:${route.params.environmentId}:${route.params.repository}:${route.params.number}:${commit ?? "all"}`}
1140 />
1141 </View>
1142 ) : filter.hiddenCount > 0 &&
1143 !data.rows.length &&
1144 !result.isPending &&
1145 !result.error &&
1146 !seekingFile ? (
1147 <View style={{ paddingTop: Platform.OS === "ios" ? insets.top : 0 }}>
1148 <EmptyState
1149 title="Only test files changed"
1150 detail="Test files are hidden from this review."
1151 action={
1152 <MaterialButton label="Show test files" tone="contrast" onPress={filter.showAll} />
1153 }
1154 variant="plain"
1155 />
1156 </View>
1157 ) : !result.isPending && !result.error && !seekingFile ? (
1158 <EmptyState
1159 title="Diff unavailable"
1160 detail="Open this pull request on its provider to view the changes."
1161 variant="plain"
1162 />
1163 ) : null}
1164 {result.nextCursor && result.isPending && data.rows.length && !seekingFile ? (
1165 <View className="flex-row items-center justify-center gap-2 py-2">
1166 <ActivityIndicator size="small" />
1167 <Text className="text-xs text-foreground-muted">Loading more files…</Text>
1168 </View>
1169 ) : null}
1170 {result.error && result.nextCursor ? (
1171 <Pressable
1172 accessibilityRole="button"
1173 onPress={result.refresh}
1174 className="min-h-11 items-center justify-center py-2"
1175 >
1176 <Text className="text-sm font-t3-medium">Retry loading remaining files</Text>
1177 </Pressable>
1178 ) : null}
1179 {parsed.kind === "files" && parsed.notice ? (
1180 <Text className="px-4 py-2 text-2xs text-foreground-muted">{parsed.notice}</Text>
1181 ) : null}
1182 </View>
1183 <PullRequestActionToolbar
1184 pr={detail.data}
1185 params={route.params}
1186 filePath={visibleFile?.path}
1187 onOpenFiles={() => navigation.navigate("PullRequestFiles", route.params)}
1188 onHeightChange={setToolbarHeight}
1189 />
1190 </View>
1191 );
1192}