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 style={{
228 bottom: 0,
229 height: 112,
230 left: 0,
231 position: "absolute",
232 right: 0,
233 zIndex: 1,
234 }}
235 >
236 <Svg width="100%" height="100%">
237 <Defs>
238 <LinearGradient id="files-toolbar-bottom-fade" x1="0%" x2="0%" y1="0%" y2="100%">
239 <Stop offset="0%" stopColor={sheetColor} stopOpacity={0} />
240 <Stop offset="58%" stopColor={sheetColor} stopOpacity={0.72} />
241 <Stop offset="100%" stopColor={sheetColor} stopOpacity={0.96} />
242 </LinearGradient>
243 </Defs>
244 <Rect width="100%" height="100%" fill="url(#files-toolbar-bottom-fade)" />
245 </Svg>
246 </View>
247 );
248}
249
250export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {
251 useAdaptiveWorkspacePaneRole("inspector");
252 const navigation = useNavigation();
253 const { fileInspector, layout, panes, showAuxiliaryPane, togglePrimarySidebar } =
254 useAdaptiveWorkspaceLayout();
255 const [searchQuery, setSearchQuery] = useState("");
256 const colorScheme = useColorScheme();
257 const highlightTheme = colorScheme === "dark" ? "dark" : "light";
258 const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace(
259 props.route.params,
260 );
261 const revealedInspectorRef = useRef(false);
262 const entriesQuery = useEnvironmentQuery(
263 environmentId !== null && cwd !== null && !fileInspector.supported
264 ? projectEnvironment.listEntries({
265 environmentId,
266 input: { cwd },
267 })
268 : null,
269 );
270 const entriesData = entriesQuery.data as ProjectListEntriesResult | null;
271 const handleReturnToThread = useCallback(() => {
272 if (navigation.canGoBack()) {
273 navigation.goBack();
274 return;
275 }
276 if (environmentId !== null && threadId !== null) {
277 navigation.dispatch(
278 StackActions.replace("Thread", {
279 environmentId: String(environmentId),
280 threadId: String(threadId),
281 }),
282 );
283 }
284 }, [environmentId, navigation, threadId]);
285
286 const handleSelectFile = useCallback(
287 (path: string) => {
288 if (environmentId === null || threadId === null) {
289 return;
290 }
291 const params = {
292 environmentId: String(environmentId),
293 threadId: String(threadId),
294 path: path.split("/").filter((segment) => segment.length > 0),
295 };
296 const navigationAction = resolveFileSelectionNavigationAction({
297 hasPersistentFileInspector: fileInspector.supported,
298 });
299 if (navigationAction === "replace") {
300 navigation.dispatch(StackActions.replace("ThreadFile", params));
301 return;
302 }
303 navigation.navigate("ThreadFile", params);
304 },
305 [environmentId, fileInspector.supported, navigation, threadId],
306 );
307 const renderInspector = useCallback(
308 (headerInset: number) =>
309 environmentId !== null && cwd !== null ? (
310 <ThreadFileNavigatorPane
311 cwd={cwd}
312 environmentId={environmentId}
313 headerInset={headerInset}
314 projectName={projectName}
315 selectedPath={null}
316 onSelectFile={handleSelectFile}
317 />
318 ) : null,
319 [cwd, environmentId, handleSelectFile, projectName],
320 );
321 const handlePreviewFile = useCallback(
322 (relativePath: string) => {
323 if (environmentId === null || cwd === null) {
324 return;
325 }
326 preloadWorkspaceFileContents({
327 cwd,
328 environmentId,
329 relativePath,
330 theme: highlightTheme,
331 });
332 },
333 [cwd, environmentId, highlightTheme],
334 );
335 useEffect(() => {
336 if (fileInspector.supported && cwd !== null && !revealedInspectorRef.current) {
337 revealedInspectorRef.current = true;
338 showAuxiliaryPane("inspector");
339 }
340 }, [cwd, fileInspector.supported, showAuxiliaryPane]);
341
342 if (selectedThread === null || environmentId === null || threadId === null) {
343 if (fileInspector.supported) {
344 return (
345 <ThreadRouteScreen
346 onReturnToThread={handleReturnToThread}
347 renderInspector={renderInspector}
348 route={props.route}
349 />
350 );
351 }
352 return <LoadingScreen message="Opening files..." messagePlacement="above-spinner" />;
353 }
354
355 if (cwd === null) {
356 return <FilesUnavailable />;
357 }
358
359 if (fileInspector.supported) {
360 return (
361 <ThreadRouteScreen
362 onReturnToThread={handleReturnToThread}
363 renderInspector={renderInspector}
364 route={props.route}
365 />
366 );
367 }
368
369 const usesCompactMailToolbar = Platform.OS === "ios" && !layout.usesSplitView;
370
371 return (
372 <>
373 {/* Static header config (glass preset, title, contentStyle) lives in Stack.tsx.
374 Only genuinely dynamic options are set here. */}
375 <NativeStackScreenOptions
376 options={{
377 unstable_headerSubtitle:
378 Platform.OS === "ios" && projectName.length > 0 ? projectName : undefined,
379 // No refresh button: the list already supports pull-to-refresh.
380 unstable_headerToolbarItems: usesCompactMailToolbar
381 ? () => [
382 createNativeMailSearchToolbarItem({
383 onSearchTextChange: setSearchQuery,
384 placeholder: "Search files",
385 searchTextChangeId: "files-search-text",
386 }),
387 ]
388 : undefined,
389 headerSearchBarOptions: usesCompactMailToolbar
390 ? undefined
391 : {
392 allowToolbarIntegration: true,
393 autoCapitalize: "none",
394 hideNavigationBar: false,
395 placeholder: "Search files",
396 onChangeText: (event) => {
397 setSearchQuery(event.nativeEvent.text);
398 },
399 onCancelButtonPress: () => {
400 setSearchQuery("");
401 },
402 },
403 }}
404 />
405 {layout.usesSplitView ? (
406 <NativeHeaderToolbar placement="left">
407 <NativeHeaderToolbar.Button
408 accessibilityLabel={panes.primarySidebarVisible ? "Maximize files" : "Show threads"}
409 icon={
410 panes.primarySidebarVisible ? "arrow.up.left.and.arrow.down.right" : "sidebar.left"
411 }
412 onPress={togglePrimarySidebar}
413 separateBackground
414 />
415 </NativeHeaderToolbar>
416 ) : null}
417 {usesCompactMailToolbar ? null : (
418 <NativeHeaderToolbar placement="bottom">
419 <NativeHeaderToolbar.SearchBarSlot />
420 </NativeHeaderToolbar>
421 )}
422 <FileTreeBrowser
423 entries={entriesData?.entries ?? []}
424 error={entriesQuery.error}
425 isPending={entriesQuery.isPending}
426 searchQuery={searchQuery}
427 selectedPath={null}
428 onPreviewFile={handlePreviewFile}
429 onRefresh={entriesQuery.refresh}
430 onSelectFile={handleSelectFile}
431 />
432 <FilesToolbarBottomFade />
433 </>
434 );
435}
436
437export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
438 useAdaptiveWorkspacePaneRole("inspector");
439 const navigation = useNavigation();
440 const { fileInspector, panes, toggleAuxiliaryPane } = useAdaptiveWorkspaceLayout();
441 const iconColor = useThemeColor("--color-icon");
442 const params = props.route.params;
443 const relativePath = normalizeRoutePath(params.path);
444 const targetLine = normalizeRouteLine(firstRouteParam(params.line));
445 const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace(
446 props.route.params,
447 );
448 const [modeOverride, setModeOverride] = useState<{
449 readonly path: string;
450 readonly mode: FileViewMode;
451 } | null>(null);
452 const [previewRevision, setPreviewRevision] = useState(0);
453 const isBrowserFile = relativePath !== null && isBrowserPreviewFile(relativePath);
454 const isImageFile = relativePath !== null && isImagePreviewFile(relativePath);
455 const canPreview =
456 relativePath !== null && (isMarkdownPreviewFile(relativePath) || isBrowserFile || isImageFile);
457 const activeMode =
458 relativePath !== null && modeOverride?.path === relativePath
459 ? modeOverride.mode
460 : defaultViewMode(relativePath);
461 const resolvedActiveMode = canPreview ? activeMode : "source";
462 const assetPreviewPath = isBrowserFile || isImageFile ? relativePath : null;
463 const assetPreviewUri = useWorkspaceFileAssetUrl({
464 cwd,
465 environmentId,
466 relativePath: assetPreviewPath,
467 threadId,
468 });
469 const previewUri =
470 assetPreviewUri === null || previewRevision === 0
471 ? assetPreviewUri
472 : `${assetPreviewUri}${assetPreviewUri.includes("?") ? "&" : "?"}revision=${previewRevision}`;
473 const needsFileContents =
474 relativePath !== null &&
475 (resolvedActiveMode === "source" || isMarkdownPreviewFile(relativePath));
476 const fileQuery = useEnvironmentQuery(
477 environmentId !== null && cwd !== null && relativePath !== null && needsFileContents
478 ? projectEnvironment.readFile({
479 environmentId,
480 input: { cwd, relativePath },
481 })
482 : null,
483 );
484 const fileData = fileQuery.data as ProjectReadFileResult | null;
485
486 const handleSelectFile = useCallback(
487 (path: string) => {
488 navigation.navigate("ThreadFile", {
489 environmentId: String(environmentId),
490 threadId: String(threadId),
491 path: path.split("/").filter(Boolean),
492 });
493 },
494 [environmentId, navigation, threadId],
495 );
496 const renderInspector = useCallback(
497 (headerInset: number) =>
498 fileInspector.supported && environmentId !== null && cwd !== null ? (
499 <ThreadFileNavigatorPane
500 cwd={cwd}
501 environmentId={environmentId}
502 headerInset={headerInset}
503 projectName={projectName}
504 selectedPath={relativePath}
505 onSelectFile={handleSelectFile}
506 />
507 ) : undefined,
508 [cwd, environmentId, fileInspector.supported, handleSelectFile, projectName, relativePath],
509 );
510 // The workspace inspector column spans the full window height. On iOS the
511 // pane brings its own nested native header; elsewhere it pads itself below
512 // the top inset.
513 const safeAreaInsets = useSafeAreaInsets();
514 const inspectorHeaderInset = Platform.OS === "ios" ? 0 : safeAreaInsets.top;
515 // Hand the file navigator to the workspace so it renders beside the
516 // navigator, outside this screen's native header.
517 const renderWorkspaceInspector = useCallback(
518 () => renderInspector(inspectorHeaderInset),
519 [inspectorHeaderInset, renderInspector],
520 );
521 useRegisterWorkspaceInspector(fileInspector.supported ? renderWorkspaceInspector : undefined);
522
523 if (selectedThread === null || environmentId === null || threadId === null) {
524 return <LoadingScreen message="Opening file..." messagePlacement="above-spinner" />;
525 }
526
527 if (cwd === null) {
528 return <FilesUnavailable />;
529 }
530
531 if (relativePath === null) {
532 return (
533 <View className="flex-1 items-center justify-center bg-sheet px-6">
534 <NativeStackScreenOptions options={{ title: "Files" }} />
535 <EmptyState title="File unavailable" detail="This file path is invalid." />
536 </View>
537 );
538 }
539
540 const parentDir = relativePath.split("/").slice(0, -1).join("/");
541 const headerSubtitle = [projectName, parentDir].filter(Boolean).join(" · ");
542
543 return (
544 <ReviewHighlighterProvider>
545 <View className="flex-1 bg-sheet">
546 <NativeStackScreenOptions
547 options={{
548 // Static header config lives in Stack.tsx (SOLID_HEADER_OPTIONS: solid
549 // sheet-colored header — this route's content scrolls internally, so
550 // there is nothing for glass to sample). Only dynamic values here.
551 headerTintColor: iconColor,
552 headerTitle: basename(relativePath),
553 title: basename(relativePath),
554 unstable_headerSubtitle:
555 Platform.OS === "ios" && headerSubtitle.length > 0 ? headerSubtitle : undefined,
556 }}
557 />
558 <WorkspaceSidebarToolbar>
559 {fileInspector.supported ? (
560 <NativeHeaderToolbar.Button
561 accessibilityLabel="Return to chat"
562 icon="chevron.left"
563 onPress={() => {
564 navigation.dispatch(
565 StackActions.replace("Thread", {
566 environmentId: String(environmentId),
567 threadId: String(threadId),
568 }),
569 );
570 }}
571 />
572 ) : null}
573 </WorkspaceSidebarToolbar>
574 <NativeHeaderToolbar placement="right">
575 {fileInspector.supported ? (
576 <NativeHeaderToolbar.Button
577 accessibilityLabel={
578 panes.auxiliaryPaneVisible ? "Hide file navigator" : "Show file navigator"
579 }
580 icon="sidebar.right"
581 onPress={toggleAuxiliaryPane}
582 separateBackground
583 />
584 ) : null}
585 <NativeHeaderToolbar.Menu accessibilityLabel="File actions" icon="ellipsis">
586 {canPreview && !isImageFile ? (
587 <NativeHeaderToolbar.Menu inline>
588 <NativeHeaderToolbar.MenuAction
589 icon="eye"
590 isOn={resolvedActiveMode === "preview"}
591 onPress={() => setModeOverride({ path: relativePath, mode: "preview" })}
592 >
593 Preview
594 </NativeHeaderToolbar.MenuAction>
595 <NativeHeaderToolbar.MenuAction
596 icon="doc.text"
597 isOn={resolvedActiveMode === "source"}
598 onPress={() => setModeOverride({ path: relativePath, mode: "source" })}
599 >
600 Source
601 </NativeHeaderToolbar.MenuAction>
602 </NativeHeaderToolbar.Menu>
603 ) : null}
604 <NativeHeaderToolbar.MenuAction
605 icon="doc.on.doc"
606 onPress={() => copyTextWithHaptic(relativePath)}
607 >
608 Copy path
609 </NativeHeaderToolbar.MenuAction>
610 {isBrowserFile && typeof assetPreviewUri === "string" ? (
611 <NativeHeaderToolbar.MenuAction
612 icon="safari"
613 onPress={() => {
614 void tryOpenExternalUrl(assetPreviewUri, "file-preview");
615 }}
616 >
617 Open in Safari
618 </NativeHeaderToolbar.MenuAction>
619 ) : null}
620 {resolvedActiveMode === "preview" && (isBrowserFile || isImageFile) ? (
621 <NativeHeaderToolbar.MenuAction
622 icon="arrow.clockwise"
623 onPress={() => {
624 setPreviewRevision((current) => current + 1);
625 }}
626 >
627 Refresh
628 </NativeHeaderToolbar.MenuAction>
629 ) : null}
630 </NativeHeaderToolbar.Menu>
631 </NativeHeaderToolbar>
632 <FileContent
633 activeMode={resolvedActiveMode}
634 previewUri={previewUri}
635 fileContents={fileData?.contents ?? null}
636 fileError={fileQuery.error}
637 initialLine={targetLine}
638 relativePath={relativePath}
639 truncated={fileData?.truncated ?? false}
640 onRefresh={() => fileQuery.refresh()}
641 />
642 </View>
643 </ReviewHighlighterProvider>
644 );
645}