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