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

ReviewSheet.tsx

879 lines32.5 KB

1import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
2import { AsyncResult } from "effect/reactivity";
3import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
4import { formatDiffCount } from "@t3tools/client-runtime/diff-count";
5import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
6import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
7import { nativeHeaderScrollEdgeEffects } from "../../native/StackHeader";
8import { AppBar } from "../../components/ui/AppBar";
9import type { AppBarMenuItem } from "../../components/ui/AppBar.types";
10import type { ReviewSectionItem } from "./reviewModel";
11import { useReviewHeaderPresentation } from "./useReviewHeaderPresentation";
12import { Screen, ScreenStack, ScreenStackHeaderConfig } from "react-native-screens";
13import { type Ref, type ReactElement, useImperativeHandle, useRef, useState } from "react";
14import {
15 FlatList,
16 Platform,
17 Pressable,
18 RefreshControl,
19 ScrollView,
20 type NativeSyntheticEvent,
21 StyleSheet,
22 View,
23} from "react-native";
24import { useSafeAreaInsets } from "react-native-safe-area-context";
25import { useReduceMotionEnabled } from "../../lib/appState";
26import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
27import { NativeInspectorContent } from "../../native/NativeInspectorContent";
28​
29import { AppText as Text } from "../../components/ui/AppText";
30import { SymbolView } from "../../components/ui/AppSymbol";
31import { AndroidScreenHeader } from "../../components/ui/AndroidScreenHeader";
32import { ScreenContent } from "../../components/ui/ScreenContent";
33import { cn } from "../../lib/cn";
34import { environmentCatalog } from "../../connection/catalog";
35import { useEnvironmentPresentation } from "../../state/presentation";
36import { useAtomCommand } from "../../state/use-atom-command";
37import { useUniwindTheme } from "../../lib/useUniwindTheme";
38import { useThreadDraftForThread } from "../../state/use-thread-composer-state";
39import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice";
40import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
41import {
42 useAdaptiveWorkspaceLayout,
43 useAdaptiveWorkspacePaneRole,
44 useRegisterWorkspaceInspector,
45} from "../layout/AdaptiveWorkspaceLayout";
46import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
47import { useReviewCacheForThread } from "./reviewState";
48import {
49 isNativeReviewDiffDrawEvent,
50 type NativeReviewDiffViewHandle,
51 resolveNativeReviewDiffView,
52} from "../diffs/nativeReviewDiffSurface";
53import { NATIVE_REVIEW_DIFF_CONTENT_WIDTH } from "./nativeReviewDiffAdapter";
54import { useAppearanceCodeSurface } from "../settings/appearance/useAppearanceCodeSurface";
55import { useReviewDiffData } from "./useReviewDiffData";
56import { useReviewDiffPrewarming } from "./useReviewDiffPrewarming";
57import { useReviewFileVisibility } from "./reviewFileVisibility";
58import { useReviewSections } from "./useReviewSections";
59import { useNativeReviewDiffBridge } from "./useNativeReviewDiffBridge";
60import { useReviewCommentSelectionController } from "./useReviewCommentSelectionController";
61import { resolveReviewAvailability } from "./reviewAvailability";
62import { resolveSelectedReviewFileId } from "./reviewPaneSelection";
63import { buildReviewSectionMenu } from "./review-section-menu";
64import { reportShowcaseSceneRendered } from "../showcase/showcaseRenderSignal";
65import { useSelectWorkspaceDetail } from "../workspace/useSelectWorkspaceDetail";
66​
67function ReviewHeader(
68 props: Parameters<typeof useReviewHeaderPresentation>[0] & {
69 readonly iconColor: string;
70 readonly sectionMenu: ReturnType<typeof buildReviewSectionMenu>;
71 readonly showSectionToolbar: boolean;
72 readonly showChangedFilesToggle: boolean;
73 readonly onSelectSection: (sectionId: string) => void;
74 readonly onReturnToThread: () => void;
75 },
76) {
77 const { panes, toggleAuxiliaryPane } = useAdaptiveWorkspaceLayout();
78 const presentation = useReviewHeaderPresentation(props);
79 const sectionAction = (section: ReviewSectionItem | null, title: string): AppBarMenuItem => ({
80 id: section ? `section:${section.id}` : `unavailable:${title}`,
81 title,
82 disabled: section === null,
83 selected: section !== null && section.id === props.selectedSection?.id,
84 onPress: () => {
85 if (section) props.onSelectSection(section.id);
86 },
87 });
88 return (
89 <AppBar
90 title={presentation.title}
91 subtitle={presentation.subtitle}
92 onBack={props.onReturnToThread}
93 hideBottomBorder
94 options={{ headerTintColor: props.iconColor, headerTitle: props.title }}
95 backInSplitView={{ accessibilityLabel: "Back to chat", icon: "chevron.left" }}
96 actions={
97 props.showChangedFilesToggle
98 ? [
99 {
100 accessibilityLabel: panes.auxiliaryPaneVisible
101 ? "Hide changed files"
102 : "Show changed files",
103 icon: "sidebar.right",
104 selected: panes.auxiliaryPaneVisible,
105 onPress: toggleAuxiliaryPane,
106 },
107 ]
108 : undefined
109 }
110 menus={[
111 ...(presentation.gitMenu ? [presentation.gitMenu] : []),
112 ...(props.showSectionToolbar
113 ? [
114 {
115 title: "Select diff",
116 icon: presentation.menuIcon,
117 items: [
118 {
119 id: "sections",
120 inline: true,
121 items: [
122 sectionAction(props.sectionMenu.branchChanges, "Changes"),
123 sectionAction(props.sectionMenu.workingTree, "Uncommitted"),
124 sectionAction(props.sectionMenu.latestTurn, "Latest turn"),
125 ],
126 },
127 ...(props.sectionMenu.turns.length > 0
128 ? [
129 {
130 id: "turns",
131 title: "Turn",
132 items: props.sectionMenu.turns.map((section) => ({
133 id: `section:${section.id}`,
134 title: section.title,
135 subtitle: section.subtitle ?? undefined,
136 selected: section.id === props.selectedSection?.id,
137 onPress: () => props.onSelectSection(section.id),
138 })),
139 },
140 ]
141 : []),
142 ...(presentation.refreshAction ? [presentation.refreshAction] : []),
143 ],
144 },
145 ]
146 : []),
147 ]}
148 />
149 );
151​
152const SHOWCASE_ENABLED = process.env.EXPO_PUBLIC_SHOWCASE === "1";
153​
154const ReviewNotice = function ReviewNotice(props: { readonly notice: string }) {
155 return (
156 <View
157 className={cn(
158 "bg-warning px-4 py-3",
159 Platform.OS === "android" ? "m-2 rounded-[20px]" : "border-b border-warning-border",
160 )}
161 >
162 <Text className="text-xs font-t3-bold uppercase text-warning-foreground">Partial diff</Text>
163 <Text className="text-xs leading-normal text-warning-foreground">{props.notice}</Text>
164 </View>
165 );
166};
167​
168function ReviewSelectionActionBar(props: {
169 readonly bottomInset: number;
170 readonly title: string | null;
171 readonly onOpenComment: (() => void) | null;
172 readonly onClear: () => void;
173}) {
174 if (!props.title) {
175 return null;
176 }
177​
178 const content = (
179 <>
180 <SymbolView
181 name={props.onOpenComment ? "text.bubble" : "line.3.horizontal.decrease.circle"}
182 size={16}
183 tintColorClassName="accent-primary-foreground"
184 type="monochrome"
185 />
186 <Text className="text-base font-t3-bold text-primary-foreground">{props.title}</Text>
187 </>
188 );
189​
190 return (
191 <View
192 pointerEvents="box-none"
193 style={{
194 position: "absolute",
195 left: 18,
196 right: 18,
197 bottom: Math.max(props.bottomInset, 10) + 18,
198 flexDirection: "row",
199 justifyContent: "center",
200 gap: 10,
201 }}
202 >
203 {props.onOpenComment ? (
204 <Pressable
205 className="h-12 flex-1 flex-row items-center justify-center gap-2 rounded-full bg-primary px-5"
206 onPress={props.onOpenComment}
207 >
208 {content}
209 </Pressable>
210 ) : (
211 <View className="h-12 flex-1 flex-row items-center justify-center gap-2 rounded-full bg-primary px-5">
212 {content}
213 </View>
214 )}
215​
216 <Pressable
217 className="h-12 w-12 items-center justify-center rounded-full bg-primary"
218 onPress={props.onClear}
219 >
220 <SymbolView
221 name="xmark"
222 size={16}
223 tintColorClassName="accent-primary-foreground"
224 type="monochrome"
225 />
226 </Pressable>
227 </View>
228 );
230​
231interface ReviewNavigatorFile {
232 readonly id: string;
233 readonly path: string;
234 readonly additions: number;
235 readonly deletions: number;
237​
238const ReviewFileNavigatorRow = function ReviewFileNavigatorRow(props: {
239 readonly file: ReviewNavigatorFile;
240 readonly selected: boolean;
241 readonly onSelectFile: (fileId: string | null) => void;
242}) {
243 const { file, selected, onSelectFile } = props;
244 const handlePress = () => {
245 onSelectFile(selected ? null : file.id);
246 };
247​
248 return (
249 <Pressable
250 accessibilityRole="button"
251 accessibilityState={{ selected }}
252 className={
253 Platform.OS === "android"
254 ? cn(
255 "mt-1 min-h-12 justify-center rounded-[20px] px-3 py-2 active:bg-subtle",
256 selected && "bg-subtle-strong",
257 )
258 : selected
259 ? "mt-1 min-h-12 justify-center rounded-xl bg-subtle-strong px-3 py-2"
260 : "mt-1 min-h-12 justify-center rounded-xl px-3 py-2 active:bg-subtle"
261 }
262 onPress={handlePress}
263 >
264 <Text
265 className={
266 selected
267 ? "text-xs font-t3-bold text-foreground"
268 : "text-xs font-t3-medium text-foreground-secondary"
269 }
270 numberOfLines={2}
271 >
272 {file.path}
273 </Text>
274 <View className="mt-1 flex-row gap-2">
275 <Text className="text-2xs font-t3-bold text-adaptive-emerald-700-300">
276 +{formatDiffCount(file.additions)}
277 </Text>
278 <Text className="text-2xs font-t3-bold text-adaptive-rose-700-300">
279 -{formatDiffCount(file.deletions)}
280 </Text>
281 </View>
282 </Pressable>
283 );
284};
285​
286interface ReviewFileNavigatorHandle {
287 readonly setVisibleFile: (fileId: string | null) => void;
289​
290interface ReviewFileNavigatorProps {
291 readonly files: ReadonlyArray<ReviewNavigatorFile>;
292 readonly headerInset: number;
293 readonly sectionId: string | null;
294 readonly onSelectFile: (fileId: string | null) => void;
295 readonly ref?: Ref<ReviewFileNavigatorHandle>;
297​
298function ReviewFileNavigator({
299 files,
300 headerInset,
301 sectionId,
302 onSelectFile,
303 ref,
304}: ReviewFileNavigatorProps) {
305 const theme = useUniwindTheme();
306 const sheetColor = theme["--color-sheet"];
307 const foregroundColor = theme["--color-foreground"];
308 const headerScrollEdgeEffects = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
309 const [fileSelection, setFileSelection] = useState<{
310 readonly sectionId: string | null;
311 readonly fileId: string | null;
312 }>({ sectionId: null, fileId: null });
313 const availableFileIds = files.map((file) => file.id);
314 const selectedFileId = resolveSelectedReviewFileId({
315 selection: fileSelection,
316 sectionId,
317 availableFileIds,
318 });
319​
320 useImperativeHandle(
321 ref,
322 () => ({
323 setVisibleFile: (fileId) => {
324 if (fileId !== null && !availableFileIds.includes(fileId)) {
325 return;
326 }
327 setFileSelection((current) => {
328 if (current.sectionId === sectionId && current.fileId === fileId) {
329 return current;
330 }
331 return { sectionId, fileId };
332 });
333 },
334 }),
335 [availableFileIds, sectionId],
336 );
337​
338 const handleSelectFile = (fileId: string | null) => {
339 setFileSelection({ sectionId, fileId });
340 onSelectFile(fileId);
341 };
342​
343 const renderFile = ({ item }: { readonly item: ReviewNavigatorFile }) => (
344 <ReviewFileNavigatorRow
345 file={item}
346 selected={selectedFileId === item.id}
347 onSelectFile={handleSelectFile}
348 />
349 );
350​
351 const fileList = (
352 <FlatList
353 data={files}
354 extraData={selectedFileId}
355 keyExtractor={(file) => file.id}
356 contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
357 contentContainerStyle={{ paddingHorizontal: 8, paddingVertical: 8 }}
358 renderItem={renderFile}
359 />
360 );
361​
362 if (Platform.OS === "ios") {
363 return (
364 <View className="flex-1 border-l border-border bg-sheet">
365 <ScreenStack style={{ flex: 1 }}>
366 <Screen
367 activityState={2}
368 enabled
369 isNativeStack
370 screenId="review-file-navigator-native"
371 scrollEdgeEffects={headerScrollEdgeEffects}
372 style={{ backgroundColor: sheetColor, flex: 1 }}
373 >
374 <NativeInspectorContent>{fileList}</NativeInspectorContent>
375 <ScreenStackHeaderConfig
376 backgroundColor="rgba(0,0,0,0)"
377 color={foregroundColor}
378 hideBackButton
379 hideShadow={false}
380 navigationItemStyle="editor"
381 subtitle={`${files.length} ${files.length === 1 ? "file" : "files"}`}
382 title="Changed files"
383 titleColor={foregroundColor}
384 titleFontSize={17}
385 titleFontWeight="700"
386 translucent
387 />
388 </Screen>
389 </ScreenStack>
390 </View>
391 );
392 }
393​
394 return (
395 <View
396 className={
397 Platform.OS === "android" ? "flex-1 bg-header" : "flex-1 border-l border-border bg-sheet"
398 }
399 >
400 {Platform.OS === "android" ? (
401 <AndroidScreenHeader
402 title="Changed files"
403 subtitle={`${files.length} ${files.length === 1 ? "file" : "files"}`}
404 hideBottomBorder
405 />
406 ) : (
407 <View className="border-b border-border" style={{ paddingTop: headerInset }}>
408 <View className="px-4 py-3">
409 <Text className="text-sm font-t3-bold text-foreground">Changed files</Text>
410 <Text className="text-xs text-foreground-muted">
411 {files.length} {files.length === 1 ? "file" : "files"}
412 </Text>
413 </View>
414 </View>
415 )}
416 <ScreenContent insetHorizontal>{fileList}</ScreenContent>
417 </View>
418 );
420​
421type ReviewSheetProps = StaticScreenProps<{
422 readonly environmentId: EnvironmentId;
423 readonly threadId: ThreadId;
424}>;
425​
426export function ReviewSheet(props: ReviewSheetProps) {
427 const reduceMotion = useReduceMotionEnabled();
428 const { nativeReviewDiffStyle } = useAppearanceCodeSurface();
429 useAdaptiveWorkspacePaneRole("inspector");
430 const { panes } = useAdaptiveWorkspaceLayout();
431 const navigation = useNavigation();
432 const selectDetail = useSelectWorkspaceDetail();
433 const insets = useSafeAreaInsets();
434 const { themeAppearance: selectedTheme } = useAppearancePreferences();
435 const headerIcon = String(useUniwindTheme()["--color-icon"]);
436 const { environmentId, threadId } = props.route.params;
437 const environment = useEnvironmentPresentation(environmentId);
438 const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, "environment retry");
439 const isEnvironmentReady = environment.presentation?.connection.phase === "connected";
440 const { draftMessage, draftContext } = useThreadDraftForThread({ environmentId, threadId });
441 const reviewCache = useReviewCacheForThread({ environmentId, threadId });
442 const { selectedThreadCwd } = useSelectedThreadWorktree();
443 const columnMetrics = useNativeColumnLayoutMetrics();
444 const safeArea = columnMetrics?.safeArea ?? insets;
445 const topContentInset = Platform.OS === "ios" ? safeArea.top : 0;
446 const bottomContentInset =
447 Platform.OS === "ios" ? safeArea.bottom + 8 : Math.max(insets.bottom, 18) + 18;
448​
449 const {
450 error,
451 reviewSections,
452 selectedSection,
453 refreshSelectedSection,
454 selectSection,
455 isSelectedSectionPending,
456 } = useReviewSections({
457 enabled: isEnvironmentReady,
458 environmentId,
459 threadId,
460 reviewCache,
461 });
462 useReviewDiffPrewarming({
463 threadKey: reviewCache.threadKey,
464 sections: reviewSections,
465 selectedSectionId: selectedSection?.id ?? null,
466 });
467 const {
468 headerDiffSummary,
469 nativeReviewDiffData,
470 parsedDiff,
471 pendingReviewCommentCount,
472 loadVisibleFile,
473 isPending: areFilePatchesPending,
474 } = useReviewDiffData({
475 threadKey: reviewCache.threadKey,
476 environmentId,
477 cwd: selectedThreadCwd,
478 selectedSection,
479 draftMessage,
480 draftContext,
481 });
482 // Expo may return null before registration or in older binaries; use the fallback.
483 const NativeReviewDiffView = resolveNativeReviewDiffView();
484 const nativeReviewDiffViewRef = useRef<NativeReviewDiffViewHandle>(null);
485 const showcasedReviewDrawRef = useRef<string | null>(null);
486 const [isPullRefreshing, setIsPullRefreshing] = useState(false);
487 const handlePullToRefresh = async () => {
488 setIsPullRefreshing(true);
489 await refreshSelectedSection();
490 setIsPullRefreshing(false);
491 };
492 const isRefreshing = isPullRefreshing || isSelectedSectionPending || areFilePatchesPending;
493 // A refresh that starts programmatically adds its height to the native top inset and
494 // subtracts it when it ends. If topContentInset changes in between, the inset ends up
495 // short and the content sits under the header, so the fallback ScrollView starts over.
496 const [fallbackInset, setFallbackInset] = useState(topContentInset);
497 const [fallbackScrollViewKey, setFallbackScrollViewKey] = useState(0);
498 if (fallbackInset !== topContentInset) {
499 setFallbackInset(topContentInset);
500 if (isRefreshing) setFallbackScrollViewKey((key) => key + 1);
501 }
502 const reviewFileNavigatorRef = useRef<ReviewFileNavigatorHandle>(null);
503 const reviewFiles = parsedDiff.kind === "files" ? parsedDiff.files : [];
504 const fileVisibility = useReviewFileVisibility({
505 threadKey: reviewCache.threadKey,
506 sectionId: selectedSection?.id ?? null,
507 files: reviewFiles,
508 cachedExpandedFileIds: selectedSection?.id
509 ? reviewCache.expandedFileIdsBySection[selectedSection.id]
510 : undefined,
511 cachedViewedFileIds: selectedSection?.id
512 ? reviewCache.viewedFileIdsBySection[selectedSection.id]
513 : undefined,
514 });
515 const { collapsedFileIds, toggleExpandedFile, toggleViewedFile, viewedFileIds } = fileVisibility;
516 const commentSelection = useReviewCommentSelectionController({
517 environmentId,
518 threadId,
519 selectedSection,
520 nativeReviewDiffData,
521 });
522 const nativeBridge = useNativeReviewDiffBridge({
523 threadKey: reviewCache.threadKey,
524 sectionId: selectedSection?.id ?? null,
525 diff: selectedSection?.diff,
526 data: nativeReviewDiffData,
527 collapsedFileIds,
528 viewedFileIds,
529 selectedRowIds: commentSelection.selectedRowIds,
530 canHighlight: parsedDiff.kind === "files",
531 });
532 const showcaseReviewKey =
533 SHOWCASE_ENABLED && parsedDiff.kind === "files" && selectedSection
534 ? `${reviewCache.threadKey}:${selectedSection.id}:${nativeBridge.tokensResetKey}:${nativeBridge.themeId}`
535 : null;
536 const handleNativeDebug = (event: NativeSyntheticEvent<Record<string, unknown>>) => {
537 nativeBridge.onDebug(event);
538 if (
539 showcaseReviewKey === null ||
540 showcasedReviewDrawRef.current === showcaseReviewKey ||
541 !isNativeReviewDiffDrawEvent(event.nativeEvent)
542 ) {
543 return;
544 }
545 showcasedReviewDrawRef.current = showcaseReviewKey;
546 reportShowcaseSceneRendered({ scene: "review", themeId: nativeBridge.themeId });
547 };
548​
549 const handleSelectFile = async (fileId: string | null) => {
550 loadVisibleFile(fileId, true);
551 commentSelection.clearSelection();
552 if (fileId !== null && collapsedFileIds.includes(fileId)) {
553 toggleExpandedFile(fileId);
554 }
555 const nativeView = nativeReviewDiffViewRef.current;
556 if (!nativeView) return;
557 const result = await settlePromise(() =>
558 fileId === null
559 ? nativeView.scrollToTop(!reduceMotion)
560 : nativeView.scrollToFile(fileId, !reduceMotion),
561 );
562 if (AsyncResult.isFailure(result)) {
563 console.error("[review] Failed to navigate to diff file", squashAtomCommandFailure(result));
564 }
565 };
566 const handleVisibleFileChange = (
567 event: NativeSyntheticEvent<{ readonly fileId?: string | null }>,
568 ) => {
569 loadVisibleFile(event.nativeEvent.fileId ?? null);
570 reviewFileNavigatorRef.current?.setVisibleFile(event.nativeEvent.fileId ?? null);
571 };
572 const renderInspector = () => (
573 <ReviewFileNavigator
574 ref={reviewFileNavigatorRef}
575 files={nativeReviewDiffData.files}
576 headerInset={insets.top}
577 sectionId={selectedSection?.id ?? null}
578 onSelectFile={(fileId) => void handleSelectFile(fileId)}
579 />
580 );
581​
582 const handleNativeToggleFile = (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => {
583 const { fileId } = event.nativeEvent;
584 if (fileId) {
585 loadVisibleFile(fileId, true);
586 toggleExpandedFile(fileId);
587 }
588 };
589​
590 const handleNativeToggleViewedFile = (
591 event: NativeSyntheticEvent<{ readonly fileId?: string }>,
592 ) => {
593 const { fileId } = event.nativeEvent;
594 if (fileId) {
595 toggleViewedFile(fileId);
596 }
597 };
598​
599 const parsedDiffNotice =
600 parsedDiff.kind === "files" || parsedDiff.kind === "raw" ? parsedDiff.notice : null;
601 const hasCachedSelectedDiff = selectedSection?.diff != null;
602 const hasAnyCachedDiff = reviewSections.some((section) => section.diff != null);
603 const sectionMenu = buildReviewSectionMenu(reviewSections);
604 const { showConnectionNotice, showSectionToolbar } = resolveReviewAvailability({
605 hasEnvironmentPresentation: environment.isReady,
606 isEnvironmentConnected: isEnvironmentReady,
607 hasCachedSelectedDiff,
608 hasAnyCachedDiff,
609 });
610 const handleRetryEnvironment = () => {
611 void retryEnvironment(environmentId);
612 };
613 const handleReturnToThread = () => {
614 if (navigation.canGoBack()) {
615 navigation.goBack();
616 return;
617 }
618 selectDetail({
619 name: "Thread",
620 params: { environmentId: String(environmentId), threadId: String(threadId) },
621 });
622 };
623 const androidHeaderSubtitle = [
624 selectedSection?.title,
625 headerDiffSummary.additions,
626 headerDiffSummary.deletions,
627 ]
628 .filter((part): part is string => Boolean(part))
629 .join(" · ");
630​
631 const showChangedFilesPane =
632 !showConnectionNotice &&
633 selectedSection !== null &&
634 parsedDiff.kind === "files" &&
635 NativeReviewDiffView !== null;
636 useRegisterWorkspaceInspector(showChangedFilesPane ? renderInspector : undefined);
637 const showChangedFilesToggle = panes.supportsAuxiliaryPane && showChangedFilesPane;
638​
639 const listHeader = (() => {
640 const children: ReactElement[] = [];
641​
642 if (error) {
643 children.push(
644 <View
645 key="review-error"
646 className={cn(
647 "bg-card px-4 py-3",
648 Platform.OS === "android" ? "m-2 rounded-[20px]" : "border-b border-border",
649 )}
650 >
651 <Text className="text-sm font-t3-bold text-foreground">Review unavailable</Text>
652 <Text className="text-xs leading-normal text-foreground-muted">{error}</Text>
653 </View>,
654 );
655 }
656​
657 if (parsedDiffNotice) {
658 children.push(<ReviewNotice key="review-notice" notice={parsedDiffNotice} />);
659 }
660​
661 if (children.length === 0) {
662 return null;
663 }
664​
665 return <>{children}</>;
666 })();
667 const headerSubtitle = [
668 headerDiffSummary.additions,
669 headerDiffSummary.deletions,
670 pendingReviewCommentCount > 0
671 ? `${pendingReviewCommentCount} comment${pendingReviewCommentCount === 1 ? "" : "s"}`
672 : null,
673 ]
674 .filter(Boolean)
675 .join(" · ");
676 const headerTitleText = selectedSection?.title ?? "Review changes";
677​
678 return (
679 <>
680 <ReviewHeader
681 environmentId={environmentId}
682 threadId={threadId}
683 title={headerTitleText}
684 subtitle={headerSubtitle}
685 androidSubtitle={androidHeaderSubtitle}
686 iconColor={headerIcon}
687 selectedThreadCwd={selectedThreadCwd}
688 sectionMenu={sectionMenu}
689 selectedSection={selectedSection}
690 showSectionToolbar={showSectionToolbar}
691 showChangedFilesToggle={showChangedFilesToggle}
692 onRefresh={handlePullToRefresh}
693 onSelectSection={selectSection}
694 onReturnToThread={handleReturnToThread}
695 />
696​
697 <ScreenContent>
698 <View className="flex-1 bg-sheet android:bg-sheet-solid">
699 {showConnectionNotice ? (
700 <View className="flex-1" style={{ paddingTop: topContentInset }}>
701 <EnvironmentConnectionNotice
702 environmentLabel={environment.presentation?.entry.target.label ?? "Environment"}
703 connection={
704 environment.presentation?.connection ?? {
705 phase: "available",
706 error: null,
707 traceId: null,
708 }
709 }
710 resourceName="review"
711 onRetry={handleRetryEnvironment}
712 />
713 </View>
714 ) : selectedSection && parsedDiff.kind === "files" && NativeReviewDiffView ? (
715 <View
716 className="flex-1"
717 style={{
718 backgroundColor: nativeBridge.theme.background,
719 }}
720 >
721 <View
722 className="min-w-0 flex-1"
723 style={listHeader ? { paddingTop: topContentInset } : undefined}
724 >
725 {listHeader}
726 <View className="min-w-0 flex-1" collapsable={false}>
727 {/* oxlint-disable-next-line react/static-components -- The resolver returns a cached native component with stable identity. */}
728 <NativeReviewDiffView
729 collapsable={false}
730 testID="review-native-diff-view"
731 refreshing={
732 isPullRefreshing || isSelectedSectionPending || areFilePatchesPending
733 }
734 onPullToRefresh={() => void handlePullToRefresh()}
735 style={StyleSheet.absoluteFill}
736 appearanceScheme={selectedTheme}
737 collapsedFileIdsJson={nativeBridge.collapsedFileIdsJson}
738 collapsedCommentIdsJson={nativeBridge.collapsedCommentIdsJson}
739 contentResetKey={`${reviewCache.threadKey}:${selectedSection.id}`}
740 contentWidth={NATIVE_REVIEW_DIFF_CONTENT_WIDTH}
741 contentInsetTop={listHeader ? 0 : topContentInset}
742 contentInsetBottom={bottomContentInset}
743 nativeViewRef={nativeReviewDiffViewRef}
744 rowHeight={nativeReviewDiffStyle.rowHeight}
745 rowsJson={nativeBridge.rowsJson}
746 selectedRowIdsJson={nativeBridge.selectedRowIdsJson}
747 styleJson={nativeBridge.styleJson}
748 themeJson={nativeBridge.themeJson}
749 tokensPatchJson={nativeBridge.tokensPatchJson}
750 tokensResetKey={nativeBridge.tokensResetKey}
751 viewedFileIdsJson={nativeBridge.viewedFileIdsJson}
752 onDebug={handleNativeDebug}
753 onPressLine={commentSelection.onPressLine}
754 onVisibleFileChange={handleVisibleFileChange}
755 onToggleComment={nativeBridge.onToggleComment}
756 onToggleFile={handleNativeToggleFile}
757 onToggleViewedFile={handleNativeToggleViewedFile}
758 />
759 </View>
760 </View>
761 </View>
762 ) : (
763 <ScrollView
764 key={fallbackScrollViewKey}
765 contentContainerStyle={
766 Platform.OS === "android" && (parsedDiff.kind === "empty" || !selectedSection)
767 ? { flexGrow: 1, justifyContent: "center" }
768 : undefined
769 }
770 contentInsetAdjustmentBehavior="never"
771 contentInset={{ top: topContentInset, bottom: bottomContentInset }}
772 contentOffset={{ x: 0, y: -topContentInset }}
773 automaticallyAdjustsScrollIndicatorInsets={false}
774 scrollIndicatorInsets={{ top: topContentInset, bottom: bottomContentInset }}
775 showsVerticalScrollIndicator={false}
776 className="flex-1"
777 refreshControl={
778 // Fallback and empty states need refresh controls; only Android has an explicit refresh menu.
779 <RefreshControl
780 refreshing={isRefreshing}
781 onRefresh={() => void handlePullToRefresh()}
782 />
783 }
784 >
785 {listHeader}
786 {!selectedSection ? (
787 error ? null : (
788 <View
789 className={
790 Platform.OS === "android"
791 ? "items-center px-6 py-5"
792 : "border-b border-border bg-card px-4 py-5"
793 }
794 >
795 <Text className="text-sm font-t3-bold text-foreground">No review diffs</Text>
796 <Text
797 className={cn(
798 "text-xs leading-normal text-foreground-muted",
799 Platform.OS === "android" && "mt-2 text-center",
800 )}
801 >
802 This thread has no ready turn diffs and the worktree diff is empty.
803 </Text>
804 </View>
805 )
806 ) : selectedSection.isLoading && selectedSection.diff === null ? (
807 <View
808 className={cn(
809 "items-center gap-3 px-4 py-6",
810 Platform.OS !== "android" && "border-b border-border bg-card",
811 )}
812 >
813 <AppActivityIndicator size="small" />
814 <Text className="text-xs text-foreground-muted">Loading diff…</Text>
815 </View>
816 ) : parsedDiff.kind === "empty" ? (
817 <View
818 className={
819 Platform.OS === "android"
820 ? "items-center px-6 py-5"
821 : "border-b border-border bg-card px-4 py-5"
822 }
823 >
824 <Text className="text-sm font-t3-bold text-foreground">No changes</Text>
825 <Text
826 className={cn(
827 "text-xs leading-normal text-foreground-muted",
828 Platform.OS === "android" && "mt-2 text-center",
829 )}
830 >
831 {selectedSection.subtitle ?? "This diff is empty."}
832 </Text>
833 </View>
834 ) : parsedDiff.kind === "raw" ? (
835 <View
836 className={cn(
837 "gap-3 bg-card px-4 py-4",
838 Platform.OS === "android" ? "m-2 rounded-[20px]" : "border-b border-border",
839 )}
840 >
841 <Text className="text-xs leading-normal text-foreground-muted">
842 {parsedDiff.reason}
843 </Text>
844 <ScrollView horizontal showsHorizontalScrollIndicator={false} bounces={false}>
845 <Text selectable className="font-mono text-xs leading-relaxed text-foreground">
846 {parsedDiff.text}
847 </Text>
848 </ScrollView>
849 </View>
850 ) : parsedDiff.kind === "files" ? (
851 <View
852 className={cn(
853 "gap-3 bg-card px-4 py-4",
854 Platform.OS === "android" ? "m-2 rounded-[20px]" : "border-b border-border",
855 )}
856 >
857 <Text className="text-xs leading-normal text-foreground-muted">
858 Native diff view unavailable. Showing the raw patch.
859 </Text>
860 <ScrollView horizontal showsHorizontalScrollIndicator={false} bounces={false}>
861 <Text selectable className="font-mono text-xs leading-relaxed text-foreground">
862 {selectedSection?.diff ?? ""}
863 </Text>
864 </ScrollView>
865 </View>
866 ) : null}
867 </ScrollView>
868 )}
869 <ReviewSelectionActionBar
870 bottomInset={insets.bottom}
871 title={commentSelection.selectionAction?.title ?? null}
872 onOpenComment={commentSelection.selectionAction?.onOpenComment ?? null}
873 onClear={commentSelection.clearSelection}
874 />
875 </View>
876 </ScreenContent>
877 </>
878 );