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