Open History to see the last commit
1import { formatFilePathForClipboard } from "@t3tools/client-runtime/media-actions";
2import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks";
3import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem";
4import { environmentSession } from "../../state/session";
5import { NativeStackScreenOptions } from "../../native/StackHeader";
6import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
7import { useEffect, useId, useRef, useState } from "react";
8import { Platform, View } from "react-native";
9import { useSafeAreaInsets } from "react-native-safe-area-context";
10import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg";
11import { EnvironmentId, type ProjectReadFileResult, ThreadId } from "@t3tools/contracts";
12import { videoMimeType } from "@t3tools/shared/video";
13import {
14 isWorkspaceBrowserPreviewPath,
15 isWorkspaceImagePreviewPath,
16 mediaMimeTypeFromExtension,
17} from "@t3tools/shared/filePreview";
18import { mediaFileReference } from "@t3tools/client-runtime/media-reference";
19
20import { ScreenContent } from "../../components/ui/ScreenContent";
21import { filePreviewDelimiter, parseDelimitedPreview } from "@t3tools/shared/delimitedPreview";
22import { DelimitedFilePreview } from "./DelimitedFilePreview";
23import { AudioFilePreview } from "./AudioFilePreview";
24import { EmptyState } from "../../components/ui/EmptyState";
25import { FilePreviewModal, type FilePreviewSource } from "../../components/FilePreviewModal";
26import { LoadingScreen } from "../../components/LoadingScreen";
27import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
28import { isPdfFile } from "../../lib/filePreview";
29import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
30import { useUniwindTheme } from "../../lib/useUniwindTheme";
31import type { MediaVideoPreviewSource } from "../../lib/videoPreviewSource";
32import { useMediaActions } from "../../state/mediaActions";
33import { type MediaActionsSource } from "../../lib/mediaActionsSource";
34import { useThreadSelection } from "../../state/use-thread-selection";
35import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
36import { useEnvironmentQuery } from "../../state/query";
37import { useEnvironmentPresentation } from "../../state/presentation";
38import { projectEnvironment } from "../../state/projects";
39import type { AssetUrlFailureReason } from "../../state/asset-url-state";
40import {
41 useAdaptiveWorkspaceLayout,
42 useAdaptiveWorkspacePaneRole,
43 useRegisterWorkspaceInspector,
44} from "../layout/AdaptiveWorkspaceLayout";
45import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
46import { ThreadRouteScreen } from "../threads/ThreadRouteScreen";
47import { FilePreviewLoading, FilePreviewNotice } from "./FilePreviewFeedback";
48import { FileMarkdownPreview } from "./FileMarkdownPreview";
49import { ThreadInspectorContentStack } from "../threads/thread-inspector-content-stack";
50import { FileTreeBrowser } from "./FileTreeBrowser";
51import { useFileTreeEntries } from "./useFileTreeEntries";
52import { preloadWorkspaceFileContents } from "./preload-workspace-file";
53import { SourceFileSurface } from "./SourceFileSurface";
54import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
55import { ThreadFileNavigatorPane } from "./thread-file-navigator-pane";
56import { AppBar } from "../../components/ui/AppBar";
57import { WorkspaceFileImagePreview } from "./WorkspaceFileImagePreview";
58import { WorkspaceFilePreviewError } from "./WorkspaceFilePreviewError";
59import { WorkspaceFileVideoPreview } from "./WorkspaceFileVideoPreview";
60import { WorkspaceFileWebPreview } from "./WorkspaceFileWebPreview";
61import {
62 basename,
63 fileHeaderSubtitle,
64 fileRoutePathSegments,
65 resolveWorkspaceFilePath,
66 resolveWorkspaceRelativeFilePath,
67 isAudioPreviewFile,
68 isMarkdownPreviewFile,
69 isSvgImagePreviewFile,
70 isVideoPreviewFile,
71} from "./filePath";
72import { useWorkspaceFileAssetUrlState } from "./workspaceFileAssetUrl";
73
74function FilesBrowserHeader(props: {
75 readonly projectName: string;
76 readonly searchQuery: string;
77 readonly onSearchQueryChange: (query: string) => void;
78 readonly onRefresh: () => void;
79 readonly onBack: () => void;
80}) {
81 return (
82 <AppBar
83 title="Files"
84 subtitle={props.projectName}
85 onBack={props.onBack}
86 hideBottomBorder
87 matchSearchSurface
88 search={{
89 value: props.searchQuery,
90 onChangeText: props.onSearchQueryChange,
91 placeholder: "Search files",
92 closeAccessibilityLabel: "Close file search",
93 clearAccessibilityLabel: "Clear file search",
94 }}
95 menus={
96 Platform.OS === "android"
97 ? [
98 {
99 title: "File options",
100 icon: "ellipsis",
101 items: [{ id: "refresh", title: "Refresh files", onPress: props.onRefresh }],
102 },
103 ]
104 : undefined
105 }
106 />
107 );
108}
109
110function FileHeader(props: {
111 readonly title: string;
112 readonly subtitle: string;
113 readonly iconColor: string;
114 readonly activeMode: string;
115 readonly fileInspectorSupported: boolean;
116 readonly onBack: () => void;
117 readonly onReturnToThread: () => void;
118 readonly actions: ReadonlyArray<{
119 readonly id: string;
120 readonly title: string;
121 readonly icon: string;
122 readonly inline: boolean;
123 readonly onPress: () => unknown;
124 }>;
125}) {
126 const { panes, toggleAuxiliaryPane } = useAdaptiveWorkspaceLayout();
127 const modes = props.actions.filter(({ inline }) => inline);
128 return (
129 <AppBar
130 title={props.title}
131 subtitle={props.subtitle}
132 onBack={props.onBack}
133 hideBottomBorder
134 options={{ headerTintColor: props.iconColor, headerTitle: props.title }}
135 backInSplitView={
136 props.fileInspectorSupported
137 ? {
138 accessibilityLabel: "Return to chat",
139 icon: "chevron.left",
140 onPress: props.onReturnToThread,
141 }
142 : undefined
143 }
144 actions={
145 props.fileInspectorSupported
146 ? [
147 {
148 accessibilityLabel: panes.auxiliaryPaneVisible
149 ? "Hide file navigator"
150 : "Show file navigator",
151 icon: "sidebar.right",
152 selected: panes.auxiliaryPaneVisible,
153 onPress: toggleAuxiliaryPane,
154 },
155 ]
156 : undefined
157 }
158 menus={[
159 {
160 title: "File actions",
161 icon: "ellipsis",
162 separateBackground: false,
163 items: [
164 ...(modes.length > 0
165 ? [
166 {
167 id: "modes",
168 inline: true,
169 items: modes.map((action) => ({
170 ...action,
171 selected: action.id === props.activeMode,
172 })),
173 },
174 ]
175 : []),
176 ...props.actions.filter(({ inline }) => !inline),
177 ],
178 },
179 ]}
180 />
181 );
182}
183
184type FileViewMode = "preview" | "source";
185
186function firstRouteParam(value: string | string[] | undefined): string | null {
187 const first = Array.isArray(value) ? value[0] : value;
188 return first === undefined || first.trim().length === 0 ? null : first;
189}
190
191function normalizeRoutePath(value: string | string[] | undefined): string | null {
192 const path = Array.isArray(value) ? value.join("/") : value;
193 if (path === undefined || path.trim().length === 0) {
194 return null;
195 }
196 return path;
197}
198
199function normalizeRouteLine(value: string | null): number | null {
200 if (value === null) {
201 return null;
202 }
203 const parsed = Number(value);
204 return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
205}
206
207function defaultViewMode(path: string | null): FileViewMode {
208 return path !== null &&
209 (isWorkspaceBrowserPreviewPath(path) ||
210 isWorkspaceImagePreviewPath(path) ||
211 isVideoPreviewFile(path) ||
212 isAudioPreviewFile(path) ||
213 filePreviewDelimiter({ name: path }) !== null)
214 ? "preview"
215 : "source";
216}
217
218function FileContent(props: {
219 readonly activeMode: FileViewMode;
220 readonly cwd: string;
221 readonly environmentId: EnvironmentId;
222 readonly previewUri: string | null;
223 readonly previewFailure: AssetUrlFailureReason | null;
224 readonly onRetryPreview: () => void;
225 readonly videoSource: MediaVideoPreviewSource | null;
226 readonly mediaSource?: MediaActionsSource;
227 readonly resolveVideoUri: () => Promise<string | null>;
228 readonly fileContents: string | null;
229 readonly fileError: string | null;
230 readonly relativePath: string;
231 readonly threadId: ThreadId | null;
232 readonly initialLine: number | null;
233 readonly truncated: boolean;
234 readonly onRefresh?: () => Promise<void> | void;
235}) {
236 // Reopening a mutable host file must not reuse a poster from an earlier visit.
237 const thumbnailInstanceId = useId();
238 const insets = useSafeAreaInsets();
239 const columnMetrics = useNativeColumnLayoutMetrics();
240 const reservedHeaderInset =
241 Platform.OS === "ios" && props.truncated ? (columnMetrics?.safeArea.top ?? insets.top) : 0;
242 const isMarkdown = isMarkdownPreviewFile(props.relativePath);
243 const delimiter = filePreviewDelimiter({ name: props.relativePath });
244 const isBrowserFile = isWorkspaceBrowserPreviewPath(props.relativePath);
245 const isImageFile = isWorkspaceImagePreviewPath(props.relativePath);
246 const isVideoFile = isVideoPreviewFile(props.relativePath);
247 const isAudioFile = isAudioPreviewFile(props.relativePath);
248 const needsAssetUrl =
249 isVideoFile ||
250 isAudioFile ||
251 (props.activeMode === "preview" && (isImageFile || isBrowserFile));
252
253 if (needsAssetUrl && props.previewFailure !== null) {
254 return (
255 <WorkspaceFilePreviewError
256 environmentId={props.environmentId}
257 reason={props.previewFailure}
258 onRetry={props.onRetryPreview}
259 />
260 );
261 }
262
263 if (isVideoFile) {
264 return (
265 <WorkspaceFileVideoPreview
266 name={basename(props.relativePath)}
267 thumbnailKey={`workspace-video:${thumbnailInstanceId}`}
268 uri={props.previewUri}
269 source={props.videoSource}
270 resolvePlaybackUri={props.resolveVideoUri}
271 />
272 );
273 }
274
275 if (isAudioFile) {
276 return props.previewUri === null ? (
277 <FilePreviewLoading message="Loading file..." />
278 ) : (
279 <AudioFilePreview uri={props.previewUri} onRetry={props.onRetryPreview} />
280 );
281 }
282
283 if (props.activeMode === "preview" && isImageFile) {
284 if (isSvgImagePreviewFile(props.relativePath)) {
285 return <WorkspaceFileWebPreview uri={props.previewUri} />;
286 }
287 return (
288 <WorkspaceFileImagePreview
289 accessibilityLabel={basename(props.relativePath)}
290 uri={props.previewUri}
291 actionsSource={props.mediaSource}
292 />
293 );
294 }
295
296 if (props.activeMode === "preview" && isBrowserFile) {
297 return <WorkspaceFileWebPreview uri={props.previewUri} />;
298 }
299
300 if (props.fileError && props.fileContents === null) {
301 return (
302 <View className="flex-1 items-center justify-center bg-sheet px-6">
303 <EmptyState title="File unavailable" detail={props.fileError} />
304 </View>
305 );
306 }
307
308 if (props.fileContents === null) {
309 return <FilePreviewLoading message="Loading file..." />;
310 }
311
312 return (
313 <View className="flex-1 bg-sheet" style={{ paddingTop: reservedHeaderInset }}>
314 {props.truncated ? (
315 <FilePreviewNotice title="Partial file">
316 Preview limited to the first 1 MB of a truncated file.
317 </FilePreviewNotice>
318 ) : null}
319 {props.activeMode === "preview" && delimiter ? (
320 <DelimitedFilePreview table={parseDelimitedPreview(props.fileContents, delimiter)} />
321 ) : props.activeMode === "preview" && isMarkdown ? (
322 <FileMarkdownPreview
323 cwd={props.cwd}
324 environmentId={props.environmentId}
325 markdown={props.fileContents}
326 relativePath={props.relativePath}
327 threadId={props.threadId}
328 onRefresh={props.onRefresh}
329 />
330 ) : (
331 <SourceFileSurface
332 contents={props.fileContents}
333 path={props.relativePath}
334 initialLine={props.initialLine}
335 headerInsetTop={props.truncated ? 0 : undefined}
336 onRefresh={props.onRefresh}
337 />
338 )}
339 </View>
340 );
341}
342
343type ThreadFilesRouteScreenProps = StaticScreenProps<{
344 readonly environmentId: string;
345 readonly threadId?: string;
346 readonly cwd?: string;
347 readonly projectName?: string;
348}>;
349
350type ThreadFileRouteScreenProps = StaticScreenProps<{
351 readonly environmentId: string;
352 readonly threadId?: string;
353 readonly path: string[];
354 readonly line?: string;
355 readonly cwd?: string;
356 readonly projectName?: string;
357}>;
358
359function useThreadFilesWorkspace(params: {
360 readonly environmentId?: string | string[];
361 readonly threadId?: string | string[];
362 readonly cwd?: string | string[];
363 readonly projectName?: string | string[];
364}) {
365 const routeEnvironmentId = firstRouteParam(params.environmentId);
366 const routeThreadId = firstRouteParam(params.threadId);
367 const routeCwd = firstRouteParam(params.cwd);
368 const routeProjectName = firstRouteParam(params.projectName);
369 const { selectedThread, selectedThreadProject } = useThreadSelection();
370 const { selectedThreadCwd } = useSelectedThreadWorktree();
371 const environmentId =
372 routeEnvironmentId !== null
373 ? EnvironmentId.make(routeEnvironmentId)
374 : (selectedThread?.environmentId ?? null);
375 const threadId = routeThreadId !== null ? ThreadId.make(routeThreadId) : null;
376 const project = selectedThreadProject as {
377 readonly title?: string;
378 readonly workspaceRoot?: string;
379 } | null;
380
381 return {
382 cwd: routeCwd ?? selectedThreadCwd ?? project?.workspaceRoot ?? null,
383 environmentId,
384 projectName: routeProjectName ?? project?.title ?? "Files",
385 selectedThread,
386 threadId,
387 };
388}
389
390function FilesUnavailable({
391 detail = "This thread does not have an active workspace path.",
392}: {
393 detail?: string;
394}) {
395 return (
396 <View className="flex-1 items-center justify-center bg-sheet px-6">
397 <NativeStackScreenOptions options={{ title: "Files" }} />
398 <EmptyState title="Files unavailable" detail={detail} />
399 </View>
400 );
401}
402
403function FilesToolbarBottomFade() {
404 const sheetColor = String(useUniwindTheme()["--color-sheet"]);
405
406 if (process.env.EXPO_OS !== "ios") {
407 return null;
408 }
409
410 return (
411 <View
412 pointerEvents="none"
413 accessibilityElementsHidden
414 importantForAccessibility="no-hide-descendants"
415 className="absolute inset-x-0 bottom-0 z-[1] h-28"
416 >
417 <Svg width="100%" height="100%">
418 <Defs>
419 <LinearGradient id="files-toolbar-bottom-fade" x1="0%" x2="0%" y1="0%" y2="100%">
420 <Stop offset="0%" stopColor={sheetColor} stopOpacity={0} />
421 <Stop offset="58%" stopColor={sheetColor} stopOpacity={0.72} />
422 <Stop offset="100%" stopColor={sheetColor} stopOpacity={0.96} />
423 </LinearGradient>
424 </Defs>
425 <Rect width="100%" height="100%" fill="url(#files-toolbar-bottom-fade)" />
426 </Svg>
427 </View>
428 );
429}
430
431export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {
432 useAdaptiveWorkspacePaneRole("inspector");
433 const navigation = useNavigation();
434 const { fileInspector, layout, showAuxiliaryPane } = useAdaptiveWorkspaceLayout();
435 const [searchQuery, setSearchQuery] = useState("");
436 const { themeAppearance: highlightTheme } = useAppearancePreferences();
437 const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace(
438 props.route.params,
439 );
440 const hasFileInspector = fileInspector.supported && threadId !== null;
441 const revealedInspectorRef = useRef(false);
442 const fileAccessSession = useEnvironmentQuery(
443 environmentId !== null ? environmentSession.sessionStateAtom(environmentId) : null,
444 );
445 const fileEnvironment = useEnvironmentPresentation(environmentId);
446 const fileAccess = resolveFilesystemReadAccess({
447 isCatalogReady: fileEnvironment.isReady,
448 connection: fileEnvironment.presentation?.connection ?? null,
449 session: fileAccessSession.data,
450 sessionError: fileAccessSession.error,
451 });
452 const { canReadFiles } = fileAccess;
453 const entriesQuery = useFileTreeEntries({
454 environmentId,
455 cwd: canReadFiles && !hasFileInspector ? cwd : null,
456 searchQuery,
457 });
458 const handleReturnToThread = () => {
459 if (navigation.canGoBack()) {
460 navigation.goBack();
461 return;
462 }
463 if (environmentId !== null && threadId !== null) {
464 navigation.dispatch(
465 StackActions.replace("Thread", {
466 environmentId: String(environmentId),
467 threadId: String(threadId),
468 }),
469 );
470 }
471 };
472
473 const handleSelectFile = (path: string) => {
474 if (environmentId === null || cwd === null) {
475 return;
476 }
477 const params = {
478 environmentId: String(environmentId),
479 ...(threadId === null ? { cwd, projectName } : { threadId: String(threadId) }),
480 path: path.split("/").filter((segment) => segment.length > 0),
481 };
482 if (threadId === null) {
483 navigation.navigate("NewTaskFile", params);
484 return;
485 }
486 if (hasFileInspector) {
487 navigation.dispatch(StackActions.replace("ThreadFile", params));
488 return;
489 }
490 navigation.navigate("ThreadFile", params);
491 };
492 const renderInspector = (headerInset: number) =>
493 environmentId !== null && cwd !== null ? (
494 <ThreadFileNavigatorPane
495 cwd={cwd}
496 environmentId={environmentId}
497 headerInset={headerInset}
498 projectName={projectName}
499 selectedPath={null}
500 onSelectFile={handleSelectFile}
501 />
502 ) : null;
503 const handlePreviewFile = (relativePath: string) => {
504 if (environmentId === null || cwd === null) {
505 return;
506 }
507 preloadWorkspaceFileContents({
508 cwd,
509 environmentId,
510 relativePath,
511 theme: highlightTheme,
512 });
513 };
514 useEffect(() => {
515 if (hasFileInspector && cwd !== null && !revealedInspectorRef.current) {
516 revealedInspectorRef.current = true;
517 showAuxiliaryPane("inspector");
518 }
519 }, [cwd, hasFileInspector, showAuxiliaryPane]);
520
521 if (environmentId === null || (threadId !== null && selectedThread === null)) {
522 if (hasFileInspector) {
523 return (
524 <ThreadRouteScreen
525 onReturnToThread={handleReturnToThread}
526 renderInspector={renderInspector}
527 route={props.route}
528 />
529 );
530 }
531 return <LoadingScreen message="Opening files..." messagePlacement="above-spinner" />;
532 }
533
534 if (!canReadFiles) {
535 if (fileAccess.isPending) {
536 return <LoadingScreen message="Checking file access..." messagePlacement="above-spinner" />;
537 }
538 return (
539 <FilesUnavailable detail={fileAccess.error ?? "This connection cannot read host files."} />
540 );
541 }
542 if (cwd === null) {
543 return <FilesUnavailable />;
544 }
545
546 if (hasFileInspector) {
547 return (
548 <ThreadRouteScreen
549 onReturnToThread={handleReturnToThread}
550 renderInspector={renderInspector}
551 route={props.route}
552 />
553 );
554 }
555
556 const content = (
557 <>
558 <FilesBrowserHeader
559 projectName={projectName}
560 searchQuery={searchQuery}
561 onSearchQueryChange={setSearchQuery}
562 onRefresh={entriesQuery.refresh}
563 onBack={handleReturnToThread}
564 />
565 <ScreenContent insetHorizontal={layout.usesSplitView}>
566 <FileTreeBrowser
567 key={JSON.stringify([environmentId, cwd])}
568 revealSelection={entriesQuery.revealSelection}
569 expandedPaths={entriesQuery.expandedPaths}
570 setExpandedPaths={entriesQuery.setExpandedPaths}
571 entries={entriesQuery.entries}
572 loadingDirectories={entriesQuery.loadingDirectories}
573 onLoadDirectory={entriesQuery.loadDirectory}
574 error={entriesQuery.error}
575 isPending={entriesQuery.isPending}
576 isRefreshing={entriesQuery.isRefreshing}
577 searchQuery={searchQuery}
578 searchResultPaths={entriesQuery.searchResultPaths}
579 searchTruncated={entriesQuery.searchTruncated}
580 selectedPath={entriesQuery.selectedPath}
581 onPreviewFile={handlePreviewFile}
582 onRefresh={entriesQuery.refresh}
583 onSelectFile={(path) => {
584 entriesQuery.selectPath(path);
585 handleSelectFile(path);
586 }}
587 />
588 <FilesToolbarBottomFade />
589 </ScreenContent>
590 </>
591 );
592
593 return Platform.OS === "android" ? <View className="flex-1 bg-header">{content}</View> : content;
594}
595
596export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
597 useAdaptiveWorkspacePaneRole("inspector");
598 const navigation = useNavigation();
599 const { fileInspector } = useAdaptiveWorkspaceLayout();
600 const { appearance, setCodeWordBreak } = useAppearancePreferences();
601 const iconColor = useUniwindTheme()["--color-icon"];
602 const params = props.route.params;
603 const relativePath = normalizeRoutePath(params.path);
604 const targetLine = normalizeRouteLine(firstRouteParam(params.line));
605 const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace(
606 props.route.params,
607 );
608 const fileAccessSession = useEnvironmentQuery(
609 environmentId !== null ? environmentSession.sessionStateAtom(environmentId) : null,
610 );
611 const fileEnvironment = useEnvironmentPresentation(environmentId);
612 const fileAccess = resolveFilesystemReadAccess({
613 isCatalogReady: fileEnvironment.isReady,
614 connection: fileEnvironment.presentation?.connection ?? null,
615 session: fileAccessSession.data,
616 sessionError: fileAccessSession.error,
617 });
618 const { canReadFiles } = fileAccess;
619 const targetPath =
620 cwd !== null && relativePath !== null ? resolveWorkspaceFilePath(cwd, relativePath) : null;
621 const metadata = useEnvironmentQuery(
622 canReadFiles && environmentId !== null && targetPath !== null
623 ? projectEnvironment.fileMetadata({ environmentId, input: { path: targetPath } })
624 : null,
625 );
626 const metadataPending = !metadata.isSuccess && metadata.error === null;
627 const directoryPath = metadata.data?.kind === "directory" ? targetPath : null;
628 const [searchQuery, setSearchQuery] = useState("");
629 const entriesQuery = useFileTreeEntries({
630 environmentId,
631 cwd: canReadFiles ? directoryPath : null,
632 searchQuery,
633 });
634 const [modeOverride, setModeOverride] = useState<{
635 readonly path: string;
636 readonly mode: FileViewMode;
637 } | null>(null);
638 const [previewRevision, setPreviewRevision] = useState(0);
639 const previewKey = JSON.stringify([environmentId, cwd, relativePath, previewRevision]);
640 const [fullScreenPreview, setFullScreenPreview] = useState<FilePreviewSource | null>(null);
641 const isVideoFile = relativePath !== null && isVideoPreviewFile(relativePath);
642 const isAudioFile = relativePath !== null && !isVideoFile && isAudioPreviewFile(relativePath);
643 const isBrowserFile =
644 relativePath !== null && !isVideoFile && isWorkspaceBrowserPreviewPath(relativePath);
645 const isImageFile =
646 relativePath !== null && !isVideoFile && isWorkspaceImagePreviewPath(relativePath);
647 const canPreview =
648 relativePath !== null &&
649 (isMarkdownPreviewFile(relativePath) ||
650 isBrowserFile ||
651 isImageFile ||
652 isVideoFile ||
653 isAudioFile ||
654 filePreviewDelimiter({ name: relativePath }) !== null);
655 const activeMode =
656 relativePath !== null && modeOverride?.path === relativePath
657 ? modeOverride.mode
658 : targetLine !== null && filePreviewDelimiter({ name: relativePath ?? "" }) !== null
659 ? "source"
660 : defaultViewMode(relativePath);
661 const resolvedActiveMode =
662 isVideoFile || isAudioFile ? "preview" : canPreview ? activeMode : "source";
663 const assetPreviewPath =
664 !metadataPending &&
665 directoryPath === null &&
666 (isBrowserFile || isImageFile || isVideoFile || isAudioFile)
667 ? relativePath
668 : null;
669 const assetPreview = useWorkspaceFileAssetUrlState({
670 cwd,
671 environmentId,
672 relativePath: assetPreviewPath,
673 threadId,
674 draftCwd: threadId === null ? cwd : null,
675 });
676 const assetPreviewUri = assetPreview._tag === "Success" ? assetPreview.url : null;
677 const mediaSource: MediaActionsSource | undefined =
678 environmentId !== null &&
679 relativePath !== null &&
680 assetPreview.resource !== null &&
681 "path" in assetPreview.resource &&
682 typeof assetPreview.resource.path === "string" &&
683 (isImageFile || isVideoFile)
684 ? {
685 reference: mediaFileReference(assetPreview.resource.path, cwd),
686 name: basename(relativePath),
687 mimeType:
688 mediaMimeTypeFromExtension(relativePath.slice(relativePath.lastIndexOf("."))) ??
689 "application/octet-stream",
690 environmentId,
691 ...(threadId === null ? {} : { threadId }),
692 resource: assetPreview.resource,
693 }
694 : undefined;
695 const mediaActions = useMediaActions(mediaSource);
696 const videoSource: MediaVideoPreviewSource | null =
697 environmentId !== null &&
698 relativePath !== null &&
699 (assetPreview.resource?._tag === "media-file" ||
700 assetPreview.resource?._tag === "draft-workspace-file")
701 ? {
702 type: "media",
703 environmentId,
704 resource: assetPreview.resource,
705 name: basename(relativePath),
706 mimeType: videoMimeType({ name: relativePath, mimeType: "" }) ?? "video/mp4",
707 actionsSource: mediaSource,
708 }
709 : null;
710 const previewUri =
711 assetPreviewUri === null || previewRevision === 0
712 ? assetPreviewUri
713 : `${assetPreviewUri}${assetPreviewUri.includes("?") ? "&" : "?"}revision=${previewRevision}`;
714 // Remounting the preview after a re-mint is what makes a failed asset URL retryable.
715 const handleRetryPreview = () => {
716 void assetPreview.refresh().finally(() => setPreviewRevision((current) => current + 1));
717 };
718 const needsFileContents =
719 !metadataPending &&
720 directoryPath === null &&
721 relativePath !== null &&
722 !isVideoFile &&
723 !isAudioFile &&
724 (resolvedActiveMode === "source" ||
725 isMarkdownPreviewFile(relativePath) ||
726 filePreviewDelimiter({ name: relativePath }) !== null);
727 const fileQuery = useEnvironmentQuery(
728 canReadFiles &&
729 environmentId !== null &&
730 cwd !== null &&
731 relativePath !== null &&
732 needsFileContents
733 ? projectEnvironment.readFile({
734 environmentId,
735 input: { cwd, relativePath },
736 })
737 : null,
738 );
739 const fileData = fileQuery.data as ProjectReadFileResult | null;
740
741 const handleSelectFile = (path: string) => {
742 const targetPath =
743 directoryPath === null ? path : resolveWorkspaceFilePath(directoryPath, path);
744 const segments = fileRoutePathSegments(
745 resolveWorkspaceRelativeFilePath(cwd, targetPath) ?? targetPath,
746 );
747 // A draft has no thread. `ThreadFile` would stringify null and then wait forever for a
748 // thread to resolve, so a draft stays on its own route and carries its workspace along.
749 if (threadId === null) {
750 navigation.dispatch(
751 StackActions.push("NewTaskFile", {
752 environmentId: String(environmentId),
753 ...(cwd === null ? {} : { cwd }),
754 projectName,
755 path: segments,
756 }),
757 );
758 return;
759 }
760 const destination = {
761 environmentId: String(environmentId),
762 threadId: String(threadId),
763 path: segments,
764 };
765 if (directoryPath !== null) navigation.dispatch(StackActions.push("ThreadFile", destination));
766 else navigation.navigate("ThreadFile", destination);
767 };
768 const renderInspector = (headerInset: number) =>
769 fileInspector.supported && environmentId !== null && cwd !== null ? (
770 <ThreadFileNavigatorPane
771 cwd={directoryPath ?? cwd}
772 environmentId={environmentId}
773 headerInset={headerInset}
774 projectName={directoryPath ?? projectName}
775 selectedPath={directoryPath === null ? relativePath : null}
776 onSelectFile={(path) => {
777 if (directoryPath !== null) entriesQuery.selectPath(path);
778 handleSelectFile(path);
779 }}
780 />
781 ) : undefined;
782 const safeAreaInsets = useSafeAreaInsets();
783 const inspectorHeaderInset = Platform.OS === "ios" ? 0 : safeAreaInsets.top;
784 const renderWorkspaceInspector = () => (
785 <ThreadInspectorContentStack
786 mode="files"
787 resetKeys={[threadId, cwd]}
788 renderFiles={() => renderInspector(inspectorHeaderInset)}
789 />
790 );
791 useRegisterWorkspaceInspector(fileInspector.supported ? renderWorkspaceInspector : undefined);
792
793 const fileMenuActions = (() => {
794 if (relativePath === null) return [];
795 const canToggleMode = canPreview && !isImageFile && !isVideoFile && !isAudioFile;
796 return [
797 canToggleMode
798 ? ({
799 id: "preview",
800 title: filePreviewDelimiter({ name: relativePath }) ? "Table" : "Preview",
801 icon: filePreviewDelimiter({ name: relativePath }) ? "tablecells" : "eye",
802 inline: true,
803 onPress: () => setModeOverride({ path: relativePath, mode: "preview" }),
804 } as const)
805 : null,
806 canToggleMode
807 ? ({
808 id: "source",
809 title: "Source",
810 icon: "doc.text",
811 inline: true,
812 onPress: () => setModeOverride({ path: relativePath, mode: "source" }),
813 } as const)
814 : null,
815 resolvedActiveMode === "source"
816 ? ({
817 id: "word-wrap",
818 title: appearance.codeWordBreak ? "Disable word wrap" : "Enable word wrap",
819 icon: "text.alignleft",
820 inline: false,
821 onPress: () => setCodeWordBreak(!appearance.codeWordBreak),
822 } as const)
823 : null,
824 ...(mediaSource
825 ? mediaActions.actions
826 .filter(({ id }) => id !== "open-file")
827 .map((action) => ({
828 id: action.id,
829 title: action.title,
830 icon:
831 action.id === "save" ? ("square.and.arrow.up" as const) : ("doc.on.doc" as const),
832 inline: false,
833 onPress: action.run,
834 }))
835 : [
836 {
837 id: "copy-path",
838 title: "Copy path",
839 icon: "doc.on.doc",
840 inline: false,
841 onPress: () =>
842 copyTextWithHaptic(
843 formatFilePathForClipboard(
844 relativePath,
845 resolvePathLinkTarget(relativePath, cwd ?? ""),
846 ),
847 ),
848 } as const,
849 ]),
850 fileData?.contents != null
851 ? ({
852 id: "copy-contents",
853 title: fileData.truncated ? "Copy preview" : "Copy contents",
854 icon: "doc.on.doc",
855 inline: false,
856 onPress: () => copyTextWithHaptic(fileData.contents),
857 } as const)
858 : null,
859 isPdfFile({ name: relativePath }) && previewUri !== null
860 ? ({
861 id: "open-pdf",
862 title: "Open PDF",
863 icon: "arrow.up.left.and.arrow.down.right",
864 inline: false,
865 onPress: () =>
866 setFullScreenPreview({
867 kind: "pdf",
868 uri: previewUri,
869 name: basename(relativePath),
870 }),
871 } as const)
872 : null,
873 isBrowserFile && typeof assetPreviewUri === "string"
874 ? ({
875 id: "open-browser",
876 title: Platform.OS === "ios" ? "Open in Safari" : "Open in browser",
877 icon: "safari",
878 inline: false,
879 onPress: () => tryOpenExternalUrl(assetPreviewUri, "file-preview"),
880 } as const)
881 : null,
882 resolvedActiveMode === "preview" &&
883 (isBrowserFile || isImageFile || isVideoFile || isAudioFile)
884 ? ({
885 id: "refresh",
886 title: "Refresh",
887 icon: "arrow.clockwise",
888 inline: false,
889 onPress: async () => {
890 if (isVideoFile || isAudioFile) await assetPreview.refresh();
891 setPreviewRevision((current) => current + 1);
892 },
893 } as const)
894 : null,
895 ].filter((action) => action !== null);
896 })();
897
898 const handleReturnToThread = () => {
899 if (environmentId !== null && threadId !== null) {
900 navigation.dispatch(
901 StackActions.replace("Thread", {
902 environmentId: String(environmentId),
903 threadId: String(threadId),
904 }),
905 );
906 }
907 };
908 const handleBack = () => {
909 if (navigation.canGoBack()) {
910 navigation.goBack();
911 return;
912 }
913 handleReturnToThread();
914 };
915
916 if (environmentId === null || (threadId !== null && selectedThread === null)) {
917 return <LoadingScreen message="Opening file..." messagePlacement="above-spinner" />;
918 }
919
920 if (!canReadFiles) {
921 if (fileAccess.isPending) {
922 return <LoadingScreen message="Checking file access..." messagePlacement="above-spinner" />;
923 }
924 return (
925 <FilesUnavailable detail={fileAccess.error ?? "This connection cannot read host files."} />
926 );
927 }
928 if (cwd === null) {
929 return <FilesUnavailable />;
930 }
931
932 if (relativePath === null) {
933 return (
934 <View className="flex-1 items-center justify-center bg-sheet px-6">
935 <NativeStackScreenOptions options={{ title: "Files" }} />
936 <EmptyState title="File unavailable" detail="This file path is invalid." />
937 </View>
938 );
939 }
940
941 if (metadataPending) {
942 return <LoadingScreen message="Opening file..." messagePlacement="above-spinner" />;
943 }
944 if (directoryPath !== null) {
945 return (
946 <View className={Platform.OS === "android" ? "flex-1 bg-header" : "flex-1 bg-sheet"}>
947 <FilesBrowserHeader
948 projectName={directoryPath}
949 searchQuery={searchQuery}
950 onSearchQueryChange={setSearchQuery}
951 onRefresh={entriesQuery.refresh}
952 onBack={handleBack}
953 />
954 <ScreenContent>
955 <FileTreeBrowser
956 key={JSON.stringify([environmentId, directoryPath])}
957 revealSelection={entriesQuery.revealSelection}
958 expandedPaths={entriesQuery.expandedPaths}
959 setExpandedPaths={entriesQuery.setExpandedPaths}
960 entries={entriesQuery.entries}
961 loadingDirectories={entriesQuery.loadingDirectories}
962 onLoadDirectory={entriesQuery.loadDirectory}
963 error={entriesQuery.error}
964 isPending={entriesQuery.isPending}
965 isRefreshing={entriesQuery.isRefreshing}
966 searchQuery={searchQuery}
967 searchResultPaths={entriesQuery.searchResultPaths}
968 searchTruncated={entriesQuery.searchTruncated}
969 selectedPath={entriesQuery.selectedPath}
970 onRefresh={entriesQuery.refresh}
971 onSelectFile={(path) => {
972 entriesQuery.selectPath(path);
973 handleSelectFile(path);
974 }}
975 />
976 <FilesToolbarBottomFade />
977 </ScreenContent>
978 </View>
979 );
980 }
981
982 const headerSubtitle = fileHeaderSubtitle(projectName, relativePath);
983
984 return (
985 <View className="flex-1 bg-sheet">
986 <FileHeader
987 title={basename(relativePath)}
988 subtitle={headerSubtitle}
989 iconColor={iconColor}
990 activeMode={resolvedActiveMode}
991 fileInspectorSupported={fileInspector.supported}
992 onBack={handleBack}
993 onReturnToThread={handleReturnToThread}
994 actions={fileMenuActions}
995 />
996 <ScreenContent>
997 <FileContent
998 key={previewKey}
999 activeMode={resolvedActiveMode}
1000 cwd={cwd}
1001 environmentId={environmentId}
1002 previewUri={previewUri}
1003 previewFailure={assetPreview._tag === "Failure" ? assetPreview.reason : null}
1004 onRetryPreview={handleRetryPreview}
1005 videoSource={videoSource}
1006 mediaSource={mediaSource}
1007 resolveVideoUri={assetPreview.refresh}
1008 fileContents={fileData?.contents ?? null}
1009 fileError={fileQuery.error}
1010 initialLine={targetLine}
1011 relativePath={relativePath}
1012 threadId={threadId}
1013 truncated={fileData?.truncated ?? false}
1014 onRefresh={() => fileQuery.refresh()}
1015 />
1016 </ScreenContent>
1017 <FilePreviewModal
1018 source={fullScreenPreview}
1019 onRequestClose={() => setFullScreenPreview(null)}
1020 />
1021 </View>
1022 );
1023}