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

ThreadFilesRouteScreen.tsx

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