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

FilePreviewPanel.tsx

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