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

ThreadFilesRouteScreen.tsx

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