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

ThreadFilesRouteScreen.tsx

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