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