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

ThreadFilesRouteScreen.tsx

926 lines31.6 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 headerColor = useUniwindTheme()["--color-header"];
421 const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace(
422 props.route.params,
423 );
424 const revealedInspectorRef = useRef(false);
425 const entriesQuery = useFileTreeEntries({
426 environmentId,
427 cwd: fileInspector.supported ? null : cwd,
428 searchQuery,
429 });
430 const handleReturnToThread = useCallback(() => {
431 if (navigation.canGoBack()) {
432 navigation.goBack();
433 return;
434 }
435 if (environmentId !== null && threadId !== null) {
436 navigation.dispatch(
437 StackActions.replace("Thread", {
438 environmentId: String(environmentId),
439 threadId: String(threadId),
440 }),
441 );
442 }
443 }, [environmentId, navigation, threadId]);
444​
445 const handleSelectFile = useCallback(
446 (path: string) => {
447 if (environmentId === null || threadId === null) {
448 return;
449 }
450 const params = {
451 environmentId: String(environmentId),
452 threadId: String(threadId),
453 path: path.split("/").filter((segment) => segment.length > 0),
454 };
455 const navigationAction = resolveFileSelectionNavigationAction({
456 hasPersistentFileInspector: fileInspector.supported,
457 });
458 if (navigationAction === "replace") {
459 navigation.dispatch(StackActions.replace("ThreadFile", params));
460 return;
461 }
462 navigation.navigate("ThreadFile", params);
463 },
464 [environmentId, fileInspector.supported, navigation, threadId],
465 );
466 const renderInspector = useCallback(
467 (headerInset: number) =>
468 environmentId !== null && cwd !== null ? (
469 <ThreadFileNavigatorPane
470 cwd={cwd}
471 environmentId={environmentId}
472 headerInset={headerInset}
473 projectName={projectName}
474 selectedPath={null}
475 onSelectFile={handleSelectFile}
476 />
477 ) : null,
478 [cwd, environmentId, handleSelectFile, projectName],
479 );
480 const handlePreviewFile = useCallback(
481 (relativePath: string) => {
482 if (environmentId === null || cwd === null) {
483 return;
484 }
485 preloadWorkspaceFileContents({
486 cwd,
487 environmentId,
488 relativePath,
489 theme: highlightTheme,
490 });
491 },
492 [cwd, environmentId, highlightTheme],
493 );
494 useEffect(() => {
495 if (fileInspector.supported && cwd !== null && !revealedInspectorRef.current) {
496 revealedInspectorRef.current = true;
497 showAuxiliaryPane("inspector");
498 }
499 }, [cwd, fileInspector.supported, showAuxiliaryPane]);
500​
501 if (selectedThread === null || environmentId === null || threadId === null) {
502 if (fileInspector.supported) {
503 return (
504 <ThreadRouteScreen
505 onReturnToThread={handleReturnToThread}
506 renderInspector={renderInspector}
507 route={props.route}
508 />
509 );
510 }
511 return <LoadingScreen message="Opening files..." messagePlacement="above-spinner" />;
512 }
513​
514 if (cwd === null) {
515 return <FilesUnavailable />;
516 }
517​
518 if (fileInspector.supported) {
519 return (
520 <ThreadRouteScreen
521 onReturnToThread={handleReturnToThread}
522 renderInspector={renderInspector}
523 route={props.route}
524 />
525 );
526 }
527​
528 const content = (
529 <>
530 <FilesBrowserHeader
531 projectName={projectName}
532 searchQuery={searchQuery}
533 onSearchQueryChange={setSearchQuery}
534 onRefresh={entriesQuery.refresh}
535 onBack={handleReturnToThread}
536 />
537 <MaterialScreenContent insetHorizontal={layout.usesSplitView}>
538 <FileTreeBrowser
539 key={JSON.stringify([environmentId, cwd])}
540 entries={entriesQuery.entries}
541 loadedDirectories={entriesQuery.loadedDirectories}
542 onLoadDirectory={entriesQuery.loadDirectory}
543 error={entriesQuery.error}
544 isPending={entriesQuery.isPending}
545 searchQuery={searchQuery}
546 searchTruncated={entriesQuery.searchTruncated}
547 selectedPath={null}
548 onPreviewFile={handlePreviewFile}
549 onRefresh={entriesQuery.refresh}
550 onSelectFile={handleSelectFile}
551 />
552 <FilesToolbarBottomFade />
553 </MaterialScreenContent>
554 </>
555 );
556​
557 return Platform.OS === "android" ? (
558 <View className="flex-1" style={{ backgroundColor: headerColor }}>
559 {content}
560 </View>
561 ) : (
562 content
563 );
565​
566export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
567 useAdaptiveWorkspacePaneRole("inspector");
568 const navigation = useNavigation();
569 const { fileInspector } = useAdaptiveWorkspaceLayout();
570 const { appearance, setCodeWordBreak } = useAppearancePreferences();
571 const iconColor = useUniwindTheme()["--color-icon"];
572 const params = props.route.params;
573 const relativePath = normalizeRoutePath(params.path);
574 const targetLine = normalizeRouteLine(firstRouteParam(params.line));
575 const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace(
576 props.route.params,
577 );
578 const [modeOverride, setModeOverride] = useState<{
579 readonly path: string;
580 readonly mode: FileViewMode;
581 } | null>(null);
582 const [previewRevision, setPreviewRevision] = useState(0);
583 const previewKey = JSON.stringify([environmentId, cwd, relativePath, previewRevision]);
584 const [fullScreenPreview, setFullScreenPreview] = useState<FilePreviewSource | null>(null);
585 const isVideoFile = relativePath !== null && isVideoPreviewFile(relativePath);
586 const isAudioFile = relativePath !== null && !isVideoFile && isAudioPreviewFile(relativePath);
587 const isBrowserFile =
588 relativePath !== null && !isVideoFile && isWorkspaceBrowserPreviewPath(relativePath);
589 const isImageFile =
590 relativePath !== null && !isVideoFile && isWorkspaceImagePreviewPath(relativePath);
591 const canPreview =
592 relativePath !== null &&
593 (isMarkdownPreviewFile(relativePath) ||
594 isBrowserFile ||
595 isImageFile ||
596 isVideoFile ||
597 isAudioFile);
598 const activeMode =
599 relativePath !== null && modeOverride?.path === relativePath
600 ? modeOverride.mode
601 : defaultViewMode(relativePath);
602 const resolvedActiveMode =
603 isVideoFile || isAudioFile ? "preview" : canPreview ? activeMode : "source";
604 const assetPreviewPath =
605 isBrowserFile || isImageFile || isVideoFile || isAudioFile ? relativePath : null;
606 const assetPreview = useWorkspaceFileAssetUrlState({
607 cwd,
608 environmentId,
609 relativePath: assetPreviewPath,
610 threadId,
611 // A project draft names its workspace root explicitly: there is no thread to resolve one.
612 draftCwd: threadId === null ? cwd : null,
613 });
614 const assetPreviewUri = assetPreview._tag === "Success" ? assetPreview.url : null;
615 const mediaSource = useMemo<MediaActionsSource | undefined>(
616 () =>
617 environmentId !== null &&
618 relativePath !== null &&
619 assetPreview.resource !== null &&
620 "path" in assetPreview.resource &&
621 typeof assetPreview.resource.path === "string" &&
622 (isImageFile || isVideoFile)
623 ? {
624 reference: mediaFileReference(assetPreview.resource.path, cwd),
625 name: basename(relativePath),
626 mimeType:
627 mediaMimeTypeFromExtension(relativePath.slice(relativePath.lastIndexOf("."))) ??
628 "application/octet-stream",
629 environmentId,
630 ...(threadId === null ? {} : { threadId }),
631 resource: assetPreview.resource,
632 }
633 : undefined,
634 [assetPreview.resource, cwd, environmentId, isImageFile, isVideoFile, relativePath, threadId],
635 );
636 const mediaActions = useMediaActions(mediaSource);
637 const videoSource = useMemo<MediaVideoPreviewSource | null>(
638 () =>
639 environmentId !== null &&
640 relativePath !== null &&
641 (assetPreview.resource?._tag === "media-file" ||
642 assetPreview.resource?._tag === "draft-workspace-file")
643 ? {
644 type: "media",
645 environmentId,
646 resource: assetPreview.resource,
647 name: basename(relativePath),
648 mimeType: videoMimeType({ name: relativePath, mimeType: "" }) ?? "video/mp4",
649 actionsSource: mediaSource,
650 }
651 : null,
652 [assetPreview.resource, environmentId, relativePath, mediaSource],
653 );
654 const previewUri =
655 assetPreviewUri === null || previewRevision === 0
656 ? assetPreviewUri
657 : `${assetPreviewUri}${assetPreviewUri.includes("?") ? "&" : "?"}revision=${previewRevision}`;
658 // Remounting the preview after a re-mint is what makes a failed asset URL retryable.
659 const handleRetryPreview = () => {
660 void assetPreview.refresh().finally(() => setPreviewRevision((current) => current + 1));
661 };
662 const needsFileContents =
663 relativePath !== null &&
664 !isVideoFile &&
665 !isAudioFile &&
666 (resolvedActiveMode === "source" || isMarkdownPreviewFile(relativePath));
667 const fileQuery = useEnvironmentQuery(
668 environmentId !== null && cwd !== null && relativePath !== null && needsFileContents
669 ? projectEnvironment.readFile({
670 environmentId,
671 input: { cwd, relativePath },
672 })
673 : null,
674 );
675 const fileData = fileQuery.data as ProjectReadFileResult | null;
676​
677 const handleSelectFile = useCallback(
678 (path: string) => {
679 const segments = path.split("/").filter(Boolean);
680 // A draft has no thread. `ThreadFile` would stringify null and then wait forever for a
681 // thread to resolve, so a draft stays on its own route and carries its workspace along.
682 if (threadId === null) {
683 navigation.dispatch(
684 StackActions.push("NewTaskFile", {
685 environmentId: String(environmentId),
686 ...(cwd === null ? {} : { cwd }),
687 projectName,
688 path: segments,
689 }),
690 );
691 return;
692 }
693 navigation.navigate("ThreadFile", {
694 environmentId: String(environmentId),
695 threadId: String(threadId),
696 path: segments,
697 });
698 },
699 [cwd, environmentId, navigation, projectName, threadId],
700 );
701 const renderInspector = useCallback(
702 (headerInset: number) =>
703 fileInspector.supported && environmentId !== null && cwd !== null ? (
704 <ThreadFileNavigatorPane
705 cwd={cwd}
706 environmentId={environmentId}
707 headerInset={headerInset}
708 projectName={projectName}
709 selectedPath={relativePath}
710 onSelectFile={handleSelectFile}
711 />
712 ) : undefined,
713 [cwd, environmentId, fileInspector.supported, handleSelectFile, projectName, relativePath],
714 );
715 // The workspace inspector column spans the full window height. On iOS the
716 // pane brings its own nested native header; elsewhere it pads itself below
717 // the top inset.
718 const safeAreaInsets = useSafeAreaInsets();
719 const inspectorHeaderInset = Platform.OS === "ios" ? 0 : safeAreaInsets.top;
720 // Hand the file navigator to the workspace so it renders beside the
721 // navigator, outside this screen's native header.
722 const renderWorkspaceInspector = useCallback(
723 () => renderInspector(inspectorHeaderInset),
724 [inspectorHeaderInset, renderInspector],
725 );
726 useRegisterWorkspaceInspector(fileInspector.supported ? renderWorkspaceInspector : undefined);
727​
728 const fileMenuActions = useMemo(() => {
729 if (relativePath === null) return [];
730 const canToggleMode = canPreview && !isImageFile && !isVideoFile && !isAudioFile;
731 return [
732 canToggleMode
733 ? ({
734 id: "preview",
735 title: "Preview",
736 icon: "eye",
737 inline: true,
738 onPress: () => setModeOverride({ path: relativePath, mode: "preview" }),
739 } as const)
740 : null,
741 canToggleMode
742 ? ({
743 id: "source",
744 title: "Source",
745 icon: "doc.text",
746 inline: true,
747 onPress: () => setModeOverride({ path: relativePath, mode: "source" }),
748 } as const)
749 : null,
750 // Only the source body wraps; a rendered preview lays itself out.
751 resolvedActiveMode === "source"
752 ? ({
753 id: "word-wrap",
754 title: appearance.codeWordBreak ? "Disable word wrap" : "Enable word wrap",
755 icon: "text.alignleft",
756 inline: false,
757 onPress: () => setCodeWordBreak(!appearance.codeWordBreak),
758 } as const)
759 : null,
760 ...(mediaSource
761 ? mediaActions.actions
762 .filter(({ id }) => id !== "open-file")
763 .map((action) => ({
764 id: action.id,
765 title: action.title,
766 icon:
767 action.id === "save" ? ("square.and.arrow.up" as const) : ("doc.on.doc" as const),
768 inline: false,
769 onPress: action.run,
770 }))
771 : [
772 {
773 id: "copy-path",
774 title: "Copy path",
775 icon: "doc.on.doc",
776 inline: false,
777 onPress: () => copyTextWithHaptic(relativePath),
778 } as const,
779 ]),
780 // Selecting a long file by hand is painful on a phone, so copying the whole thing is
781 // the action most readers actually want. The attachment screen already offers it.
782 fileData?.contents != null
783 ? ({
784 id: "copy-contents",
785 title: fileData.truncated ? "Copy preview" : "Copy contents",
786 icon: "doc.on.doc",
787 inline: false,
788 onPress: () => copyTextWithHaptic(fileData.contents),
789 } as const)
790 : null,
791 isPdfFile({ name: relativePath }) && previewUri !== null
792 ? ({
793 id: "open-pdf",
794 title: "Open PDF",
795 icon: "arrow.up.left.and.arrow.down.right",
796 inline: false,
797 onPress: () =>
798 setFullScreenPreview({
799 kind: "pdf",
800 uri: previewUri,
801 name: basename(relativePath),
802 }),
803 } as const)
804 : null,
805 isBrowserFile && typeof assetPreviewUri === "string"
806 ? ({
807 id: "open-browser",
808 title: Platform.OS === "ios" ? "Open in Safari" : "Open in browser",
809 icon: "safari",
810 inline: false,
811 onPress: () => tryOpenExternalUrl(assetPreviewUri, "file-preview"),
812 } as const)
813 : null,
814 resolvedActiveMode === "preview" &&
815 (isBrowserFile || isImageFile || isVideoFile || isAudioFile)
816 ? ({
817 id: "refresh",
818 title: "Refresh",
819 icon: "arrow.clockwise",
820 inline: false,
821 onPress: async () => {
822 if (isVideoFile || isAudioFile) await assetPreview.refresh();
823 setPreviewRevision((current) => current + 1);
824 },
825 } as const)
826 : null,
827 ].filter((action) => action !== null);
828 }, [
829 appearance.codeWordBreak,
830 setCodeWordBreak,
831 assetPreviewUri,
832 assetPreview.refresh,
833 previewUri,
834 canPreview,
835 isAudioFile,
836 isBrowserFile,
837 isImageFile,
838 isVideoFile,
839 relativePath,
840 resolvedActiveMode,
841 mediaSource,
842 mediaActions.actions,
843 fileData?.contents,
844 fileData?.truncated,
845 ]);
846​
847 const handleReturnToThread = useCallback(() => {
848 if (environmentId !== null && threadId !== null) {
849 navigation.dispatch(
850 StackActions.replace("Thread", {
851 environmentId: String(environmentId),
852 threadId: String(threadId),
853 }),
854 );
855 }
856 }, [environmentId, navigation, threadId]);
857 const handleBack = useCallback(() => {
858 if (navigation.canGoBack()) {
859 navigation.goBack();
860 return;
861 }
862 handleReturnToThread();
863 }, [handleReturnToThread, navigation]);
864​
865 // A file opened from a project draft has no thread, and needs none: the thread only supplies
866 // the workspace to read from and the target to navigate back to, both of which a draft names
867 // for itself. Wait only for what this file actually cannot render without.
868 if (environmentId === null || (threadId !== null && selectedThread === null)) {
869 return <LoadingScreen message="Opening file..." messagePlacement="above-spinner" />;
870 }
871​
872 if (cwd === null) {
873 return <FilesUnavailable />;
874 }
875​
876 if (relativePath === null) {
877 return (
878 <View className="flex-1 items-center justify-center bg-sheet px-6">
879 <NativeStackScreenOptions options={{ title: "Files" }} />
880 <EmptyState title="File unavailable" detail="This file path is invalid." />
881 </View>
882 );
883 }
884​
885 const headerSubtitle = fileHeaderSubtitle(projectName, relativePath);
886​
887 return (
888 <View className="flex-1 bg-sheet">
889 <FileHeader
890 title={basename(relativePath)}
891 subtitle={headerSubtitle}
892 iconColor={iconColor}
893 activeMode={resolvedActiveMode}
894 fileInspectorSupported={fileInspector.supported}
895 onBack={handleBack}
896 onReturnToThread={handleReturnToThread}
897 actions={fileMenuActions}
898 />
899 <MaterialScreenContent>
900 <FileContent
901 key={previewKey}
902 activeMode={resolvedActiveMode}
903 cwd={cwd}
904 environmentId={environmentId}
905 previewUri={previewUri}
906 previewFailure={assetPreview._tag === "Failure" ? assetPreview.reason : null}
907 onRetryPreview={handleRetryPreview}
908 videoSource={videoSource}
909 mediaSource={mediaSource}
910 resolveVideoUri={assetPreview.refresh}
911 fileContents={fileData?.contents ?? null}
912 fileError={fileQuery.error}
913 initialLine={targetLine}
914 relativePath={relativePath}
915 threadId={threadId}
916 truncated={fileData?.truncated ?? false}
917 onRefresh={() => fileQuery.refresh()}
918 />
919 </MaterialScreenContent>
920 <FilePreviewModal
921 source={fullScreenPreview}
922 onRequestClose={() => setFullScreenPreview(null)}
923 />
924 </View>
925 );