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

ThreadFilesRouteScreen.tsx

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