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