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

ThreadFilesRouteScreen.tsx

1,002 lines35.6 KB

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