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

FilePreviewPanel.tsx

1,387 lines48.8 KB

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