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

ThreadFilesRouteScreen.tsx

1,015 lines35.4 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 { useId, 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 } = 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 fileAccessSession = useEnvironmentQuery(
442 environmentId !== null ? environmentSession.sessionStateAtom(environmentId) : null,
443 );
444 const fileEnvironment = useEnvironmentPresentation(environmentId);
445 const fileAccess = resolveFilesystemReadAccess({
446 isCatalogReady: fileEnvironment.isReady,
447 connection: fileEnvironment.presentation?.connection ?? null,
448 session: fileAccessSession.data,
449 sessionError: fileAccessSession.error,
450 });
451 const { canReadFiles } = fileAccess;
452 const entriesQuery = useFileTreeEntries({
453 environmentId,
454 cwd: canReadFiles && !hasFileInspector ? cwd : null,
455 searchQuery,
456 });
457 const handleReturnToThread = () => {
458 if (navigation.canGoBack()) {
459 navigation.goBack();
460 return;
461 }
462 if (environmentId !== null && threadId !== null) {
463 navigation.dispatch(
464 StackActions.replace("Thread", {
465 environmentId: String(environmentId),
466 threadId: String(threadId),
467 }),
468 );
469 }
470 };
471​
472 const handleSelectFile = (path: string) => {
473 if (environmentId === null || cwd === null) {
474 return;
475 }
476 const params = {
477 environmentId: String(environmentId),
478 ...(threadId === null ? { cwd, projectName } : { threadId: String(threadId) }),
479 path: path.split("/").filter((segment) => segment.length > 0),
480 };
481 if (threadId === null) {
482 navigation.navigate("NewTaskFile", params);
483 return;
484 }
485 if (hasFileInspector) {
486 navigation.dispatch(StackActions.replace("ThreadFile", params));
487 return;
488 }
489 navigation.navigate("ThreadFile", params);
490 };
491 const renderInspector = (headerInset: number) =>
492 environmentId !== null && cwd !== null ? (
493 <ThreadFileNavigatorPane
494 cwd={cwd}
495 environmentId={environmentId}
496 headerInset={headerInset}
497 projectName={projectName}
498 selectedPath={null}
499 onSelectFile={handleSelectFile}
500 />
501 ) : null;
502 const handlePreviewFile = (relativePath: string) => {
503 if (environmentId === null || cwd === null) {
504 return;
505 }
506 preloadWorkspaceFileContents({
507 cwd,
508 environmentId,
509 relativePath,
510 theme: highlightTheme,
511 });
512 };
513 if (environmentId === null || (threadId !== null && selectedThread === null)) {
514 if (hasFileInspector) {
515 return (
516 <ThreadRouteScreen
517 onReturnToThread={handleReturnToThread}
518 renderInspector={renderInspector}
519 route={props.route}
520 />
521 );
522 }
523 return <LoadingScreen message="Opening files..." messagePlacement="above-spinner" />;
524 }
525​
526 if (!canReadFiles) {
527 if (fileAccess.isPending) {
528 return <LoadingScreen message="Checking file access..." messagePlacement="above-spinner" />;
529 }
530 return (
531 <FilesUnavailable detail={fileAccess.error ?? "This connection cannot read host files."} />
532 );
533 }
534 if (cwd === null) {
535 return <FilesUnavailable />;
536 }
537​
538 if (hasFileInspector) {
539 return (
540 <ThreadRouteScreen
541 onReturnToThread={handleReturnToThread}
542 renderInspector={renderInspector}
543 route={props.route}
544 />
545 );
546 }
547​
548 const content = (
549 <>
550 <FilesBrowserHeader
551 projectName={projectName}
552 searchQuery={searchQuery}
553 onSearchQueryChange={setSearchQuery}
554 onRefresh={entriesQuery.refresh}
555 onBack={handleReturnToThread}
556 />
557 <ScreenContent insetHorizontal={layout.usesSplitView}>
558 <FileTreeBrowser
559 key={JSON.stringify([environmentId, cwd])}
560 revealSelection={entriesQuery.revealSelection}
561 expandedPaths={entriesQuery.expandedPaths}
562 setExpandedPaths={entriesQuery.setExpandedPaths}
563 entries={entriesQuery.entries}
564 loadingDirectories={entriesQuery.loadingDirectories}
565 onLoadDirectory={entriesQuery.loadDirectory}
566 error={entriesQuery.error}
567 isPending={entriesQuery.isPending}
568 isRefreshing={entriesQuery.isRefreshing}
569 searchQuery={searchQuery}
570 searchResultPaths={entriesQuery.searchResultPaths}
571 searchTruncated={entriesQuery.searchTruncated}
572 selectedPath={entriesQuery.selectedPath}
573 onPreviewFile={handlePreviewFile}
574 onRefresh={entriesQuery.refresh}
575 onSelectFile={(path) => {
576 entriesQuery.selectPath(path);
577 handleSelectFile(path);
578 }}
579 />
580 <FilesToolbarBottomFade />
581 </ScreenContent>
582 </>
583 );
584​
585 return Platform.OS === "android" ? <View className="flex-1 bg-header">{content}</View> : content;
587​
588export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
589 useAdaptiveWorkspacePaneRole("inspector");
590 const navigation = useNavigation();
591 const { fileInspector } = useAdaptiveWorkspaceLayout();
592 const { appearance, setCodeWordBreak } = useAppearancePreferences();
593 const iconColor = useUniwindTheme()["--color-icon"];
594 const params = props.route.params;
595 const relativePath = normalizeRoutePath(params.path);
596 const targetLine = normalizeRouteLine(firstRouteParam(params.line));
597 const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace(
598 props.route.params,
599 );
600 const fileAccessSession = useEnvironmentQuery(
601 environmentId !== null ? environmentSession.sessionStateAtom(environmentId) : null,
602 );
603 const fileEnvironment = useEnvironmentPresentation(environmentId);
604 const fileAccess = resolveFilesystemReadAccess({
605 isCatalogReady: fileEnvironment.isReady,
606 connection: fileEnvironment.presentation?.connection ?? null,
607 session: fileAccessSession.data,
608 sessionError: fileAccessSession.error,
609 });
610 const { canReadFiles } = fileAccess;
611 const targetPath =
612 cwd !== null && relativePath !== null ? resolveWorkspaceFilePath(cwd, relativePath) : null;
613 const metadata = useEnvironmentQuery(
614 canReadFiles && environmentId !== null && targetPath !== null
615 ? projectEnvironment.fileMetadata({ environmentId, input: { path: targetPath } })
616 : null,
617 );
618 const metadataPending = !metadata.isSuccess && metadata.error === null;
619 const directoryPath = metadata.data?.kind === "directory" ? targetPath : null;
620 const [searchQuery, setSearchQuery] = useState("");
621 const entriesQuery = useFileTreeEntries({
622 environmentId,
623 cwd: canReadFiles ? directoryPath : null,
624 searchQuery,
625 });
626 const [modeOverride, setModeOverride] = useState<{
627 readonly path: string;
628 readonly mode: FileViewMode;
629 } | null>(null);
630 const [previewRevision, setPreviewRevision] = useState(0);
631 const previewKey = JSON.stringify([environmentId, cwd, relativePath, previewRevision]);
632 const [fullScreenPreview, setFullScreenPreview] = useState<FilePreviewSource | null>(null);
633 const isVideoFile = relativePath !== null && isVideoPreviewFile(relativePath);
634 const isAudioFile = relativePath !== null && !isVideoFile && isAudioPreviewFile(relativePath);
635 const isBrowserFile =
636 relativePath !== null && !isVideoFile && isWorkspaceBrowserPreviewPath(relativePath);
637 const isImageFile =
638 relativePath !== null && !isVideoFile && isWorkspaceImagePreviewPath(relativePath);
639 const canPreview =
640 relativePath !== null &&
641 (isMarkdownPreviewFile(relativePath) ||
642 isBrowserFile ||
643 isImageFile ||
644 isVideoFile ||
645 isAudioFile ||
646 filePreviewDelimiter({ name: relativePath }) !== null);
647 const activeMode =
648 relativePath !== null && modeOverride?.path === relativePath
649 ? modeOverride.mode
650 : targetLine !== null && filePreviewDelimiter({ name: relativePath ?? "" }) !== null
651 ? "source"
652 : defaultViewMode(relativePath);
653 const resolvedActiveMode =
654 isVideoFile || isAudioFile ? "preview" : canPreview ? activeMode : "source";
655 const assetPreviewPath =
656 !metadataPending &&
657 directoryPath === null &&
658 (isBrowserFile || isImageFile || isVideoFile || isAudioFile)
659 ? relativePath
660 : null;
661 const assetPreview = useWorkspaceFileAssetUrlState({
662 cwd,
663 environmentId,
664 relativePath: assetPreviewPath,
665 threadId,
666 draftCwd: threadId === null ? cwd : null,
667 });
668 const assetPreviewUri = assetPreview._tag === "Success" ? assetPreview.url : null;
669 const mediaSource: MediaActionsSource | undefined =
670 environmentId !== null &&
671 relativePath !== null &&
672 assetPreview.resource !== null &&
673 "path" in assetPreview.resource &&
674 typeof assetPreview.resource.path === "string" &&
675 (isImageFile || isVideoFile)
676 ? {
677 reference: mediaFileReference(assetPreview.resource.path, cwd),
678 name: basename(relativePath),
679 mimeType:
680 mediaMimeTypeFromExtension(relativePath.slice(relativePath.lastIndexOf("."))) ??
681 "application/octet-stream",
682 environmentId,
683 ...(threadId === null ? {} : { threadId }),
684 resource: assetPreview.resource,
685 }
686 : undefined;
687 const mediaActions = useMediaActions(mediaSource);
688 const videoSource: MediaVideoPreviewSource | null =
689 environmentId !== null &&
690 relativePath !== null &&
691 (assetPreview.resource?._tag === "media-file" ||
692 assetPreview.resource?._tag === "draft-workspace-file")
693 ? {
694 type: "media",
695 environmentId,
696 resource: assetPreview.resource,
697 name: basename(relativePath),
698 mimeType: videoMimeType({ name: relativePath, mimeType: "" }) ?? "video/mp4",
699 actionsSource: mediaSource,
700 }
701 : null;
702 const previewUri =
703 assetPreviewUri === null || previewRevision === 0
704 ? assetPreviewUri
705 : `${assetPreviewUri}${assetPreviewUri.includes("?") ? "&" : "?"}revision=${previewRevision}`;
706 // Remounting the preview after a re-mint is what makes a failed asset URL retryable.
707 const handleRetryPreview = () => {
708 void assetPreview.refresh().finally(() => setPreviewRevision((current) => current + 1));
709 };
710 const needsFileContents =
711 !metadataPending &&
712 directoryPath === null &&
713 relativePath !== null &&
714 !isVideoFile &&
715 !isAudioFile &&
716 (resolvedActiveMode === "source" ||
717 isMarkdownPreviewFile(relativePath) ||
718 filePreviewDelimiter({ name: relativePath }) !== null);
719 const fileQuery = useEnvironmentQuery(
720 canReadFiles &&
721 environmentId !== null &&
722 cwd !== null &&
723 relativePath !== null &&
724 needsFileContents
725 ? projectEnvironment.readFile({
726 environmentId,
727 input: { cwd, relativePath },
728 })
729 : null,
730 );
731 const fileData = fileQuery.data as ProjectReadFileResult | null;
732​
733 const handleSelectFile = (path: string) => {
734 const targetPath =
735 directoryPath === null ? path : resolveWorkspaceFilePath(directoryPath, path);
736 const segments = fileRoutePathSegments(
737 resolveWorkspaceRelativeFilePath(cwd, targetPath) ?? targetPath,
738 );
739 // A draft has no thread. `ThreadFile` would stringify null and then wait forever for a
740 // thread to resolve, so a draft stays on its own route and carries its workspace along.
741 if (threadId === null) {
742 navigation.dispatch(
743 StackActions.push("NewTaskFile", {
744 environmentId: String(environmentId),
745 ...(cwd === null ? {} : { cwd }),
746 projectName,
747 path: segments,
748 }),
749 );
750 return;
751 }
752 const destination = {
753 environmentId: String(environmentId),
754 threadId: String(threadId),
755 path: segments,
756 };
757 if (directoryPath !== null) navigation.dispatch(StackActions.push("ThreadFile", destination));
758 else navigation.navigate("ThreadFile", destination);
759 };
760 const renderInspector = (headerInset: number) =>
761 fileInspector.supported && environmentId !== null && cwd !== null ? (
762 <ThreadFileNavigatorPane
763 cwd={directoryPath ?? cwd}
764 environmentId={environmentId}
765 headerInset={headerInset}
766 projectName={directoryPath ?? projectName}
767 selectedPath={directoryPath === null ? relativePath : null}
768 onSelectFile={(path) => {
769 if (directoryPath !== null) entriesQuery.selectPath(path);
770 handleSelectFile(path);
771 }}
772 />
773 ) : undefined;
774 const safeAreaInsets = useSafeAreaInsets();
775 const inspectorHeaderInset = Platform.OS === "ios" ? 0 : safeAreaInsets.top;
776 const renderWorkspaceInspector = () => (
777 <ThreadInspectorContentStack
778 mode="files"
779 resetKeys={[threadId, cwd]}
780 renderFiles={() => renderInspector(inspectorHeaderInset)}
781 />
782 );
783 useRegisterWorkspaceInspector(fileInspector.supported ? renderWorkspaceInspector : undefined);
784​
785 const fileMenuActions = (() => {
786 if (relativePath === null) return [];
787 const canToggleMode = canPreview && !isImageFile && !isVideoFile && !isAudioFile;
788 return [
789 canToggleMode
790 ? ({
791 id: "preview",
792 title: filePreviewDelimiter({ name: relativePath }) ? "Table" : "Preview",
793 icon: filePreviewDelimiter({ name: relativePath }) ? "tablecells" : "eye",
794 inline: true,
795 onPress: () => setModeOverride({ path: relativePath, mode: "preview" }),
796 } as const)
797 : null,
798 canToggleMode
799 ? ({
800 id: "source",
801 title: "Source",
802 icon: "doc.text",
803 inline: true,
804 onPress: () => setModeOverride({ path: relativePath, mode: "source" }),
805 } as const)
806 : null,
807 resolvedActiveMode === "source"
808 ? ({
809 id: "word-wrap",
810 title: appearance.codeWordBreak ? "Disable word wrap" : "Enable word wrap",
811 icon: "text.alignleft",
812 inline: false,
813 onPress: () => setCodeWordBreak(!appearance.codeWordBreak),
814 } as const)
815 : null,
816 ...(mediaSource
817 ? mediaActions.actions
818 .filter(({ id }) => id !== "open-file")
819 .map((action) => ({
820 id: action.id,
821 title: action.title,
822 icon:
823 action.id === "save" ? ("square.and.arrow.up" as const) : ("doc.on.doc" as const),
824 inline: false,
825 onPress: action.run,
826 }))
827 : [
828 {
829 id: "copy-path",
830 title: "Copy path",
831 icon: "doc.on.doc",
832 inline: false,
833 onPress: () =>
834 copyTextWithHaptic(
835 formatFilePathForClipboard(
836 relativePath,
837 resolvePathLinkTarget(relativePath, cwd ?? ""),
838 ),
839 ),
840 } as const,
841 ]),
842 fileData?.contents != null
843 ? ({
844 id: "copy-contents",
845 title: fileData.truncated ? "Copy preview" : "Copy contents",
846 icon: "doc.on.doc",
847 inline: false,
848 onPress: () => copyTextWithHaptic(fileData.contents),
849 } as const)
850 : null,
851 isPdfFile({ name: relativePath }) && previewUri !== null
852 ? ({
853 id: "open-pdf",
854 title: "Open PDF",
855 icon: "arrow.up.left.and.arrow.down.right",
856 inline: false,
857 onPress: () =>
858 setFullScreenPreview({
859 kind: "pdf",
860 uri: previewUri,
861 name: basename(relativePath),
862 }),
863 } as const)
864 : null,
865 isBrowserFile && typeof assetPreviewUri === "string"
866 ? ({
867 id: "open-browser",
868 title: Platform.OS === "ios" ? "Open in Safari" : "Open in browser",
869 icon: "safari",
870 inline: false,
871 onPress: () => tryOpenExternalUrl(assetPreviewUri, "file-preview"),
872 } as const)
873 : null,
874 resolvedActiveMode === "preview" &&
875 (isBrowserFile || isImageFile || isVideoFile || isAudioFile)
876 ? ({
877 id: "refresh",
878 title: "Refresh",
879 icon: "arrow.clockwise",
880 inline: false,
881 onPress: async () => {
882 if (isVideoFile || isAudioFile) await assetPreview.refresh();
883 setPreviewRevision((current) => current + 1);
884 },
885 } as const)
886 : null,
887 ].filter((action) => action !== null);
888 })();
889​
890 const handleReturnToThread = () => {
891 if (environmentId !== null && threadId !== null) {
892 navigation.dispatch(
893 StackActions.replace("Thread", {
894 environmentId: String(environmentId),
895 threadId: String(threadId),
896 }),
897 );
898 }
899 };
900 const handleBack = () => {
901 if (navigation.canGoBack()) {
902 navigation.goBack();
903 return;
904 }
905 handleReturnToThread();
906 };
907​
908 if (environmentId === null || (threadId !== null && selectedThread === null)) {
909 return <LoadingScreen message="Opening file..." messagePlacement="above-spinner" />;
910 }
911​
912 if (!canReadFiles) {
913 if (fileAccess.isPending) {
914 return <LoadingScreen message="Checking file access..." messagePlacement="above-spinner" />;
915 }
916 return (
917 <FilesUnavailable detail={fileAccess.error ?? "This connection cannot read host files."} />
918 );
919 }
920 if (cwd === null) {
921 return <FilesUnavailable />;
922 }
923​
924 if (relativePath === null) {
925 return (
926 <View className="flex-1 items-center justify-center bg-sheet px-6">
927 <NativeStackScreenOptions options={{ title: "Files" }} />
928 <EmptyState title="File unavailable" detail="This file path is invalid." />
929 </View>
930 );
931 }
932​
933 if (metadataPending) {
934 return <LoadingScreen message="Opening file..." messagePlacement="above-spinner" />;
935 }
936 if (directoryPath !== null) {
937 return (
938 <View className={Platform.OS === "android" ? "flex-1 bg-header" : "flex-1 bg-sheet"}>
939 <FilesBrowserHeader
940 projectName={directoryPath}
941 searchQuery={searchQuery}
942 onSearchQueryChange={setSearchQuery}
943 onRefresh={entriesQuery.refresh}
944 onBack={handleBack}
945 />
946 <ScreenContent>
947 <FileTreeBrowser
948 key={JSON.stringify([environmentId, directoryPath])}
949 revealSelection={entriesQuery.revealSelection}
950 expandedPaths={entriesQuery.expandedPaths}
951 setExpandedPaths={entriesQuery.setExpandedPaths}
952 entries={entriesQuery.entries}
953 loadingDirectories={entriesQuery.loadingDirectories}
954 onLoadDirectory={entriesQuery.loadDirectory}
955 error={entriesQuery.error}
956 isPending={entriesQuery.isPending}
957 isRefreshing={entriesQuery.isRefreshing}
958 searchQuery={searchQuery}
959 searchResultPaths={entriesQuery.searchResultPaths}
960 searchTruncated={entriesQuery.searchTruncated}
961 selectedPath={entriesQuery.selectedPath}
962 onRefresh={entriesQuery.refresh}
963 onSelectFile={(path) => {
964 entriesQuery.selectPath(path);
965 handleSelectFile(path);
966 }}
967 />
968 <FilesToolbarBottomFade />
969 </ScreenContent>
970 </View>
971 );
972 }
973​
974 const headerSubtitle = fileHeaderSubtitle(projectName, relativePath);
975​
976 return (
977 <View className="flex-1 bg-sheet">
978 <FileHeader
979 title={basename(relativePath)}
980 subtitle={headerSubtitle}
981 iconColor={iconColor}
982 activeMode={resolvedActiveMode}
983 fileInspectorSupported={fileInspector.supported}
984 onBack={handleBack}
985 onReturnToThread={handleReturnToThread}
986 actions={fileMenuActions}
987 />
988 <ScreenContent>
989 <FileContent
990 key={previewKey}
991 activeMode={resolvedActiveMode}
992 cwd={cwd}
993 environmentId={environmentId}
994 previewUri={previewUri}
995 previewFailure={assetPreview._tag === "Failure" ? assetPreview.reason : null}
996 onRetryPreview={handleRetryPreview}
997 videoSource={videoSource}
998 mediaSource={mediaSource}
999 resolveVideoUri={assetPreview.refresh}
1000 fileContents={fileData?.contents ?? null}
1001 fileError={fileQuery.error}
1002 initialLine={targetLine}
1003 relativePath={relativePath}
1004 threadId={threadId}
1005 truncated={fileData?.truncated ?? false}
1006 onRefresh={() => fileQuery.refresh()}
1007 />
1008 </ScreenContent>
1009 <FilePreviewModal
1010 source={fullScreenPreview}
1011 onRequestClose={() => setFullScreenPreview(null)}
1012 />
1013 </View>
1014 );