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

ThreadFilesRouteScreen.tsx

994 lines34.3 KB

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