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

FilePreviewPanel.tsx

1,321 lines47.8 KB

1import { Spinner } from "~/components/ui/spinner";
2import type {
3 EditorId,
4 EnvironmentId,
5 ResolvedKeybindingsConfig,
6 ScopedThreadRef,
7} from "@t3tools/contracts";
8import { filePreviewDelimiter } from "@t3tools/shared/delimitedPreview";
9import {
10 isWorkspaceAudioPreviewPath,
11 isWorkspaceImagePreviewPath,
12 isWorkspaceVideoPreviewPath,
13} from "@t3tools/shared/filePreview";
14import { VirtualizedFile, type SelectedLineRange } from "@pierre/diffs";
15import { Editor } from "@pierre/diffs/editor";
16import { EditProvider, File, type FileOptions, Virtualizer } from "@pierre/diffs/react";
17import { DiffWorkerPoolProvider } from "../DiffWorkerPoolProvider";
18import {
19 isAtomCommandInterrupted,
20 squashAtomCommandFailure,
21} from "@t3tools/client-runtime/state/runtime";
22import { mediaFileReference } from "@t3tools/client-runtime/media-reference";
23import { FolderTree, Globe2, WrapTextIcon } from "lucide-react";
24import { Code2, Eye, Table2 } from "lucide";
25import * as Schema from "effect/Schema";
26import { useCallback, useEffect, useMemo, useRef, useState } from "react";
27​
28import { isBrowserPreviewFile, openFileInPreview } from "~/browser/openFileInPreview";
29import { useAssetUrlRefresh, useAssetUrlState } from "~/assets/assetUrls";
30import { OpenInPicker } from "~/components/chat/OpenInPicker";
31import { MediaVideoPlayer } from "~/components/media/MediaVideoPlayer";
32import { MediaActions, type MediaActionSource } from "~/components/media/MediaActions";
33import { MorphIcon } from "~/components/MorphIcon";
34import { useRemoteOpenState } from "~/remoteOpen";
35import { useClientSettings, useUpdateClientSettings } from "~/hooks/useSettings";
36import { useTheme } from "~/hooks/useTheme";
37import { getLocalStorageItem, setLocalStorageItem, useLocalStorage } from "~/hooks/useLocalStorage";
38import { useWorkspaceMutationRefresh } from "~/hooks/useWorkspaceMutationRefresh";
39import { resolveDiffThemeName } from "~/lib/diffRendering";
40import { PREFERRED_HIGHLIGHTER } from "~/lib/syntaxHighlighting";
41import { cn } from "~/lib/utils";
42import type { ChatFileAttachment } from "~/types";
43import { isAbsolutePath, resolvePathLinkTarget } from "~/terminal-links";
44import { ScrollArea } from "~/components/ui/scroll-area";
45import { stackedThreadToast, toastManager } from "~/components/ui/toast";
46import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
47import { buildFileReviewComment } from "~/reviewCommentContext";
48import { assetEnvironment } from "~/state/assets";
49import { usePreviewAvailable } from "~/browser/previewRuntime";
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;
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 );
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 );
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 );
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)} />;
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);
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, "");
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;
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 );
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;
561​
562interface FileSelectionOverride {
563 revealRequestId: number;
564 range: SelectedLineRange | null;
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 );
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 );
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";
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 }
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 previewAvailable = usePreviewAvailable(environmentId);
934 const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
935 reportFailure: false,
936 });
937 const openPreview = useAtomCommand(previewEnvironment.open, {
938 reportFailure: false,
939 });
940 const isVideo = relativePath !== null && isWorkspaceVideoPreviewPath(relativePath);
941 const isAudio = relativePath !== null && !isVideo && isWorkspaceAudioPreviewPath(relativePath);
942 const isImage = relativePath !== null && !isVideo && isWorkspaceImagePreviewPath(relativePath);
943 const isMedia = isImage || isVideo || isAudio;
944 // PDFs have no text to show; HTML has, and can toggle between page and source.
945 const isPdf = relativePath !== null && isPdfPreviewFile(relativePath);
946 const isHtml = relativePath !== null && !isPdf && isBrowserPreviewFile(relativePath);
947 // A file outside the workspace (an absolute path) is shown, never edited.
948 const isHostFile =
949 attachment !== undefined || (relativePath !== null && isAbsolutePath(relativePath));
950 // Media and PDFs render from their absolute path, so their contents are never
951 // shown. The read still runs: a folder named `assets.png` is only knowable as a
952 // folder from the read failure, and the server stats before reading, so a folder
953 // costs an open and a stat and returns no body.
954 const file = useProjectFileQuery(
955 environmentId,
956 cwd,
957 relativePath,
958 attachment === undefined && relativePath !== null,
959 );
960 // A chat link cannot tell a folder from a file, so a folder arrives here as
961 // a file surface and the read fails. Keep the breadcrumbs, drop the preview
962 // pane, and let the tree fill the surface with the folder revealed. Mutation
963 // refresh stays on so the surface notices if the path becomes a file. A host
964 // path cannot be revealed in the workspace tree, so it keeps the read error.
965 const isDirectory = file.isNotFile && !isHostFile;
966 // Everything preview-related keys off previewPath; a folder has no preview.
967 const previewPath = isDirectory ? null : relativePath;
968 const [explorerOpen, setExplorerOpen] = useState(initialExplorerOpen);
969 const showExplorer = shouldShowFileExplorer({
970 relativePath: previewPath,
971 explorerOpen,
972 attachmentOpen: attachment !== undefined,
973 });
974 // Reading markdown rendered is a preference, not a property of one file. Keeping
975 // it on the panel meant a thread switch dropped it and forced source back.
976 const [renderMarkdownPreferred, setRenderMarkdownPreferred] = useLocalStorage(
977 RENDER_MARKDOWN_STORAGE_KEY,
978 false,
979 Schema.Boolean,
980 );
981 const [renderBrowserFilePreferred, setRenderBrowserFilePreferred] = useLocalStorage(
982 RENDER_BROWSER_FILE_STORAGE_KEY,
983 true,
984 Schema.Boolean,
985 );
986 const [renderTablePreferred, setRenderTablePreferred] = useLocalStorage(
987 RENDER_TABLE_STORAGE_KEY,
988 true,
989 Schema.Boolean,
990 );
991 // Paired with the path on purpose: each file surface counts its reveals from
992 // one, so a bare id would let a dismissed reveal on one file swallow the first
993 // reveal on the next.
994 const [handledReveal, setHandledReveal] = useState<{ path: string; requestId: number } | null>(
995 null,
996 );
997 const breadcrumbRef = useRef<HTMLDivElement>(null);
998 const isMarkdown = previewPath ? isMarkdownPreviewFile(previewPath) : false;
999 const tableDelimiter =
1000 previewPath && attachment === undefined ? filePreviewDelimiter({ name: previewPath }) : null;
1001 // A reveal still wins over the preference: the line only exists in the source.
1002 const revealHandled =
1003 revealLine === null ||
1004 (handledReveal?.path === relativePath && handledReveal.requestId === revealRequestId);
1005 const renderMarkdown = isMarkdown && renderMarkdownPreferred && revealHandled;
1006 const renderBrowserFile = isPdf || (isHtml && renderBrowserFilePreferred && revealHandled);
1007 const renderTable = tableDelimiter !== null && renderTablePreferred && revealHandled;
1008 const renderedMode = isMarkdown
1009 ? ("markdown" as const)
1010 : tableDelimiter
1011 ? ("table" as const)
1012 : isHtml
1013 ? ("html" as const)
1014 : null;
1015 const canToggleRendered =
1016 previewPath !== null && attachment === undefined && renderedMode !== null;
1017 const updateClientSettings = useUpdateClientSettings();
1018 // Word wrap only reaches the text bodies. A rendered Markdown document, a table and the
1019 // browser frame all lay themselves out, so the toggle stays hidden rather than inert.
1020 const showsRawText =
1021 previewPath !== null &&
1022 file.data !== null &&
1023 !(isMarkdown && renderMarkdown) &&
1024 !(tableDelimiter && renderTable) &&
1025 !renderBrowserFile;
1026 const rendered = isMarkdown ? renderMarkdown : tableDelimiter ? renderTable : renderBrowserFile;
1027 const setRenderedPreferred = isMarkdown
1028 ? setRenderMarkdownPreferred
1029 : tableDelimiter
1030 ? setRenderTablePreferred
1031 : setRenderBrowserFilePreferred;
1032 const canOpenInBrowser =
1033 previewPath !== null &&
1034 attachment === undefined &&
1035 !isVideo &&
1036 previewAvailable &&
1037 isBrowserPreviewFile(previewPath);
1038 const absolutePath =
1039 relativePath && attachment === undefined ? resolvePathLinkTarget(relativePath, cwd) : null;
1040 const onFilePostRender = useFileLineReveal(relativePath, revealLine, revealRequestId);
1041 useWorkspaceMutationRefresh({
1042 enabled:
1043 attachment === undefined &&
1044 relativePath !== null &&
1045 // Media and PDFs never show their contents, so re-reading them on every
1046 // workspace mutation is waste. A folder named like one still re-reads, so
1047 // it notices when the path becomes a file.
1048 (isDirectory || (!isMedia && !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);
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;
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 && attachment === undefined ? (
1102 <div className={FILE_SURFACE_SUBHEADER_CLASS} data-surface-subheader>
1103 <ScrollArea
1104 radius="none"
1105 ref={breadcrumbRef}
1106 hideScrollbars
1107 scrollFade
1108 className="min-w-0 flex-1"
1109 data-file-breadcrumbs
1111 <div className="flex h-full w-max min-w-full items-center text-xs">
1112 <FileBreadcrumbs
1113 cwd={cwd}
1114 environmentId={environmentId}
1115 onOpenFile={onOpenFile}
1116 projectName={projectName}
1117 relativePath={relativePath}
1118 workspaceMutationId={workspaceMutationId}
1119 />
1120 </div>
1121 </ScrollArea>
1122 {absolutePath &&
1123 (environmentId === primaryEnvironmentId || remoteOpenState.mode !== "local-exec") ? (
1124 <OpenInPicker
1125 environmentId={environmentId}
1126 keybindings={keybindings}
1127 availableEditors={availableEditors}
1128 openInCwd={absolutePath}
1129 compact
1130 />
1131 ) : null}
1132 {canToggleRendered && renderedMode ? (
1133 <FileSurfaceAction
1134 label={renderedToggleLabel(renderedMode, rendered)}
1135 pressed={rendered}
1136 onPress={() => {
1137 const pressed = !rendered;
1138 setRenderedPreferred(pressed);
1139 setHandledReveal(
1140 pressed && relativePath !== null
1141 ? { path: relativePath, requestId: revealRequestId }
1142 : null,
1143 );
1144 }}
1146 <MorphIcon
1147 className="size-3.5"
1148 icon={rendered ? Code2 : renderedMode === "table" ? Table2 : Eye}
1149 />
1150 </FileSurfaceAction>
1151 ) : null}
1152 {showsRawText ? (
1153 <FileSurfaceAction
1154 label={wordWrap ? "Disable word wrap" : "Enable word wrap"}
1155 pressed={wordWrap}
1156 onPress={() => updateClientSettings({ wordWrap: !wordWrap })}
1158 <WrapTextIcon className="size-3.5" />
1159 </FileSurfaceAction>
1160 ) : null}
1161 {canOpenInBrowser ? (
1162 <FileSurfaceAction label="Open file in preview browser" onPress={handleOpenInBrowser}>
1163 <Globe2 className="size-3.5" />
1164 </FileSurfaceAction>
1165 ) : null}
1166 {!isHostFile && previewPath !== null ? (
1167 <FileSurfaceAction
1168 label={explorerOpen ? "Hide file explorer" : "Show file explorer"}
1169 pressed={explorerOpen}
1170 onPress={toggleExplorer}
1172 <FolderTree className="size-3.5" />
1173 </FileSurfaceAction>
1174 ) : null}
1175 </div>
1176 ) : null}
1177 {previewPath &&
1178 attachment === undefined &&
1179 !isMedia &&
1180 !renderBrowserFile &&
1181 file.data?.truncated ? (
1182 <div className="shrink-0 border-b border-warning/20 bg-warning-surface px-3 py-1.5 text-2xs text-warning-foreground">
1183 Preview limited to the first 1 MB of a {file.data.byteLength.toLocaleString()} byte file.
1184 </div>
1185 ) : null}
1186 <div className="flex min-h-0 flex-1 overflow-hidden">
1187 <div
1188 className={cn("min-w-0 flex-1 flex-col overflow-hidden", previewPath ? "flex" : "hidden")}
1190 {isDirectory ? null : relativePath && attachment ? (
1191 <AttachmentFilePreview
1192 key={`${environmentId}:${attachment.id}`}
1193 name={attachment.name}
1194 mimeType={attachment.mimeType}
1195 sizeBytes={attachment.sizeBytes}
1196 asset={{ environmentId, attachmentId: attachment.id }}
1197 htmlRender={attachment.htmlRender === true}
1198 />
1199 ) : relativePath && isVideo && absolutePath ? (
1200 <WorkspaceVideoPreview
1201 key={`${environmentId}:${threadRef.threadId}:${absolutePath}`}
1202 environmentId={environmentId}
1203 threadRef={threadRef}
1204 absolutePath={absolutePath}
1205 workspaceRoot={cwd}
1206 name={relativePath}
1207 workspaceMutationId={workspaceMutationId}
1208 />
1209 ) : relativePath && isAudio && absolutePath ? (
1210 <WorkspaceAudioPreview
1211 key={`${environmentId}:${threadRef.threadId}:${absolutePath}`}
1212 environmentId={environmentId}
1213 threadRef={threadRef}
1214 absolutePath={absolutePath}
1215 name={relativePath}
1216 workspaceMutationId={workspaceMutationId}
1217 />
1218 ) : relativePath && isImage && absolutePath ? (
1219 <WorkspaceImagePreview
1220 key={absolutePath}
1221 environmentId={environmentId}
1222 threadRef={threadRef}
1223 absolutePath={absolutePath}
1224 workspaceRoot={cwd}
1225 alt={relativePath}
1226 workspaceMutationId={workspaceMutationId}
1227 />
1228 ) : relativePath && renderBrowserFile && absolutePath ? (
1229 <WorkspaceBrowserPreview
1230 key={absolutePath}
1231 environmentId={environmentId}
1232 threadRef={threadRef}
1233 absolutePath={absolutePath}
1234 workspaceRoot={cwd}
1235 title={relativePath}
1236 workspaceMutationId={workspaceMutationId}
1237 />
1238 ) : relativePath && file.error && file.data === null ? (
1239 <div className="flex min-h-0 flex-1 items-center justify-center px-6 text-center text-xs leading-relaxed text-destructive">
1240 {file.error}
1241 </div>
1242 ) : relativePath && file.data === null ? (
1243 <div className="flex min-h-0 flex-1 items-center justify-center text-muted-foreground">
1244 <Spinner size="lg" />
1245 </div>
1246 ) : relativePath && file.data ? (
1247 isMarkdown && renderMarkdown ? (
1248 // Markdown reconciles in place across text updates, so a file
1249 // switch needs a new key or the previous file's disclosure and
1250 // wrap state carries into the next document.
1251 <RenderedMarkdownSurface
1252 key={relativePath}
1253 environmentId={environmentId}
1254 cwd={cwd}
1255 relativePath={relativePath}
1256 threadRef={threadRef}
1257 contents={file.data.contents}
1258 readOnly={isHostFile}
1259 onPendingChange={onPendingChange}
1260 />
1261 ) : tableDelimiter && renderTable ? (
1262 <DelimitedTablePreview
1263 key={relativePath}
1264 name={relativePath}
1265 text={file.data.contents}
1266 delimiter={tableDelimiter}
1267 />
1268 ) : file.data.truncated || isHostFile ? (
1269 <SourceFilePreview
1270 name={relativePath}
1271 text={file.data.contents}
1272 cacheKey={projectFileCacheKey(cwd, relativePath, file.data.contents)}
1273 onPostRender={onFilePostRender}
1274 />
1275 ) : (
1276 <DiffWorkerPoolProvider>
1277 <EditableFileSurface
1278 key={`${relativePath}:${resolvedTheme}`}
1279 environmentId={environmentId}
1280 cwd={cwd}
1281 relativePath={relativePath}
1282 composerDraftTarget={composerDraftTarget}
1283 contents={file.data.contents}
1284 resolvedTheme={resolvedTheme}
1285 revealRequestId={revealRequestId}
1286 wordWrap={wordWrap}
1287 onPostRender={onFilePostRender}
1288 onPendingChange={onPendingChange}
1289 />
1290 </DiffWorkerPoolProvider>
1292 ) : null}
1293 </div>
1294 {showExplorer ? (
1295 <aside
1296 className={cn(
1297 "flex min-h-0 shrink-0 bg-background",
1298 previewPath
1299 ? "w-[min(22rem,46%)] min-w-64 border-l border-border/60"
1300 : "min-w-0 flex-1",
1301 )}
1303 <FileBrowserPanel
1304 key={`${environmentId}:${cwd}`}
1305 environmentId={environmentId}
1306 cwd={cwd}
1307 projectName={projectName}
1308 selectedPath={relativePath}
1309 selectedPathRevealId={revealRequestId}
1310 onOpenFile={onOpenFile}
1311 workspaceMutationId={workspaceMutationId}
1312 {...(previewPath && !isMedia && !isPdf
1313 ? { onRefreshSelectedFile: file.refresh }
1314 : {})}
1315 />
1316 </aside>
1317 ) : null}
1318 </div>
1319 </div>
1320 );