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

ReviewSheet.tsx

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