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

FilePreviewPanel.tsx

1,065 lines36.9 KB

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;
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 );
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);
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, "");
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;
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 );
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;
386​
387interface FileSelectionOverride {
388 revealRequestId: number;
389 range: SelectedLineRange | null;
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;
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 );
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 );
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 }
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 enableShortcut={false}
891 />
892 ) : null}
893 {isMarkdown ? (
894 <Tooltip>
895 <TooltipTrigger
896 render={
897 <Toggle
898 className="shrink-0"
899 pressed={renderMarkdown}
900 onPressedChange={(pressed) => {
901 setRenderMarkdownPreferred(pressed);
902 setHandledReveal(
903 pressed && relativePath !== null
904 ? { path: relativePath, requestId: revealRequestId }
905 : null,
906 );
907 }}
908 aria-label={renderMarkdown ? "Show markdown source" : "Show rendered markdown"}
909 variant="ghost"
910 size="sm"
911 >
912 {renderMarkdown ? <Code2 className="size-3.5" /> : <Eye className="size-3.5" />}
913 </Toggle>
914 }
915 />
916 <TooltipPopup>
917 {renderMarkdown ? "Show markdown source" : "Show rendered markdown"}
918 </TooltipPopup>
919 </Tooltip>
920 ) : null}
921 {canOpenInBrowser ? (
922 <Tooltip>
923 <TooltipTrigger
924 render={
925 <Toggle
926 className="shrink-0"
927 pressed={false}
928 onPressedChange={handleOpenInBrowser}
929 aria-label="Open file in preview browser"
930 variant="ghost"
931 size="sm"
932 >
933 <Globe2 className="size-3.5" />
934 </Toggle>
935 }
936 />
937 <TooltipPopup>Open file in preview browser</TooltipPopup>
938 </Tooltip>
939 ) : null}
940 <Tooltip>
941 <TooltipTrigger
942 render={
943 <Toggle
944 className="shrink-0"
945 pressed={explorerOpen}
946 onPressedChange={toggleExplorer}
947 aria-label={explorerOpen ? "Hide file explorer" : "Show file explorer"}
948 variant="ghost"
949 size="sm"
950 >
951 <FolderTree className="size-3.5" />
952 </Toggle>
953 }
954 />
955 <TooltipPopup>
956 {explorerOpen ? "Hide file explorer" : "Show file explorer"}
957 </TooltipPopup>
958 </Tooltip>
959 </div>
960 ) : null}
961 {relativePath && file.data?.truncated ? (
962 <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">
963 Preview limited to the first 1 MB of a {file.data.byteLength.toLocaleString()} byte file.
964 </div>
965 ) : null}
966 <div className="flex min-h-0 flex-1 overflow-hidden">
967 <div
968 className={cn(
969 "min-w-0 flex-1 flex-col overflow-hidden",
970 relativePath ? "flex" : "hidden",
971 )}
972 >
973 {relativePath && isImage && absolutePath ? (
974 <WorkspaceImagePreview
975 key={absolutePath}
976 environmentId={environmentId}
977 threadRef={threadRef}
978 absolutePath={absolutePath}
979 alt={relativePath}
980 />
981 ) : relativePath && file.error && file.data === null ? (
982 <div className="flex min-h-0 flex-1 items-center justify-center px-6 text-center text-xs leading-relaxed text-destructive">
983 {file.error}
984 </div>
985 ) : relativePath && file.data === null ? (
986 <div className="flex min-h-0 flex-1 items-center justify-center text-muted-foreground">
987 <LoaderCircle className="size-5 animate-spin" />
988 </div>
989 ) : relativePath && file.data ? (
990 isMarkdown && renderMarkdown ? (
991 <RenderedMarkdownSurface
992 environmentId={environmentId}
993 cwd={cwd}
994 relativePath={relativePath}
995 threadRef={threadRef}
996 contents={file.data.contents}
997 onPendingChange={onPendingChange}
998 />
999 ) : file.data.truncated ? (
1000 <Virtualizer
1001 key={`${relativePath}:${resolvedTheme}:${file.data.byteLength}`}
1002 className="file-preview-virtualizer min-h-0 flex-1 overflow-auto"
1003 config={{
1004 overscrollSize: 600,
1005 intersectionObserverMargin: 1200,
1006 }}
1008 <File
1009 file={{
1010 name: relativePath,
1011 contents: file.data.contents,
1012 cacheKey: projectFileCacheKey(cwd, relativePath, file.data.contents),
1013 }}
1014 options={{
1015 disableFileHeader: true,
1016 overflow: wordWrap ? "wrap" : "scroll",
1017 theme: resolveDiffThemeName(resolvedTheme),
1018 themeType: resolvedTheme,
1019 unsafeCSS: FILE_LINK_REVEAL_UNSAFE_CSS,
1020 onPostRender: onFilePostRender,
1021 }}
1022 className="min-h-full"
1023 />
1024 </Virtualizer>
1025 ) : (
1026 <EditableFileSurface
1027 key={`${relativePath}:${resolvedTheme}`}
1028 environmentId={environmentId}
1029 cwd={cwd}
1030 relativePath={relativePath}
1031 composerDraftTarget={composerDraftTarget}
1032 contents={file.data.contents}
1033 resolvedTheme={resolvedTheme}
1034 revealRequestId={revealRequestId}
1035 wordWrap={wordWrap}
1036 onPostRender={onFilePostRender}
1037 onPendingChange={onPendingChange}
1038 />
1040 ) : null}
1041 </div>
1042 {explorerOpen || relativePath === null ? (
1043 <aside
1044 className={cn(
1045 "flex min-h-0 shrink-0 bg-background",
1046 relativePath
1047 ? "w-[min(22rem,46%)] min-w-64 border-l border-border/60"
1048 : "min-w-0 flex-1",
1049 )}
1051 <FileBrowserPanel
1052 key={`${environmentId}:${cwd}`}
1053 environmentId={environmentId}
1054 cwd={cwd}
1055 projectName={projectName}
1056 selectedPath={relativePath}
1057 selectedPathRevealId={revealRequestId}
1058 onOpenFile={onOpenFile}
1059 />
1060 </aside>
1061 ) : null}
1062 </div>
1063 </div>
1064 );