Open History to see the last commit
1import type {
2 EditorId,
3 EnvironmentId,
4 ResolvedKeybindingsConfig,
5 ScopedThreadRef,
6} from "@t3tools/contracts";
7import { isWorkspaceImagePreviewPath } from "@t3tools/shared/filePreview";
8import { VirtualizedFile, type SelectedLineRange } from "@pierre/diffs";
9import { Editor } from "@pierre/diffs/editor";
10import { EditProvider, File, type FileOptions, Virtualizer } from "@pierre/diffs/react";
11import {
12 isAtomCommandInterrupted,
13 squashAtomCommandFailure,
14} from "@t3tools/client-runtime/state/runtime";
15import { ChevronRight, Code2, Eye, FolderTree, Globe2, LoaderCircle } from "lucide-react";
16import * as Schema from "effect/Schema";
17import { useCallback, useEffect, useMemo, useRef, useState } from "react";
18
19import { isBrowserPreviewFile, openFileInPreview } from "~/browser/openFileInPreview";
20import { useAssetUrlState } from "~/assets/assetUrls";
21import ChatMarkdown from "~/components/ChatMarkdown";
22import { OpenInPicker } from "~/components/chat/OpenInPicker";
23import { useClientSettings } from "~/hooks/useSettings";
24import { useTheme } from "~/hooks/useTheme";
25import { getLocalStorageItem, setLocalStorageItem, useLocalStorage } from "~/hooks/useLocalStorage";
26import { resolveDiffThemeName } from "~/lib/diffRendering";
27import { cn } from "~/lib/utils";
28import { isPreviewSupportedInRuntime } from "~/previewStateStore";
29import { resolvePathLinkTarget } from "~/terminal-links";
30import { ScrollArea } from "~/components/ui/scroll-area";
31import { Toggle } from "~/components/ui/toggle";
32import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
33import { stackedThreadToast, toastManager } from "~/components/ui/toast";
34import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
35import { buildFileReviewComment } from "~/reviewCommentContext";
36import { assetEnvironment } from "~/state/assets";
37import { useEnvironmentHttpBaseUrl, usePrimaryEnvironmentId } from "~/state/environments";
38import { previewEnvironment } from "~/state/preview";
39import { projectEnvironment } from "~/state/projects";
40import { useAtomCommand } from "~/state/use-atom-command";
41import { useAtomQueryRunner } from "~/state/use-atom-query-runner";
42
43import FileBrowserPanel from "./FileBrowserPanel";
44import {
45 type FileCommentAnnotationEntry,
46 type FileCommentAnnotationGroup,
47 type FileCommentLineAnnotation,
48 formatFileCommentRange,
49 nextFileCommentId,
50 normalizeFileCommentRange,
51 remapFileCommentAnnotations,
52} from "./fileCommentAnnotations";
53import { installFileEditorDismissal } from "./fileEditorDismissal";
54import { LocalCommentAnnotation } from "./LocalCommentAnnotation";
55import { projectFileCacheKey, projectFileEditorCacheKey } from "./fileContentRevision";
56import { fileBreadcrumbs } from "./filePath";
57import { isMarkdownPreviewFile, setMarkdownTaskChecked } from "./filePreviewMode";
58import { FileSaveCoordinator } from "./fileSaveCoordinator";
59import {
60 confirmProjectFileQueryData,
61 getOptimisticProjectFileQueryData,
62 setProjectFileQueryData,
63 useProjectFileQuery,
64} from "./projectFilesQueryState";
65
66interface FilePreviewPanelProps {
67 environmentId: EnvironmentId;
68 cwd: string;
69 projectName: string;
70 relativePath: string | null;
71 threadRef: ScopedThreadRef;
72 composerDraftTarget: ScopedThreadRef | DraftId;
73 keybindings: ResolvedKeybindingsConfig;
74 availableEditors: ReadonlyArray<EditorId>;
75 revealLine: number | null;
76 revealRequestId: number;
77 onOpenFile: (relativePath: string) => void;
78 onPendingChange: (relativePath: string, pending: boolean) => void;
79}
80
81const FILE_EXPLORER_STORAGE_KEY = "t3code.fileExplorerOpen";
82const RENDER_MARKDOWN_STORAGE_KEY = "t3code.renderMarkdown";
83const FILE_SAVE_DEBOUNCE_MS = 500;
84const FILE_LINK_REVEAL_ATTRIBUTE = "data-file-link-reveal";
85const FILE_LINK_REVEAL_UNSAFE_CSS = `
86 [${FILE_LINK_REVEAL_ATTRIBUTE}][data-line] {
87 background-color: light-dark(
88 color-mix(
89 in lab,
90 var(--diffs-computed-diff-line-bg) 82%,
91 var(--diffs-bg-selection-override, var(--diffs-selection-base))
92 ),
93 color-mix(
94 in lab,
95 var(--diffs-computed-diff-line-bg) 75%,
96 var(--diffs-bg-selection-override, var(--diffs-selection-base))
97 )
98 ) !important;
99 }
100
101 [${FILE_LINK_REVEAL_ATTRIBUTE}][data-column-number] {
102 background-color: light-dark(
103 color-mix(
104 in lab,
105 var(--diffs-computed-diff-line-bg) 75%,
106 var(--diffs-bg-selection-number-override, var(--diffs-selection-base))
107 ),
108 color-mix(
109 in lab,
110 var(--diffs-computed-diff-line-bg) 60%,
111 var(--diffs-bg-selection-number-override, var(--diffs-selection-base))
112 )
113 ) !important;
114 color: var(--diffs-selection-number-fg) !important;
115 }
116`;
117type FilePostRender = NonNullable<FileOptions<unknown>["onPostRender"]>;
118
119function WorkspaceImagePreview(props: {
120 readonly environmentId: EnvironmentId;
121 readonly threadRef: ScopedThreadRef;
122 readonly absolutePath: string;
123 readonly alt: string;
124}) {
125 const assetUrl = useAssetUrlState(props.environmentId, {
126 _tag: "workspace-file",
127 threadId: props.threadRef.threadId,
128 path: props.absolutePath,
129 });
130 const [failedUrl, setFailedUrl] = useState<string | null>(null);
131
132 if (assetUrl._tag === "Failure" || (assetUrl._tag === "Success" && failedUrl === assetUrl.url)) {
133 return (
134 <div className="flex min-h-0 flex-1 items-center justify-center px-6 text-center text-xs leading-relaxed text-destructive">
135 Unable to load workspace image.
136 </div>
137 );
138 }
139
140 return assetUrl._tag === "Success" ? (
141 <div className="flex min-h-0 flex-1 items-center justify-center overflow-auto p-4">
142 <img
143 className="max-h-full max-w-full object-contain"
144 src={assetUrl.url}
145 alt={props.alt}
146 onError={() => setFailedUrl(assetUrl.url)}
147 />
148 </div>
149 ) : (
150 <div className="flex min-h-0 flex-1 items-center justify-center text-muted-foreground">
151 <LoaderCircle className="size-5 animate-spin" />
152 </div>
153 );
154}
155
156function clampFileLine(contents: string, requestedLine: number): number {
157 let lineCount = 1;
158 for (let index = 0; index < contents.length; index += 1) {
159 const character = contents.charCodeAt(index);
160 if (character === 10) {
161 lineCount += 1;
162 } else if (character === 13) {
163 lineCount += 1;
164 if (contents.charCodeAt(index + 1) === 10) index += 1;
165 }
166 }
167 return Math.min(Math.max(1, requestedLine), lineCount);
168}
169
170function updateFileLinkReveal(fileContainer: HTMLElement, line: number | null): void {
171 const root = fileContainer.shadowRoot ?? fileContainer;
172 for (const element of root.querySelectorAll<HTMLElement>(`[${FILE_LINK_REVEAL_ATTRIBUTE}]`)) {
173 element.removeAttribute(FILE_LINK_REVEAL_ATTRIBUTE);
174 }
175 if (line === null) return;
176
177 root
178 .querySelector<HTMLElement>(`[data-line="${line}"]`)
179 ?.setAttribute(FILE_LINK_REVEAL_ATTRIBUTE, "");
180 root
181 .querySelector<HTMLElement>(`[data-column-number="${line}"]`)
182 ?.setAttribute(FILE_LINK_REVEAL_ATTRIBUTE, "");
183}
184
185function useFileLineReveal(
186 relativePath: string | null,
187 revealLine: number | null,
188 revealRequestId: number,
189): FilePostRender {
190 const [handledRequestIdsByPath] = useState(() => new Map<string, number>());
191 const [latestRequestIdsByPath] = useState(() => new Map<string, number>());
192 const [pendingFramesByPath] = useState(() => new Map<string, number>());
193
194 return useCallback<FilePostRender>(
195 (fileContainer, instance, phase) => {
196 if (relativePath === null) return;
197
198 const cancelPendingReveal = () => {
199 const frameId = pendingFramesByPath.get(relativePath);
200 if (frameId !== undefined) {
201 cancelAnimationFrame(frameId);
202 pendingFramesByPath.delete(relativePath);
203 }
204 };
205
206 if (phase === "unmount") {
207 cancelPendingReveal();
208 return;
209 }
210
211 const targetLine =
212 revealLine === null ? null : clampFileLine(instance.file?.contents ?? "", revealLine);
213 updateFileLinkReveal(fileContainer, targetLine);
214
215 if (!(instance instanceof VirtualizedFile)) return;
216
217 if (latestRequestIdsByPath.get(relativePath) !== revealRequestId) {
218 cancelPendingReveal();
219 latestRequestIdsByPath.set(relativePath, revealRequestId);
220 }
221
222 if (targetLine === null) {
223 fileContainer.style.minHeight = "";
224 return;
225 }
226
227 const scrollContainer = fileContainer.closest<HTMLElement>(".file-preview-virtualizer");
228 if (!scrollContainer) return;
229 fileContainer.style.minHeight = `${Math.ceil(
230 Math.max(instance.height, scrollContainer.clientHeight),
231 )}px`;
232
233 if (
234 handledRequestIdsByPath.get(relativePath) === revealRequestId ||
235 pendingFramesByPath.has(relativePath)
236 ) {
237 return;
238 }
239
240 const reveal = () => {
241 pendingFramesByPath.delete(relativePath);
242 if (
243 latestRequestIdsByPath.get(relativePath) !== revealRequestId ||
244 !fileContainer.isConnected
245 ) {
246 return;
247 }
248
249 const linePosition = instance.getLinePosition(targetLine);
250 if (!linePosition) return;
251
252 const fileTop =
253 scrollContainer.scrollTop +
254 fileContainer.getBoundingClientRect().top -
255 scrollContainer.getBoundingClientRect().top;
256 const centeredTop = Math.max(
257 0,
258 fileTop +
259 linePosition.top -
260 Math.max(0, (scrollContainer.clientHeight - linePosition.height) / 2),
261 );
262 const maxScrollTop = Math.max(
263 0,
264 scrollContainer.scrollHeight - scrollContainer.clientHeight,
265 );
266
267 scrollContainer.scrollTop = Math.min(centeredTop, maxScrollTop);
268 handledRequestIdsByPath.set(relativePath, revealRequestId);
269 };
270
271 pendingFramesByPath.set(relativePath, requestAnimationFrame(reveal));
272 },
273 [
274 handledRequestIdsByPath,
275 latestRequestIdsByPath,
276 pendingFramesByPath,
277 relativePath,
278 revealLine,
279 revealRequestId,
280 ],
281 );
282}
283
284interface EditableFileSurfaceProps {
285 environmentId: EnvironmentId;
286 cwd: string;
287 relativePath: string;
288 composerDraftTarget: ScopedThreadRef | DraftId;
289 contents: string;
290 resolvedTheme: "light" | "dark";
291 revealRequestId: number;
292 wordWrap: boolean;
293 onPostRender: FilePostRender;
294 onPendingChange: (relativePath: string, pending: boolean) => void;
295}
296
297interface FileSelectionOverride {
298 revealRequestId: number;
299 range: SelectedLineRange | null;
300}
301
302function useFileSaveCoordinator({
303 environmentId,
304 cwd,
305 relativePath,
306 onPendingChange,
307}: Pick<
308 EditableFileSurfaceProps,
309 "environmentId" | "cwd" | "relativePath" | "onPendingChange"
310>): FileSaveCoordinator {
311 const writeFile = useAtomCommand(projectEnvironment.writeFile);
312 const coordinator = useMemo(
313 () =>
314 new FileSaveCoordinator({
315 debounceMs: FILE_SAVE_DEBOUNCE_MS,
316 onPendingChange: (pending) => onPendingChange(relativePath, pending),
317 persist: (nextContents) =>
318 writeFile({
319 environmentId,
320 input: { cwd, relativePath, contents: nextContents },
321 }),
322 onConfirmed: (confirmedContents) => {
323 confirmProjectFileQueryData(environmentId, cwd, relativePath, confirmedContents);
324 },
325 }),
326 [cwd, environmentId, onPendingChange, relativePath, writeFile],
327 );
328
329 useEffect(() => () => coordinator.dispose(), [coordinator]);
330 return coordinator;
331}
332
333function EditableFileSurface({
334 environmentId,
335 cwd,
336 relativePath,
337 composerDraftTarget,
338 contents,
339 resolvedTheme,
340 revealRequestId,
341 wordWrap,
342 onPostRender,
343 onPendingChange,
344}: EditableFileSurfaceProps) {
345 const addReviewComment = useComposerDraftStore((store) => store.addReviewComment);
346 const removeReviewComment = useComposerDraftStore((store) => store.removeReviewComment);
347 const [lineAnnotations, setLineAnnotations] = useState<FileCommentLineAnnotation[]>([]);
348 const [selectionOverride, setSelectionOverride] = useState<FileSelectionOverride | null>(null);
349 const selectedRange =
350 selectionOverride?.revealRequestId === revealRequestId ? selectionOverride.range : null;
351 const setSelectedRange = useCallback(
352 (range: SelectedLineRange | null) => {
353 setSelectionOverride({ revealRequestId, range });
354 },
355 [revealRequestId],
356 );
357 const surfaceRef = useRef<HTMLDivElement>(null);
358 const selectionFrameRef = useRef<number | null>(null);
359 const saveCoordinator = useFileSaveCoordinator({
360 environmentId,
361 cwd,
362 relativePath,
363 onPendingChange,
364 });
365 const editor = useMemo(
366 () =>
367 new Editor<FileCommentAnnotationGroup>({
368 persistState: true,
369 persistStateStorage: "inMemory",
370 onChange: (file, nextLineAnnotations) => {
371 setProjectFileQueryData(environmentId, cwd, relativePath, file.contents);
372 saveCoordinator.change(file.contents);
373 if (nextLineAnnotations) {
374 const remapped = remapFileCommentAnnotations(
375 nextLineAnnotations as FileCommentLineAnnotation[],
376 );
377 setLineAnnotations(remapped);
378 for (const annotation of remapped) {
379 for (const entry of annotation.metadata.entries) {
380 if (entry.kind !== "comment") continue;
381 addReviewComment(
382 composerDraftTarget,
383 buildFileReviewComment({
384 id: entry.id,
385 filePath: relativePath,
386 startLine: entry.startLine,
387 endLine: entry.endLine,
388 text: entry.text,
389 contents: file.contents,
390 }),
391 );
392 }
393 }
394 }
395 },
396 }),
397 [addReviewComment, composerDraftTarget, cwd, environmentId, relativePath, saveCoordinator],
398 );
399
400 useEffect(
401 () => () => {
402 editor.cleanUp();
403 },
404 [editor],
405 );
406
407 const removeAnnotationEntry = useCallback(
408 (entryId: string) => {
409 setSelectedRange(null);
410 removeReviewComment(composerDraftTarget, entryId);
411 setLineAnnotations((current) => {
412 return current.flatMap((annotation) => {
413 const entries = annotation.metadata.entries.filter((entry) => entry.id !== entryId);
414 return entries.length > 0 ? [{ ...annotation, metadata: { entries } }] : [];
415 });
416 });
417 },
418 [composerDraftTarget, removeReviewComment, setSelectedRange],
419 );
420
421 const submitAnnotationEntry = useCallback(
422 (entryId: string, text: string) => {
423 setSelectedRange(null);
424 const entry = lineAnnotations
425 .flatMap((annotation) => annotation.metadata.entries)
426 .find((candidate) => candidate.id === entryId);
427 if (entry) {
428 addReviewComment(
429 composerDraftTarget,
430 buildFileReviewComment({
431 id: entry.id,
432 filePath: relativePath,
433 startLine: entry.startLine,
434 endLine: entry.endLine,
435 text,
436 contents,
437 }),
438 );
439 }
440 setLineAnnotations((current) =>
441 current.map((annotation) => ({
442 ...annotation,
443 metadata: {
444 entries: annotation.metadata.entries.map((annotationEntry) =>
445 annotationEntry.id === entryId
446 ? { ...annotationEntry, kind: "comment", text }
447 : annotationEntry,
448 ),
449 },
450 })),
451 );
452 },
453 [
454 addReviewComment,
455 composerDraftTarget,
456 contents,
457 lineAnnotations,
458 relativePath,
459 setSelectedRange,
460 ],
461 );
462
463 const beginComment = useCallback((range: SelectedLineRange) => {
464 const { startLine, endLine } = normalizeFileCommentRange(range);
465 const draftEntry: FileCommentAnnotationEntry = {
466 id: nextFileCommentId(),
467 kind: "draft",
468 startLine,
469 endLine,
470 text: "",
471 };
472 setLineAnnotations((current) => {
473 const withoutDraft = current.flatMap((annotation) => {
474 const entries = annotation.metadata.entries.filter((entry) => entry.kind !== "draft");
475 return entries.length > 0 ? [{ ...annotation, metadata: { entries } }] : [];
476 });
477 const existingIndex = withoutDraft.findIndex(
478 (annotation) => annotation.lineNumber === endLine,
479 );
480 if (existingIndex < 0) {
481 return [
482 ...withoutDraft,
483 {
484 lineNumber: endLine,
485 metadata: { entries: [draftEntry] },
486 },
487 ];
488 }
489 return withoutDraft.map((annotation, index) =>
490 index === existingIndex
491 ? {
492 ...annotation,
493 metadata: { entries: [...annotation.metadata.entries, draftEntry] },
494 }
495 : annotation,
496 );
497 });
498 }, []);
499 const hasOpenCommentForm = lineAnnotations.some((annotation) =>
500 annotation.metadata.entries.some((entry) => entry.kind === "draft"),
501 );
502 useEffect(() => {
503 const root = surfaceRef.current;
504 if (!root) return;
505 return installFileEditorDismissal({
506 root,
507 editor,
508 isBlocked: () => hasOpenCommentForm,
509 onDismiss: () => setSelectedRange(null),
510 });
511 }, [editor, hasOpenCommentForm, setSelectedRange]);
512 const handleLineSelectionEnd = useCallback(
513 (range: SelectedLineRange | null) => {
514 setSelectedRange(range);
515 if (range) {
516 beginComment(range);
517 }
518 },
519 [beginComment, setSelectedRange],
520 );
521
522 const handlePostRender = useCallback<FilePostRender>(
523 (fileContainer, instance, phase) => {
524 onPostRender(fileContainer, instance, phase);
525
526 if (selectionFrameRef.current !== null) {
527 cancelAnimationFrame(selectionFrameRef.current);
528 selectionFrameRef.current = null;
529 }
530 if (phase === "unmount") return;
531
532 selectionFrameRef.current = requestAnimationFrame(() => {
533 selectionFrameRef.current = null;
534 if (!fileContainer.isConnected) return;
535 instance.setSelectedLines(selectedRange, { notify: false });
536 });
537 },
538 [onPostRender, selectedRange],
539 );
540
541 return (
542 <EditProvider editor={editor}>
543 <div ref={surfaceRef} className="flex min-h-0 flex-1">
544 <Virtualizer
545 className="file-preview-virtualizer min-h-0 flex-1 overflow-auto"
546 config={{
547 overscrollSize: 600,
548 intersectionObserverMargin: 1200,
549 }}
550 >
551 <File<FileCommentAnnotationGroup>
552 file={{
553 name: relativePath,
554 contents,
555 cacheKey: projectFileEditorCacheKey(
556 environmentId,
557 cwd,
558 relativePath,
559 contents,
560 editor.getFile(),
561 ),
562 }}
563 options={{
564 disableFileHeader: true,
565 enableGutterUtility: !hasOpenCommentForm,
566 enableLineSelection: !hasOpenCommentForm,
567 onGutterUtilityClick: setSelectedRange,
568 onLineSelectionChange: setSelectedRange,
569 onLineSelectionEnd: handleLineSelectionEnd,
570 overflow: wordWrap ? "wrap" : "scroll",
571 theme: resolveDiffThemeName(resolvedTheme),
572 themeType: resolvedTheme,
573 unsafeCSS: FILE_LINK_REVEAL_UNSAFE_CSS,
574 onPostRender: handlePostRender,
575 }}
576 selectedLines={selectedRange}
577 lineAnnotations={lineAnnotations}
578 renderAnnotation={(annotation) => (
579 <div className="py-1">
580 {annotation.metadata.entries.map((entry) => (
581 <LocalCommentAnnotation
582 key={entry.id}
583 kind={entry.kind}
584 rangeLabel={formatFileCommentRange(entry.startLine, entry.endLine)}
585 text={entry.text}
586 onCancel={() => removeAnnotationEntry(entry.id)}
587 onComment={(text) => submitAnnotationEntry(entry.id, text)}
588 onDelete={() => removeAnnotationEntry(entry.id)}
589 />
590 ))}
591 </div>
592 )}
593 className="min-h-full"
594 contentEditable
595 />
596 </Virtualizer>
597 </div>
598 </EditProvider>
599 );
600}
601
602function RenderedMarkdownSurface({
603 environmentId,
604 cwd,
605 relativePath,
606 contents,
607 threadRef,
608 onPendingChange,
609}: Omit<
610 EditableFileSurfaceProps,
611 | "resolvedTheme"
612 | "composerDraftTarget"
613 | "revealLine"
614 | "revealRequestId"
615 | "wordWrap"
616 | "onPostRender"
617> & {
618 threadRef: ScopedThreadRef;
619}) {
620 const saveCoordinator = useFileSaveCoordinator({
621 environmentId,
622 cwd,
623 relativePath,
624 onPendingChange,
625 });
626
627 return (
628 <ScrollArea className="min-h-0 flex-1">
629 <ChatMarkdown
630 text={contents}
631 cwd={cwd}
632 threadRef={threadRef}
633 className="mx-auto max-w-4xl px-6 py-5"
634 onTaskListChange={({ markerOffset, checked }) => {
635 const currentContents =
636 getOptimisticProjectFileQueryData(environmentId, cwd, relativePath)?.contents ??
637 contents;
638 const nextContents = setMarkdownTaskChecked(currentContents, markerOffset, checked);
639 if (nextContents === currentContents) return;
640 setProjectFileQueryData(environmentId, cwd, relativePath, nextContents);
641 saveCoordinator.change(nextContents);
642 }}
643 />
644 </ScrollArea>
645 );
646}
647
648function initialExplorerOpen(): boolean {
649 try {
650 return getLocalStorageItem(FILE_EXPLORER_STORAGE_KEY, Schema.Boolean) ?? true;
651 } catch (error) {
652 console.error(error);
653 return true;
654 }
655}
656
657export default function FilePreviewPanel({
658 environmentId,
659 cwd,
660 projectName,
661 relativePath,
662 threadRef,
663 composerDraftTarget,
664 keybindings,
665 availableEditors,
666 revealLine,
667 revealRequestId,
668 onOpenFile,
669 onPendingChange,
670}: FilePreviewPanelProps) {
671 const { resolvedTheme } = useTheme();
672 const wordWrap = useClientSettings((settings) => settings.wordWrap);
673 const primaryEnvironmentId = usePrimaryEnvironmentId();
674 const environmentHttpBaseUrl = useEnvironmentHttpBaseUrl(environmentId);
675 const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
676 reportFailure: false,
677 });
678 const openPreview = useAtomCommand(previewEnvironment.open, {
679 reportFailure: false,
680 });
681 const isImage = relativePath !== null && isWorkspaceImagePreviewPath(relativePath);
682 const file = useProjectFileQuery(environmentId, cwd, relativePath, !isImage);
683 const [explorerOpen, setExplorerOpen] = useState(initialExplorerOpen);
684 // Reading markdown rendered is a preference, not a property of one file. Keeping
685 // it on the panel meant a thread switch dropped it and forced source back.
686 const [renderMarkdownPreferred, setRenderMarkdownPreferred] = useLocalStorage(
687 RENDER_MARKDOWN_STORAGE_KEY,
688 false,
689 Schema.Boolean,
690 );
691 // Paired with the path on purpose: each file surface counts its reveals from
692 // one, so a bare id would let a dismissed reveal on one file swallow the first
693 // reveal on the next.
694 const [handledReveal, setHandledReveal] = useState<{ path: string; requestId: number } | null>(
695 null,
696 );
697 const breadcrumbRef = useRef<HTMLDivElement>(null);
698 const isMarkdown = relativePath ? isMarkdownPreviewFile(relativePath) : false;
699 // A reveal still wins over the preference: the line only exists in the source.
700 const renderMarkdown =
701 isMarkdown &&
702 renderMarkdownPreferred &&
703 (revealLine === null ||
704 (handledReveal?.path === relativePath && handledReveal.requestId === revealRequestId));
705 const canOpenInBrowser =
706 relativePath !== null && isPreviewSupportedInRuntime() && isBrowserPreviewFile(relativePath);
707 const absolutePath = relativePath ? resolvePathLinkTarget(relativePath, cwd) : null;
708 const breadcrumbs = useMemo(
709 () => (relativePath ? fileBreadcrumbs(projectName, relativePath) : []),
710 [projectName, relativePath],
711 );
712 const onFilePostRender = useFileLineReveal(relativePath, revealLine, revealRequestId);
713
714 useEffect(() => {
715 const currentCrumb = breadcrumbRef.current?.querySelector<HTMLElement>(
716 "[data-current-file-crumb='true']",
717 );
718 currentCrumb?.scrollIntoView({ block: "nearest", inline: "end" });
719 }, [relativePath]);
720
721 const toggleExplorer = () => {
722 setExplorerOpen((current) => {
723 const next = !current;
724 try {
725 setLocalStorageItem(FILE_EXPLORER_STORAGE_KEY, next, Schema.Boolean);
726 } catch (error) {
727 console.error(error);
728 }
729 return next;
730 });
731 };
732
733 const handleOpenInBrowser = useCallback(() => {
734 if (!absolutePath || !environmentHttpBaseUrl) return;
735 void (async () => {
736 const result = await openFileInPreview({
737 threadRef,
738 filePath: absolutePath,
739 httpBaseUrl: environmentHttpBaseUrl,
740 createAssetUrl,
741 openPreview,
742 });
743 if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
744 return;
745 }
746 const error = squashAtomCommandFailure(result);
747 toastManager.add(
748 stackedThreadToast({
749 type: "error",
750 title: "Unable to open file in browser",
751 description: error instanceof Error ? error.message : "An error occurred.",
752 }),
753 );
754 })();
755 }, [absolutePath, createAssetUrl, environmentHttpBaseUrl, openPreview, threadRef]);
756
757 return (
758 <div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-background">
759 {relativePath ? (
760 <div className="surface-subheader gap-2 px-3" data-surface-subheader>
761 <ScrollArea
762 ref={breadcrumbRef}
763 hideScrollbars
764 scrollFade
765 className="min-w-0 flex-1 rounded-none"
766 data-file-breadcrumbs
767 >
768 <div className="flex h-full w-max min-w-full items-center text-xs">
769 {breadcrumbs.map((crumb, index) => (
770 <div
771 key={crumb.path || "project"}
772 className="flex min-w-0 shrink-0 items-center"
773 data-current-file-crumb={crumb.kind === "file"}
774 >
775 {index > 0 ? (
776 <ChevronRight className="mx-1 size-3.5 shrink-0 text-muted-foreground/60" />
777 ) : null}
778 <span
779 className={cn(
780 "max-w-40 truncate",
781 crumb.kind === "file"
782 ? "font-medium text-foreground"
783 : "text-muted-foreground",
784 )}
785 title={crumb.path || projectName}
786 >
787 {crumb.label}
788 </span>
789 </div>
790 ))}
791 </div>
792 </ScrollArea>
793 {absolutePath && environmentId === primaryEnvironmentId ? (
794 <OpenInPicker
795 environmentId={environmentId}
796 keybindings={keybindings}
797 availableEditors={availableEditors}
798 openInCwd={absolutePath}
799 compact
800 enableShortcut={false}
801 />
802 ) : null}
803 {isMarkdown ? (
804 <Tooltip>
805 <TooltipTrigger
806 render={
807 <Toggle
808 className="shrink-0"
809 pressed={renderMarkdown}
810 onPressedChange={(pressed) => {
811 setRenderMarkdownPreferred(pressed);
812 setHandledReveal(
813 pressed && relativePath !== null
814 ? { path: relativePath, requestId: revealRequestId }
815 : null,
816 );
817 }}
818 aria-label={renderMarkdown ? "Show markdown source" : "Show rendered markdown"}
819 variant="ghost"
820 size="sm"
821 >
822 {renderMarkdown ? <Code2 className="size-3.5" /> : <Eye className="size-3.5" />}
823 </Toggle>
824 }
825 />
826 <TooltipPopup>
827 {renderMarkdown ? "Show markdown source" : "Show rendered markdown"}
828 </TooltipPopup>
829 </Tooltip>
830 ) : null}
831 {canOpenInBrowser ? (
832 <Tooltip>
833 <TooltipTrigger
834 render={
835 <Toggle
836 className="shrink-0"
837 pressed={false}
838 onPressedChange={handleOpenInBrowser}
839 aria-label="Open file in preview browser"
840 variant="ghost"
841 size="sm"
842 >
843 <Globe2 className="size-3.5" />
844 </Toggle>
845 }
846 />
847 <TooltipPopup>Open file in preview browser</TooltipPopup>
848 </Tooltip>
849 ) : null}
850 <Tooltip>
851 <TooltipTrigger
852 render={
853 <Toggle
854 className="shrink-0"
855 pressed={explorerOpen}
856 onPressedChange={toggleExplorer}
857 aria-label={explorerOpen ? "Hide file explorer" : "Show file explorer"}
858 variant="ghost"
859 size="sm"
860 >
861 <FolderTree className="size-3.5" />
862 </Toggle>
863 }
864 />
865 <TooltipPopup>
866 {explorerOpen ? "Hide file explorer" : "Show file explorer"}
867 </TooltipPopup>
868 </Tooltip>
869 </div>
870 ) : null}
871 {relativePath && file.data?.truncated ? (
872 <div className="shrink-0 border-b border-amber-500/20 bg-amber-500/8 px-3 py-1.5 text-[11px] text-amber-700 dark:text-amber-300">
873 Preview limited to the first 1 MB of a {file.data.byteLength.toLocaleString()} byte file.
874 </div>
875 ) : null}
876 <div className="flex min-h-0 flex-1 overflow-hidden">
877 <div
878 className={cn(
879 "min-w-0 flex-1 flex-col overflow-hidden",
880 relativePath ? "flex" : "hidden",
881 )}
882 >
883 {relativePath && isImage && absolutePath ? (
884 <WorkspaceImagePreview
885 key={absolutePath}
886 environmentId={environmentId}
887 threadRef={threadRef}
888 absolutePath={absolutePath}
889 alt={relativePath}
890 />
891 ) : relativePath && file.error && file.data === null ? (
892 <div className="flex min-h-0 flex-1 items-center justify-center px-6 text-center text-xs leading-relaxed text-destructive">
893 {file.error}
894 </div>
895 ) : relativePath && file.data === null ? (
896 <div className="flex min-h-0 flex-1 items-center justify-center text-muted-foreground">
897 <LoaderCircle className="size-5 animate-spin" />
898 </div>
899 ) : relativePath && file.data ? (
900 isMarkdown && renderMarkdown ? (
901 <RenderedMarkdownSurface
902 environmentId={environmentId}
903 cwd={cwd}
904 relativePath={relativePath}
905 threadRef={threadRef}
906 contents={file.data.contents}
907 onPendingChange={onPendingChange}
908 />
909 ) : file.data.truncated ? (
910 <Virtualizer
911 key={`${relativePath}:${resolvedTheme}:${file.data.byteLength}`}
912 className="file-preview-virtualizer min-h-0 flex-1 overflow-auto"
913 config={{
914 overscrollSize: 600,
915 intersectionObserverMargin: 1200,
916 }}
917 >
918 <File
919 file={{
920 name: relativePath,
921 contents: file.data.contents,
922 cacheKey: projectFileCacheKey(cwd, relativePath, file.data.contents),
923 }}
924 options={{
925 disableFileHeader: true,
926 overflow: wordWrap ? "wrap" : "scroll",
927 theme: resolveDiffThemeName(resolvedTheme),
928 themeType: resolvedTheme,
929 unsafeCSS: FILE_LINK_REVEAL_UNSAFE_CSS,
930 onPostRender: onFilePostRender,
931 }}
932 className="min-h-full"
933 />
934 </Virtualizer>
935 ) : (
936 <EditableFileSurface
937 key={`${relativePath}:${resolvedTheme}`}
938 environmentId={environmentId}
939 cwd={cwd}
940 relativePath={relativePath}
941 composerDraftTarget={composerDraftTarget}
942 contents={file.data.contents}
943 resolvedTheme={resolvedTheme}
944 revealRequestId={revealRequestId}
945 wordWrap={wordWrap}
946 onPostRender={onFilePostRender}
947 onPendingChange={onPendingChange}
948 />
949 )
950 ) : null}
951 </div>
952 {explorerOpen || relativePath === null ? (
953 <aside
954 className={cn(
955 "flex min-h-0 shrink-0 bg-background",
956 relativePath
957 ? "w-[min(22rem,46%)] min-w-64 border-l border-border/60"
958 : "min-w-0 flex-1",
959 )}
960 >
961 <FileBrowserPanel
962 key={`${environmentId}:${cwd}`}
963 environmentId={environmentId}
964 cwd={cwd}
965 projectName={projectName}
966 onOpenFile={onOpenFile}
967 />
968 </aside>
969 ) : null}
970 </div>
971 </div>
972 );
973}