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