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