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

ThreadFilesRouteScreen.tsx

945 lines33.3 KB

1import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
2import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
3import type { MenuAction } from "@react-native-menu/menu";
4import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
5import { ActivityIndicator, Platform, View } from "react-native";
6import { useSafeAreaInsets } from "react-native-safe-area-context";
7import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg";
8import {
9 EnvironmentId,
10 type ProjectListEntriesResult,
11 type ProjectReadFileResult,
12 ThreadId,
13} from "@t3tools/contracts";
14import { videoMimeType } from "@t3tools/shared/video";
15import {
16 isWorkspaceBrowserPreviewPath,
17 isWorkspaceImagePreviewPath,
18 mediaMimeTypeFromExtension,
19} from "@t3tools/shared/filePreview";
20import { mediaFileReference } from "@t3tools/client-runtime/media-reference";
21​
22import { AndroidHeaderIconButton, AndroidScreenHeader } from "../../components/AndroidScreenHeader";
23import { SymbolView } from "../../components/AppSymbol";
24import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
25import { ControlPillMenu } from "../../components/ControlPill";
26import { EmptyState } from "../../components/EmptyState";
27import { FilePreviewModal, type FilePreviewSource } from "../../components/FilePreviewModal";
28import { LoadingScreen } from "../../components/LoadingScreen";
29import { resolveFileSelectionNavigationAction } from "../../lib/adaptive-navigation";
30import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
31import { isPdfFile } from "../../lib/filePreview";
32import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
33import { useUniwindTheme } from "../../lib/useUniwindTheme";
34import type { MediaVideoPreviewSource } from "../../lib/videoPreviewSource";
35import { useMediaActions, type MediaActionsSource } from "../../lib/mediaActions";
36import { useThreadSelection } from "../../state/use-thread-selection";
37import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
38import { useEnvironmentQuery } from "../../state/query";
39import { projectEnvironment } from "../../state/projects";
40import type { AssetUrlFailureReason } from "../../state/asset-url-state";
41import {
42 useAdaptiveWorkspaceLayout,
43 useAdaptiveWorkspacePaneRole,
44 useRegisterWorkspaceInspector,
45} from "../layout/AdaptiveWorkspaceLayout";
46import {
47 createNativeMailSearchToolbarItem,
48 NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED,
49} from "../layout/native-mail-search-toolbar";
50import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
51import { ReviewHighlighterProvider } from "../review/ReviewHighlighterProvider";
52import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
53import { ThreadRouteScreen } from "../threads/ThreadRouteScreen";
54import { FileMarkdownPreview } from "./FileMarkdownPreview";
55import { FileTreeBrowser } from "./FileTreeBrowser";
56import { preloadWorkspaceFileContents } from "./preload-workspace-file";
57import { SourceFileSurface } from "./SourceFileSurface";
58import { ThreadFileNavigatorPane } from "./thread-file-navigator-pane";
59import { WorkspaceFileImagePreview } from "./WorkspaceFileImagePreview";
60import { WorkspaceFilePreviewError } from "./WorkspaceFilePreviewError";
61import { WorkspaceFileVideoPreview } from "./WorkspaceFileVideoPreview";
62import { WorkspaceFileWebPreview } from "./WorkspaceFileWebPreview";
63import {
64 basename,
65 isAbsolutePath,
66 isMarkdownPreviewFile,
67 isSvgImagePreviewFile,
68 isVideoPreviewFile,
69} from "./filePath";
70import { useWorkspaceFileAssetUrlState } from "./workspaceFileAssetUrl";
71​
72type FileViewMode = "preview" | "source";
73​
74function firstRouteParam(value: string | string[] | undefined): string | null {
75 if (Array.isArray(value)) {
76 return value[0] ?? null;
77 }
78​
79 return value ?? null;
81​
82function normalizeRoutePath(value: string | string[] | undefined): string | null {
83 const path = Array.isArray(value) ? value.join("/") : value;
84 if (path === undefined || path.trim().length === 0) {
85 return null;
86 }
87 return path;
89​
90function normalizeRouteLine(value: string | null): number | null {
91 if (value === null) {
92 return null;
93 }
94 const parsed = Number(value);
95 return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
97​
98function defaultViewMode(path: string | null): FileViewMode {
99 return path !== null &&
100 (isWorkspaceBrowserPreviewPath(path) ||
101 isWorkspaceImagePreviewPath(path) ||
102 isVideoPreviewFile(path))
103 ? "preview"
104 : "source";
106​
107function FileContent(props: {
108 readonly activeMode: FileViewMode;
109 readonly cwd: string;
110 readonly environmentId: EnvironmentId;
111 readonly previewUri: string | null;
112 readonly previewFailure: AssetUrlFailureReason | null;
113 readonly onRetryPreview: () => void;
114 readonly videoSource: MediaVideoPreviewSource | null;
115 readonly mediaSource?: MediaActionsSource;
116 readonly resolveVideoUri: () => Promise<string | null>;
117 readonly fileContents: string | null;
118 readonly fileError: string | null;
119 readonly relativePath: string;
120 readonly threadId: ThreadId;
121 readonly initialLine: number | null;
122 readonly truncated: boolean;
123 readonly onRefresh?: () => Promise<void> | void;
124}) {
125 // Reopening a mutable host file must not reuse a poster from an earlier visit.
126 const thumbnailInstanceId = useId();
127 const isMarkdown = isMarkdownPreviewFile(props.relativePath);
128 const isBrowserFile = isWorkspaceBrowserPreviewPath(props.relativePath);
129 const isImageFile = isWorkspaceImagePreviewPath(props.relativePath);
130 const isVideoFile = isVideoPreviewFile(props.relativePath);
131 // Only the surfaces that wait on a signed asset URL can be blocked by one.
132 const needsAssetUrl =
133 isVideoFile || (props.activeMode === "preview" && (isImageFile || isBrowserFile));
134​
135 if (needsAssetUrl && props.previewFailure !== null) {
136 return (
137 <WorkspaceFilePreviewError
138 environmentId={props.environmentId}
139 reason={props.previewFailure}
140 onRetry={props.onRetryPreview}
141 />
142 );
143 }
144​
145 if (isVideoFile) {
146 return (
147 <WorkspaceFileVideoPreview
148 name={basename(props.relativePath)}
149 thumbnailKey={`workspace-video:${thumbnailInstanceId}`}
150 uri={props.previewUri}
151 source={props.videoSource}
152 resolvePlaybackUri={props.resolveVideoUri}
153 />
154 );
155 }
156​
157 if (props.activeMode === "preview" && isImageFile) {
158 if (isSvgImagePreviewFile(props.relativePath)) {
159 return <WorkspaceFileWebPreview uri={props.previewUri} />;
160 }
161 return (
162 <WorkspaceFileImagePreview
163 accessibilityLabel={basename(props.relativePath)}
164 uri={props.previewUri}
165 actionsSource={props.mediaSource}
166 />
167 );
168 }
169​
170 if (props.activeMode === "preview" && isBrowserFile) {
171 return <WorkspaceFileWebPreview uri={props.previewUri} />;
172 }
173​
174 if (props.fileError && props.fileContents === null) {
175 return (
176 <View className="flex-1 items-center justify-center bg-sheet px-6">
177 <EmptyState title="File unavailable" detail={props.fileError} />
178 </View>
179 );
180 }
181​
182 if (props.fileContents === null) {
183 return (
184 <View className="flex-1 items-center justify-center gap-3 bg-sheet px-6">
185 <ActivityIndicator />
186 <Text className="text-center text-sm text-foreground-muted">Loading file...</Text>
187 </View>
188 );
189 }
190​
191 return (
192 <View className="flex-1 bg-sheet">
193 {props.truncated ? (
194 <View className="border-b border-adaptive-amber-200-900-a60 bg-adaptive-amber-50-950-a40 px-4 py-2">
195 <Text className="text-2xs font-t3-bold uppercase text-adaptive-amber-700-300">
196 Partial file
197 </Text>
198 <Text className="text-xs leading-snug text-adaptive-amber-800-200">
199 Preview limited to the first 1 MB of a truncated file.
200 </Text>
201 </View>
202 ) : null}
203 {props.activeMode === "preview" && isMarkdown ? (
204 <FileMarkdownPreview
205 cwd={props.cwd}
206 environmentId={props.environmentId}
207 markdown={props.fileContents}
208 relativePath={props.relativePath}
209 threadId={props.threadId}
210 onRefresh={props.onRefresh}
211 />
212 ) : (
213 <SourceFileSurface
214 contents={props.fileContents}
215 path={props.relativePath}
216 initialLine={props.initialLine}
217 onRefresh={props.onRefresh}
218 />
219 )}
220 </View>
221 );
223​
224type ThreadFilesRouteScreenProps = StaticScreenProps<{
225 readonly environmentId: string;
226 readonly threadId: string;
227}>;
228​
229type ThreadFileRouteScreenProps = StaticScreenProps<{
230 readonly environmentId: string;
231 readonly threadId: string;
232 readonly path: string[];
233 readonly line?: string;
234}>;
235​
236function useThreadFilesWorkspace(params: {
237 readonly environmentId?: string | string[];
238 readonly threadId?: string | string[];
239}) {
240 const routeEnvironmentId = firstRouteParam(params.environmentId);
241 const routeThreadId = firstRouteParam(params.threadId);
242 const { selectedThread, selectedThreadProject } = useThreadSelection();
243 const { selectedThreadCwd } = useSelectedThreadWorktree();
244 const environmentId =
245 routeEnvironmentId !== null
246 ? EnvironmentId.make(routeEnvironmentId)
247 : (selectedThread?.environmentId ?? null);
248 const threadId = routeThreadId !== null ? ThreadId.make(routeThreadId) : null;
249 const project = selectedThreadProject as {
250 readonly title?: string;
251 readonly workspaceRoot?: string;
252 } | null;
253​
254 return {
255 cwd: selectedThreadCwd ?? project?.workspaceRoot ?? null,
256 environmentId,
257 projectName: project?.title ?? "Files",
258 selectedThread,
259 threadId,
260 };
262​
263function FilesUnavailable() {
264 return (
265 <View className="flex-1 items-center justify-center bg-sheet px-6">
266 <NativeStackScreenOptions options={{ title: "Files" }} />
267 <EmptyState
268 title="Files unavailable"
269 detail="This thread does not have an active workspace path."
270 />
271 </View>
272 );
274​
275function FilesToolbarBottomFade() {
276 const sheetColor = String(useUniwindTheme()["--color-sheet"]);
277​
278 if (process.env.EXPO_OS !== "ios") {
279 return null;
280 }
281​
282 return (
283 <View
284 pointerEvents="none"
285 accessibilityElementsHidden
286 importantForAccessibility="no-hide-descendants"
287 className="absolute inset-x-0 bottom-0 z-[1] h-28"
288 >
289 <Svg width="100%" height="100%">
290 <Defs>
291 <LinearGradient id="files-toolbar-bottom-fade" x1="0%" x2="0%" y1="0%" y2="100%">
292 <Stop offset="0%" stopColor={sheetColor} stopOpacity={0} />
293 <Stop offset="58%" stopColor={sheetColor} stopOpacity={0.72} />
294 <Stop offset="100%" stopColor={sheetColor} stopOpacity={0.96} />
295 </LinearGradient>
296 </Defs>
297 <Rect width="100%" height="100%" fill="url(#files-toolbar-bottom-fade)" />
298 </Svg>
299 </View>
300 );
302​
303export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {
304 useAdaptiveWorkspacePaneRole("inspector");
305 const navigation = useNavigation();
306 const { fileInspector, layout, panes, showAuxiliaryPane, togglePrimarySidebar } =
307 useAdaptiveWorkspaceLayout();
308 const [searchQuery, setSearchQuery] = useState("");
309 const isAndroid = Platform.OS === "android";
310 const { themeAppearance: highlightTheme } = useAppearancePreferences();
311 const theme = useUniwindTheme();
312 const sheetSurfaceColor = theme["--color-sheet-solid"];
313 const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace(
314 props.route.params,
315 );
316 const revealedInspectorRef = useRef(false);
317 const entriesQuery = useEnvironmentQuery(
318 environmentId !== null && cwd !== null && !fileInspector.supported
319 ? projectEnvironment.listEntries({
320 environmentId,
321 input: { cwd },
322 })
323 : null,
324 );
325 const entriesData = entriesQuery.data as ProjectListEntriesResult | null;
326 const handleReturnToThread = useCallback(() => {
327 if (navigation.canGoBack()) {
328 navigation.goBack();
329 return;
330 }
331 if (environmentId !== null && threadId !== null) {
332 navigation.dispatch(
333 StackActions.replace("Thread", {
334 environmentId: String(environmentId),
335 threadId: String(threadId),
336 }),
337 );
338 }
339 }, [environmentId, navigation, threadId]);
340​
341 const handleSelectFile = useCallback(
342 (path: string) => {
343 if (environmentId === null || threadId === null) {
344 return;
345 }
346 const params = {
347 environmentId: String(environmentId),
348 threadId: String(threadId),
349 path: path.split("/").filter((segment) => segment.length > 0),
350 };
351 const navigationAction = resolveFileSelectionNavigationAction({
352 hasPersistentFileInspector: fileInspector.supported,
353 });
354 if (navigationAction === "replace") {
355 navigation.dispatch(StackActions.replace("ThreadFile", params));
356 return;
357 }
358 navigation.navigate("ThreadFile", params);
359 },
360 [environmentId, fileInspector.supported, navigation, threadId],
361 );
362 const renderInspector = useCallback(
363 (headerInset: number) =>
364 environmentId !== null && cwd !== null ? (
365 <ThreadFileNavigatorPane
366 cwd={cwd}
367 environmentId={environmentId}
368 headerInset={headerInset}
369 projectName={projectName}
370 selectedPath={null}
371 onSelectFile={handleSelectFile}
372 />
373 ) : null,
374 [cwd, environmentId, handleSelectFile, projectName],
375 );
376 const handlePreviewFile = useCallback(
377 (relativePath: string) => {
378 if (environmentId === null || cwd === null) {
379 return;
380 }
381 preloadWorkspaceFileContents({
382 cwd,
383 environmentId,
384 relativePath,
385 theme: highlightTheme,
386 });
387 },
388 [cwd, environmentId, highlightTheme],
389 );
390 useEffect(() => {
391 if (fileInspector.supported && cwd !== null && !revealedInspectorRef.current) {
392 revealedInspectorRef.current = true;
393 showAuxiliaryPane("inspector");
394 }
395 }, [cwd, fileInspector.supported, showAuxiliaryPane]);
396​
397 if (selectedThread === null || environmentId === null || threadId === null) {
398 if (fileInspector.supported) {
399 return (
400 <ThreadRouteScreen
401 onReturnToThread={handleReturnToThread}
402 renderInspector={renderInspector}
403 route={props.route}
404 />
405 );
406 }
407 return <LoadingScreen message="Opening files..." messagePlacement="above-spinner" />;
408 }
409​
410 if (cwd === null) {
411 return <FilesUnavailable />;
412 }
413​
414 if (fileInspector.supported) {
415 return (
416 <ThreadRouteScreen
417 onReturnToThread={handleReturnToThread}
418 renderInspector={renderInspector}
419 route={props.route}
420 />
421 );
422 }
423​
424 const usesCompactMailToolbar =
425 Platform.OS === "ios" && !layout.usesSplitView && NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED;
426​
427 return (
428 <>
429 {/* Static header config (glass preset and title) lives in Stack.tsx. The
430 live sheet color stays dynamic here so the FlatList can remain the
431 direct scene child for native scroll-edge sampling. */}
432 <NativeStackScreenOptions
433 options={{
434 contentStyle: { backgroundColor: sheetSurfaceColor },
435 headerShown: !isAndroid,
436 unstable_headerSubtitle:
437 Platform.OS === "ios" && projectName.length > 0 ? projectName : undefined,
438 // No refresh button: the list already supports pull-to-refresh.
439 unstable_headerToolbarItems: usesCompactMailToolbar
440 ? () => [
441 createNativeMailSearchToolbarItem({
442 onSearchTextChange: setSearchQuery,
443 placeholder: "Search files",
444 searchTextChangeId: "files-search-text",
445 }),
446 ]
447 : undefined,
448 headerSearchBarOptions: usesCompactMailToolbar
449 ? undefined
450 : {
451 allowToolbarIntegration: true,
452 autoCapitalize: "none",
453 hideNavigationBar: false,
454 placeholder: "Search files",
455 onChangeText: (event) => {
456 setSearchQuery(event.nativeEvent.text);
457 },
458 onCancelButtonPress: () => {
459 setSearchQuery("");
460 },
461 },
462 }}
463 />
464 {isAndroid ? (
465 <>
466 <AndroidScreenHeader
467 title="Files"
468 subtitle={projectName}
469 onBack={handleReturnToThread}
470 actions={[
471 {
472 accessibilityLabel: "Refresh files",
473 icon: "arrow.clockwise",
474 onPress: entriesQuery.refresh,
475 },
476 ]}
477 />
478 <View className="flex-row items-center gap-2 border-b border-border px-3 py-2">
479 <SymbolView
480 name="magnifyingglass"
481 size={17}
482 tintColorClassName={"accent-icon-muted"}
483 type="monochrome"
484 />
485 <TextInput
486 accessibilityLabel="Search files"
487 autoCapitalize="none"
488 autoCorrect={false}
489 className="min-h-10 flex-1 rounded-xl py-2 text-sm"
490 placeholder="Search files"
491 value={searchQuery}
492 onChangeText={setSearchQuery}
493 />
494 </View>
495 </>
496 ) : (
497 <>
498 {layout.usesSplitView ? (
499 <NativeHeaderToolbar placement="left">
500 <NativeHeaderToolbar.Button
501 accessibilityLabel={panes.primarySidebarVisible ? "Maximize files" : "Show threads"}
502 icon={
503 panes.primarySidebarVisible
504 ? "arrow.up.left.and.arrow.down.right"
505 : "sidebar.left"
506 }
507 onPress={togglePrimarySidebar}
508 separateBackground
509 />
510 </NativeHeaderToolbar>
511 ) : null}
512 {usesCompactMailToolbar ? null : (
513 <NativeHeaderToolbar placement="bottom">
514 <NativeHeaderToolbar.SearchBarSlot />
515 </NativeHeaderToolbar>
516 )}
517 </>
518 )}
519 <FileTreeBrowser
520 entries={entriesData?.entries ?? []}
521 error={entriesQuery.error}
522 isPending={entriesQuery.isPending}
523 searchQuery={searchQuery}
524 selectedPath={null}
525 onPreviewFile={handlePreviewFile}
526 onRefresh={entriesQuery.refresh}
527 onSelectFile={handleSelectFile}
528 />
529 <FilesToolbarBottomFade />
530 </>
531 );
533​
534export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
535 useAdaptiveWorkspacePaneRole("inspector");
536 const navigation = useNavigation();
537 const { fileInspector, panes, toggleAuxiliaryPane } = useAdaptiveWorkspaceLayout();
538 const iconColor = useUniwindTheme()["--color-icon"];
539 const isAndroid = Platform.OS === "android";
540 const params = props.route.params;
541 const relativePath = normalizeRoutePath(params.path);
542 const targetLine = normalizeRouteLine(firstRouteParam(params.line));
543 const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace(
544 props.route.params,
545 );
546 const [modeOverride, setModeOverride] = useState<{
547 readonly path: string;
548 readonly mode: FileViewMode;
549 } | null>(null);
550 const [previewRevision, setPreviewRevision] = useState(0);
551 const previewKey = JSON.stringify([environmentId, cwd, relativePath, previewRevision]);
552 const [fullScreenPreview, setFullScreenPreview] = useState<FilePreviewSource | null>(null);
553 const isVideoFile = relativePath !== null && isVideoPreviewFile(relativePath);
554 const isBrowserFile =
555 relativePath !== null && !isVideoFile && isWorkspaceBrowserPreviewPath(relativePath);
556 const isImageFile =
557 relativePath !== null && !isVideoFile && isWorkspaceImagePreviewPath(relativePath);
558 const canPreview =
559 relativePath !== null &&
560 (isMarkdownPreviewFile(relativePath) || isBrowserFile || isImageFile || isVideoFile);
561 const activeMode =
562 relativePath !== null && modeOverride?.path === relativePath
563 ? modeOverride.mode
564 : defaultViewMode(relativePath);
565 const resolvedActiveMode = isVideoFile ? "preview" : canPreview ? activeMode : "source";
566 const assetPreviewPath = isBrowserFile || isImageFile || isVideoFile ? relativePath : null;
567 const assetPreview = useWorkspaceFileAssetUrlState({
568 cwd,
569 environmentId,
570 relativePath: assetPreviewPath,
571 threadId,
572 });
573 const assetPreviewUri = assetPreview._tag === "Success" ? assetPreview.url : null;
574 const mediaSource = useMemo<MediaActionsSource | undefined>(
575 () =>
576 environmentId !== null &&
577 threadId !== null &&
578 relativePath !== null &&
579 assetPreview.resource !== null &&
580 "path" in assetPreview.resource &&
581 typeof assetPreview.resource.path === "string" &&
582 (isImageFile || isVideoFile)
583 ? {
584 reference: mediaFileReference(assetPreview.resource.path, cwd),
585 name: basename(relativePath),
586 mimeType:
587 mediaMimeTypeFromExtension(relativePath.slice(relativePath.lastIndexOf("."))) ??
588 "application/octet-stream",
589 environmentId,
590 threadId,
591 resource: assetPreview.resource,
592 }
593 : undefined,
594 [assetPreview.resource, cwd, environmentId, isImageFile, isVideoFile, relativePath, threadId],
595 );
596 const mediaActions = useMediaActions(mediaSource);
597 const videoSource = useMemo<MediaVideoPreviewSource | null>(
598 () =>
599 environmentId !== null &&
600 relativePath !== null &&
601 assetPreview.resource?._tag === "media-file"
602 ? {
603 type: "media",
604 environmentId,
605 resource: assetPreview.resource,
606 name: basename(relativePath),
607 mimeType: videoMimeType({ name: relativePath, mimeType: "" }) ?? "video/mp4",
608 actionsSource: mediaSource,
609 }
610 : null,
611 [assetPreview.resource, environmentId, relativePath, mediaSource],
612 );
613 const previewUri =
614 assetPreviewUri === null || previewRevision === 0
615 ? assetPreviewUri
616 : `${assetPreviewUri}${assetPreviewUri.includes("?") ? "&" : "?"}revision=${previewRevision}`;
617 // Remounting the preview after a re-mint is what makes a failed asset URL retryable.
618 const handleRetryPreview = () => {
619 void assetPreview.refresh().finally(() => setPreviewRevision((current) => current + 1));
620 };
621 const needsFileContents =
622 relativePath !== null &&
623 !isVideoFile &&
624 (resolvedActiveMode === "source" || isMarkdownPreviewFile(relativePath));
625 const fileQuery = useEnvironmentQuery(
626 environmentId !== null && cwd !== null && relativePath !== null && needsFileContents
627 ? projectEnvironment.readFile({
628 environmentId,
629 input: { cwd, relativePath },
630 })
631 : null,
632 );
633 const fileData = fileQuery.data as ProjectReadFileResult | null;
634​
635 const handleSelectFile = useCallback(
636 (path: string) => {
637 navigation.navigate("ThreadFile", {
638 environmentId: String(environmentId),
639 threadId: String(threadId),
640 path: path.split("/").filter(Boolean),
641 });
642 },
643 [environmentId, navigation, threadId],
644 );
645 const renderInspector = useCallback(
646 (headerInset: number) =>
647 fileInspector.supported && environmentId !== null && cwd !== null ? (
648 <ThreadFileNavigatorPane
649 cwd={cwd}
650 environmentId={environmentId}
651 headerInset={headerInset}
652 projectName={projectName}
653 selectedPath={relativePath}
654 onSelectFile={handleSelectFile}
655 />
656 ) : undefined,
657 [cwd, environmentId, fileInspector.supported, handleSelectFile, projectName, relativePath],
658 );
659 // The workspace inspector column spans the full window height. On iOS the
660 // pane brings its own nested native header; elsewhere it pads itself below
661 // the top inset.
662 const safeAreaInsets = useSafeAreaInsets();
663 const inspectorHeaderInset = Platform.OS === "ios" ? 0 : safeAreaInsets.top;
664 // Hand the file navigator to the workspace so it renders beside the
665 // navigator, outside this screen's native header.
666 const renderWorkspaceInspector = useCallback(
667 () => renderInspector(inspectorHeaderInset),
668 [inspectorHeaderInset, renderInspector],
669 );
670 useRegisterWorkspaceInspector(fileInspector.supported ? renderWorkspaceInspector : undefined);
671​
672 const fileMenuActions = useMemo(() => {
673 if (relativePath === null) return [];
674 const canToggleMode = canPreview && !isImageFile && !isVideoFile;
675 return [
676 canToggleMode
677 ? ({
678 id: "preview",
679 title: "Preview",
680 icon: "eye",
681 inline: true,
682 onPress: () => setModeOverride({ path: relativePath, mode: "preview" }),
683 } as const)
684 : null,
685 canToggleMode
686 ? ({
687 id: "source",
688 title: "Source",
689 icon: "doc.text",
690 inline: true,
691 onPress: () => setModeOverride({ path: relativePath, mode: "source" }),
692 } as const)
693 : null,
694 ...(mediaSource
695 ? mediaActions.actions
696 .filter(({ id }) => id !== "open-file")
697 .map((action) => ({
698 id: action.id,
699 title: action.title,
700 icon:
701 action.id === "save" ? ("square.and.arrow.up" as const) : ("doc.on.doc" as const),
702 inline: false,
703 onPress: action.run,
704 }))
705 : [
706 {
707 id: "copy-path",
708 title: "Copy path",
709 icon: "doc.on.doc",
710 inline: false,
711 onPress: () => copyTextWithHaptic(relativePath),
712 } as const,
713 ]),
714 isPdfFile({ name: relativePath }) && previewUri !== null
715 ? ({
716 id: "open-pdf",
717 title: "Open PDF",
718 icon: "arrow.up.left.and.arrow.down.right",
719 inline: false,
720 onPress: () =>
721 setFullScreenPreview({
722 kind: "pdf",
723 uri: previewUri,
724 name: basename(relativePath),
725 }),
726 } as const)
727 : null,
728 isBrowserFile && typeof assetPreviewUri === "string"
729 ? ({
730 id: "open-browser",
731 title: Platform.OS === "ios" ? "Open in Safari" : "Open in browser",
732 icon: "safari",
733 inline: false,
734 onPress: () => tryOpenExternalUrl(assetPreviewUri, "file-preview"),
735 } as const)
736 : null,
737 resolvedActiveMode === "preview" && (isBrowserFile || isImageFile || isVideoFile)
738 ? ({
739 id: "refresh",
740 title: "Refresh",
741 icon: "arrow.clockwise",
742 inline: false,
743 onPress: async () => {
744 if (isVideoFile) await assetPreview.refresh();
745 setPreviewRevision((current) => current + 1);
746 },
747 } as const)
748 : null,
749 ].filter((action) => action !== null);
750 }, [
751 assetPreviewUri,
752 assetPreview.refresh,
753 previewUri,
754 canPreview,
755 isBrowserFile,
756 isImageFile,
757 isVideoFile,
758 relativePath,
759 resolvedActiveMode,
760 mediaSource,
761 mediaActions.actions,
762 ]);
763​
764 const androidFileMenuActions = useMemo<MenuAction[]>(
765 () =>
766 fileMenuActions.map((action) => ({
767 id: action.id,
768 title: action.title,
769 image: action.icon,
770 state: action.id === resolvedActiveMode ? "on" : undefined,
771 })),
772 [fileMenuActions, resolvedActiveMode],
773 );
774 const handleAndroidFileMenuAction = useCallback(
775 (event: { nativeEvent: { event: string } }) => {
776 const action = fileMenuActions.find(({ id }) => id === event.nativeEvent.event);
777 void action?.onPress();
778 },
779 [fileMenuActions],
780 );
781 const handleReturnToThread = useCallback(() => {
782 if (environmentId !== null && threadId !== null) {
783 navigation.dispatch(
784 StackActions.replace("Thread", {
785 environmentId: String(environmentId),
786 threadId: String(threadId),
787 }),
788 );
789 }
790 }, [environmentId, navigation, threadId]);
791 const handleBack = useCallback(() => {
792 if (navigation.canGoBack()) {
793 navigation.goBack();
794 return;
795 }
796 handleReturnToThread();
797 }, [handleReturnToThread, navigation]);
798​
799 if (selectedThread === null || environmentId === null || threadId === null) {
800 return <LoadingScreen message="Opening file..." messagePlacement="above-spinner" />;
801 }
802​
803 if (cwd === null) {
804 return <FilesUnavailable />;
805 }
806​
807 if (relativePath === null) {
808 return (
809 <View className="flex-1 items-center justify-center bg-sheet px-6">
810 <NativeStackScreenOptions options={{ title: "Files" }} />
811 <EmptyState title="File unavailable" detail="This file path is invalid." />
812 </View>
813 );
814 }
815​
816 const parentDir = relativePath.slice(
817 0,
818 Math.max(relativePath.lastIndexOf("/"), relativePath.lastIndexOf("\\"), 0),
819 );
820 // A host file outside the workspace is not under the project name.
821 const headerSubtitle = isAbsolutePath(relativePath)
822 ? parentDir
823 : [projectName, parentDir].filter(Boolean).join(" · ");
824​
825 return (
826 <ReviewHighlighterProvider>
827 <View className="flex-1 bg-sheet">
828 <NativeStackScreenOptions
829 options={{
830 // Static header config lives in Stack.tsx (SOLID_HEADER_OPTIONS: solid
831 // sheet-colored header — this route's content scrolls internally, so
832 // there is nothing for glass to sample). Only dynamic values here.
833 headerShown: !isAndroid,
834 headerTintColor: iconColor,
835 headerTitle: basename(relativePath),
836 title: basename(relativePath),
837 unstable_headerSubtitle:
838 Platform.OS === "ios" && headerSubtitle.length > 0 ? headerSubtitle : undefined,
839 }}
840 />
841 {isAndroid ? (
842 <AndroidScreenHeader
843 title={basename(relativePath)}
844 subtitle={headerSubtitle}
845 onBack={handleBack}
846 trailing={
847 <>
848 {fileInspector.supported ? (
849 <AndroidHeaderIconButton
850 accessibilityLabel={
851 panes.auxiliaryPaneVisible ? "Hide file navigator" : "Show file navigator"
852 }
853 icon="sidebar.right"
854 onPress={toggleAuxiliaryPane}
855 />
856 ) : null}
857 <ControlPillMenu
858 actions={androidFileMenuActions}
859 isAnchoredToRight
860 title="File actions"
861 onPressAction={handleAndroidFileMenuAction}
862 >
863 <AndroidHeaderIconButton accessibilityLabel="File actions" icon="ellipsis" />
864 </ControlPillMenu>
865 </>
866 }
867 />
868 ) : null}
869 <WorkspaceSidebarToolbar>
870 {fileInspector.supported ? (
871 <NativeHeaderToolbar.Button
872 accessibilityLabel="Return to chat"
873 icon="chevron.left"
874 onPress={handleReturnToThread}
875 />
876 ) : null}
877 </WorkspaceSidebarToolbar>
878 <NativeHeaderToolbar placement="right">
879 {fileInspector.supported ? (
880 <NativeHeaderToolbar.Button
881 accessibilityLabel={
882 panes.auxiliaryPaneVisible ? "Hide file navigator" : "Show file navigator"
883 }
884 icon="sidebar.right"
885 onPress={toggleAuxiliaryPane}
886 separateBackground
887 />
888 ) : null}
889 <NativeHeaderToolbar.Menu accessibilityLabel="File actions" icon="ellipsis">
890 {fileMenuActions.some(({ inline }) => inline) ? (
891 <NativeHeaderToolbar.Menu inline>
892 {fileMenuActions
893 .filter(({ inline }) => inline)
894 .map((action) => (
895 <NativeHeaderToolbar.MenuAction
896 key={action.id}
897 icon={action.icon}
898 isOn={action.id === resolvedActiveMode}
899 onPress={action.onPress}
900 >
901 {action.title}
902 </NativeHeaderToolbar.MenuAction>
903 ))}
904 </NativeHeaderToolbar.Menu>
905 ) : null}
906 {fileMenuActions
907 .filter(({ inline }) => !inline)
908 .map((action) => (
909 <NativeHeaderToolbar.MenuAction
910 key={action.id}
911 icon={action.icon}
912 onPress={action.onPress}
913 >
914 {action.title}
915 </NativeHeaderToolbar.MenuAction>
916 ))}
917 </NativeHeaderToolbar.Menu>
918 </NativeHeaderToolbar>
919 <FileContent
920 key={previewKey}
921 activeMode={resolvedActiveMode}
922 cwd={cwd}
923 environmentId={environmentId}
924 previewUri={previewUri}
925 previewFailure={assetPreview._tag === "Failure" ? assetPreview.reason : null}
926 onRetryPreview={handleRetryPreview}
927 videoSource={videoSource}
928 mediaSource={mediaSource}
929 resolveVideoUri={assetPreview.refresh}
930 fileContents={fileData?.contents ?? null}
931 fileError={fileQuery.error}
932 initialLine={targetLine}
933 relativePath={relativePath}
934 threadId={threadId}
935 truncated={fileData?.truncated ?? false}
936 onRefresh={() => fileQuery.refresh()}
937 />
938 <FilePreviewModal
939 source={fullScreenPreview}
940 onRequestClose={() => setFullScreenPreview(null)}
941 />
942 </View>
943 </ReviewHighlighterProvider>
944 );