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