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