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

FilePreviewPanel.tsx

1,357 lines47.9 KB

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