Open History to see the last commit
1import Stack from "expo-router/stack";
2import { SymbolView } from "expo-symbols";
3import { useLocalSearchParams, useRouter } from "expo-router";
4import { useCallback, useMemo, useRef, useState } from "react";
5import { ActivityIndicator, Pressable, ScrollView, Text as RNText, View } from "react-native";
6import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg";
7import {
8 EnvironmentId,
9 type ProjectListEntriesResult,
10 type ProjectReadFileResult,
11 ThreadId,
12} from "@t3tools/contracts";
13
14import { AppText as Text } from "../../components/AppText";
15import { CopyTextButton } from "../../components/CopyTextButton";
16import { EmptyState } from "../../components/EmptyState";
17import { LoadingScreen } from "../../components/LoadingScreen";
18import { cn } from "../../lib/cn";
19import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
20import { buildThreadFilesNavigation } from "../../lib/routes";
21import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
22import { useThemeColor } from "../../lib/useThemeColor";
23import { useThreadSelection } from "../../state/use-thread-selection";
24import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
25import { useEnvironmentQuery } from "../../state/query";
26import { projectEnvironment } from "../../state/projects";
27import { ReviewHighlighterProvider } from "../review/ReviewHighlighterProvider";
28import { FileMarkdownPreview } from "./FileMarkdownPreview";
29import { FileTreeBrowser } from "./FileTreeBrowser";
30import { SourceFileSurface } from "./SourceFileSurface";
31import { WorkspaceFileImagePreview } from "./WorkspaceFileImagePreview";
32import { WorkspaceFileWebPreview } from "./WorkspaceFileWebPreview";
33import {
34 basename,
35 fileBreadcrumbs,
36 isBrowserPreviewFile,
37 isImagePreviewFile,
38 isMarkdownPreviewFile,
39 isSvgImagePreviewFile,
40} from "./filePath";
41import { useWorkspaceFileAssetUrl } from "./workspaceFileAssetUrl";
42
43type FileViewMode = "preview" | "source";
44
45function firstRouteParam(value: string | string[] | undefined): string | null {
46 if (Array.isArray(value)) {
47 return value[0] ?? null;
48 }
49
50 return value ?? null;
51}
52
53function normalizeRoutePath(value: string | string[] | undefined): string | null {
54 const path = Array.isArray(value) ? value.join("/") : value;
55 if (path === undefined || path.trim().length === 0) {
56 return null;
57 }
58 return path;
59}
60
61function normalizeRouteLine(value: string | null): number | null {
62 if (value === null) {
63 return null;
64 }
65 const parsed = Number(value);
66 return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
67}
68
69function defaultViewMode(path: string | null): FileViewMode {
70 return path !== null && (isBrowserPreviewFile(path) || isImagePreviewFile(path))
71 ? "preview"
72 : "source";
73}
74
75function ModeButton(props: {
76 readonly active: boolean;
77 readonly icon: "doc.text" | "eye";
78 readonly label: string;
79 readonly onPress: () => void;
80}) {
81 const iconColor = String(
82 useThemeColor(props.active ? "--color-primary-foreground" : "--color-icon-muted"),
83 );
84
85 return (
86 <Pressable
87 accessibilityRole="button"
88 accessibilityState={{ selected: props.active }}
89 className={cn(
90 "h-8 flex-row items-center justify-center gap-1.5 rounded-full px-3 active:opacity-70",
91 props.active ? "bg-primary" : "bg-subtle",
92 )}
93 onPress={props.onPress}
94 >
95 <SymbolView name={props.icon} size={13} tintColor={iconColor} type="monochrome" />
96 <Text
97 className={cn(
98 "text-xs font-t3-bold",
99 props.active ? "text-primary-foreground" : "text-foreground-muted",
100 )}
101 >
102 {props.label}
103 </Text>
104 </Pressable>
105 );
106}
107
108function BreadcrumbFade(props: { readonly color: string; readonly side: "left" | "right" }) {
109 const gradientId = `file-breadcrumb-${props.side}-fade`;
110 const isLeft = props.side === "left";
111
112 return (
113 <View
114 pointerEvents="none"
115 className={cn("absolute inset-y-0 w-7", isLeft ? "left-0" : "right-0")}
116 >
117 <Svg width="100%" height="100%">
118 <Defs>
119 <LinearGradient id={gradientId} x1="0%" x2="100%" y1="0%" y2="0%">
120 <Stop offset="0%" stopColor={props.color} stopOpacity={isLeft ? 1 : 0} />
121 <Stop offset="100%" stopColor={props.color} stopOpacity={isLeft ? 0 : 1} />
122 </LinearGradient>
123 </Defs>
124 <Rect width="100%" height="100%" fill={`url(#${gradientId})`} />
125 </Svg>
126 </View>
127 );
128}
129
130function FileBreadcrumbs(props: { readonly projectName: string; readonly relativePath: string }) {
131 const iconColor = String(useThemeColor("--color-icon-muted"));
132 const cardColor = String(useThemeColor("--color-card"));
133 const scrollMetrics = useRef({ contentWidth: 0, offsetX: 0, viewportWidth: 0 });
134 const [fadeVisibility, setFadeVisibility] = useState({ left: false, right: false });
135 const breadcrumbs = useMemo(
136 () => fileBreadcrumbs(props.projectName, props.relativePath),
137 [props.projectName, props.relativePath],
138 );
139 const updateFadeVisibility = useCallback(
140 (metrics: Partial<(typeof scrollMetrics)["current"]>) => {
141 Object.assign(scrollMetrics.current, metrics);
142 const { contentWidth, offsetX, viewportWidth } = scrollMetrics.current;
143 const maxOffset = Math.max(0, contentWidth - viewportWidth);
144 const next = {
145 left: maxOffset > 1 && offsetX > 1,
146 right: maxOffset > 1 && offsetX < maxOffset - 1,
147 };
148
149 setFadeVisibility((current) =>
150 current.left === next.left && current.right === next.right ? current : next,
151 );
152 },
153 [],
154 );
155
156 return (
157 <View className="min-w-0 flex-1">
158 <ScrollView
159 horizontal
160 showsHorizontalScrollIndicator={false}
161 onContentSizeChange={(contentWidth) => {
162 updateFadeVisibility({ contentWidth });
163 }}
164 onLayout={(event) => {
165 updateFadeVisibility({ viewportWidth: event.nativeEvent.layout.width });
166 }}
167 onScroll={(event) => {
168 updateFadeVisibility({ offsetX: event.nativeEvent.contentOffset.x });
169 }}
170 scrollEventThrottle={16}
171 >
172 <View className="h-8 flex-row items-center">
173 {breadcrumbs.map((crumb, index) => (
174 <View key={crumb.path || "project"} className="flex-row items-center">
175 {index > 0 ? (
176 <SymbolView
177 name="chevron.right"
178 size={10}
179 tintColor={iconColor}
180 type="monochrome"
181 />
182 ) : null}
183 <Text
184 className={cn(
185 "max-w-[180px] px-1 text-xs",
186 crumb.kind === "file"
187 ? "font-t3-bold text-foreground"
188 : "font-t3-medium text-foreground-muted",
189 )}
190 numberOfLines={1}
191 >
192 {crumb.label}
193 </Text>
194 </View>
195 ))}
196 </View>
197 </ScrollView>
198 {fadeVisibility.left ? <BreadcrumbFade color={cardColor} side="left" /> : null}
199 {fadeVisibility.right ? <BreadcrumbFade color={cardColor} side="right" /> : null}
200 </View>
201 );
202}
203
204function FilePreviewHeader(props: {
205 readonly activeMode: FileViewMode;
206 readonly showModeSelector: boolean;
207 readonly externalPreviewUri?: string | null;
208 readonly projectName: string;
209 readonly relativePath: string;
210 readonly onSetMode: (mode: FileViewMode) => void;
211}) {
212 const iconColor = String(useThemeColor("--color-icon-muted"));
213
214 return (
215 <View className="border-b border-border bg-card px-3 py-2">
216 <View className="flex-row items-center gap-2">
217 <FileBreadcrumbs projectName={props.projectName} relativePath={props.relativePath} />
218 <CopyTextButton
219 accessibilityLabel="Copy file path"
220 text={props.relativePath}
221 tintColor={iconColor}
222 buttonSize={32}
223 iconSize={13}
224 />
225 </View>
226 {props.showModeSelector ? (
227 <View className="mt-2 flex-row items-center gap-2">
228 <ModeButton
229 active={props.activeMode === "preview"}
230 icon="eye"
231 label="Preview"
232 onPress={() => props.onSetMode("preview")}
233 />
234 <ModeButton
235 active={props.activeMode === "source"}
236 icon="doc.text"
237 label="Source"
238 onPress={() => props.onSetMode("source")}
239 />
240 {props.externalPreviewUri !== undefined ? (
241 <Pressable
242 accessibilityRole="button"
243 accessibilityLabel="Open preview in Safari"
244 disabled={props.externalPreviewUri === null}
245 hitSlop={8}
246 className={cn(
247 "ml-auto h-8 w-8 items-center justify-center rounded-full bg-subtle active:opacity-70",
248 props.externalPreviewUri === null && "opacity-40",
249 )}
250 onPress={() => {
251 if (typeof props.externalPreviewUri === "string") {
252 void tryOpenExternalUrl(props.externalPreviewUri, "file-preview");
253 }
254 }}
255 >
256 <SymbolView name="safari" size={15} tintColor={iconColor} type="monochrome" />
257 </Pressable>
258 ) : null}
259 </View>
260 ) : null}
261 </View>
262 );
263}
264
265function FileContent(props: {
266 readonly activeMode: FileViewMode;
267 readonly previewUri: string | null;
268 readonly fileContents: string | null;
269 readonly fileError: string | null;
270 readonly relativePath: string;
271 readonly initialLine: number | null;
272 readonly truncated: boolean;
273}) {
274 const isMarkdown = isMarkdownPreviewFile(props.relativePath);
275 const isBrowserFile = isBrowserPreviewFile(props.relativePath);
276 const isImageFile = isImagePreviewFile(props.relativePath);
277
278 if (props.activeMode === "preview" && isImageFile) {
279 if (isSvgImagePreviewFile(props.relativePath)) {
280 return <WorkspaceFileWebPreview uri={props.previewUri} />;
281 }
282 return (
283 <WorkspaceFileImagePreview
284 accessibilityLabel={basename(props.relativePath)}
285 uri={props.previewUri}
286 />
287 );
288 }
289
290 if (props.activeMode === "preview" && isBrowserFile) {
291 return <WorkspaceFileWebPreview uri={props.previewUri} />;
292 }
293
294 if (props.fileError && props.fileContents === null) {
295 return (
296 <View className="flex-1 items-center justify-center bg-card px-6">
297 <EmptyState title="File unavailable" detail={props.fileError} />
298 </View>
299 );
300 }
301
302 if (props.fileContents === null) {
303 return (
304 <View className="flex-1 items-center justify-center gap-3 bg-card px-6">
305 <ActivityIndicator />
306 <Text className="text-center text-sm text-foreground-muted">Loading file...</Text>
307 </View>
308 );
309 }
310
311 return (
312 <View className="flex-1 bg-card">
313 {props.truncated ? (
314 <View className="border-b border-amber-200 bg-amber-50 px-4 py-2 dark:border-amber-900/60 dark:bg-amber-950/40">
315 <Text className="text-2xs font-t3-bold uppercase text-amber-700 dark:text-amber-300">
316 Partial file
317 </Text>
318 <Text className="text-xs leading-[17px] text-amber-800 dark:text-amber-200">
319 Preview limited to the first 1 MB of a truncated file.
320 </Text>
321 </View>
322 ) : null}
323 {props.activeMode === "preview" && isMarkdown ? (
324 <FileMarkdownPreview markdown={props.fileContents} />
325 ) : (
326 <SourceFileSurface
327 contents={props.fileContents}
328 path={props.relativePath}
329 initialLine={props.initialLine}
330 />
331 )}
332 </View>
333 );
334}
335
336function useThreadFilesWorkspace() {
337 const params = useLocalSearchParams<{
338 environmentId?: string | string[];
339 threadId?: string | string[];
340 }>();
341 const routeEnvironmentId = firstRouteParam(params.environmentId);
342 const routeThreadId = firstRouteParam(params.threadId);
343 const { selectedThread, selectedThreadProject } = useThreadSelection();
344 const { selectedThreadCwd } = useSelectedThreadWorktree();
345 const environmentId =
346 routeEnvironmentId !== null
347 ? EnvironmentId.make(routeEnvironmentId)
348 : (selectedThread?.environmentId ?? null);
349 const threadId = routeThreadId !== null ? ThreadId.make(routeThreadId) : null;
350 const project = selectedThreadProject as {
351 readonly title?: string;
352 readonly workspaceRoot?: string;
353 } | null;
354
355 return {
356 cwd: selectedThreadCwd ?? project?.workspaceRoot ?? null,
357 environmentId,
358 projectName: project?.title ?? "Files",
359 selectedThread,
360 threadId,
361 };
362}
363
364function FilesUnavailable() {
365 return (
366 <View className="flex-1 items-center justify-center bg-sheet px-6">
367 <Stack.Screen options={{ title: "Files" }} />
368 <EmptyState
369 title="Files unavailable"
370 detail="This thread does not have an active workspace path."
371 />
372 </View>
373 );
374}
375
376function FilesHeaderTitle(props: { readonly projectName: string }) {
377 const foregroundColor = String(useThemeColor("--color-foreground"));
378 const secondaryForegroundColor = String(useThemeColor("--color-foreground-secondary"));
379
380 return (
381 <View style={{ alignItems: "center", maxWidth: 220 }}>
382 <RNText
383 numberOfLines={1}
384 style={{
385 color: foregroundColor,
386 fontFamily: "DMSans_700Bold",
387 fontSize: MOBILE_TYPOGRAPHY.headline.fontSize,
388 fontWeight: "900",
389 letterSpacing: -0.4,
390 }}
391 >
392 Files
393 </RNText>
394 <RNText
395 numberOfLines={1}
396 style={{
397 color: secondaryForegroundColor,
398 fontFamily: "DMSans_500Medium",
399 fontSize: MOBILE_TYPOGRAPHY.label.fontSize,
400 fontWeight: "500",
401 letterSpacing: 0.2,
402 }}
403 >
404 {props.projectName}
405 </RNText>
406 </View>
407 );
408}
409
410function FilesToolbarBottomFade() {
411 const sheetColor = String(useThemeColor("--color-sheet"));
412
413 if (process.env.EXPO_OS !== "ios") {
414 return null;
415 }
416
417 return (
418 <View
419 pointerEvents="none"
420 accessibilityElementsHidden
421 importantForAccessibility="no-hide-descendants"
422 style={{
423 bottom: 0,
424 height: 112,
425 left: 0,
426 position: "absolute",
427 right: 0,
428 zIndex: 1,
429 }}
430 >
431 <Svg width="100%" height="100%">
432 <Defs>
433 <LinearGradient id="files-toolbar-bottom-fade" x1="0%" x2="0%" y1="0%" y2="100%">
434 <Stop offset="0%" stopColor={sheetColor} stopOpacity={0} />
435 <Stop offset="58%" stopColor={sheetColor} stopOpacity={0.72} />
436 <Stop offset="100%" stopColor={sheetColor} stopOpacity={0.96} />
437 </LinearGradient>
438 </Defs>
439 <Rect width="100%" height="100%" fill="url(#files-toolbar-bottom-fade)" />
440 </Svg>
441 </View>
442 );
443}
444
445export function ThreadFilesTreeScreen() {
446 const router = useRouter();
447 const [searchQuery, setSearchQuery] = useState("");
448 const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace();
449 const entriesQuery = useEnvironmentQuery(
450 environmentId !== null && cwd !== null
451 ? projectEnvironment.listEntries({
452 environmentId,
453 input: { cwd },
454 })
455 : null,
456 );
457 const entriesData = entriesQuery.data as ProjectListEntriesResult | null;
458
459 const handleSelectFile = useCallback(
460 (path: string) => {
461 if (environmentId === null || threadId === null) {
462 return;
463 }
464 router.push(buildThreadFilesNavigation({ environmentId, threadId }, path));
465 },
466 [environmentId, router, threadId],
467 );
468
469 if (selectedThread === null || environmentId === null || threadId === null) {
470 return <LoadingScreen message="Opening files..." messagePlacement="above-spinner" />;
471 }
472
473 if (cwd === null) {
474 return <FilesUnavailable />;
475 }
476
477 return (
478 <View className="flex-1 bg-sheet">
479 <Stack.Screen
480 options={{
481 title: "Files",
482 headerShown: true,
483 headerTransparent: true,
484 headerStyle: { backgroundColor: "transparent" },
485 headerShadowVisible: false,
486 headerTitle: () => <FilesHeaderTitle projectName={projectName} />,
487 headerSearchBarOptions: {
488 allowToolbarIntegration: true,
489 autoCapitalize: "none",
490 hideNavigationBar: false,
491 placeholder: "Search files",
492 onChangeText: (event) => {
493 setSearchQuery(event.nativeEvent.text);
494 },
495 onCancelButtonPress: () => {
496 setSearchQuery("");
497 },
498 },
499 }}
500 />
501 <Stack.Toolbar placement="right">
502 <Stack.Toolbar.Button
503 accessibilityLabel="Refresh files"
504 icon="arrow.clockwise"
505 onPress={entriesQuery.refresh}
506 />
507 </Stack.Toolbar>
508 <Stack.Toolbar placement="bottom">
509 <Stack.Toolbar.SearchBarSlot />
510 </Stack.Toolbar>
511 <FileTreeBrowser
512 entries={entriesData?.entries ?? []}
513 error={entriesQuery.error}
514 isPending={entriesQuery.isPending}
515 searchQuery={searchQuery}
516 selectedPath={null}
517 onRefresh={entriesQuery.refresh}
518 onSelectFile={handleSelectFile}
519 />
520 <FilesToolbarBottomFade />
521 </View>
522 );
523}
524
525export function ThreadFileScreen() {
526 const params = useLocalSearchParams<{
527 line?: string | string[];
528 path?: string | string[];
529 }>();
530 const relativePath = normalizeRoutePath(params.path);
531 const targetLine = normalizeRouteLine(firstRouteParam(params.line));
532 const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace();
533 const [modeOverride, setModeOverride] = useState<{
534 readonly path: string;
535 readonly mode: FileViewMode;
536 } | null>(null);
537 const [previewRevision, setPreviewRevision] = useState(0);
538 const isBrowserFile = relativePath !== null && isBrowserPreviewFile(relativePath);
539 const isImageFile = relativePath !== null && isImagePreviewFile(relativePath);
540 const canPreview =
541 relativePath !== null && (isMarkdownPreviewFile(relativePath) || isBrowserFile || isImageFile);
542 const activeMode =
543 relativePath !== null && modeOverride?.path === relativePath
544 ? modeOverride.mode
545 : defaultViewMode(relativePath);
546 const resolvedActiveMode = canPreview ? activeMode : "source";
547 const assetPreviewPath = isBrowserFile || isImageFile ? relativePath : null;
548 const assetPreviewUri = useWorkspaceFileAssetUrl({
549 cwd,
550 environmentId,
551 relativePath: assetPreviewPath,
552 threadId,
553 });
554 const previewUri =
555 assetPreviewUri === null || previewRevision === 0
556 ? assetPreviewUri
557 : `${assetPreviewUri}${assetPreviewUri.includes("?") ? "&" : "?"}revision=${previewRevision}`;
558 const needsFileContents =
559 relativePath !== null &&
560 (resolvedActiveMode === "source" || isMarkdownPreviewFile(relativePath));
561 const fileQuery = useEnvironmentQuery(
562 environmentId !== null && cwd !== null && relativePath !== null && needsFileContents
563 ? projectEnvironment.readFile({
564 environmentId,
565 input: { cwd, relativePath },
566 })
567 : null,
568 );
569 const fileData = fileQuery.data as ProjectReadFileResult | null;
570
571 if (selectedThread === null || environmentId === null || threadId === null) {
572 return <LoadingScreen message="Opening file..." messagePlacement="above-spinner" />;
573 }
574
575 if (cwd === null) {
576 return <FilesUnavailable />;
577 }
578
579 if (relativePath === null) {
580 return (
581 <View className="flex-1 items-center justify-center bg-sheet px-6">
582 <Stack.Screen options={{ title: "Files" }} />
583 <EmptyState title="File unavailable" detail="This file path is invalid." />
584 </View>
585 );
586 }
587
588 return (
589 <ReviewHighlighterProvider>
590 <View className="flex-1 bg-sheet">
591 <Stack.Screen options={{ title: basename(relativePath) }} />
592 <Stack.Toolbar placement="right">
593 <Stack.Toolbar.Button
594 icon="arrow.clockwise"
595 onPress={() => {
596 if (resolvedActiveMode === "preview" && (isBrowserFile || isImageFile)) {
597 setPreviewRevision((current) => current + 1);
598 return;
599 }
600 fileQuery.refresh();
601 }}
602 />
603 </Stack.Toolbar>
604 <FilePreviewHeader
605 activeMode={resolvedActiveMode}
606 showModeSelector={canPreview && !isImageFile}
607 externalPreviewUri={isBrowserFile ? assetPreviewUri : undefined}
608 projectName={projectName}
609 relativePath={relativePath}
610 onSetMode={(mode) => {
611 setModeOverride({ path: relativePath, mode });
612 }}
613 />
614 <FileContent
615 activeMode={resolvedActiveMode}
616 previewUri={previewUri}
617 fileContents={fileData?.contents ?? null}
618 fileError={fileQuery.error}
619 initialLine={targetLine}
620 relativePath={relativePath}
621 truncated={fileData?.truncated ?? false}
622 />
623 </View>
624 </ReviewHighlighterProvider>
625 );
626}