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

ThreadFilesRouteScreen.tsx

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