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