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