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

FilePreviewPanel.tsx

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