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

ThreadFilesRouteScreen.tsx

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