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

ThreadFilesRouteScreen.tsx

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