Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadFilesRouteScreen.tsx

929 lines31.8 KB

1import { formatFilePathForClipboard } from "@t3tools/client-runtime/media-actions";
2import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks";
3import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem";
4import { environmentSession } from "../../state/session";
5import { NativeStackScreenOptions } from "../../native/StackHeader";
6import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
7import { useEffect, useId, useRef, useState } from "react";
8import { Platform, View } from "react-native";
9import { useSafeAreaInsets } from "react-native-safe-area-context";
10import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg";
11import { EnvironmentId, type ProjectReadFileResult, ThreadId } from "@t3tools/contracts";
12import { videoMimeType } from "@t3tools/shared/video";
13import {
14 isWorkspaceBrowserPreviewPath,
15 isWorkspaceImagePreviewPath,
16 mediaMimeTypeFromExtension,
17} from "@t3tools/shared/filePreview";
18import { mediaFileReference } from "@t3tools/client-runtime/media-reference";
19​
20import { ScreenContent } from "../../components/ui/ScreenContent";
21import { AudioFilePreview } from "./AudioFilePreview";
22import { EmptyState } from "../../components/ui/EmptyState";
23import { FilePreviewModal, type FilePreviewSource } from "../../components/FilePreviewModal";
24import { LoadingScreen } from "../../components/LoadingScreen";
25import { resolveFileSelectionNavigationAction } from "../../lib/adaptive-navigation";
26import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
27import { isPdfFile } from "../../lib/filePreview";
28import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
29import { useUniwindTheme } from "../../lib/useUniwindTheme";
30import type { MediaVideoPreviewSource } from "../../lib/videoPreviewSource";
31import { useMediaActions } from "../../state/mediaActions";
32import { type MediaActionsSource } from "../../lib/mediaActionsSource";
33import { useThreadSelection } from "../../state/use-thread-selection";
34import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
35import { useEnvironmentQuery } from "../../state/query";
36import { useEnvironmentPresentation } from "../../state/presentation";
37import { projectEnvironment } from "../../state/projects";
38import type { AssetUrlFailureReason } from "../../state/asset-url-state";
39import {
40 useAdaptiveWorkspaceLayout,
41 useAdaptiveWorkspacePaneRole,
42 useRegisterWorkspaceInspector,
43} from "../layout/AdaptiveWorkspaceLayout";
44import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
45import { ThreadRouteScreen } from "../threads/ThreadRouteScreen";
46import { FilePreviewLoading, FilePreviewNotice } from "./FilePreviewFeedback";
47import { FileMarkdownPreview } from "./FileMarkdownPreview";
48import { ThreadInspectorContentStack } from "../threads/thread-inspector-content-stack";
49import { FileTreeBrowser } from "./FileTreeBrowser";
50import { useFileTreeEntries } from "./useFileTreeEntries";
51import { preloadWorkspaceFileContents } from "./preload-workspace-file";
52import { SourceFileSurface } from "./SourceFileSurface";
53import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
54import { ThreadFileNavigatorPane } from "./thread-file-navigator-pane";
55import { AppBar } from "../../components/ui/AppBar";
56import { WorkspaceFileImagePreview } from "./WorkspaceFileImagePreview";
57import { WorkspaceFilePreviewError } from "./WorkspaceFilePreviewError";
58import { WorkspaceFileVideoPreview } from "./WorkspaceFileVideoPreview";
59import { WorkspaceFileWebPreview } from "./WorkspaceFileWebPreview";
60import {
61 basename,
62 fileHeaderSubtitle,
63 isAudioPreviewFile,
64 isMarkdownPreviewFile,
65 isSvgImagePreviewFile,
66 isVideoPreviewFile,
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 );
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 );
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;
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;
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;
202​
203function defaultViewMode(path: string | null): FileViewMode {
204 return path !== null &&
205 (isWorkspaceBrowserPreviewPath(path) ||
206 isWorkspaceImagePreviewPath(path) ||
207 isVideoPreviewFile(path) ||
208 isAudioPreviewFile(path))
209 ? "preview"
210 : "source";
212​
213function FileContent(props: {
214 readonly activeMode: FileViewMode;
215 readonly cwd: string;
216 readonly environmentId: EnvironmentId;
217 readonly previewUri: string | null;
218 readonly previewFailure: AssetUrlFailureReason | null;
219 readonly onRetryPreview: () => void;
220 readonly videoSource: MediaVideoPreviewSource | null;
221 readonly mediaSource?: MediaActionsSource;
222 readonly resolveVideoUri: () => Promise<string | null>;
223 readonly fileContents: string | null;
224 readonly fileError: string | null;
225 readonly relativePath: string;
226 readonly threadId: ThreadId | null;
227 readonly initialLine: number | null;
228 readonly truncated: boolean;
229 readonly onRefresh?: () => Promise<void> | void;
230}) {
231 // Reopening a mutable host file must not reuse a poster from an earlier visit.
232 const thumbnailInstanceId = useId();
233 const insets = useSafeAreaInsets();
234 const columnMetrics = useNativeColumnLayoutMetrics();
235 const reservedHeaderInset =
236 Platform.OS === "ios" && props.truncated ? (columnMetrics?.safeArea.top ?? insets.top) : 0;
237 const isMarkdown = isMarkdownPreviewFile(props.relativePath);
238 const isBrowserFile = isWorkspaceBrowserPreviewPath(props.relativePath);
239 const isImageFile = isWorkspaceImagePreviewPath(props.relativePath);
240 const isVideoFile = isVideoPreviewFile(props.relativePath);
241 const isAudioFile = isAudioPreviewFile(props.relativePath);
242 const needsAssetUrl =
243 isVideoFile ||
244 isAudioFile ||
245 (props.activeMode === "preview" && (isImageFile || isBrowserFile));
246​
247 if (needsAssetUrl && props.previewFailure !== null) {
248 return (
249 <WorkspaceFilePreviewError
250 environmentId={props.environmentId}
251 reason={props.previewFailure}
252 onRetry={props.onRetryPreview}
253 />
254 );
255 }
256​
257 if (isVideoFile) {
258 return (
259 <WorkspaceFileVideoPreview
260 name={basename(props.relativePath)}
261 thumbnailKey={`workspace-video:${thumbnailInstanceId}`}
262 uri={props.previewUri}
263 source={props.videoSource}
264 resolvePlaybackUri={props.resolveVideoUri}
265 />
266 );
267 }
268​
269 if (isAudioFile) {
270 return props.previewUri === null ? (
271 <FilePreviewLoading message="Loading file..." />
272 ) : (
273 <AudioFilePreview uri={props.previewUri} onRetry={props.onRetryPreview} />
274 );
275 }
276​
277 if (props.activeMode === "preview" && isImageFile) {
278 if (isSvgImagePreviewFile(props.relativePath)) {
279 return <WorkspaceFileWebPreview uri={props.previewUri} />;
280 }
281 return (
282 <WorkspaceFileImagePreview
283 accessibilityLabel={basename(props.relativePath)}
284 uri={props.previewUri}
285 actionsSource={props.mediaSource}
286 />
287 );
288 }
289​
290 if (props.activeMode === "preview" && isBrowserFile) {
291 return <WorkspaceFileWebPreview uri={props.previewUri} />;
292 }
293​
294 if (props.fileError && props.fileContents === null) {
295 return (
296 <View className="flex-1 items-center justify-center bg-sheet px-6">
297 <EmptyState title="File unavailable" detail={props.fileError} />
298 </View>
299 );
300 }
301​
302 if (props.fileContents === null) {
303 return <FilePreviewLoading message="Loading file..." />;
304 }
305​
306 return (
307 <View className="flex-1 bg-sheet" style={{ paddingTop: reservedHeaderInset }}>
308 {props.truncated ? (
309 <FilePreviewNotice title="Partial file">
310 Preview limited to the first 1 MB of a truncated file.
311 </FilePreviewNotice>
312 ) : null}
313 {props.activeMode === "preview" && isMarkdown ? (
314 <FileMarkdownPreview
315 cwd={props.cwd}
316 environmentId={props.environmentId}
317 markdown={props.fileContents}
318 relativePath={props.relativePath}
319 threadId={props.threadId}
320 onRefresh={props.onRefresh}
321 />
322 ) : (
323 <SourceFileSurface
324 contents={props.fileContents}
325 path={props.relativePath}
326 initialLine={props.initialLine}
327 headerInsetTop={props.truncated ? 0 : undefined}
328 onRefresh={props.onRefresh}
329 />
330 )}
331 </View>
332 );
334​
335type ThreadFilesRouteScreenProps = StaticScreenProps<{
336 readonly environmentId: string;
337 readonly threadId: string;
338}>;
339​
340type ThreadFileRouteScreenProps = StaticScreenProps<{
341 readonly environmentId: string;
342 readonly threadId?: string;
343 readonly path: string[];
344 readonly line?: string;
345 readonly cwd?: string;
346 readonly projectName?: string;
347}>;
348​
349function useThreadFilesWorkspace(params: {
350 readonly environmentId?: string | string[];
351 readonly threadId?: string | string[];
352 readonly cwd?: string | string[];
353 readonly projectName?: string | string[];
354}) {
355 const routeEnvironmentId = firstRouteParam(params.environmentId);
356 const routeThreadId = firstRouteParam(params.threadId);
357 const routeCwd = firstRouteParam(params.cwd);
358 const routeProjectName = firstRouteParam(params.projectName);
359 const { selectedThread, selectedThreadProject } = useThreadSelection();
360 const { selectedThreadCwd } = useSelectedThreadWorktree();
361 const environmentId =
362 routeEnvironmentId !== null
363 ? EnvironmentId.make(routeEnvironmentId)
364 : (selectedThread?.environmentId ?? null);
365 const threadId = routeThreadId !== null ? ThreadId.make(routeThreadId) : null;
366 const project = selectedThreadProject as {
367 readonly title?: string;
368 readonly workspaceRoot?: string;
369 } | null;
370​
371 return {
372 cwd: routeCwd ?? selectedThreadCwd ?? project?.workspaceRoot ?? null,
373 environmentId,
374 projectName: routeProjectName ?? project?.title ?? "Files",
375 selectedThread,
376 threadId,
377 };
379​
380function FilesUnavailable({
381 detail = "This thread does not have an active workspace path.",
382}: {
383 detail?: string;
384}) {
385 return (
386 <View className="flex-1 items-center justify-center bg-sheet px-6">
387 <NativeStackScreenOptions options={{ title: "Files" }} />
388 <EmptyState title="Files unavailable" detail={detail} />
389 </View>
390 );
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 );
420​
421export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {
422 useAdaptiveWorkspacePaneRole("inspector");
423 const navigation = useNavigation();
424 const { fileInspector, layout, showAuxiliaryPane } = useAdaptiveWorkspaceLayout();
425 const [searchQuery, setSearchQuery] = useState("");
426 const { themeAppearance: highlightTheme } = useAppearancePreferences();
427 const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace(
428 props.route.params,
429 );
430 const revealedInspectorRef = useRef(false);
431 const fileAccessSession = useEnvironmentQuery(
432 environmentId !== null ? environmentSession.sessionStateAtom(environmentId) : null,
433 );
434 const fileEnvironment = useEnvironmentPresentation(environmentId);
435 const fileAccess = resolveFilesystemReadAccess({
436 isCatalogReady: fileEnvironment.isReady,
437 connection: fileEnvironment.presentation?.connection ?? null,
438 session: fileAccessSession.data,
439 sessionError: fileAccessSession.error,
440 });
441 const { canReadFiles } = fileAccess;
442 const entriesQuery = useFileTreeEntries({
443 environmentId,
444 cwd: !canReadFiles || fileInspector.supported ? null : cwd,
445 searchQuery,
446 });
447 const handleReturnToThread = () => {
448 if (navigation.canGoBack()) {
449 navigation.goBack();
450 return;
451 }
452 if (environmentId !== null && threadId !== null) {
453 navigation.dispatch(
454 StackActions.replace("Thread", {
455 environmentId: String(environmentId),
456 threadId: String(threadId),
457 }),
458 );
459 }
460 };
461​
462 const handleSelectFile = (path: string) => {
463 if (environmentId === null || threadId === null) {
464 return;
465 }
466 const params = {
467 environmentId: String(environmentId),
468 threadId: String(threadId),
469 path: path.split("/").filter((segment) => segment.length > 0),
470 };
471 const navigationAction = resolveFileSelectionNavigationAction({
472 hasPersistentFileInspector: fileInspector.supported,
473 });
474 if (navigationAction === "replace") {
475 navigation.dispatch(StackActions.replace("ThreadFile", params));
476 return;
477 }
478 navigation.navigate("ThreadFile", params);
479 };
480 const renderInspector = (headerInset: number) =>
481 environmentId !== null && cwd !== null ? (
482 <ThreadFileNavigatorPane
483 cwd={cwd}
484 environmentId={environmentId}
485 headerInset={headerInset}
486 projectName={projectName}
487 selectedPath={null}
488 onSelectFile={handleSelectFile}
489 />
490 ) : null;
491 const handlePreviewFile = (relativePath: string) => {
492 if (environmentId === null || cwd === null) {
493 return;
494 }
495 preloadWorkspaceFileContents({
496 cwd,
497 environmentId,
498 relativePath,
499 theme: highlightTheme,
500 });
501 };
502 useEffect(() => {
503 if (fileInspector.supported && cwd !== null && !revealedInspectorRef.current) {
504 revealedInspectorRef.current = true;
505 showAuxiliaryPane("inspector");
506 }
507 }, [cwd, fileInspector.supported, showAuxiliaryPane]);
508​
509 if (selectedThread === null || environmentId === null || threadId === null) {
510 if (fileInspector.supported) {
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 (fileInspector.supported) {
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 entries={entriesQuery.entries}
557 loadingDirectories={entriesQuery.loadingDirectories}
558 onLoadDirectory={entriesQuery.loadDirectory}
559 error={entriesQuery.error}
560 isPending={entriesQuery.isPending}
561 isRefreshing={entriesQuery.isRefreshing}
562 searchQuery={searchQuery}
563 searchResultPaths={entriesQuery.searchResultPaths}
564 searchTruncated={entriesQuery.searchTruncated}
565 selectedPath={null}
566 onPreviewFile={handlePreviewFile}
567 onRefresh={entriesQuery.refresh}
568 onSelectFile={handleSelectFile}
569 />
570 <FilesToolbarBottomFade />
571 </ScreenContent>
572 </>
573 );
574​
575 return Platform.OS === "android" ? <View className="flex-1 bg-header">{content}</View> : content;
577​
578export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
579 useAdaptiveWorkspacePaneRole("inspector");
580 const navigation = useNavigation();
581 const { fileInspector } = useAdaptiveWorkspaceLayout();
582 const { appearance, setCodeWordBreak } = useAppearancePreferences();
583 const iconColor = useUniwindTheme()["--color-icon"];
584 const params = props.route.params;
585 const relativePath = normalizeRoutePath(params.path);
586 const targetLine = normalizeRouteLine(firstRouteParam(params.line));
587 const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace(
588 props.route.params,
589 );
590 const [modeOverride, setModeOverride] = useState<{
591 readonly path: string;
592 readonly mode: FileViewMode;
593 } | null>(null);
594 const [previewRevision, setPreviewRevision] = useState(0);
595 const previewKey = JSON.stringify([environmentId, cwd, relativePath, previewRevision]);
596 const [fullScreenPreview, setFullScreenPreview] = useState<FilePreviewSource | null>(null);
597 const isVideoFile = relativePath !== null && isVideoPreviewFile(relativePath);
598 const isAudioFile = relativePath !== null && !isVideoFile && isAudioPreviewFile(relativePath);
599 const isBrowserFile =
600 relativePath !== null && !isVideoFile && isWorkspaceBrowserPreviewPath(relativePath);
601 const isImageFile =
602 relativePath !== null && !isVideoFile && isWorkspaceImagePreviewPath(relativePath);
603 const canPreview =
604 relativePath !== null &&
605 (isMarkdownPreviewFile(relativePath) ||
606 isBrowserFile ||
607 isImageFile ||
608 isVideoFile ||
609 isAudioFile);
610 const activeMode =
611 relativePath !== null && modeOverride?.path === relativePath
612 ? modeOverride.mode
613 : defaultViewMode(relativePath);
614 const resolvedActiveMode =
615 isVideoFile || isAudioFile ? "preview" : canPreview ? activeMode : "source";
616 const assetPreviewPath =
617 isBrowserFile || isImageFile || isVideoFile || isAudioFile ? relativePath : null;
618 const assetPreview = useWorkspaceFileAssetUrlState({
619 cwd,
620 environmentId,
621 relativePath: assetPreviewPath,
622 threadId,
623 draftCwd: threadId === null ? cwd : null,
624 });
625 const assetPreviewUri = assetPreview._tag === "Success" ? assetPreview.url : null;
626 const mediaSource: MediaActionsSource | undefined =
627 environmentId !== null &&
628 relativePath !== null &&
629 assetPreview.resource !== null &&
630 "path" in assetPreview.resource &&
631 typeof assetPreview.resource.path === "string" &&
632 (isImageFile || isVideoFile)
633 ? {
634 reference: mediaFileReference(assetPreview.resource.path, cwd),
635 name: basename(relativePath),
636 mimeType:
637 mediaMimeTypeFromExtension(relativePath.slice(relativePath.lastIndexOf("."))) ??
638 "application/octet-stream",
639 environmentId,
640 ...(threadId === null ? {} : { threadId }),
641 resource: assetPreview.resource,
642 }
643 : undefined;
644 const mediaActions = useMediaActions(mediaSource);
645 const videoSource: MediaVideoPreviewSource | null =
646 environmentId !== null &&
647 relativePath !== null &&
648 (assetPreview.resource?._tag === "media-file" ||
649 assetPreview.resource?._tag === "draft-workspace-file")
650 ? {
651 type: "media",
652 environmentId,
653 resource: assetPreview.resource,
654 name: basename(relativePath),
655 mimeType: videoMimeType({ name: relativePath, mimeType: "" }) ?? "video/mp4",
656 actionsSource: mediaSource,
657 }
658 : null;
659 const previewUri =
660 assetPreviewUri === null || previewRevision === 0
661 ? assetPreviewUri
662 : `${assetPreviewUri}${assetPreviewUri.includes("?") ? "&" : "?"}revision=${previewRevision}`;
663 // Remounting the preview after a re-mint is what makes a failed asset URL retryable.
664 const handleRetryPreview = () => {
665 void assetPreview.refresh().finally(() => setPreviewRevision((current) => current + 1));
666 };
667 const needsFileContents =
668 relativePath !== null &&
669 !isVideoFile &&
670 !isAudioFile &&
671 (resolvedActiveMode === "source" || isMarkdownPreviewFile(relativePath));
672 const fileAccessSession = useEnvironmentQuery(
673 environmentId !== null ? environmentSession.sessionStateAtom(environmentId) : null,
674 );
675 const fileEnvironment = useEnvironmentPresentation(environmentId);
676 const fileAccess = resolveFilesystemReadAccess({
677 isCatalogReady: fileEnvironment.isReady,
678 connection: fileEnvironment.presentation?.connection ?? null,
679 session: fileAccessSession.data,
680 sessionError: fileAccessSession.error,
681 });
682 const { canReadFiles } = fileAccess;
683 const fileQuery = useEnvironmentQuery(
684 canReadFiles &&
685 environmentId !== null &&
686 cwd !== null &&
687 relativePath !== null &&
688 needsFileContents
689 ? projectEnvironment.readFile({
690 environmentId,
691 input: { cwd, relativePath },
692 })
693 : null,
694 );
695 const fileData = fileQuery.data as ProjectReadFileResult | null;
696​
697 const handleSelectFile = (path: string) => {
698 const segments = path.split("/").filter(Boolean);
699 // A draft has no thread. `ThreadFile` would stringify null and then wait forever for a
700 // thread to resolve, so a draft stays on its own route and carries its workspace along.
701 if (threadId === null) {
702 navigation.dispatch(
703 StackActions.push("NewTaskFile", {
704 environmentId: String(environmentId),
705 ...(cwd === null ? {} : { cwd }),
706 projectName,
707 path: segments,
708 }),
709 );
710 return;
711 }
712 navigation.navigate("ThreadFile", {
713 environmentId: String(environmentId),
714 threadId: String(threadId),
715 path: segments,
716 });
717 };
718 const renderInspector = (headerInset: number) =>
719 fileInspector.supported && environmentId !== null && cwd !== null ? (
720 <ThreadFileNavigatorPane
721 cwd={cwd}
722 environmentId={environmentId}
723 headerInset={headerInset}
724 projectName={projectName}
725 selectedPath={relativePath}
726 onSelectFile={handleSelectFile}
727 />
728 ) : undefined;
729 const safeAreaInsets = useSafeAreaInsets();
730 const inspectorHeaderInset = Platform.OS === "ios" ? 0 : safeAreaInsets.top;
731 const renderWorkspaceInspector = () => (
732 <ThreadInspectorContentStack
733 mode="files"
734 resetKeys={[threadId, cwd]}
735 renderFiles={() => renderInspector(inspectorHeaderInset)}
736 />
737 );
738 useRegisterWorkspaceInspector(fileInspector.supported ? renderWorkspaceInspector : undefined);
739​
740 const fileMenuActions = (() => {
741 if (relativePath === null) return [];
742 const canToggleMode = canPreview && !isImageFile && !isVideoFile && !isAudioFile;
743 return [
744 canToggleMode
745 ? ({
746 id: "preview",
747 title: "Preview",
748 icon: "eye",
749 inline: true,
750 onPress: () => setModeOverride({ path: relativePath, mode: "preview" }),
751 } as const)
752 : null,
753 canToggleMode
754 ? ({
755 id: "source",
756 title: "Source",
757 icon: "doc.text",
758 inline: true,
759 onPress: () => setModeOverride({ path: relativePath, mode: "source" }),
760 } as const)
761 : null,
762 resolvedActiveMode === "source"
763 ? ({
764 id: "word-wrap",
765 title: appearance.codeWordBreak ? "Disable word wrap" : "Enable word wrap",
766 icon: "text.alignleft",
767 inline: false,
768 onPress: () => setCodeWordBreak(!appearance.codeWordBreak),
769 } as const)
770 : null,
771 ...(mediaSource
772 ? mediaActions.actions
773 .filter(({ id }) => id !== "open-file")
774 .map((action) => ({
775 id: action.id,
776 title: action.title,
777 icon:
778 action.id === "save" ? ("square.and.arrow.up" as const) : ("doc.on.doc" as const),
779 inline: false,
780 onPress: action.run,
781 }))
782 : [
783 {
784 id: "copy-path",
785 title: "Copy path",
786 icon: "doc.on.doc",
787 inline: false,
788 onPress: () =>
789 copyTextWithHaptic(
790 formatFilePathForClipboard(
791 relativePath,
792 resolvePathLinkTarget(relativePath, cwd ?? ""),
793 ),
794 ),
795 } as const,
796 ]),
797 fileData?.contents != null
798 ? ({
799 id: "copy-contents",
800 title: fileData.truncated ? "Copy preview" : "Copy contents",
801 icon: "doc.on.doc",
802 inline: false,
803 onPress: () => copyTextWithHaptic(fileData.contents),
804 } as const)
805 : null,
806 isPdfFile({ name: relativePath }) && previewUri !== null
807 ? ({
808 id: "open-pdf",
809 title: "Open PDF",
810 icon: "arrow.up.left.and.arrow.down.right",
811 inline: false,
812 onPress: () =>
813 setFullScreenPreview({
814 kind: "pdf",
815 uri: previewUri,
816 name: basename(relativePath),
817 }),
818 } as const)
819 : null,
820 isBrowserFile && typeof assetPreviewUri === "string"
821 ? ({
822 id: "open-browser",
823 title: Platform.OS === "ios" ? "Open in Safari" : "Open in browser",
824 icon: "safari",
825 inline: false,
826 onPress: () => tryOpenExternalUrl(assetPreviewUri, "file-preview"),
827 } as const)
828 : null,
829 resolvedActiveMode === "preview" &&
830 (isBrowserFile || isImageFile || isVideoFile || isAudioFile)
831 ? ({
832 id: "refresh",
833 title: "Refresh",
834 icon: "arrow.clockwise",
835 inline: false,
836 onPress: async () => {
837 if (isVideoFile || isAudioFile) await assetPreview.refresh();
838 setPreviewRevision((current) => current + 1);
839 },
840 } as const)
841 : null,
842 ].filter((action) => action !== null);
843 })();
844​
845 const handleReturnToThread = () => {
846 if (environmentId !== null && threadId !== null) {
847 navigation.dispatch(
848 StackActions.replace("Thread", {
849 environmentId: String(environmentId),
850 threadId: String(threadId),
851 }),
852 );
853 }
854 };
855 const handleBack = () => {
856 if (navigation.canGoBack()) {
857 navigation.goBack();
858 return;
859 }
860 handleReturnToThread();
861 };
862​
863 if (environmentId === null || (threadId !== null && selectedThread === null)) {
864 return <LoadingScreen message="Opening file..." messagePlacement="above-spinner" />;
865 }
866​
867 if (!canReadFiles) {
868 if (fileAccess.isPending) {
869 return <LoadingScreen message="Checking file access..." messagePlacement="above-spinner" />;
870 }
871 return (
872 <FilesUnavailable detail={fileAccess.error ?? "This connection cannot read host files."} />
873 );
874 }
875 if (cwd === null) {
876 return <FilesUnavailable />;
877 }
878​
879 if (relativePath === null) {
880 return (
881 <View className="flex-1 items-center justify-center bg-sheet px-6">
882 <NativeStackScreenOptions options={{ title: "Files" }} />
883 <EmptyState title="File unavailable" detail="This file path is invalid." />
884 </View>
885 );
886 }
887​
888 const headerSubtitle = fileHeaderSubtitle(projectName, relativePath);
889​
890 return (
891 <View className="flex-1 bg-sheet">
892 <FileHeader
893 title={basename(relativePath)}
894 subtitle={headerSubtitle}
895 iconColor={iconColor}
896 activeMode={resolvedActiveMode}
897 fileInspectorSupported={fileInspector.supported}
898 onBack={handleBack}
899 onReturnToThread={handleReturnToThread}
900 actions={fileMenuActions}
901 />
902 <ScreenContent>
903 <FileContent
904 key={previewKey}
905 activeMode={resolvedActiveMode}
906 cwd={cwd}
907 environmentId={environmentId}
908 previewUri={previewUri}
909 previewFailure={assetPreview._tag === "Failure" ? assetPreview.reason : null}
910 onRetryPreview={handleRetryPreview}
911 videoSource={videoSource}
912 mediaSource={mediaSource}
913 resolveVideoUri={assetPreview.refresh}
914 fileContents={fileData?.contents ?? null}
915 fileError={fileQuery.error}
916 initialLine={targetLine}
917 relativePath={relativePath}
918 threadId={threadId}
919 truncated={fileData?.truncated ?? false}
920 onRefresh={() => fileQuery.refresh()}
921 />
922 </ScreenContent>
923 <FilePreviewModal
924 source={fullScreenPreview}
925 onRequestClose={() => setFullScreenPreview(null)}
926 />
927 </View>
928 );