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