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

ThreadFilesRouteScreen.tsx

921 lines31.5 KB

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