Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

FilePreviewPanel.tsx

903 lines30.3 KB

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