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

ThreadFilesRouteScreen.tsx

965 lines33.5 KB

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