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