Open History to see the last commit
1import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
2import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
3import { useCallback, useEffect, useMemo, useRef, useState } from "react";
4import {
5 ActivityIndicator,
6 Platform,
7 Pressable,
8 ScrollView,
9 useColorScheme,
10 View,
11} from "react-native";
12import { useSafeAreaInsets } from "react-native-safe-area-context";
13import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg";
14import {
15 EnvironmentId,
16 type ProjectListEntriesResult,
17 type ProjectReadFileResult,
18 ThreadId,
19} from "@t3tools/contracts";
20
21import { AppText as Text } from "../../components/AppText";
22import { EmptyState } from "../../components/EmptyState";
23import { LoadingScreen } from "../../components/LoadingScreen";
24import { cn } from "../../lib/cn";
25import { resolveFileSelectionNavigationAction } from "../../lib/adaptive-navigation";
26import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
27import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
28import { useThemeColor } from "../../lib/useThemeColor";
29import { useThreadSelection } from "../../state/use-thread-selection";
30import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
31import { useEnvironmentQuery } from "../../state/query";
32import { projectEnvironment } from "../../state/projects";
33import {
34 useAdaptiveWorkspaceLayout,
35 useAdaptiveWorkspacePaneRole,
36 useRegisterWorkspaceInspector,
37} from "../layout/AdaptiveWorkspaceLayout";
38import { createNativeMailSearchToolbarItem } from "../layout/native-mail-search-toolbar";
39import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
40import { ReviewHighlighterProvider } from "../review/ReviewHighlighterProvider";
41import { ThreadRouteScreen } from "../threads/ThreadRouteScreen";
42import { FileMarkdownPreview } from "./FileMarkdownPreview";
43import { FileTreeBrowser } from "./FileTreeBrowser";
44import { preloadWorkspaceFileContents } from "./preload-workspace-file";
45import { SourceFileSurface } from "./SourceFileSurface";
46import { ThreadFileNavigatorPane } from "./thread-file-navigator-pane";
47import { WorkspaceFileImagePreview } from "./WorkspaceFileImagePreview";
48import { WorkspaceFileWebPreview } from "./WorkspaceFileWebPreview";
49import {
50 basename,
51 fileBreadcrumbs,
52 isBrowserPreviewFile,
53 isImagePreviewFile,
54 isMarkdownPreviewFile,
55 isSvgImagePreviewFile,
56} from "./filePath";
57import { useWorkspaceFileAssetUrl } from "./workspaceFileAssetUrl";
58
59type FileViewMode = "preview" | "source";
60
61function firstRouteParam(value: string | string[] | undefined): string | null {
62 if (Array.isArray(value)) {
63 return value[0] ?? null;
64 }
65
66 return value ?? null;
67}
68
69function normalizeRoutePath(value: string | string[] | undefined): string | null {
70 const path = Array.isArray(value) ? value.join("/") : value;
71 if (path === undefined || path.trim().length === 0) {
72 return null;
73 }
74 return path;
75}
76
77function normalizeRouteLine(value: string | null): number | null {
78 if (value === null) {
79 return null;
80 }
81 const parsed = Number(value);
82 return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
83}
84
85function defaultViewMode(path: string | null): FileViewMode {
86 return path !== null && (isBrowserPreviewFile(path) || isImagePreviewFile(path))
87 ? "preview"
88 : "source";
89}
90
91function FileContent(props: {
92 readonly activeMode: FileViewMode;
93 readonly previewUri: string | null;
94 readonly fileContents: string | null;
95 readonly fileError: string | null;
96 readonly relativePath: string;
97 readonly initialLine: number | null;
98 readonly truncated: boolean;
99 readonly onRefresh?: () => Promise<void> | void;
100}) {
101 const isMarkdown = isMarkdownPreviewFile(props.relativePath);
102 const isBrowserFile = isBrowserPreviewFile(props.relativePath);
103 const isImageFile = isImagePreviewFile(props.relativePath);
104
105 if (props.activeMode === "preview" && isImageFile) {
106 if (isSvgImagePreviewFile(props.relativePath)) {
107 return <WorkspaceFileWebPreview uri={props.previewUri} />;
108 }
109 return (
110 <WorkspaceFileImagePreview
111 accessibilityLabel={basename(props.relativePath)}
112 uri={props.previewUri}
113 />
114 );
115 }
116
117 if (props.activeMode === "preview" && isBrowserFile) {
118 return <WorkspaceFileWebPreview uri={props.previewUri} />;
119 }
120
121 if (props.fileError && props.fileContents === null) {
122 return (
123 <View className="flex-1 items-center justify-center bg-sheet px-6">
124 <EmptyState title="File unavailable" detail={props.fileError} />
125 </View>
126 );
127 }
128
129 if (props.fileContents === null) {
130 return (
131 <View className="flex-1 items-center justify-center gap-3 bg-sheet px-6">
132 <ActivityIndicator />
133 <Text className="text-center text-sm text-foreground-muted">Loading file...</Text>
134 </View>
135 );
136 }
137
138 return (
139 <View className="flex-1 bg-sheet">
140 {props.truncated ? (
141 <View className="border-b border-amber-200 bg-amber-50 px-4 py-2 dark:border-amber-900/60 dark:bg-amber-950/40">
142 <Text className="text-2xs font-t3-bold uppercase text-amber-700 dark:text-amber-300">
143 Partial file
144 </Text>
145 <Text className="text-xs leading-snug text-amber-800 dark:text-amber-200">
146 Preview limited to the first 1 MB of a truncated file.
147 </Text>
148 </View>
149 ) : null}
150 {props.activeMode === "preview" && isMarkdown ? (
151 <FileMarkdownPreview markdown={props.fileContents} onRefresh={props.onRefresh} />
152 ) : (
153 <SourceFileSurface
154 contents={props.fileContents}
155 path={props.relativePath}
156 initialLine={props.initialLine}
157 onRefresh={props.onRefresh}
158 />
159 )}
160 </View>
161 );
162}
163
164type ThreadFilesRouteScreenProps = StaticScreenProps<{
165 readonly environmentId: string;
166 readonly threadId: string;
167}>;
168
169type ThreadFileRouteScreenProps = StaticScreenProps<{
170 readonly environmentId: string;
171 readonly threadId: string;
172 readonly path: string[];
173 readonly line?: string;
174}>;
175
176function useThreadFilesWorkspace(params: {
177 readonly environmentId?: string | string[];
178 readonly threadId?: string | string[];
179}) {
180 const routeEnvironmentId = firstRouteParam(params.environmentId);
181 const routeThreadId = firstRouteParam(params.threadId);
182 const { selectedThread, selectedThreadProject } = useThreadSelection();
183 const { selectedThreadCwd } = useSelectedThreadWorktree();
184 const environmentId =
185 routeEnvironmentId !== null
186 ? EnvironmentId.make(routeEnvironmentId)
187 : (selectedThread?.environmentId ?? null);
188 const threadId = routeThreadId !== null ? ThreadId.make(routeThreadId) : null;
189 const project = selectedThreadProject as {
190 readonly title?: string;
191 readonly workspaceRoot?: string;
192 } | null;
193
194 return {
195 cwd: selectedThreadCwd ?? project?.workspaceRoot ?? null,
196 environmentId,
197 projectName: project?.title ?? "Files",
198 selectedThread,
199 threadId,
200 };
201}
202
203function FilesUnavailable() {
204 return (
205 <View className="flex-1 items-center justify-center bg-sheet px-6">
206 <NativeStackScreenOptions options={{ title: "Files" }} />
207 <EmptyState
208 title="Files unavailable"
209 detail="This thread does not have an active workspace path."
210 />
211 </View>
212 );
213}
214
215function FilesToolbarBottomFade() {
216 const sheetColor = String(useThemeColor("--color-sheet"));
217
218 if (process.env.EXPO_OS !== "ios") {
219 return null;
220 }
221
222 return (
223 <View
224 pointerEvents="none"
225 accessibilityElementsHidden
226 importantForAccessibility="no-hide-descendants"
227 className="absolute inset-x-0 bottom-0 z-[1] h-28"
228 >
229 <Svg width="100%" height="100%">
230 <Defs>
231 <LinearGradient id="files-toolbar-bottom-fade" x1="0%" x2="0%" y1="0%" y2="100%">
232 <Stop offset="0%" stopColor={sheetColor} stopOpacity={0} />
233 <Stop offset="58%" stopColor={sheetColor} stopOpacity={0.72} />
234 <Stop offset="100%" stopColor={sheetColor} stopOpacity={0.96} />
235 </LinearGradient>
236 </Defs>
237 <Rect width="100%" height="100%" fill="url(#files-toolbar-bottom-fade)" />
238 </Svg>
239 </View>
240 );
241}
242
243export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {
244 useAdaptiveWorkspacePaneRole("inspector");
245 const navigation = useNavigation();
246 const { fileInspector, layout, panes, showAuxiliaryPane, togglePrimarySidebar } =
247 useAdaptiveWorkspaceLayout();
248 const [searchQuery, setSearchQuery] = useState("");
249 const colorScheme = useColorScheme();
250 const highlightTheme = colorScheme === "dark" ? "dark" : "light";
251 const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace(
252 props.route.params,
253 );
254 const revealedInspectorRef = useRef(false);
255 const entriesQuery = useEnvironmentQuery(
256 environmentId !== null && cwd !== null && !fileInspector.supported
257 ? projectEnvironment.listEntries({
258 environmentId,
259 input: { cwd },
260 })
261 : null,
262 );
263 const entriesData = entriesQuery.data as ProjectListEntriesResult | null;
264 const handleReturnToThread = useCallback(() => {
265 if (navigation.canGoBack()) {
266 navigation.goBack();
267 return;
268 }
269 if (environmentId !== null && threadId !== null) {
270 navigation.dispatch(
271 StackActions.replace("Thread", {
272 environmentId: String(environmentId),
273 threadId: String(threadId),
274 }),
275 );
276 }
277 }, [environmentId, navigation, threadId]);
278
279 const handleSelectFile = useCallback(
280 (path: string) => {
281 if (environmentId === null || threadId === null) {
282 return;
283 }
284 const params = {
285 environmentId: String(environmentId),
286 threadId: String(threadId),
287 path: path.split("/").filter((segment) => segment.length > 0),
288 };
289 const navigationAction = resolveFileSelectionNavigationAction({
290 hasPersistentFileInspector: fileInspector.supported,
291 });
292 if (navigationAction === "replace") {
293 navigation.dispatch(StackActions.replace("ThreadFile", params));
294 return;
295 }
296 navigation.navigate("ThreadFile", params);
297 },
298 [environmentId, fileInspector.supported, navigation, threadId],
299 );
300 const renderInspector = useCallback(
301 (headerInset: number) =>
302 environmentId !== null && cwd !== null ? (
303 <ThreadFileNavigatorPane
304 cwd={cwd}
305 environmentId={environmentId}
306 headerInset={headerInset}
307 projectName={projectName}
308 selectedPath={null}
309 onSelectFile={handleSelectFile}
310 />
311 ) : null,
312 [cwd, environmentId, handleSelectFile, projectName],
313 );
314 const handlePreviewFile = useCallback(
315 (relativePath: string) => {
316 if (environmentId === null || cwd === null) {
317 return;
318 }
319 preloadWorkspaceFileContents({
320 cwd,
321 environmentId,
322 relativePath,
323 theme: highlightTheme,
324 });
325 },
326 [cwd, environmentId, highlightTheme],
327 );
328 useEffect(() => {
329 if (fileInspector.supported && cwd !== null && !revealedInspectorRef.current) {
330 revealedInspectorRef.current = true;
331 showAuxiliaryPane("inspector");
332 }
333 }, [cwd, fileInspector.supported, showAuxiliaryPane]);
334
335 if (selectedThread === null || environmentId === null || threadId === null) {
336 if (fileInspector.supported) {
337 return (
338 <ThreadRouteScreen
339 onReturnToThread={handleReturnToThread}
340 renderInspector={renderInspector}
341 route={props.route}
342 />
343 );
344 }
345 return <LoadingScreen message="Opening files..." messagePlacement="above-spinner" />;
346 }
347
348 if (cwd === null) {
349 return <FilesUnavailable />;
350 }
351
352 if (fileInspector.supported) {
353 return (
354 <ThreadRouteScreen
355 onReturnToThread={handleReturnToThread}
356 renderInspector={renderInspector}
357 route={props.route}
358 />
359 );
360 }
361
362 const usesCompactMailToolbar = Platform.OS === "ios" && !layout.usesSplitView;
363
364 return (
365 <>
366 {/* Static header config (glass preset, title, contentStyle) lives in Stack.tsx.
367 Only genuinely dynamic options are set here. */}
368 <NativeStackScreenOptions
369 options={{
370 unstable_headerSubtitle:
371 Platform.OS === "ios" && projectName.length > 0 ? projectName : undefined,
372 // No refresh button: the list already supports pull-to-refresh.
373 unstable_headerToolbarItems: usesCompactMailToolbar
374 ? () => [
375 createNativeMailSearchToolbarItem({
376 onSearchTextChange: setSearchQuery,
377 placeholder: "Search files",
378 searchTextChangeId: "files-search-text",
379 }),
380 ]
381 : undefined,
382 headerSearchBarOptions: usesCompactMailToolbar
383 ? undefined
384 : {
385 allowToolbarIntegration: true,
386 autoCapitalize: "none",
387 hideNavigationBar: false,
388 placeholder: "Search files",
389 onChangeText: (event) => {
390 setSearchQuery(event.nativeEvent.text);
391 },
392 onCancelButtonPress: () => {
393 setSearchQuery("");
394 },
395 },
396 }}
397 />
398 {layout.usesSplitView ? (
399 <NativeHeaderToolbar placement="left">
400 <NativeHeaderToolbar.Button
401 accessibilityLabel={panes.primarySidebarVisible ? "Maximize files" : "Show threads"}
402 icon={
403 panes.primarySidebarVisible ? "arrow.up.left.and.arrow.down.right" : "sidebar.left"
404 }
405 onPress={togglePrimarySidebar}
406 separateBackground
407 />
408 </NativeHeaderToolbar>
409 ) : null}
410 {usesCompactMailToolbar ? null : (
411 <NativeHeaderToolbar placement="bottom">
412 <NativeHeaderToolbar.SearchBarSlot />
413 </NativeHeaderToolbar>
414 )}
415 <FileTreeBrowser
416 entries={entriesData?.entries ?? []}
417 error={entriesQuery.error}
418 isPending={entriesQuery.isPending}
419 searchQuery={searchQuery}
420 selectedPath={null}
421 onPreviewFile={handlePreviewFile}
422 onRefresh={entriesQuery.refresh}
423 onSelectFile={handleSelectFile}
424 />
425 <FilesToolbarBottomFade />
426 </>
427 );
428}
429
430export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
431 useAdaptiveWorkspacePaneRole("inspector");
432 const navigation = useNavigation();
433 const { fileInspector, panes, toggleAuxiliaryPane } = useAdaptiveWorkspaceLayout();
434 const iconColor = useThemeColor("--color-icon");
435 const params = props.route.params;
436 const relativePath = normalizeRoutePath(params.path);
437 const targetLine = normalizeRouteLine(firstRouteParam(params.line));
438 const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace(
439 props.route.params,
440 );
441 const [modeOverride, setModeOverride] = useState<{
442 readonly path: string;
443 readonly mode: FileViewMode;
444 } | null>(null);
445 const [previewRevision, setPreviewRevision] = useState(0);
446 const isBrowserFile = relativePath !== null && isBrowserPreviewFile(relativePath);
447 const isImageFile = relativePath !== null && isImagePreviewFile(relativePath);
448 const canPreview =
449 relativePath !== null && (isMarkdownPreviewFile(relativePath) || isBrowserFile || isImageFile);
450 const activeMode =
451 relativePath !== null && modeOverride?.path === relativePath
452 ? modeOverride.mode
453 : defaultViewMode(relativePath);
454 const resolvedActiveMode = canPreview ? activeMode : "source";
455 const assetPreviewPath = isBrowserFile || isImageFile ? relativePath : null;
456 const assetPreviewUri = useWorkspaceFileAssetUrl({
457 cwd,
458 environmentId,
459 relativePath: assetPreviewPath,
460 threadId,
461 });
462 const previewUri =
463 assetPreviewUri === null || previewRevision === 0
464 ? assetPreviewUri
465 : `${assetPreviewUri}${assetPreviewUri.includes("?") ? "&" : "?"}revision=${previewRevision}`;
466 const needsFileContents =
467 relativePath !== null &&
468 (resolvedActiveMode === "source" || isMarkdownPreviewFile(relativePath));
469 const fileQuery = useEnvironmentQuery(
470 environmentId !== null && cwd !== null && relativePath !== null && needsFileContents
471 ? projectEnvironment.readFile({
472 environmentId,
473 input: { cwd, relativePath },
474 })
475 : null,
476 );
477 const fileData = fileQuery.data as ProjectReadFileResult | null;
478
479 const handleSelectFile = useCallback(
480 (path: string) => {
481 navigation.navigate("ThreadFile", {
482 environmentId: String(environmentId),
483 threadId: String(threadId),
484 path: path.split("/").filter(Boolean),
485 });
486 },
487 [environmentId, navigation, threadId],
488 );
489 const renderInspector = useCallback(
490 (headerInset: number) =>
491 fileInspector.supported && environmentId !== null && cwd !== null ? (
492 <ThreadFileNavigatorPane
493 cwd={cwd}
494 environmentId={environmentId}
495 headerInset={headerInset}
496 projectName={projectName}
497 selectedPath={relativePath}
498 onSelectFile={handleSelectFile}
499 />
500 ) : undefined,
501 [cwd, environmentId, fileInspector.supported, handleSelectFile, projectName, relativePath],
502 );
503 // The workspace inspector column spans the full window height. On iOS the
504 // pane brings its own nested native header; elsewhere it pads itself below
505 // the top inset.
506 const safeAreaInsets = useSafeAreaInsets();
507 const inspectorHeaderInset = Platform.OS === "ios" ? 0 : safeAreaInsets.top;
508 // Hand the file navigator to the workspace so it renders beside the
509 // navigator, outside this screen's native header.
510 const renderWorkspaceInspector = useCallback(
511 () => renderInspector(inspectorHeaderInset),
512 [inspectorHeaderInset, renderInspector],
513 );
514 useRegisterWorkspaceInspector(fileInspector.supported ? renderWorkspaceInspector : undefined);
515
516 if (selectedThread === null || environmentId === null || threadId === null) {
517 return <LoadingScreen message="Opening file..." messagePlacement="above-spinner" />;
518 }
519
520 if (cwd === null) {
521 return <FilesUnavailable />;
522 }
523
524 if (relativePath === null) {
525 return (
526 <View className="flex-1 items-center justify-center bg-sheet px-6">
527 <NativeStackScreenOptions options={{ title: "Files" }} />
528 <EmptyState title="File unavailable" detail="This file path is invalid." />
529 </View>
530 );
531 }
532
533 const parentDir = relativePath.split("/").slice(0, -1).join("/");
534 const headerSubtitle = [projectName, parentDir].filter(Boolean).join(" · ");
535
536 return (
537 <ReviewHighlighterProvider>
538 <View className="flex-1 bg-sheet">
539 <NativeStackScreenOptions
540 options={{
541 // Static header config lives in Stack.tsx (SOLID_HEADER_OPTIONS: solid
542 // sheet-colored header — this route's content scrolls internally, so
543 // there is nothing for glass to sample). Only dynamic values here.
544 headerTintColor: iconColor,
545 headerTitle: basename(relativePath),
546 title: basename(relativePath),
547 unstable_headerSubtitle:
548 Platform.OS === "ios" && headerSubtitle.length > 0 ? headerSubtitle : undefined,
549 }}
550 />
551 <WorkspaceSidebarToolbar>
552 {fileInspector.supported ? (
553 <NativeHeaderToolbar.Button
554 accessibilityLabel="Return to chat"
555 icon="chevron.left"
556 onPress={() => {
557 navigation.dispatch(
558 StackActions.replace("Thread", {
559 environmentId: String(environmentId),
560 threadId: String(threadId),
561 }),
562 );
563 }}
564 />
565 ) : null}
566 </WorkspaceSidebarToolbar>
567 <NativeHeaderToolbar placement="right">
568 {fileInspector.supported ? (
569 <NativeHeaderToolbar.Button
570 accessibilityLabel={
571 panes.auxiliaryPaneVisible ? "Hide file navigator" : "Show file navigator"
572 }
573 icon="sidebar.right"
574 onPress={toggleAuxiliaryPane}
575 separateBackground
576 />
577 ) : null}
578 <NativeHeaderToolbar.Menu accessibilityLabel="File actions" icon="ellipsis">
579 {canPreview && !isImageFile ? (
580 <NativeHeaderToolbar.Menu inline>
581 <NativeHeaderToolbar.MenuAction
582 icon="eye"
583 isOn={resolvedActiveMode === "preview"}
584 onPress={() => setModeOverride({ path: relativePath, mode: "preview" })}
585 >
586 Preview
587 </NativeHeaderToolbar.MenuAction>
588 <NativeHeaderToolbar.MenuAction
589 icon="doc.text"
590 isOn={resolvedActiveMode === "source"}
591 onPress={() => setModeOverride({ path: relativePath, mode: "source" })}
592 >
593 Source
594 </NativeHeaderToolbar.MenuAction>
595 </NativeHeaderToolbar.Menu>
596 ) : null}
597 <NativeHeaderToolbar.MenuAction
598 icon="doc.on.doc"
599 onPress={() => copyTextWithHaptic(relativePath)}
600 >
601 Copy path
602 </NativeHeaderToolbar.MenuAction>
603 {isBrowserFile && typeof assetPreviewUri === "string" ? (
604 <NativeHeaderToolbar.MenuAction
605 icon="safari"
606 onPress={() => {
607 void tryOpenExternalUrl(assetPreviewUri, "file-preview");
608 }}
609 >
610 Open in Safari
611 </NativeHeaderToolbar.MenuAction>
612 ) : null}
613 {resolvedActiveMode === "preview" && (isBrowserFile || isImageFile) ? (
614 <NativeHeaderToolbar.MenuAction
615 icon="arrow.clockwise"
616 onPress={() => {
617 setPreviewRevision((current) => current + 1);
618 }}
619 >
620 Refresh
621 </NativeHeaderToolbar.MenuAction>
622 ) : null}
623 </NativeHeaderToolbar.Menu>
624 </NativeHeaderToolbar>
625 <FileContent
626 activeMode={resolvedActiveMode}
627 previewUri={previewUri}
628 fileContents={fileData?.contents ?? null}
629 fileError={fileQuery.error}
630 initialLine={targetLine}
631 relativePath={relativePath}
632 truncated={fileData?.truncated ?? false}
633 onRefresh={() => fileQuery.refresh()}
634 />
635 </View>
636 </ReviewHighlighterProvider>
637 );
638}