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