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