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

ThreadFilesRouteScreen.tsx

919 lines31.5 KB

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