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