Open History to see the last commit
1import type {
2 ChatFileAttachment,
3 EditorId,
4 EnvironmentId,
5 ResolvedKeybindingsConfig,
6 ScopedThreadRef,
7} from "@t3tools/contracts";
8import {
9 isWorkspaceImagePreviewPath,
10 isWorkspaceVideoPreviewPath,
11} from "@t3tools/shared/filePreview";
12import { VirtualizedFile, type SelectedLineRange } from "@pierre/diffs";
13import { Editor } from "@pierre/diffs/editor";
14import { EditProvider, File, type FileOptions, Virtualizer } from "@pierre/diffs/react";
15import {
16 isAtomCommandInterrupted,
17 squashAtomCommandFailure,
18} from "@t3tools/client-runtime/state/runtime";
19import { mediaFileReference } from "@t3tools/client-runtime/media-reference";
20import { Code2, Eye, FolderTree, Globe2, LoaderCircle } from "lucide-react";
21import * as Schema from "effect/Schema";
22import { useCallback, useEffect, useMemo, useRef, useState } from "react";
23
24import { isBrowserPreviewFile, openFileInPreview } from "~/browser/openFileInPreview";
25import { useAssetUrlRefresh, useAssetUrlState } from "~/assets/assetUrls";
26import { OpenInPicker } from "~/components/chat/OpenInPicker";
27import { PierreEntryIcon } from "~/components/chat/PierreEntryIcon";
28import { MediaVideoPlayer } from "~/components/media/MediaVideoPlayer";
29import { MediaActions, type MediaActionSource } from "~/components/media/MediaActions";
30import { useRemoteOpenState } from "~/remoteOpen";
31import { useClientSettings } from "~/hooks/useSettings";
32import { useTheme } from "~/hooks/useTheme";
33import { getLocalStorageItem, setLocalStorageItem, useLocalStorage } from "~/hooks/useLocalStorage";
34import { useWorkspaceMutationRefresh } from "~/hooks/useWorkspaceMutationRefresh";
35import { DIFF_SURFACE_THEME_UNSAFE_CSS, resolveDiffThemeName } from "~/lib/diffRendering";
36import { PREFERRED_HIGHLIGHTER } from "~/lib/syntaxHighlighting";
37import { cn } from "~/lib/utils";
38import { isPreviewSupportedInRuntime } from "~/previewStateStore";
39import { isAbsolutePath, resolvePathLinkTarget } from "~/terminal-links";
40import { ScrollArea } from "~/components/ui/scroll-area";
41import { Toggle } from "~/components/ui/toggle";
42import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
43import { stackedThreadToast, toastManager } from "~/components/ui/toast";
44import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
45import { buildFileReviewComment } from "~/reviewCommentContext";
46import { assetEnvironment } from "~/state/assets";
47import { useEnvironmentHttpBaseUrl, usePrimaryEnvironmentId } from "~/state/environments";
48import { previewEnvironment } from "~/state/preview";
49import { projectEnvironment } from "~/state/projects";
50import { useAtomCommand } from "~/state/use-atom-command";
51import { useAtomQueryRunner } from "~/state/use-atom-query-runner";
52
53import FileBrowserPanel from "./FileBrowserPanel";
54import { FileBreadcrumbs } from "./FileBreadcrumbs";
55import { FileMarkdownPreview } from "./FileMarkdownPreview";
56import {
57 type FileCommentAnnotationEntry,
58 type FileCommentAnnotationGroup,
59 type FileCommentLineAnnotation,
60 formatFileCommentRange,
61 nextFileCommentId,
62 normalizeFileCommentRange,
63 remapFileCommentAnnotations,
64} from "./fileCommentAnnotations";
65import { installFileEditorDismissal } from "./fileEditorDismissal";
66import { resolveCenteredFileLineScrollTop } from "./fileLineReveal";
67import { DiffCommentAnnotation } from "../diffs/DiffCommentAnnotation";
68import { projectFileCacheKey, projectFileEditorCacheKey } from "./fileContentRevision";
69import {
70 isMarkdownPreviewFile,
71 setMarkdownTaskChecked,
72 shouldShowFileExplorer,
73} from "./filePreviewMode";
74import { FileSaveCoordinator } from "./fileSaveCoordinator";
75import {
76 confirmProjectFileQueryData,
77 getOptimisticProjectFileQueryData,
78 setProjectFileQueryData,
79 useProjectFileQuery,
80} from "./projectFilesQueryState";
81
82interface FilePreviewPanelProps {
83 environmentId: EnvironmentId;
84 cwd: string;
85 projectName: string;
86 relativePath: string | null;
87 attachment?: ChatFileAttachment;
88 threadRef: ScopedThreadRef;
89 composerDraftTarget: ScopedThreadRef | DraftId;
90 keybindings: ResolvedKeybindingsConfig;
91 availableEditors: ReadonlyArray<EditorId>;
92 revealLine: number | null;
93 revealRequestId: number;
94 onOpenFile: (relativePath: string) => void;
95 onPendingChange: (relativePath: string, pending: boolean) => void;
96 selectedFilePending: boolean;
97 workspaceMutationId: string | null;
98}
99
100const FILE_EXPLORER_STORAGE_KEY = "t3code.fileExplorerOpen";
101const RENDER_MARKDOWN_STORAGE_KEY = "t3code.renderMarkdown";
102const RENDER_BROWSER_FILE_STORAGE_KEY = "t3code.renderBrowserFile";
103const FILE_SAVE_DEBOUNCE_MS = 500;
104const FILE_LINK_REVEAL_ATTRIBUTE = "data-file-link-reveal";
105const FILE_LINK_REVEAL_UNSAFE_CSS = `
106 ${DIFF_SURFACE_THEME_UNSAFE_CSS}
107
108 diffs-container {
109 --diffs-bg: var(--code-background, var(--background)) !important;
110 --diffs-light-bg: var(--code-background, var(--background)) !important;
111 --diffs-dark-bg: var(--code-background, var(--background)) !important;
112 background-color: var(--code-background, var(--background)) !important;
113 color: var(--code-foreground, var(--foreground)) !important;
114 }
115
116 [${FILE_LINK_REVEAL_ATTRIBUTE}][data-line] {
117 background-color: light-dark(
118 color-mix(
119 in lab,
120 var(--diffs-computed-diff-line-bg) 82%,
121 var(--diffs-bg-selection-override, var(--diffs-selection-base))
122 ),
123 color-mix(
124 in lab,
125 var(--diffs-computed-diff-line-bg) 75%,
126 var(--diffs-bg-selection-override, var(--diffs-selection-base))
127 )
128 ) !important;
129 }
130
131 [${FILE_LINK_REVEAL_ATTRIBUTE}][data-column-number] {
132 background-color: light-dark(
133 color-mix(
134 in lab,
135 var(--diffs-computed-diff-line-bg) 75%,
136 var(--diffs-bg-selection-number-override, var(--diffs-selection-base))
137 ),
138 color-mix(
139 in lab,
140 var(--diffs-computed-diff-line-bg) 60%,
141 var(--diffs-bg-selection-number-override, var(--diffs-selection-base))
142 )
143 ) !important;
144 color: var(--diffs-selection-number-fg) !important;
145 }
146`;
147type FilePostRender = NonNullable<FileOptions<unknown>["onPostRender"]>;
148
149function WorkspaceImagePreview(props: {
150 readonly environmentId: EnvironmentId;
151 readonly threadRef: ScopedThreadRef;
152 readonly absolutePath: string;
153 readonly workspaceRoot: string;
154 readonly alt: string;
155 readonly workspaceMutationId: string | null;
156}) {
157 const resource = useMemo(
158 () => ({
159 _tag: "workspace-file" as const,
160 threadId: props.threadRef.threadId,
161 path: props.absolutePath,
162 }),
163 [props.threadRef.threadId, props.absolutePath],
164 );
165 const assetUrl = useAssetUrlState(props.environmentId, resource);
166 const [failedUrl, setFailedUrl] = useState<string | null>(null);
167 const revisionSuffix =
168 props.workspaceMutationId === null
169 ? ""
170 : `${assetUrl._tag === "Success" && assetUrl.url.includes("?") ? "&" : "?"}workspace-revision=${encodeURIComponent(props.workspaceMutationId)}`;
171 const imageUrl = assetUrl._tag === "Success" ? `${assetUrl.url}${revisionSuffix}` : null;
172 const actionsSource: MediaActionSource = {
173 kind: "image",
174 name: props.alt,
175 src: imageUrl,
176 reference: mediaFileReference(props.absolutePath, props.workspaceRoot),
177 asset: { environmentId: props.environmentId, resource },
178 };
179
180 if (assetUrl._tag === "Failure" || (imageUrl !== null && failedUrl === imageUrl)) {
181 return (
182 <MediaActions source={actionsSource}>
183 <div className="flex min-h-0 flex-1 items-center justify-center px-6 text-center text-xs leading-relaxed text-destructive">
184 Unable to load workspace image.
185 </div>
186 </MediaActions>
187 );
188 }
189
190 return assetUrl._tag === "Success" && imageUrl !== null ? (
191 <div className="flex min-h-0 flex-1 items-center justify-center overflow-auto p-4">
192 <MediaActions source={actionsSource}>
193 <img
194 className="max-h-full max-w-full object-contain"
195 src={imageUrl}
196 alt={props.alt}
197 onError={() => setFailedUrl(imageUrl)}
198 />
199 </MediaActions>
200 </div>
201 ) : (
202 <div className="flex min-h-0 flex-1 items-center justify-center text-muted-foreground">
203 <LoaderCircle className="size-5 animate-spin" />
204 </div>
205 );
206}
207
208const isPdfPreviewFile = (path: string): boolean => /\.pdf$/i.test(path.split(/[?#]/, 1)[0] ?? "");
209
210function BrowserDocumentFrame(props: {
211 readonly src: string;
212 readonly title: string;
213 readonly pdf: boolean;
214}) {
215 const className = "min-h-0 flex-1 border-0 bg-white";
216 // The built-in PDF viewer needs an unsandboxed frame; a PDF runs no scripts.
217 return props.pdf ? (
218 // oxlint-disable-next-line react/iframe-missing-sandbox
219 <iframe key={props.src} src={props.src} title={props.title} className={className} />
220 ) : (
221 <iframe
222 key={props.src}
223 src={props.src}
224 title={props.title}
225 className={className}
226 sandbox="allow-scripts allow-forms allow-popups allow-modals"
227 />
228 );
229}
230
231function AttachmentBrowserPreview(props: {
232 readonly environmentId: EnvironmentId;
233 readonly attachment: ChatFileAttachment;
234}) {
235 const resource = useMemo(
236 () => ({
237 _tag: "attachment" as const,
238 attachmentId: props.attachment.id,
239 fileName: props.attachment.name,
240 mimeType: props.attachment.mimeType,
241 disposition: "inline" as const,
242 }),
243 [props.attachment.id, props.attachment.mimeType, props.attachment.name],
244 );
245 const assetUrl = useAssetUrlState(props.environmentId, resource);
246
247 if (assetUrl._tag === "Failure") {
248 return (
249 <div className="flex min-h-0 flex-1 items-center justify-center px-6 text-center text-xs leading-relaxed text-destructive">
250 Unable to load attachment preview.
251 </div>
252 );
253 }
254 if (assetUrl._tag !== "Success") {
255 return (
256 <div className="flex min-h-0 flex-1 items-center justify-center text-muted-foreground">
257 <LoaderCircle className="size-5 animate-spin" />
258 </div>
259 );
260 }
261 return (
262 <BrowserDocumentFrame
263 src={assetUrl.url}
264 title={props.attachment.name}
265 pdf={
266 isPdfPreviewFile(props.attachment.name) ||
267 props.attachment.mimeType.split(";", 1)[0]?.trim().toLowerCase() === "application/pdf"
268 }
269 />
270 );
271}
272
273/**
274 * Renders an HTML or PDF file in place from its signed asset URL. HTML runs in
275 * a sandboxed frame with an opaque origin, so a page cannot reach the app's
276 * session or storage. A file inside the workspace may load sibling assets; a
277 * host file outside it is served on its own.
278 */
279function WorkspaceBrowserPreview(props: {
280 readonly environmentId: EnvironmentId;
281 readonly threadRef: ScopedThreadRef;
282 readonly absolutePath: string;
283 readonly workspaceRoot: string;
284 readonly title: string;
285 readonly workspaceMutationId: string | null;
286}) {
287 const insideWorkspace =
288 mediaFileReference(props.absolutePath, props.workspaceRoot).relativePath !== undefined;
289 const resource = useMemo(
290 () => ({
291 _tag: insideWorkspace ? ("workspace-file" as const) : ("media-file" as const),
292 threadId: props.threadRef.threadId,
293 path: props.absolutePath,
294 }),
295 [insideWorkspace, props.threadRef.threadId, props.absolutePath],
296 );
297 const assetUrl = useAssetUrlState(props.environmentId, resource);
298 const revisionSuffix =
299 props.workspaceMutationId === null
300 ? ""
301 : `${assetUrl._tag === "Success" && assetUrl.url.includes("?") ? "&" : "?"}workspace-revision=${encodeURIComponent(props.workspaceMutationId)}`;
302
303 if (assetUrl._tag === "Failure") {
304 return (
305 <div className="flex min-h-0 flex-1 items-center justify-center px-6 text-center text-xs leading-relaxed text-destructive">
306 Unable to load file preview.
307 </div>
308 );
309 }
310 if (assetUrl._tag !== "Success") {
311 return (
312 <div className="flex min-h-0 flex-1 items-center justify-center text-muted-foreground">
313 <LoaderCircle className="size-5 animate-spin" />
314 </div>
315 );
316 }
317 return (
318 <BrowserDocumentFrame
319 src={`${assetUrl.url}${revisionSuffix}`}
320 title={props.title}
321 pdf={isPdfPreviewFile(props.absolutePath)}
322 />
323 );
324}
325
326function WorkspaceVideoPreview(props: {
327 readonly environmentId: EnvironmentId;
328 readonly threadRef: ScopedThreadRef;
329 readonly absolutePath: string;
330 readonly workspaceRoot: string;
331 readonly name: string;
332 readonly workspaceMutationId: string | null;
333}) {
334 const resource = useMemo(
335 () => ({
336 _tag: "media-file" as const,
337 threadId: props.threadRef.threadId,
338 path: props.absolutePath,
339 }),
340 [props.threadRef.threadId, props.absolutePath],
341 );
342 const assetUrl = useAssetUrlState(props.environmentId, resource);
343 const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, resource);
344 useWorkspaceMutationRefresh({
345 mutationId: props.workspaceMutationId,
346 resourceKey: JSON.stringify([props.environmentId, resource]),
347 refresh: () => {
348 // Failed refreshes flow through assetUrl and can be retried from the player.
349 void refreshAssetUrl().catch(() => undefined);
350 },
351 });
352 const revisionSuffix =
353 props.workspaceMutationId === null
354 ? ""
355 : `${assetUrl._tag === "Success" && assetUrl.url.includes("?") ? "&" : "?"}workspace-revision=${encodeURIComponent(props.workspaceMutationId)}`;
356 const latestUrl = assetUrl._tag === "Success" ? `${assetUrl.url}${revisionSuffix}` : null;
357
358 return (
359 <div className="flex min-h-0 flex-1 items-center justify-center overflow-hidden p-4">
360 <MediaVideoPlayer
361 src={latestUrl}
362 sourceFailed={assetUrl._tag === "Failure"}
363 label={props.name}
364 revision={props.workspaceMutationId}
365 preload="metadata"
366 className="flex h-full min-h-0 w-full max-w-5xl items-center justify-center"
367 onRetry={refreshAssetUrl}
368 actionsSource={{
369 kind: "video",
370 name: props.name,
371 src: latestUrl,
372 reference: mediaFileReference(props.absolutePath, props.workspaceRoot),
373 asset: { environmentId: props.environmentId, resource },
374 }}
375 />
376 </div>
377 );
378}
379
380function clampFileLine(contents: string, requestedLine: number): number {
381 let lineCount = 1;
382 for (let index = 0; index < contents.length; index += 1) {
383 const character = contents.charCodeAt(index);
384 if (character === 10) {
385 lineCount += 1;
386 } else if (character === 13) {
387 lineCount += 1;
388 if (contents.charCodeAt(index + 1) === 10) index += 1;
389 }
390 }
391 return Math.min(Math.max(1, requestedLine), lineCount);
392}
393
394function updateFileLinkReveal(fileContainer: HTMLElement, line: number | null): void {
395 const root = fileContainer.shadowRoot ?? fileContainer;
396 for (const element of root.querySelectorAll<HTMLElement>(`[${FILE_LINK_REVEAL_ATTRIBUTE}]`)) {
397 element.removeAttribute(FILE_LINK_REVEAL_ATTRIBUTE);
398 }
399 if (line === null) return;
400
401 root
402 .querySelector<HTMLElement>(`[data-line="${line}"]`)
403 ?.setAttribute(FILE_LINK_REVEAL_ATTRIBUTE, "");
404 root
405 .querySelector<HTMLElement>(`[data-column-number="${line}"]`)
406 ?.setAttribute(FILE_LINK_REVEAL_ATTRIBUTE, "");
407}
408
409/**
410 * Frames to keep retrying while the file contents or line metrics are not
411 * available yet (fresh mounts hydrate asynchronously).
412 */
413const REVEAL_MAX_ATTEMPTS = 30;
414/**
415 * After scrolling to the target, hold it for a short window so late
416 * programmatic scroll resets (editable-editor focus and state restoration)
417 * cannot silently snap the file back to the top. Real user input cancels the
418 * guard immediately.
419 */
420const REVEAL_GUARD_FRAMES = 20;
421const REVEAL_GUARD_TOLERANCE_PX = 2;
422
423interface FileRevealState {
424 frameId: number | null;
425 cancelGuard: (() => void) | null;
426 handledRequestId: number | null;
427 latestRequestId: number | null;
428}
429
430function useFileLineReveal(
431 relativePath: string | null,
432 revealLine: number | null,
433 revealRequestId: number,
434): FilePostRender {
435 const [revealStatesByPath] = useState(() => new Map<string, FileRevealState>());
436
437 return useCallback<FilePostRender>(
438 (fileContainer, instance, phase) => {
439 if (relativePath === null) return;
440
441 const existingState = revealStatesByPath.get(relativePath);
442 const state: FileRevealState = existingState ?? {
443 frameId: null,
444 cancelGuard: null,
445 handledRequestId: null,
446 latestRequestId: null,
447 };
448 if (!existingState) revealStatesByPath.set(relativePath, state);
449
450 const cancelPendingReveal = () => {
451 if (state.frameId !== null) {
452 cancelAnimationFrame(state.frameId);
453 state.frameId = null;
454 }
455 state.cancelGuard?.();
456 };
457
458 if (phase === "unmount") {
459 cancelPendingReveal();
460 return;
461 }
462
463 const contents = instance.file?.contents;
464 const targetLine =
465 revealLine === null || contents === undefined ? null : clampFileLine(contents, revealLine);
466 updateFileLinkReveal(fileContainer, targetLine);
467
468 if (!(instance instanceof VirtualizedFile)) return;
469
470 if (state.latestRequestId !== revealRequestId) {
471 cancelPendingReveal();
472 state.latestRequestId = revealRequestId;
473 state.handledRequestId = null;
474 }
475
476 if (revealLine === null) {
477 fileContainer.style.minHeight = "";
478 return;
479 }
480
481 const scrollContainer = fileContainer.closest<HTMLElement>(".file-preview-virtualizer");
482 if (!scrollContainer) return;
483 fileContainer.style.minHeight = `${Math.ceil(
484 Math.max(instance.height, scrollContainer.clientHeight),
485 )}px`;
486
487 if (state.handledRequestId === revealRequestId || state.frameId !== null) {
488 return;
489 }
490
491 const resolveScrollTarget = (line: number): number | null => {
492 const linePosition = instance.getLinePosition(line);
493 if (!linePosition) return null;
494
495 const scrollContainerRect = scrollContainer.getBoundingClientRect();
496 const fileTop =
497 scrollContainer.scrollTop +
498 fileContainer.getBoundingClientRect().top -
499 scrollContainerRect.top;
500 const root = fileContainer.shadowRoot ?? fileContainer;
501 const renderedLineElement = root.querySelector<HTMLElement>(`[data-line="${line}"]`);
502 const renderedLineRect = renderedLineElement?.getBoundingClientRect();
503
504 return resolveCenteredFileLineScrollTop({
505 scrollTop: scrollContainer.scrollTop,
506 scrollHeight: scrollContainer.scrollHeight,
507 viewportTop: scrollContainerRect.top,
508 viewportHeight: scrollContainer.clientHeight,
509 fileTop,
510 estimatedLine: linePosition,
511 ...(renderedLineRect && renderedLineRect.height > 0
512 ? {
513 renderedLine: {
514 top: renderedLineRect.top,
515 height: renderedLineRect.height,
516 },
517 }
518 : {}),
519 });
520 };
521
522 const guardScrollTarget = (line: number) => {
523 let framesLeft = REVEAL_GUARD_FRAMES;
524 let guardFrameId: number | null = null;
525 const cancelGuard = () => {
526 if (guardFrameId !== null) {
527 cancelAnimationFrame(guardFrameId);
528 guardFrameId = null;
529 }
530 scrollContainer.removeEventListener("wheel", cancelGuard);
531 scrollContainer.removeEventListener("touchstart", cancelGuard);
532 scrollContainer.removeEventListener("pointerdown", cancelGuard, true);
533 window.removeEventListener("keydown", cancelGuard, true);
534 if (state.cancelGuard === cancelGuard) state.cancelGuard = null;
535 };
536 scrollContainer.addEventListener("wheel", cancelGuard, { passive: true });
537 scrollContainer.addEventListener("touchstart", cancelGuard, { passive: true });
538 // Pierre stops gutter pointer events from bubbling. Listen in capture
539 // so starting a comment cancels the reveal guard before the row expands.
540 scrollContainer.addEventListener("pointerdown", cancelGuard, {
541 passive: true,
542 capture: true,
543 });
544 window.addEventListener("keydown", cancelGuard, true);
545 const holdTarget = () => {
546 guardFrameId = null;
547 framesLeft -= 1;
548 if (framesLeft <= 0 || !scrollContainer.isConnected) {
549 cancelGuard();
550 return;
551 }
552 const targetTop = resolveScrollTarget(line);
553 if (
554 targetTop !== null &&
555 Math.abs(scrollContainer.scrollTop - targetTop) > REVEAL_GUARD_TOLERANCE_PX
556 ) {
557 scrollContainer.scrollTop = targetTop;
558 }
559 guardFrameId = requestAnimationFrame(holdTarget);
560 };
561 guardFrameId = requestAnimationFrame(holdTarget);
562 state.cancelGuard = cancelGuard;
563 };
564
565 const scheduleReveal = (attempt: number) => {
566 state.frameId = requestAnimationFrame(() => {
567 state.frameId = null;
568 if (state.latestRequestId !== revealRequestId || !fileContainer.isConnected) {
569 return;
570 }
571
572 // Contents and line metrics can lag the first post-render on fresh
573 // mounts; clamping against missing contents would scroll to line 1
574 // and wrongly mark the request handled.
575 const currentContents = instance.file?.contents;
576 const line =
577 currentContents === undefined ? null : clampFileLine(currentContents, revealLine);
578 const targetTop = line === null ? null : resolveScrollTarget(line);
579 if (line === null || targetTop === null) {
580 if (attempt < REVEAL_MAX_ATTEMPTS) scheduleReveal(attempt + 1);
581 return;
582 }
583 updateFileLinkReveal(fileContainer, line);
584
585 scrollContainer.scrollTop = targetTop;
586 state.handledRequestId = revealRequestId;
587 guardScrollTarget(line);
588 });
589 };
590
591 scheduleReveal(0);
592 },
593 [revealStatesByPath, relativePath, revealLine, revealRequestId],
594 );
595}
596
597interface EditableFileSurfaceProps {
598 environmentId: EnvironmentId;
599 cwd: string;
600 relativePath: string;
601 composerDraftTarget: ScopedThreadRef | DraftId;
602 contents: string;
603 resolvedTheme: "light" | "dark";
604 revealRequestId: number;
605 wordWrap: boolean;
606 onPostRender: FilePostRender;
607 onPendingChange: (relativePath: string, pending: boolean) => void;
608}
609
610interface FileSelectionOverride {
611 revealRequestId: number;
612 range: SelectedLineRange | null;
613}
614
615function useFileSaveCoordinator({
616 environmentId,
617 cwd,
618 relativePath,
619 onPendingChange,
620}: Pick<
621 EditableFileSurfaceProps,
622 "environmentId" | "cwd" | "relativePath" | "onPendingChange"
623>): FileSaveCoordinator {
624 const writeFile = useAtomCommand(projectEnvironment.writeFile);
625 const coordinator = useMemo(
626 () =>
627 new FileSaveCoordinator({
628 debounceMs: FILE_SAVE_DEBOUNCE_MS,
629 onPendingChange: (pending) => onPendingChange(relativePath, pending),
630 persist: (nextContents) =>
631 writeFile({
632 environmentId,
633 input: { cwd, relativePath, contents: nextContents },
634 }),
635 onConfirmed: (confirmedContents) => {
636 confirmProjectFileQueryData(environmentId, cwd, relativePath, confirmedContents);
637 },
638 }),
639 [cwd, environmentId, onPendingChange, relativePath, writeFile],
640 );
641
642 useEffect(() => () => coordinator.dispose(), [coordinator]);
643 return coordinator;
644}
645
646function EditableFileSurface({
647 environmentId,
648 cwd,
649 relativePath,
650 composerDraftTarget,
651 contents,
652 resolvedTheme,
653 revealRequestId,
654 wordWrap,
655 onPostRender,
656 onPendingChange,
657}: EditableFileSurfaceProps) {
658 const addReviewComment = useComposerDraftStore((store) => store.addReviewComment);
659 const removeReviewComment = useComposerDraftStore((store) => store.removeReviewComment);
660 const [lineAnnotations, setLineAnnotations] = useState<FileCommentLineAnnotation[]>([]);
661 const [selectionOverride, setSelectionOverride] = useState<FileSelectionOverride | null>(null);
662 const selectedRange =
663 selectionOverride?.revealRequestId === revealRequestId ? selectionOverride.range : null;
664 const setSelectedRange = useCallback(
665 (range: SelectedLineRange | null) => {
666 setSelectionOverride({ revealRequestId, range });
667 },
668 [revealRequestId],
669 );
670 const surfaceRef = useRef<HTMLDivElement>(null);
671 const selectionFrameRef = useRef<number | null>(null);
672 const saveCoordinator = useFileSaveCoordinator({
673 environmentId,
674 cwd,
675 relativePath,
676 onPendingChange,
677 });
678 const editor = useMemo(
679 () =>
680 new Editor<FileCommentAnnotationGroup>({
681 persistState: true,
682 persistStateStorage: "inMemory",
683 onChange: (file, nextLineAnnotations) => {
684 setProjectFileQueryData(environmentId, cwd, relativePath, file.contents);
685 saveCoordinator.change(file.contents);
686 if (nextLineAnnotations) {
687 const remapped = remapFileCommentAnnotations(
688 nextLineAnnotations as FileCommentLineAnnotation[],
689 );
690 setLineAnnotations(remapped);
691 for (const annotation of remapped) {
692 for (const entry of annotation.metadata.entries) {
693 if (entry.kind !== "comment") continue;
694 addReviewComment(
695 composerDraftTarget,
696 buildFileReviewComment({
697 id: entry.id,
698 filePath: relativePath,
699 startLine: entry.startLine,
700 endLine: entry.endLine,
701 text: entry.text,
702 contents: file.contents,
703 }),
704 );
705 }
706 }
707 }
708 },
709 }),
710 [addReviewComment, composerDraftTarget, cwd, environmentId, relativePath, saveCoordinator],
711 );
712
713 useEffect(
714 () => () => {
715 editor.cleanUp();
716 },
717 [editor],
718 );
719
720 const removeAnnotationEntry = useCallback(
721 (entryId: string) => {
722 setSelectedRange(null);
723 removeReviewComment(composerDraftTarget, entryId);
724 setLineAnnotations((current) => {
725 return current.flatMap((annotation) => {
726 const entries = annotation.metadata.entries.filter((entry) => entry.id !== entryId);
727 return entries.length > 0 ? [{ ...annotation, metadata: { entries } }] : [];
728 });
729 });
730 },
731 [composerDraftTarget, removeReviewComment, setSelectedRange],
732 );
733
734 const submitAnnotationEntry = useCallback(
735 (entryId: string, text: string) => {
736 setSelectedRange(null);
737 const entry = lineAnnotations
738 .flatMap((annotation) => annotation.metadata.entries)
739 .find((candidate) => candidate.id === entryId);
740 if (entry) {
741 addReviewComment(
742 composerDraftTarget,
743 buildFileReviewComment({
744 id: entry.id,
745 filePath: relativePath,
746 startLine: entry.startLine,
747 endLine: entry.endLine,
748 text,
749 contents,
750 }),
751 );
752 }
753 setLineAnnotations((current) =>
754 current.map((annotation) => ({
755 ...annotation,
756 metadata: {
757 entries: annotation.metadata.entries.map((annotationEntry) =>
758 annotationEntry.id === entryId
759 ? { ...annotationEntry, kind: "comment", text }
760 : annotationEntry,
761 ),
762 },
763 })),
764 );
765 },
766 [
767 addReviewComment,
768 composerDraftTarget,
769 contents,
770 lineAnnotations,
771 relativePath,
772 setSelectedRange,
773 ],
774 );
775
776 const beginComment = useCallback((range: SelectedLineRange) => {
777 const { startLine, endLine } = normalizeFileCommentRange(range);
778 const draftEntry: FileCommentAnnotationEntry = {
779 id: nextFileCommentId(),
780 kind: "draft",
781 startLine,
782 endLine,
783 text: "",
784 };
785 setLineAnnotations((current) => {
786 const withoutDraft = current.flatMap((annotation) => {
787 const entries = annotation.metadata.entries.filter((entry) => entry.kind !== "draft");
788 return entries.length > 0 ? [{ ...annotation, metadata: { entries } }] : [];
789 });
790 const existingIndex = withoutDraft.findIndex(
791 (annotation) => annotation.lineNumber === endLine,
792 );
793 if (existingIndex < 0) {
794 return [
795 ...withoutDraft,
796 {
797 lineNumber: endLine,
798 metadata: { entries: [draftEntry] },
799 },
800 ];
801 }
802 return withoutDraft.map((annotation, index) =>
803 index === existingIndex
804 ? {
805 ...annotation,
806 metadata: { entries: [...annotation.metadata.entries, draftEntry] },
807 }
808 : annotation,
809 );
810 });
811 }, []);
812 const hasOpenCommentForm = lineAnnotations.some((annotation) =>
813 annotation.metadata.entries.some((entry) => entry.kind === "draft"),
814 );
815 useEffect(() => {
816 const root = surfaceRef.current;
817 if (!root) return;
818 return installFileEditorDismissal({
819 root,
820 editor,
821 isBlocked: () => hasOpenCommentForm,
822 onDismiss: () => setSelectedRange(null),
823 });
824 }, [editor, hasOpenCommentForm, setSelectedRange]);
825 const handleLineSelectionEnd = useCallback(
826 (range: SelectedLineRange | null) => {
827 setSelectedRange(range);
828 if (range) {
829 beginComment(range);
830 }
831 },
832 [beginComment, setSelectedRange],
833 );
834
835 const handlePostRender = useCallback<FilePostRender>(
836 (fileContainer, instance, phase) => {
837 onPostRender(fileContainer, instance, phase);
838
839 if (selectionFrameRef.current !== null) {
840 cancelAnimationFrame(selectionFrameRef.current);
841 selectionFrameRef.current = null;
842 }
843 if (phase === "unmount") return;
844
845 selectionFrameRef.current = requestAnimationFrame(() => {
846 selectionFrameRef.current = null;
847 if (!fileContainer.isConnected) return;
848 instance.setSelectedLines(selectedRange, { notify: false });
849 });
850 },
851 [onPostRender, selectedRange],
852 );
853
854 return (
855 <EditProvider editor={editor}>
856 <div ref={surfaceRef} className="flex min-h-0 flex-1">
857 <Virtualizer
858 className="file-preview-virtualizer min-h-0 flex-1 overflow-auto"
859 config={{
860 overscrollSize: 600,
861 intersectionObserverMargin: 1200,
862 }}
863 >
864 <File<FileCommentAnnotationGroup>
865 file={{
866 name: relativePath,
867 contents,
868 cacheKey: projectFileEditorCacheKey(
869 environmentId,
870 cwd,
871 relativePath,
872 contents,
873 editor.getFile(),
874 ),
875 }}
876 options={{
877 disableFileHeader: true,
878 enableGutterUtility: !hasOpenCommentForm,
879 enableLineSelection: !hasOpenCommentForm,
880 onGutterUtilityClick: setSelectedRange,
881 onLineSelectionChange: setSelectedRange,
882 onLineSelectionEnd: handleLineSelectionEnd,
883 overflow: wordWrap ? "wrap" : "scroll",
884 theme: resolveDiffThemeName(resolvedTheme),
885 preferredHighlighter: PREFERRED_HIGHLIGHTER,
886 themeType: resolvedTheme,
887 unsafeCSS: FILE_LINK_REVEAL_UNSAFE_CSS,
888 onPostRender: handlePostRender,
889 }}
890 selectedLines={selectedRange}
891 lineAnnotations={lineAnnotations}
892 renderAnnotation={(annotation) => (
893 <div className="py-1">
894 {annotation.metadata.entries.map((entry) => (
895 <DiffCommentAnnotation
896 key={entry.id}
897 kind={entry.kind}
898 rangeLabel={formatFileCommentRange(entry.startLine, entry.endLine)}
899 text={entry.text}
900 onCancel={() => removeAnnotationEntry(entry.id)}
901 onComment={(text) => submitAnnotationEntry(entry.id, text)}
902 onDelete={() => removeAnnotationEntry(entry.id)}
903 />
904 ))}
905 </div>
906 )}
907 className="min-h-full"
908 contentEditable
909 />
910 </Virtualizer>
911 </div>
912 </EditProvider>
913 );
914}
915
916function RenderedMarkdownSurface({
917 environmentId,
918 cwd,
919 relativePath,
920 contents,
921 threadRef,
922 readOnly,
923 onPendingChange,
924}: Omit<
925 EditableFileSurfaceProps,
926 | "resolvedTheme"
927 | "composerDraftTarget"
928 | "revealLine"
929 | "revealRequestId"
930 | "wordWrap"
931 | "onPostRender"
932> & {
933 threadRef: ScopedThreadRef;
934 readOnly: boolean;
935}) {
936 const saveCoordinator = useFileSaveCoordinator({
937 environmentId,
938 cwd,
939 relativePath,
940 onPendingChange,
941 });
942
943 return (
944 <ScrollArea className="min-h-0 flex-1">
945 <FileMarkdownPreview
946 text={contents}
947 cwd={cwd}
948 relativePath={relativePath}
949 threadRef={threadRef}
950 onTaskListChange={
951 readOnly
952 ? undefined
953 : ({ markerOffset, checked }) => {
954 const currentContents =
955 getOptimisticProjectFileQueryData(environmentId, cwd, relativePath)?.contents ??
956 contents;
957 const nextContents = setMarkdownTaskChecked(currentContents, markerOffset, checked);
958 if (nextContents === currentContents) return;
959 setProjectFileQueryData(environmentId, cwd, relativePath, nextContents);
960 saveCoordinator.change(nextContents);
961 }
962 }
963 />
964 </ScrollArea>
965 );
966}
967
968function renderedToggleLabel(isMarkdown: boolean, rendered: boolean): string {
969 if (isMarkdown) return rendered ? "Show markdown source" : "Show rendered markdown";
970 return rendered ? "Show HTML source" : "Show rendered page";
971}
972
973function initialExplorerOpen(): boolean {
974 try {
975 return getLocalStorageItem(FILE_EXPLORER_STORAGE_KEY, Schema.Boolean) ?? true;
976 } catch (error) {
977 console.error(error);
978 return true;
979 }
980}
981
982export default function FilePreviewPanel({
983 environmentId,
984 cwd,
985 projectName,
986 relativePath,
987 attachment,
988 threadRef,
989 composerDraftTarget,
990 keybindings,
991 availableEditors,
992 revealLine,
993 revealRequestId,
994 onOpenFile,
995 onPendingChange,
996 selectedFilePending,
997 workspaceMutationId,
998}: FilePreviewPanelProps) {
999 const { resolvedTheme } = useTheme();
1000 const wordWrap = useClientSettings((settings) => settings.wordWrap);
1001 const primaryEnvironmentId = usePrimaryEnvironmentId();
1002 const remoteOpenState = useRemoteOpenState(environmentId);
1003 const environmentHttpBaseUrl = useEnvironmentHttpBaseUrl(environmentId);
1004 const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
1005 reportFailure: false,
1006 });
1007 const openPreview = useAtomCommand(previewEnvironment.open, {
1008 reportFailure: false,
1009 });
1010 const isVideo = relativePath !== null && isWorkspaceVideoPreviewPath(relativePath);
1011 const isImage = relativePath !== null && !isVideo && isWorkspaceImagePreviewPath(relativePath);
1012 const isMedia = isImage || isVideo;
1013 // PDFs have no text to show; HTML has, and can toggle between page and source.
1014 const isPdf = relativePath !== null && isPdfPreviewFile(relativePath);
1015 const isHtml = relativePath !== null && !isPdf && isBrowserPreviewFile(relativePath);
1016 // A file outside the workspace (an absolute path) is shown, never edited.
1017 const isHostFile =
1018 attachment !== undefined || (relativePath !== null && isAbsolutePath(relativePath));
1019 const file = useProjectFileQuery(
1020 environmentId,
1021 cwd,
1022 relativePath,
1023 attachment === undefined && !isMedia && !isPdf,
1024 );
1025 const [explorerOpen, setExplorerOpen] = useState(initialExplorerOpen);
1026 const showExplorer = shouldShowFileExplorer({
1027 relativePath,
1028 explorerOpen,
1029 attachmentOpen: attachment !== undefined,
1030 });
1031 // Reading markdown rendered is a preference, not a property of one file. Keeping
1032 // it on the panel meant a thread switch dropped it and forced source back.
1033 const [renderMarkdownPreferred, setRenderMarkdownPreferred] = useLocalStorage(
1034 RENDER_MARKDOWN_STORAGE_KEY,
1035 false,
1036 Schema.Boolean,
1037 );
1038 const [renderBrowserFilePreferred, setRenderBrowserFilePreferred] = useLocalStorage(
1039 RENDER_BROWSER_FILE_STORAGE_KEY,
1040 true,
1041 Schema.Boolean,
1042 );
1043 // Paired with the path on purpose: each file surface counts its reveals from
1044 // one, so a bare id would let a dismissed reveal on one file swallow the first
1045 // reveal on the next.
1046 const [handledReveal, setHandledReveal] = useState<{ path: string; requestId: number } | null>(
1047 null,
1048 );
1049 const breadcrumbRef = useRef<HTMLDivElement>(null);
1050 const isMarkdown = relativePath ? isMarkdownPreviewFile(relativePath) : false;
1051 // A reveal still wins over the preference: the line only exists in the source.
1052 const revealHandled =
1053 revealLine === null ||
1054 (handledReveal?.path === relativePath && handledReveal.requestId === revealRequestId);
1055 const renderMarkdown = isMarkdown && renderMarkdownPreferred && revealHandled;
1056 const renderBrowserFile = isPdf || (isHtml && renderBrowserFilePreferred && revealHandled);
1057 const canToggleRendered = attachment === undefined && (isMarkdown || isHtml);
1058 const rendered = isMarkdown ? renderMarkdown : renderBrowserFile;
1059 const setRenderedPreferred = isMarkdown
1060 ? setRenderMarkdownPreferred
1061 : setRenderBrowserFilePreferred;
1062 const canOpenInBrowser =
1063 relativePath !== null &&
1064 attachment === undefined &&
1065 !isVideo &&
1066 isPreviewSupportedInRuntime() &&
1067 isBrowserPreviewFile(relativePath);
1068 const absolutePath =
1069 relativePath && attachment === undefined ? resolvePathLinkTarget(relativePath, cwd) : null;
1070 const onFilePostRender = useFileLineReveal(relativePath, revealLine, revealRequestId);
1071 useWorkspaceMutationRefresh({
1072 enabled:
1073 attachment === undefined &&
1074 relativePath !== null &&
1075 !isMedia &&
1076 !isPdf &&
1077 !selectedFilePending,
1078 mutationId: workspaceMutationId,
1079 refresh: file.refresh,
1080 resourceKey: `file:${environmentId}:${cwd}:${relativePath ?? ""}`,
1081 });
1082
1083 useEffect(() => {
1084 const currentCrumb = breadcrumbRef.current?.querySelector<HTMLElement>(
1085 "[data-current-file-crumb='true']",
1086 );
1087 currentCrumb?.scrollIntoView({ block: "nearest", inline: "end" });
1088 }, [relativePath]);
1089
1090 const toggleExplorer = () => {
1091 setExplorerOpen((current) => {
1092 const next = !current;
1093 try {
1094 setLocalStorageItem(FILE_EXPLORER_STORAGE_KEY, next, Schema.Boolean);
1095 } catch (error) {
1096 console.error(error);
1097 }
1098 return next;
1099 });
1100 };
1101
1102 const handleOpenInBrowser = useCallback(() => {
1103 if (!absolutePath || !environmentHttpBaseUrl) return;
1104 void (async () => {
1105 const result = await openFileInPreview({
1106 threadRef,
1107 filePath: absolutePath,
1108 workspaceRoot: cwd,
1109 httpBaseUrl: environmentHttpBaseUrl,
1110 createAssetUrl,
1111 openPreview,
1112 });
1113 if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
1114 return;
1115 }
1116 const error = squashAtomCommandFailure(result);
1117 toastManager.add(
1118 stackedThreadToast({
1119 type: "error",
1120 title: "Unable to open file in browser",
1121 description: error instanceof Error ? error.message : "An error occurred.",
1122 }),
1123 );
1124 })();
1125 }, [absolutePath, createAssetUrl, cwd, environmentHttpBaseUrl, openPreview, threadRef]);
1126
1127 return (
1128 <div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-background">
1129 {relativePath ? (
1130 <div
1131 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"
1132 data-surface-subheader
1133 >
1134 {attachment ? (
1135 <div className="flex min-w-0 flex-1 items-center gap-1.5 text-xs">
1136 <PierreEntryIcon
1137 pathValue={attachment.name}
1138 kind="file"
1139 theme={resolvedTheme}
1140 className="size-3.5"
1141 />
1142 <span className="truncate font-medium">{attachment.name}</span>
1143 </div>
1144 ) : (
1145 <ScrollArea
1146 ref={breadcrumbRef}
1147 hideScrollbars
1148 scrollFade
1149 className="min-w-0 flex-1 rounded-none"
1150 data-file-breadcrumbs
1151 >
1152 <div className="flex h-full w-max min-w-full items-center text-xs">
1153 <FileBreadcrumbs
1154 cwd={cwd}
1155 environmentId={environmentId}
1156 onOpenFile={onOpenFile}
1157 projectName={projectName}
1158 relativePath={relativePath}
1159 workspaceMutationId={workspaceMutationId}
1160 />
1161 </div>
1162 </ScrollArea>
1163 )}
1164 {absolutePath &&
1165 (environmentId === primaryEnvironmentId || remoteOpenState.mode !== "local-exec") ? (
1166 <OpenInPicker
1167 environmentId={environmentId}
1168 keybindings={keybindings}
1169 availableEditors={availableEditors}
1170 openInCwd={absolutePath}
1171 compact
1172 enableShortcut={false}
1173 />
1174 ) : null}
1175 {canToggleRendered ? (
1176 <Tooltip>
1177 <TooltipTrigger
1178 render={
1179 <Toggle
1180 className="shrink-0"
1181 pressed={rendered}
1182 onPressedChange={(pressed) => {
1183 setRenderedPreferred(pressed);
1184 setHandledReveal(
1185 pressed && relativePath !== null
1186 ? { path: relativePath, requestId: revealRequestId }
1187 : null,
1188 );
1189 }}
1190 aria-label={renderedToggleLabel(isMarkdown, rendered)}
1191 variant="ghost"
1192 size="sm"
1193 >
1194 {rendered ? <Code2 className="size-3.5" /> : <Eye className="size-3.5" />}
1195 </Toggle>
1196 }
1197 />
1198 <TooltipPopup>{renderedToggleLabel(isMarkdown, rendered)}</TooltipPopup>
1199 </Tooltip>
1200 ) : null}
1201 {canOpenInBrowser ? (
1202 <Tooltip>
1203 <TooltipTrigger
1204 render={
1205 <Toggle
1206 className="shrink-0"
1207 pressed={false}
1208 onPressedChange={handleOpenInBrowser}
1209 aria-label="Open file in preview browser"
1210 variant="ghost"
1211 size="sm"
1212 >
1213 <Globe2 className="size-3.5" />
1214 </Toggle>
1215 }
1216 />
1217 <TooltipPopup>Open file in preview browser</TooltipPopup>
1218 </Tooltip>
1219 ) : null}
1220 {!isHostFile ? (
1221 <Tooltip>
1222 <TooltipTrigger
1223 render={
1224 <Toggle
1225 className="shrink-0"
1226 pressed={explorerOpen}
1227 onPressedChange={toggleExplorer}
1228 aria-label={explorerOpen ? "Hide file explorer" : "Show file explorer"}
1229 variant="ghost"
1230 size="sm"
1231 >
1232 <FolderTree className="size-3.5" />
1233 </Toggle>
1234 }
1235 />
1236 <TooltipPopup>
1237 {explorerOpen ? "Hide file explorer" : "Show file explorer"}
1238 </TooltipPopup>
1239 </Tooltip>
1240 ) : null}
1241 </div>
1242 ) : null}
1243 {relativePath && !isMedia && !renderBrowserFile && file.data?.truncated ? (
1244 <div className="shrink-0 border-b border-warning/20 bg-warning-surface px-3 py-1.5 text-[11px] text-warning-foreground">
1245 Preview limited to the first 1 MB of a {file.data.byteLength.toLocaleString()} byte file.
1246 </div>
1247 ) : null}
1248 <div className="flex min-h-0 flex-1 overflow-hidden">
1249 <div
1250 className={cn(
1251 "min-w-0 flex-1 flex-col overflow-hidden",
1252 relativePath ? "flex" : "hidden",
1253 )}
1254 >
1255 {relativePath && attachment ? (
1256 <AttachmentBrowserPreview environmentId={environmentId} attachment={attachment} />
1257 ) : relativePath && isVideo && absolutePath ? (
1258 <WorkspaceVideoPreview
1259 key={`${environmentId}:${threadRef.threadId}:${absolutePath}`}
1260 environmentId={environmentId}
1261 threadRef={threadRef}
1262 absolutePath={absolutePath}
1263 workspaceRoot={cwd}
1264 name={relativePath}
1265 workspaceMutationId={workspaceMutationId}
1266 />
1267 ) : relativePath && isImage && absolutePath ? (
1268 <WorkspaceImagePreview
1269 key={absolutePath}
1270 environmentId={environmentId}
1271 threadRef={threadRef}
1272 absolutePath={absolutePath}
1273 workspaceRoot={cwd}
1274 alt={relativePath}
1275 workspaceMutationId={workspaceMutationId}
1276 />
1277 ) : relativePath && renderBrowserFile && absolutePath ? (
1278 <WorkspaceBrowserPreview
1279 key={absolutePath}
1280 environmentId={environmentId}
1281 threadRef={threadRef}
1282 absolutePath={absolutePath}
1283 workspaceRoot={cwd}
1284 title={relativePath}
1285 workspaceMutationId={workspaceMutationId}
1286 />
1287 ) : relativePath && file.error && file.data === null ? (
1288 <div className="flex min-h-0 flex-1 items-center justify-center px-6 text-center text-xs leading-relaxed text-destructive">
1289 {file.error}
1290 </div>
1291 ) : relativePath && file.data === null ? (
1292 <div className="flex min-h-0 flex-1 items-center justify-center text-muted-foreground">
1293 <LoaderCircle className="size-5 animate-spin" />
1294 </div>
1295 ) : relativePath && file.data ? (
1296 isMarkdown && renderMarkdown ? (
1297 <RenderedMarkdownSurface
1298 environmentId={environmentId}
1299 cwd={cwd}
1300 relativePath={relativePath}
1301 threadRef={threadRef}
1302 contents={file.data.contents}
1303 readOnly={isHostFile}
1304 onPendingChange={onPendingChange}
1305 />
1306 ) : file.data.truncated || isHostFile ? (
1307 <Virtualizer
1308 key={`${relativePath}:${resolvedTheme}:${file.data.byteLength}`}
1309 className="file-preview-virtualizer min-h-0 flex-1 overflow-auto"
1310 config={{
1311 overscrollSize: 600,
1312 intersectionObserverMargin: 1200,
1313 }}
1314 >
1315 <File
1316 file={{
1317 name: relativePath,
1318 contents: file.data.contents,
1319 cacheKey: projectFileCacheKey(cwd, relativePath, file.data.contents),
1320 }}
1321 options={{
1322 disableFileHeader: true,
1323 overflow: wordWrap ? "wrap" : "scroll",
1324 theme: resolveDiffThemeName(resolvedTheme),
1325 preferredHighlighter: PREFERRED_HIGHLIGHTER,
1326 themeType: resolvedTheme,
1327 unsafeCSS: FILE_LINK_REVEAL_UNSAFE_CSS,
1328 onPostRender: onFilePostRender,
1329 }}
1330 className="min-h-full"
1331 />
1332 </Virtualizer>
1333 ) : (
1334 <EditableFileSurface
1335 key={`${relativePath}:${resolvedTheme}`}
1336 environmentId={environmentId}
1337 cwd={cwd}
1338 relativePath={relativePath}
1339 composerDraftTarget={composerDraftTarget}
1340 contents={file.data.contents}
1341 resolvedTheme={resolvedTheme}
1342 revealRequestId={revealRequestId}
1343 wordWrap={wordWrap}
1344 onPostRender={onFilePostRender}
1345 onPendingChange={onPendingChange}
1346 />
1347 )
1348 ) : null}
1349 </div>
1350 {showExplorer ? (
1351 <aside
1352 className={cn(
1353 "flex min-h-0 shrink-0 bg-background",
1354 relativePath
1355 ? "w-[min(22rem,46%)] min-w-64 border-l border-border/60"
1356 : "min-w-0 flex-1",
1357 )}
1358 >
1359 <FileBrowserPanel
1360 key={`${environmentId}:${cwd}`}
1361 environmentId={environmentId}
1362 cwd={cwd}
1363 projectName={projectName}
1364 selectedPath={relativePath}
1365 selectedPathRevealId={revealRequestId}
1366 onOpenFile={onOpenFile}
1367 workspaceMutationId={workspaceMutationId}
1368 {...(relativePath && !isMedia && !isPdf
1369 ? { onRefreshSelectedFile: file.refresh }
1370 : {})}
1371 />
1372 </aside>
1373 ) : null}
1374 </div>
1375 </div>
1376 );
1377}