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

FilePreviewPanel.tsx

1,321 lines47.7 KB

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