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

ThreadFilesRouteScreen.tsx

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