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

FilePreviewPanel.tsx

1,474 lines54.4 KB

1import { Spinner } from "~/components/ui/spinner";
2import {
3 AuthPreviewOperateScope,
4 type EditorId,
5 type EnvironmentId,
6 type ResolvedKeybindingsConfig,
7 type ScopedThreadRef,
8} from "@t3tools/contracts";
9import { filePreviewDelimiter } from "@t3tools/shared/delimitedPreview";
10import { AuthFilesystemWriteScope } from "@t3tools/contracts";
11import {
12 isWorkspaceAudioPreviewPath,
13 isWorkspaceImagePreviewPath,
14 isWorkspaceVideoPreviewPath,
15} from "@t3tools/shared/filePreview";
16import { useAtomValue } from "@effect/atom-react";
17import {
18 DEFAULT_TOKENIZE_MAX_LENGTH,
19 VirtualizedFile,
20 getFiletypeFromFileName,
21 type File as FileInstance,
22 type FileContents,
23 type PostRenderPhase,
24 type SelectedLineRange,
25} from "@pierre/diffs";
26import {
27 Editor,
28 type EditorChangeEvent,
29 type EditorFactory,
30 type EditorOptions,
31} from "@pierre/diffs/edit";
32import type { WorkerPoolManager } from "@pierre/diffs/worker";
33import { EditProvider, File, Virtualizer, useWorkerPool } from "@pierre/diffs/react";
34import { DiffWorkerPoolProvider } from "../DiffWorkerPoolProvider";
35import { useFilesystemReadAccess } from "~/state/filesystem";
36import {
37 isAtomCommandInterrupted,
38 squashAtomCommandFailure,
39} from "@t3tools/client-runtime/state/runtime";
40import { mediaFileReference } from "@t3tools/client-runtime/media-reference";
41import { FolderTree, Globe2, WrapTextIcon } from "lucide-react";
42import { Code2, Eye, Table2 } from "lucide";
43import * as Schema from "effect/Schema";
44import { useEffect, useRef, useState } from "react";
45​
46import { isBrowserPreviewFile, openFileInPreview } from "~/browser/openFileInPreview";
47import { useAssetUrlRefresh, useAssetUrlState } from "~/assets/assetUrls";
48import { OpenInPicker } from "~/components/chat/OpenInPicker";
49import { MediaVideoPlayer } from "~/components/media/MediaVideoPlayer";
50import { MediaActions, type MediaActionSource } from "~/components/media/MediaActions";
51import { MorphIcon } from "~/components/MorphIcon";
52import { useRemoteOpenState } from "~/remoteOpen";
53import { useClientSettings, updateClientSettings } from "~/hooks/useSettings";
54import { useTheme } from "~/hooks/useTheme";
55import { getLocalStorageItem, setLocalStorageItem, useLocalStorage } from "~/hooks/useLocalStorage";
56import { useWorkspaceMutationRefresh } from "~/hooks/useWorkspaceMutationRefresh";
57import { resolveDiffThemeName } from "~/lib/diffRendering";
58import { PREFERRED_HIGHLIGHTER } from "~/lib/syntaxHighlighting";
59import { cn } from "~/lib/utils";
60import type { ChatFileAttachment } from "~/types";
61import { isAbsolutePath } from "@t3tools/shared/path";
62import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks";
63import { ScrollArea } from "~/components/ui/scroll-area";
64import { stackedThreadToast, toastManager } from "~/components/ui/toast";
65import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
66import { buildFileReviewComment } from "~/reviewCommentContext";
67import { assetEnvironment } from "~/state/assets";
68import { usePreviewAvailable } from "~/browser/previewRuntime";
69import { useEnvironmentHttpBaseUrl, usePrimaryEnvironmentId } from "~/state/environments";
70import { previewEnvironment } from "~/state/preview";
71import { serverEnvironment } from "~/state/server";
72import { useEnvironmentScope } from "~/state/session";
73import { useAtomCommand } from "~/state/use-atom-command";
74import { useAtomQueryRunner } from "~/state/use-atom-query-runner";
75​
76import { AttachmentFilePreview } from "./AttachmentFilePreview";
77import { AudioPreview } from "./AudioPreview";
78import { BrowserDocumentFrame, isPdfPreviewFile } from "./BrowserDocumentFrame";
79import { DelimitedTablePreview } from "./DelimitedTablePreview";
80import FileBrowserPanel from "./FileBrowserPanel";
81import { FileBreadcrumbs } from "./FileBreadcrumbs";
82import { breadcrumbPathOf, retainedBreadcrumbTrail, trailChildOf } from "./filePath";
83import { FileMarkdownPreview } from "./FileMarkdownPreview";
84import {
85 type FileCommentAnnotationEntry,
86 type FileCommentAnnotationGroup,
87 type FileCommentLineAnnotation,
88 formatFileCommentRange,
89 nextFileCommentId,
90 normalizeFileCommentRange,
91 remapFileCommentAnnotations,
92} from "./fileCommentAnnotations";
93import { installFileEditorDismissal } from "./fileEditorDismissal";
94import {
95 FILE_LINK_REVEAL_ATTRIBUTE,
96 FILE_LINK_REVEAL_UNSAFE_CSS,
97 FILE_SURFACE_SUBHEADER_CLASS,
98 FileSurfaceAction,
99 FileSurfaceFailure,
100 FileSurfaceLoading,
101} from "./fileSurfaceChrome";
102import SourceFilePreview from "./ReadOnlySourcePreview";
103import { resolveCenteredFileLineScrollTop } from "./fileLineReveal";
104import { DiffCommentAnnotation } from "../diffs/DiffCommentAnnotation";
105import { projectFileCacheKey } from "./fileContentRevision";
106import {
107 filePreviewReadErrorMessage,
108 isMarkdownPreviewFile,
109 resolveFilePreviewPath,
110 setMarkdownTaskChecked,
111 shouldShowFileExplorer,
112 workspaceAssetResource,
113} from "./filePreviewMode";
114import { useFileSaveCoordinator } from "./useFileSaveCoordinator";
115import {
116 getOptimisticProjectFileQueryData,
117 getProjectFileContents,
118 setProjectFileQueryData,
119 useProjectFileQuery,
120} from "./projectFilesQueryState";
121​
122interface FilePreviewPanelProps {
123 environmentId: EnvironmentId;
124 cwd: string;
125 projectName: string;
126 relativePath: string | null;
127 attachment?: ChatFileAttachment;
128 threadRef: ScopedThreadRef;
129 composerDraftTarget: ScopedThreadRef | DraftId;
130 keybindings: ResolvedKeybindingsConfig;
131 availableEditors: ReadonlyArray<EditorId>;
132 revealLine: number | null;
133 revealRequestId: number;
134 onOpenFile: (relativePath: string) => void;
135 /** Moves this folder browser to another folder in place; see `navigateFolder`. */
136 onNavigateFolder: (relativePath: string, folderTrail: string, keepSource: boolean) => void;
137 /** The deeper path breadcrumbs keep after the browser moved up; see `navigateFolder`. */
138 folderTrail: string | undefined;
139 onPendingChange: (relativePath: string, pending: boolean) => void;
140 selectedFilePending: boolean;
141 workspaceMutationId: string | null;
143​
144const FILE_EXPLORER_STORAGE_KEY = "t3code.fileExplorerOpen";
145const RENDER_MARKDOWN_STORAGE_KEY = "t3code.renderMarkdown";
146const RENDER_BROWSER_FILE_STORAGE_KEY = "t3code.renderBrowserFile";
147const RENDER_TABLE_STORAGE_KEY = "t3code.renderTable";
148type FilePostRender = <LAnnotation>(
149 fileContainer: HTMLElement,
150 instance: FileInstance<LAnnotation, undefined>,
151 phase: PostRenderPhase,
152) => void;
153​
154function WorkspaceImagePreview(props: {
155 readonly environmentId: EnvironmentId;
156 readonly threadRef: ScopedThreadRef;
157 readonly draft: boolean;
158 readonly absolutePath: string;
159 readonly workspaceRoot: string;
160 readonly alt: string;
161 readonly workspaceMutationId: string | null;
162}) {
163 const resource = workspaceAssetResource({
164 kind: "workspace-file",
165 threadRef: props.threadRef,
166 draft: props.draft,
167 workspaceRoot: props.workspaceRoot,
168 absolutePath: props.absolutePath,
169 });
170 const assetUrl = useAssetUrlState(props.environmentId, resource);
171 const [failedUrl, setFailedUrl] = useState<string | null>(null);
172 const revisionSuffix =
173 props.workspaceMutationId === null
174 ? ""
175 : `${assetUrl._tag === "Success" && assetUrl.url.includes("?") ? "&" : "?"}workspace-revision=${encodeURIComponent(props.workspaceMutationId)}`;
176 const imageUrl = assetUrl._tag === "Success" ? `${assetUrl.url}${revisionSuffix}` : null;
177 const actionsSource: MediaActionSource = {
178 kind: "image",
179 name: props.alt,
180 src: imageUrl,
181 reference: mediaFileReference(props.absolutePath, props.workspaceRoot),
182 asset: { environmentId: props.environmentId, resource },
183 };
184​
185 if (assetUrl._tag === "Failure" || (imageUrl !== null && failedUrl === imageUrl)) {
186 return (
187 <MediaActions source={actionsSource}>
188 <div className="flex min-h-0 flex-1 items-center justify-center px-6 text-center text-xs leading-relaxed text-destructive">
189 Unable to load workspace image.
190 </div>
191 </MediaActions>
192 );
193 }
194​
195 return assetUrl._tag === "Success" && imageUrl !== null ? (
196 // oxlint-disable-next-line t3code/require-centered-scroll-gutter -- The image is capped at max-h-full max-w-full, so this never scrolls.
197 <div className="flex min-h-0 flex-1 items-center justify-center overflow-auto p-4">
198 <MediaActions source={actionsSource}>
199 <img
200 className="max-h-full max-w-full object-contain"
201 src={imageUrl}
202 alt={props.alt}
203 onError={() => setFailedUrl(imageUrl)}
204 />
205 </MediaActions>
206 </div>
207 ) : (
208 <div className="flex min-h-0 flex-1 items-center justify-center text-muted-foreground">
209 <Spinner size="lg" />
210 </div>
211 );
213​
214/**
215 * HTML runs in a sandboxed frame with an opaque origin, so a page cannot reach
216 * the app's session or storage.
217 */
218function WorkspaceBrowserPreview(props: {
219 readonly environmentId: EnvironmentId;
220 readonly threadRef: ScopedThreadRef;
221 readonly draft: boolean;
222 readonly absolutePath: string;
223 readonly workspaceRoot: string;
224 readonly title: string;
225 readonly workspaceMutationId: string | null;
226}) {
227 const insideWorkspace =
228 mediaFileReference(props.absolutePath, props.workspaceRoot).relativePath !== undefined;
229 const resource = workspaceAssetResource({
230 kind: insideWorkspace ? "workspace-file" : "media-file",
231 threadRef: props.threadRef,
232 draft: props.draft,
233 workspaceRoot: props.workspaceRoot,
234 absolutePath: props.absolutePath,
235 });
236 const assetUrl = useAssetUrlState(props.environmentId, resource);
237 const revisionSuffix =
238 props.workspaceMutationId === null
239 ? ""
240 : `${assetUrl._tag === "Success" && assetUrl.url.includes("?") ? "&" : "?"}workspace-revision=${encodeURIComponent(props.workspaceMutationId)}`;
241​
242 if (assetUrl._tag === "Failure") {
243 return (
244 <div className="flex min-h-0 flex-1 items-center justify-center px-6 text-center text-xs leading-relaxed text-destructive">
245 Unable to load file preview.
246 </div>
247 );
248 }
249 if (assetUrl._tag !== "Success") {
250 return (
251 <div className="flex min-h-0 flex-1 items-center justify-center text-muted-foreground">
252 <Spinner size="lg" />
253 </div>
254 );
255 }
256 return (
257 <BrowserDocumentFrame
258 src={`${assetUrl.url}${revisionSuffix}`}
259 title={props.title}
260 pdf={isPdfPreviewFile(props.absolutePath)}
261 />
262 );
264​
265function WorkspaceVideoPreview(props: {
266 readonly environmentId: EnvironmentId;
267 readonly threadRef: ScopedThreadRef;
268 readonly draft: boolean;
269 readonly absolutePath: string;
270 readonly workspaceRoot: string;
271 readonly name: string;
272 readonly workspaceMutationId: string | null;
273}) {
274 const resource = workspaceAssetResource({
275 kind: "media-file",
276 threadRef: props.threadRef,
277 draft: props.draft,
278 workspaceRoot: props.workspaceRoot,
279 absolutePath: props.absolutePath,
280 });
281 const assetUrl = useAssetUrlState(props.environmentId, resource);
282 const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, resource);
283 useWorkspaceMutationRefresh({
284 mutationId: props.workspaceMutationId,
285 resourceKey: JSON.stringify([props.environmentId, resource]),
286 refresh: () => {
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 );
317​
318function WorkspaceAudioPreview(props: {
319 readonly environmentId: EnvironmentId;
320 readonly threadRef: ScopedThreadRef;
321 readonly draft: boolean;
322 readonly absolutePath: string;
323 readonly workspaceRoot: string;
324 readonly name: string;
325 readonly workspaceMutationId: string | null;
326}) {
327 const resource = workspaceAssetResource({
328 kind: "media-file",
329 threadRef: props.threadRef,
330 draft: props.draft,
331 workspaceRoot: props.workspaceRoot,
332 absolutePath: props.absolutePath,
333 });
334 const assetUrl = useAssetUrlState(props.environmentId, resource);
335 const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, resource);
336 const [failedUrl, setFailedUrl] = useState<string | null>(null);
337 useWorkspaceMutationRefresh({
338 mutationId: props.workspaceMutationId,
339 resourceKey: JSON.stringify([props.environmentId, resource]),
340 refresh: () => {
341 void refreshAssetUrl().catch(() => undefined);
342 },
343 });
344 const revisionSuffix =
345 props.workspaceMutationId === null
346 ? ""
347 : `${assetUrl._tag === "Success" && assetUrl.url.includes("?") ? "&" : "?"}workspace-revision=${encodeURIComponent(props.workspaceMutationId)}`;
348 const url = assetUrl._tag === "Success" ? `${assetUrl.url}${revisionSuffix}` : null;
349 if (assetUrl._tag === "Failure" || (url !== null && failedUrl === url)) {
350 return (
351 <FileSurfaceFailure
352 message="Unable to load audio."
353 onRetry={() => {
354 setFailedUrl(null);
355 void refreshAssetUrl().catch(() => undefined);
356 }}
357 />
358 );
359 }
360 if (url === null) return <FileSurfaceLoading />;
361 return <AudioPreview src={url} name={props.name} onError={() => setFailedUrl(url)} />;
363​
364function clampFileLine(contents: string, requestedLine: number): number {
365 let lineCount = 1;
366 for (let index = 0; index < contents.length; index += 1) {
367 const character = contents.charCodeAt(index);
368 if (character === 10) {
369 lineCount += 1;
370 } else if (character === 13) {
371 lineCount += 1;
372 if (contents.charCodeAt(index + 1) === 10) index += 1;
373 }
374 }
375 return Math.min(Math.max(1, requestedLine), lineCount);
377​
378function updateFileLinkReveal(fileContainer: HTMLElement, line: number | null): void {
379 const root = fileContainer.shadowRoot ?? fileContainer;
380 for (const element of root.querySelectorAll<HTMLElement>(`[${FILE_LINK_REVEAL_ATTRIBUTE}]`)) {
381 element.removeAttribute(FILE_LINK_REVEAL_ATTRIBUTE);
382 }
383 if (line === null) return;
384​
385 root
386 .querySelector<HTMLElement>(`[data-line="${line}"]`)
387 ?.setAttribute(FILE_LINK_REVEAL_ATTRIBUTE, "");
388 root
389 .querySelector<HTMLElement>(`[data-column-number="${line}"]`)
390 ?.setAttribute(FILE_LINK_REVEAL_ATTRIBUTE, "");
392​
393const REVEAL_MAX_ATTEMPTS = 30;
394/**
395 * After scrolling to the target, hold it for a short window so late
396 * programmatic scroll resets (editable-editor focus and state restoration)
397 * cannot silently snap the file back to the top.
398 */
399const REVEAL_GUARD_FRAMES = 20;
400const REVEAL_GUARD_TOLERANCE_PX = 2;
401​
402interface FileRevealState {
403 frameId: number | null;
404 cancelGuard: (() => void) | null;
405 handledRequestId: number | null;
406 latestRequestId: number | null;
408​
409function useFileLineReveal(
410 relativePath: string | null,
411 revealLine: number | null,
412 revealRequestId: number,
413): FilePostRender {
414 const [revealStatesByPath] = useState(() => new Map<string, FileRevealState>());
415​
416 return (fileContainer, instance, phase) => {
417 if (relativePath === null) return;
418​
419 const existingState = revealStatesByPath.get(relativePath);
420 const state: FileRevealState = existingState ?? {
421 frameId: null,
422 cancelGuard: null,
423 handledRequestId: null,
424 latestRequestId: null,
425 };
426 if (!existingState) revealStatesByPath.set(relativePath, state);
427​
428 const cancelPendingReveal = () => {
429 if (state.frameId !== null) {
430 cancelAnimationFrame(state.frameId);
431 state.frameId = null;
432 }
433 state.cancelGuard?.();
434 };
435​
436 if (phase === "unmount") {
437 cancelPendingReveal();
438 return;
439 }
440​
441 const contents = instance.file?.contents;
442 const targetLine =
443 revealLine === null || contents === undefined ? null : clampFileLine(contents, revealLine);
444 updateFileLinkReveal(fileContainer, targetLine);
445​
446 if (!(instance instanceof VirtualizedFile)) return;
447​
448 if (state.latestRequestId !== revealRequestId) {
449 cancelPendingReveal();
450 state.latestRequestId = revealRequestId;
451 state.handledRequestId = null;
452 }
453​
454 if (revealLine === null) {
455 fileContainer.style.minHeight = "";
456 return;
457 }
458​
459 const scrollContainer = fileContainer.closest<HTMLElement>(".file-preview-virtualizer");
460 if (!scrollContainer) return;
461 fileContainer.style.minHeight = `${Math.ceil(
462 Math.max(instance.height, scrollContainer.clientHeight),
463 )}px`;
464​
465 if (state.handledRequestId === revealRequestId || state.frameId !== null) {
466 return;
467 }
468​
469 const resolveScrollTarget = (line: number): number | null => {
470 const linePosition = instance.getLinePosition(line);
471 if (!linePosition) return null;
472​
473 const scrollContainerRect = scrollContainer.getBoundingClientRect();
474 const fileTop =
475 scrollContainer.scrollTop +
476 fileContainer.getBoundingClientRect().top -
477 scrollContainerRect.top;
478 const root = fileContainer.shadowRoot ?? fileContainer;
479 const renderedLineElement = root.querySelector<HTMLElement>(`[data-line="${line}"]`);
480 const renderedLineRect = renderedLineElement?.getBoundingClientRect();
481​
482 return resolveCenteredFileLineScrollTop({
483 scrollTop: scrollContainer.scrollTop,
484 scrollHeight: scrollContainer.scrollHeight,
485 viewportTop: scrollContainerRect.top,
486 viewportHeight: scrollContainer.clientHeight,
487 fileTop,
488 estimatedLine: linePosition,
489 ...(renderedLineRect && renderedLineRect.height > 0
490 ? {
491 renderedLine: {
492 top: renderedLineRect.top,
493 height: renderedLineRect.height,
494 },
495 }
496 : {}),
497 });
498 };
499​
500 const guardScrollTarget = (line: number) => {
501 let framesLeft = REVEAL_GUARD_FRAMES;
502 let guardFrameId: number | null = null;
503 const cancelGuard = () => {
504 if (guardFrameId !== null) {
505 cancelAnimationFrame(guardFrameId);
506 guardFrameId = null;
507 }
508 scrollContainer.removeEventListener("wheel", cancelGuard);
509 scrollContainer.removeEventListener("touchstart", cancelGuard);
510 scrollContainer.removeEventListener("pointerdown", cancelGuard, true);
511 window.removeEventListener("keydown", cancelGuard, true);
512 if (state.cancelGuard === cancelGuard) state.cancelGuard = null;
513 };
514 scrollContainer.addEventListener("wheel", cancelGuard, { passive: true });
515 scrollContainer.addEventListener("touchstart", cancelGuard, { passive: true });
516 // Pierre stops gutter pointer events from bubbling. Listen in capture
517 // so starting a comment cancels the reveal guard before the row expands.
518 scrollContainer.addEventListener("pointerdown", cancelGuard, {
519 passive: true,
520 capture: true,
521 });
522 window.addEventListener("keydown", cancelGuard, true);
523 const holdTarget = () => {
524 guardFrameId = null;
525 framesLeft -= 1;
526 if (framesLeft <= 0 || !scrollContainer.isConnected) {
527 cancelGuard();
528 return;
529 }
530 const targetTop = resolveScrollTarget(line);
531 if (
532 targetTop !== null &&
533 Math.abs(scrollContainer.scrollTop - targetTop) > REVEAL_GUARD_TOLERANCE_PX
534 ) {
535 scrollContainer.scrollTop = targetTop;
536 }
537 guardFrameId = requestAnimationFrame(holdTarget);
538 };
539 guardFrameId = requestAnimationFrame(holdTarget);
540 state.cancelGuard = cancelGuard;
541 };
542​
543 const scheduleReveal = (attempt: number) => {
544 state.frameId = requestAnimationFrame(() => {
545 state.frameId = null;
546 if (state.latestRequestId !== revealRequestId || !fileContainer.isConnected) {
547 return;
548 }
549​
550 // Contents and line metrics can lag the first post-render on fresh
551 // mounts; clamping against missing contents would scroll to line 1
552 // and wrongly mark the request handled.
553 const currentContents = instance.file?.contents;
554 const line =
555 currentContents === undefined ? null : clampFileLine(currentContents, revealLine);
556 const targetTop = line === null ? null : resolveScrollTarget(line);
557 if (line === null || targetTop === null) {
558 if (attempt < REVEAL_MAX_ATTEMPTS) scheduleReveal(attempt + 1);
559 return;
560 }
561 updateFileLinkReveal(fileContainer, line);
562​
563 scrollContainer.scrollTop = targetTop;
564 state.handledRequestId = revealRequestId;
565 guardScrollTarget(line);
566 });
567 };
568​
569 scheduleReveal(0);
570 };
572​
573const createFileEditor: EditorFactory<FileCommentAnnotationGroup, undefined> = (
574 editorType,
575 options,
576 editStateKey,
577) => new Editor(editorType, options, editStateKey);
578​
579function editableFileContents(
580 environmentId: EnvironmentId,
581 cwd: string,
582 relativePath: string,
583 contents: string,
584): FileContents {
585 return {
586 name: relativePath,
587 contents,
588 cacheKey: `editor:${environmentId}:${projectFileCacheKey(cwd, relativePath, contents)}`,
589 };
591​
592function needsWorkerHighlight(workerPool: WorkerPoolManager | undefined, file: FileContents) {
593 if (workerPool?.isWorkingPool() !== true) return false;
594 if ((file.lang ?? getFiletypeFromFileName(file.name)) === "text") return false;
595 let lines = 1;
596 for (
597 let index = file.contents.indexOf("\n");
598 index !== -1;
599 index = file.contents.indexOf("\n", index + 1)
600 ) {
601 lines += 1;
602 }
603 return lines <= DEFAULT_TOKENIZE_MAX_LENGTH;
605​
606/**
607 * Pierre highlights an active edit session on the main thread, so each version
608 * of the file becomes editable only once it has rendered the worker's
609 * highlight.
610 */
611function useEditableAfterHighlight(file: FileContents) {
612 const workerPool = useWorkerPool();
613 const [highlightedFile, setHighlightedFile] = useState<FileContents | null>(null);
614 const needsHighlight = needsWorkerHighlight(workerPool, file);
615 const ready = !needsHighlight || highlightedFile === file;
616​
617 useEffect(() => {
618 if (ready || workerPool === undefined) return;
619 workerPool.primeFileHighlightCache(file).catch(() => setHighlightedFile(file));
620 }, [file, ready, workerPool]);
621​
622 const onPostRender = (renderedFile: FileContents | undefined, phase: PostRenderPhase) => {
623 if (ready || phase === "unmount" || renderedFile?.cacheKey !== file.cacheKey) return;
624 // The pool caches a result just before the instance renders it, so a
625 // render that sees the cache has painted highlighted rows.
626 if (workerPool?.getFileResultCache(file) !== undefined) setHighlightedFile(file);
627 };
628 return { ready, onPostRender };
630​
631interface EditableFileSurfaceProps {
632 environmentId: EnvironmentId;
633 cwd: string;
634 relativePath: string;
635 composerDraftTarget: ScopedThreadRef | DraftId;
636 contents: string;
637 resolvedTheme: "light" | "dark";
638 revealRequestId: number;
639 wordWrap: boolean;
640 onPostRender: FilePostRender;
641 onPendingChange: (relativePath: string, pending: boolean) => void;
643​
644interface FileSelectionOverride {
645 revealRequestId: number;
646 range: SelectedLineRange | null;
648​
649function EditableFileSurface({
650 environmentId,
651 cwd,
652 relativePath,
653 composerDraftTarget,
654 contents,
655 resolvedTheme,
656 revealRequestId,
657 wordWrap,
658 onPostRender,
659 onPendingChange,
660}: EditableFileSurfaceProps) {
661 const addReviewComment = useComposerDraftStore((store) => store.addReviewComment);
662 const removeReviewComment = useComposerDraftStore((store) => store.removeReviewComment);
663 const [lineAnnotations, setLineAnnotations] = useState<FileCommentLineAnnotation[]>([]);
664 const [selectionOverride, setSelectionOverride] = useState<FileSelectionOverride | null>(null);
665 const selectedRange =
666 selectionOverride?.revealRequestId === revealRequestId ? selectionOverride.range : null;
667 const setSelectedRange = (range: SelectedLineRange | null) => {
668 setSelectionOverride({ revealRequestId, range });
669 };
670 const surfaceRef = useRef<HTMLDivElement>(null);
671 const selectionFrameRef = useRef<number | null>(null);
672 const saveCoordinator = useFileSaveCoordinator({
673 environmentId,
674 cwd,
675 relativePath,
676 onPendingChange,
677 });
678 // The editor owns the draft, so its own edits echoing back through the file
679 // query keep the file identity. Only a change from elsewhere replaces it.
680 const [externalFile, setExternalFile] = useState(() =>
681 editableFileContents(environmentId, cwd, relativePath, contents),
682 );
683 const [editedContents, setEditedContents] = useState<string | null>(null);
684 if (contents !== (editedContents ?? externalFile.contents)) {
685 setExternalFile(editableFileContents(environmentId, cwd, relativePath, contents));
686 setEditedContents(null);
687 }
688 const { ready: editable, onPostRender: onEditablePostRender } =
689 useEditableAfterHighlight(externalFile);
690 const editorRef = useRef<Editor<"file", FileCommentAnnotationGroup, undefined> | null>(null);
691 const editorOptions: EditorOptions<"file", FileCommentAnnotationGroup, undefined> = {
692 onAttach: (editor) => {
693 editorRef.current = editor;
694 },
695 onComplete: () => {
696 editorRef.current = null;
697 },
698 };
699​
700 const handleEditChange = ({
701 file,
702 lineAnnotations: nextLineAnnotations,
703 }: EditorChangeEvent<"file", FileCommentAnnotationGroup, undefined>) => {
704 if (file.contents === getProjectFileContents(environmentId, cwd, relativePath)) return;
705 setEditedContents(file.contents);
706 setProjectFileQueryData(environmentId, cwd, relativePath, file.contents);
707 saveCoordinator.change(file.contents);
708 if (!nextLineAnnotations) return;
709 const remapped = remapFileCommentAnnotations(nextLineAnnotations);
710 // The editor hands back the array it was given until an edit moves an annotation.
711 setLineAnnotations((current) => (current === nextLineAnnotations ? current : remapped));
712 for (const annotation of remapped) {
713 for (const entry of annotation.metadata.entries) {
714 if (entry.kind !== "comment") continue;
715 addReviewComment(
716 composerDraftTarget,
717 buildFileReviewComment({
718 id: entry.id,
719 filePath: relativePath,
720 startLine: entry.startLine,
721 endLine: entry.endLine,
722 text: entry.text,
723 contents: file.contents,
724 }),
725 );
726 }
727 }
728 };
729​
730 const removeAnnotationEntry = (entryId: string) => {
731 setSelectedRange(null);
732 removeReviewComment(composerDraftTarget, entryId);
733 setLineAnnotations((current) => {
734 return current.flatMap((annotation) => {
735 const entries = annotation.metadata.entries.filter((entry) => entry.id !== entryId);
736 return entries.length > 0 ? [{ ...annotation, metadata: { entries } }] : [];
737 });
738 });
739 };
740​
741 const submitAnnotationEntry = (entryId: string, text: string) => {
742 setSelectedRange(null);
743 const entry = lineAnnotations
744 .flatMap((annotation) => annotation.metadata.entries)
745 .find((candidate) => candidate.id === entryId);
746 if (entry) {
747 addReviewComment(
748 composerDraftTarget,
749 buildFileReviewComment({
750 id: entry.id,
751 filePath: relativePath,
752 startLine: entry.startLine,
753 endLine: entry.endLine,
754 text,
755 contents,
756 }),
757 );
758 }
759 setLineAnnotations((current) =>
760 current.map((annotation) => ({
761 ...annotation,
762 metadata: {
763 entries: annotation.metadata.entries.map((annotationEntry) =>
764 annotationEntry.id === entryId
765 ? { ...annotationEntry, kind: "comment", text }
766 : annotationEntry,
767 ),
768 },
769 })),
770 );
771 };
772​
773 const beginComment = (range: SelectedLineRange) => {
774 editorRef.current?.setSelections([]);
775 editorRef.current?.blur();
776 const { startLine, endLine } = normalizeFileCommentRange(range);
777 const draftEntry: FileCommentAnnotationEntry = {
778 id: nextFileCommentId(),
779 kind: "draft",
780 startLine,
781 endLine,
782 text: "",
783 };
784 setLineAnnotations((current) => {
785 const withoutDraft = current.flatMap((annotation) => {
786 const entries = annotation.metadata.entries.filter((entry) => entry.kind !== "draft");
787 return entries.length > 0 ? [{ ...annotation, metadata: { entries } }] : [];
788 });
789 const existingIndex = withoutDraft.findIndex(
790 (annotation) => annotation.lineNumber === endLine,
791 );
792 if (existingIndex < 0) {
793 return [
794 ...withoutDraft,
795 {
796 lineNumber: endLine,
797 metadata: { entries: [draftEntry] },
798 },
799 ];
800 }
801 return withoutDraft.map((annotation, index) =>
802 index === existingIndex
803 ? {
804 ...annotation,
805 metadata: { entries: [...annotation.metadata.entries, draftEntry] },
806 }
807 : annotation,
808 );
809 });
810 };
811 const hasOpenCommentForm = lineAnnotations.some((annotation) =>
812 annotation.metadata.entries.some((entry) => entry.kind === "draft"),
813 );
814 useEffect(() => {
815 const root = surfaceRef.current;
816 if (!root) return;
817 return installFileEditorDismissal({
818 root,
819 editor: { setSelections: (selections) => editorRef.current?.setSelections(selections) },
820 isBlocked: () => hasOpenCommentForm,
821 onDismiss: () => setSelectedRange(null),
822 });
823 }, [hasOpenCommentForm, setSelectedRange]);
824 const handleLineSelectionEnd = (range: SelectedLineRange | null) => {
825 setSelectedRange(range);
826 if (range) {
827 beginComment(range);
828 }
829 };
830​
831 const handlePostRender: FilePostRender = (fileContainer, instance, phase) => {
832 onPostRender(fileContainer, instance, phase);
833 onEditablePostRender(instance.file, phase);
834​
835 if (selectionFrameRef.current !== null) {
836 cancelAnimationFrame(selectionFrameRef.current);
837 selectionFrameRef.current = null;
838 }
839 if (phase === "unmount") return;
840​
841 selectionFrameRef.current = requestAnimationFrame(() => {
842 selectionFrameRef.current = null;
843 if (!fileContainer.isConnected) return;
844 instance.setSelectedLines(selectedRange, { notify: false });
845 });
846 };
847​
848 return (
849 <EditProvider createEditor={createFileEditor}>
850 <div ref={surfaceRef} className="flex min-h-0 flex-1">
851 <Virtualizer
852 className="file-preview-virtualizer min-h-0 flex-1 overflow-auto"
853 config={{
854 overscrollSize: 600,
855 intersectionObserverMargin: 1200,
856 }}
857 >
858 <File<FileCommentAnnotationGroup>
859 file={externalFile}
860 edit={editable}
861 editorOptions={editorOptions}
862 onEditChange={handleEditChange}
863 options={{
864 disableFileHeader: true,
865 enableGutterUtility: !hasOpenCommentForm,
866 enableLineSelection: !hasOpenCommentForm,
867 onGutterUtilityClick: setSelectedRange,
868 onLineSelectionChange: setSelectedRange,
869 onLineSelectionEnd: handleLineSelectionEnd,
870 overflow: wordWrap ? "wrap" : "scroll",
871 theme: resolveDiffThemeName(resolvedTheme),
872 preferredHighlighter: PREFERRED_HIGHLIGHTER,
873 themeType: resolvedTheme,
874 unsafeCSS: FILE_LINK_REVEAL_UNSAFE_CSS,
875 onPostRender: handlePostRender,
876 }}
877 selectedLines={selectedRange}
878 lineAnnotations={lineAnnotations}
879 renderAnnotation={(annotation) => (
880 <div className="py-1">
881 {annotation.metadata.entries.map((entry) => (
882 <DiffCommentAnnotation
883 key={entry.id}
884 kind={entry.kind}
885 rangeLabel={formatFileCommentRange(entry.startLine, entry.endLine)}
886 text={entry.text}
887 onCancel={() => removeAnnotationEntry(entry.id)}
888 onComment={(text) => submitAnnotationEntry(entry.id, text)}
889 onDelete={() => removeAnnotationEntry(entry.id)}
890 />
891 ))}
892 </div>
893 )}
894 className="min-h-full"
895 />
896 </Virtualizer>
897 </div>
898 </EditProvider>
899 );
901​
902function RenderedMarkdownSurface({
903 environmentId,
904 cwd,
905 relativePath,
906 contents,
907 threadRef,
908 workspaceMutationId,
909 readOnly,
910 onPendingChange,
911}: Omit<
912 EditableFileSurfaceProps,
913 | "resolvedTheme"
914 | "composerDraftTarget"
915 | "revealLine"
916 | "revealRequestId"
917 | "wordWrap"
918 | "onPostRender"
919> & {
920 threadRef: ScopedThreadRef;
921 readOnly: boolean;
922 workspaceMutationId: string | null;
923}) {
924 const saveCoordinator = useFileSaveCoordinator({
925 environmentId,
926 cwd,
927 relativePath,
928 onPendingChange,
929 });
930​
931 return (
932 <ScrollArea className="min-h-0 flex-1">
933 <FileMarkdownPreview
934 text={contents}
935 cwd={cwd}
936 relativePath={relativePath}
937 threadRef={threadRef}
938 workspaceMutationId={workspaceMutationId}
939 onTaskListChange={
940 readOnly
941 ? undefined
942 : ({ markerOffset, checked }) => {
943 const currentContents =
944 getOptimisticProjectFileQueryData(environmentId, cwd, relativePath)?.contents ??
945 contents;
946 const nextContents = setMarkdownTaskChecked(currentContents, markerOffset, checked);
947 if (nextContents === currentContents) return;
948 setProjectFileQueryData(environmentId, cwd, relativePath, nextContents);
949 saveCoordinator.change(nextContents);
950 }
951 }
952 />
953 </ScrollArea>
954 );
956​
957function renderedToggleLabel(mode: "markdown" | "html" | "table", rendered: boolean): string {
958 if (mode === "markdown") return rendered ? "Show markdown source" : "Show rendered markdown";
959 if (mode === "table") return rendered ? "Show source" : "Show table";
960 return rendered ? "Show HTML source" : "Show rendered page";
962​
963function initialExplorerOpen(): boolean {
964 try {
965 return getLocalStorageItem(FILE_EXPLORER_STORAGE_KEY, Schema.Boolean) ?? true;
966 } catch (error) {
967 console.error(error);
968 return true;
969 }
971​
972export default function FilePreviewPanel({
973 environmentId,
974 cwd,
975 projectName,
976 relativePath: requestedPath,
977 attachment,
978 threadRef,
979 composerDraftTarget,
980 keybindings,
981 availableEditors,
982 revealLine,
983 revealRequestId,
984 onOpenFile,
985 onNavigateFolder,
986 folderTrail,
987 onPendingChange,
988 selectedFilePending,
989 workspaceMutationId,
990}: FilePreviewPanelProps) {
991 const relativePath =
992 attachment === undefined ? resolveFilePreviewPath(requestedPath, cwd) : requestedPath;
993 const draft = typeof composerDraftTarget === "string";
994 const { resolvedTheme } = useTheme();
995 const wordWrap = useClientSettings((settings) => settings.wordWrap);
996 const canOperatePreview = useEnvironmentScope(environmentId, AuthPreviewOperateScope);
997 const primaryEnvironmentId = usePrimaryEnvironmentId();
998 const remoteOpenState = useRemoteOpenState(environmentId);
999 const serverConfig = useAtomValue(serverEnvironment.configValueAtom(environmentId));
1000 const environmentHttpBaseUrl = useEnvironmentHttpBaseUrl(environmentId);
1001 const previewAvailable = usePreviewAvailable(environmentId);
1002 const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
1003 reportFailure: false,
1004 });
1005 const openPreview = useAtomCommand(previewEnvironment.open, {
1006 reportFailure: false,
1007 });
1008 const isVideo = relativePath !== null && isWorkspaceVideoPreviewPath(relativePath);
1009 const isAudio = relativePath !== null && !isVideo && isWorkspaceAudioPreviewPath(relativePath);
1010 const isImage = relativePath !== null && !isVideo && isWorkspaceImagePreviewPath(relativePath);
1011 const isMedia = isImage || isVideo || isAudio;
1012 const isPdf = relativePath !== null && isPdfPreviewFile(relativePath);
1013 const isHtml = relativePath !== null && !isPdf && isBrowserPreviewFile(relativePath);
1014 const isHostFile =
1015 attachment !== undefined || (relativePath !== null && isAbsolutePath(relativePath));
1016 const fileAccess = useFilesystemReadAccess(environmentId);
1017 const { canReadFiles } = fileAccess;
1018 const canWriteFiles = useEnvironmentScope(environmentId, AuthFilesystemWriteScope);
1019 const file = useProjectFileQuery(
1020 environmentId,
1021 cwd,
1022 relativePath,
1023 attachment === undefined && relativePath !== null,
1024 );
1025 const attemptedPath = file.readError?.resolvedPath ?? file.readError?.operationPath;
1026 // A chat link cannot tell a folder from a file, so a folder arrives here as
1027 // a file surface and the read fails. Keep the breadcrumbs, drop the preview
1028 // pane, and let the tree fill the surface with the folder revealed. Mutation
1029 // refresh stays on so the surface notices if the path becomes a file. A host
1030 // folder outside the workspace gets a tree of its own, rooted at that folder.
1031 // `folderTrail` is set only when crumbs walked the browser up: the deeper path
1032 // kept for the way back down. The explorer (`""`) shows crumbs only then.
1033 const breadcrumbPath =
1034 attachment !== undefined ? null : (relativePath ?? (folderTrail === undefined ? null : ""));
1035 // A host trail that walked up to the workspace root (`/repo/project` is `""`) no
1036 // longer passes through the current path, so the crumbs start over there.
1037 const breadcrumbTrail =
1038 breadcrumbPath === null ? null : retainedBreadcrumbTrail(folderTrail, breadcrumbPath);
1039 // The trail only continues below folders, so a surface with one is a folder
1040 // before its read settles, and walking up never flashes a file preview.
1041 const isFolder =
1042 attachment === undefined &&
1043 (file.isNotFile || (folderTrail !== undefined && file.data === null && file.error === null));
1044 const hostFolderPath = isFolder && isHostFile ? relativePath : null;
1045 // A chat-linked folder reads as a file until its read settles, and revealing a
1046 // folder selects it in its parent instead of opening it, so reveal waits.
1047 const revealsInFileManager =
1048 !isFolder &&
1049 (file.data !== null || file.error !== null) &&
1050 serverConfig?.shellRevealInFileManager === true;
1051 // Everything preview-related keys off previewPath; a folder has no preview.
1052 const previewPath = isFolder ? null : relativePath;
1053 const [explorerOpen, setExplorerOpen] = useState(initialExplorerOpen);
1054 const showExplorer = shouldShowFileExplorer({
1055 relativePath: previewPath,
1056 explorerOpen,
1057 attachmentOpen: attachment !== undefined,
1058 });
1059 const [renderMarkdownPreferred, setRenderMarkdownPreferred] = useLocalStorage(
1060 RENDER_MARKDOWN_STORAGE_KEY,
1061 false,
1062 Schema.Boolean,
1063 );
1064 const [renderBrowserFilePreferred, setRenderBrowserFilePreferred] = useLocalStorage(
1065 RENDER_BROWSER_FILE_STORAGE_KEY,
1066 true,
1067 Schema.Boolean,
1068 );
1069 const [renderTablePreferred, setRenderTablePreferred] = useLocalStorage(
1070 RENDER_TABLE_STORAGE_KEY,
1071 true,
1072 Schema.Boolean,
1073 );
1074 // Paired with the path on purpose: each file surface counts its reveals from
1075 // one, so a bare id would let a dismissed reveal on one file swallow the first
1076 // reveal on the next.
1077 const [handledReveal, setHandledReveal] = useState<{ path: string; requestId: number } | null>(
1078 null,
1079 );
1080 const breadcrumbRef = useRef<HTMLDivElement>(null);
1081 const isMarkdown = previewPath ? isMarkdownPreviewFile(previewPath) : false;
1082 const tableDelimiter =
1083 previewPath && attachment === undefined ? filePreviewDelimiter({ name: previewPath }) : null;
1084 const revealHandled =
1085 revealLine === null ||
1086 (handledReveal?.path === relativePath && handledReveal.requestId === revealRequestId);
1087 const renderMarkdown = isMarkdown && renderMarkdownPreferred && revealHandled;
1088 const renderBrowserFile = isPdf || (isHtml && renderBrowserFilePreferred && revealHandled);
1089 const renderTable = tableDelimiter !== null && renderTablePreferred && revealHandled;
1090 const renderedMode = isMarkdown
1091 ? ("markdown" as const)
1092 : tableDelimiter
1093 ? ("table" as const)
1094 : isHtml
1095 ? ("html" as const)
1096 : null;
1097 const canToggleRendered =
1098 previewPath !== null && attachment === undefined && renderedMode !== null;
1099 const showsRawText =
1100 previewPath !== null &&
1101 file.data !== null &&
1102 !(isMarkdown && renderMarkdown) &&
1103 !(tableDelimiter && renderTable) &&
1104 !renderBrowserFile;
1105 const rendered = isMarkdown ? renderMarkdown : tableDelimiter ? renderTable : renderBrowserFile;
1106 const setRenderedPreferred = isMarkdown
1107 ? setRenderMarkdownPreferred
1108 : tableDelimiter
1109 ? setRenderTablePreferred
1110 : setRenderBrowserFilePreferred;
1111 const canOpenInBrowser =
1112 canOperatePreview &&
1113 previewPath !== null &&
1114 attachment === undefined &&
1115 !isVideo &&
1116 previewAvailable &&
1117 isBrowserPreviewFile(previewPath);
1118 // A file keeps its tab; walking up from it opens a folder browser beside it.
1119 // The trail's end keeps its own spelling (`C:/a` or `C:\a`), so it finds its tab.
1120 const navigateToFolder = (crumbPath: string) => {
1121 const path =
1122 breadcrumbTrail !== null && breadcrumbPathOf(breadcrumbTrail) === crumbPath
1123 ? breadcrumbTrail
1124 : crumbPath;
1125 onNavigateFolder(path, retainedBreadcrumbTrail(breadcrumbTrail ?? undefined, path), !isFolder);
1126 };
1127 const absolutePath =
1128 breadcrumbPath === ""
1129 ? cwd
1130 : relativePath && attachment === undefined
1131 ? resolvePathLinkTarget(relativePath, cwd)
1132 : null;
1133 const onFilePostRender = useFileLineReveal(relativePath, revealLine, revealRequestId);
1134 useWorkspaceMutationRefresh({
1135 enabled:
1136 attachment === undefined &&
1137 relativePath !== null &&
1138 // Media and PDFs never show their contents, so re-reading them on every
1139 // workspace mutation is waste. A folder named like one still re-reads, so
1140 // it notices when the path becomes a file.
1141 (isFolder || (!isMedia && !isPdf)) &&
1142 !selectedFilePending,
1143 mutationId: workspaceMutationId,
1144 refresh: file.refresh,
1145 resourceKey: `file:${environmentId}:${cwd}:${relativePath ?? ""}`,
1146 });
1147​
1148 useEffect(() => {
1149 const crumbs = breadcrumbRef.current?.querySelectorAll<HTMLElement>("[data-file-crumb]");
1150 // Show the deepest crumb when it fits, but never at the cost of the current one.
1151 crumbs?.[crumbs.length - 1]?.scrollIntoView({ block: "nearest", inline: "end" });
1152 breadcrumbRef.current
1153 ?.querySelector<HTMLElement>("[data-current-file-crumb='true']")
1154 ?.scrollIntoView({ block: "nearest", inline: "nearest" });
1155 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A new path or trail re-renders the crumbs, so the current one scrolls back into view.
1156 }, [breadcrumbPath, breadcrumbTrail]);
1157​
1158 const toggleExplorer = () => {
1159 setExplorerOpen((current) => {
1160 const next = !current;
1161 try {
1162 setLocalStorageItem(FILE_EXPLORER_STORAGE_KEY, next, Schema.Boolean);
1163 } catch (error) {
1164 console.error(error);
1166 return next;
1167 });
1168 };
1169​
1170 const handleOpenInBrowser = () => {
1171 if (!canReadFiles || !canOperatePreview || !absolutePath || !environmentHttpBaseUrl) return;
1172 void (async () => {
1173 const result = await openFileInPreview({
1174 threadRef,
1175 filePath: absolutePath,
1176 workspaceRoot: cwd,
1177 httpBaseUrl: environmentHttpBaseUrl,
1178 createAssetUrl,
1179 openPreview,
1180 });
1181 if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
1182 return;
1184 const error = squashAtomCommandFailure(result);
1185 toastManager.add(
1186 stackedThreadToast({
1187 type: "error",
1188 title: "Unable to open file in browser",
1189 description: error instanceof Error ? error.message : "An error occurred.",
1190 }),
1191 );
1192 })();
1193 };
1194​
1195 if (attachment === undefined && !canReadFiles) {
1196 if (fileAccess.isPending) {
1197 return (
1198 <div className="flex min-h-0 flex-1 items-center justify-center gap-2 text-sm text-muted-foreground">
1199 <Spinner className="size-4" />
1200 Checking file access...
1201 </div>
1202 );
1204 return (
1205 <div className="p-4 text-sm text-muted-foreground">
1206 {fileAccess.error ?? "This connection cannot read host files."}
1207 </div>
1208 );
1210​
1211 return (
1212 <div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-background">
1213 {breadcrumbPath !== null && breadcrumbTrail !== null ? (
1214 <div className={FILE_SURFACE_SUBHEADER_CLASS} data-surface-subheader>
1215 <ScrollArea
1216 radius="none"
1217 ref={breadcrumbRef}
1218 hideScrollbars
1219 scrollFade
1220 className="min-w-0 flex-1"
1221 data-file-breadcrumbs
1223 <div className="flex h-full w-max min-w-full items-center text-xs">
1224 <FileBreadcrumbs
1225 cwd={cwd}
1226 environmentId={environmentId}
1227 onNavigateFolder={navigateToFolder}
1228 onOpenFile={onOpenFile}
1229 projectName={projectName}
1230 relativePath={breadcrumbPath}
1231 trail={breadcrumbTrail}
1232 workspaceMutationId={workspaceMutationId}
1233 />
1234 </div>
1235 </ScrollArea>
1236 {absolutePath &&
1237 (environmentId === primaryEnvironmentId || remoteOpenState.mode !== "local-exec") ? (
1238 <OpenInPicker
1239 environmentId={environmentId}
1240 keybindings={keybindings}
1241 availableEditors={availableEditors}
1242 openInCwd={absolutePath}
1243 compact
1244 revealFileManager={revealsInFileManager}
1245 />
1246 ) : null}
1247 {canToggleRendered && renderedMode ? (
1248 <FileSurfaceAction
1249 label={renderedToggleLabel(renderedMode, rendered)}
1250 pressed={rendered}
1251 onPress={() => {
1252 const pressed = !rendered;
1253 setRenderedPreferred(pressed);
1254 setHandledReveal(
1255 pressed && relativePath !== null
1256 ? { path: relativePath, requestId: revealRequestId }
1257 : null,
1258 );
1259 }}
1261 <MorphIcon
1262 className="size-3.5"
1263 icon={rendered ? Code2 : renderedMode === "table" ? Table2 : Eye}
1264 />
1265 </FileSurfaceAction>
1266 ) : null}
1267 {showsRawText ? (
1268 <FileSurfaceAction
1269 label={wordWrap ? "Disable word wrap" : "Enable word wrap"}
1270 pressed={wordWrap}
1271 onPress={() => updateClientSettings({ wordWrap: !wordWrap })}
1273 <WrapTextIcon className="size-3.5" />
1274 </FileSurfaceAction>
1275 ) : null}
1276 {canOpenInBrowser ? (
1277 <FileSurfaceAction label="Open file in preview browser" onPress={handleOpenInBrowser}>
1278 <Globe2 className="size-3.5" />
1279 </FileSurfaceAction>
1280 ) : null}
1281 {!isHostFile && previewPath !== null ? (
1282 <FileSurfaceAction
1283 label={explorerOpen ? "Hide file explorer" : "Show file explorer"}
1284 pressed={explorerOpen}
1285 onPress={toggleExplorer}
1287 <FolderTree className="size-3.5" />
1288 </FileSurfaceAction>
1289 ) : null}
1290 </div>
1291 ) : null}
1292 {relativePath && !attachment && !isHostFile && !canWriteFiles && !fileAccess.isPending ? (
1293 <div className="shrink-0 border-b px-3 py-1.5 text-2xs text-muted-foreground">
1294 Read-only connection. Unsaved edits are kept until write access returns.
1295 </div>
1296 ) : null}
1297 {previewPath &&
1298 attachment === undefined &&
1299 !isMedia &&
1300 !renderBrowserFile &&
1301 file.data?.truncated ? (
1302 <div className="shrink-0 border-b border-warning/20 bg-warning-surface px-3 py-1.5 text-2xs text-warning-foreground">
1303 Preview limited to the first 1 MB of a {file.data.byteLength.toLocaleString()} byte file.
1304 </div>
1305 ) : null}
1306 <div className="flex min-h-0 flex-1 overflow-hidden">
1307 <div
1308 className={cn("min-w-0 flex-1 flex-col overflow-hidden", previewPath ? "flex" : "hidden")}
1310 {isFolder ? null : relativePath && attachment ? (
1311 <AttachmentFilePreview
1312 key={`${environmentId}:${attachment.id}`}
1313 name={attachment.name}
1314 mimeType={attachment.mimeType}
1315 sizeBytes={attachment.sizeBytes}
1316 asset={{ environmentId, attachmentId: attachment.id }}
1317 htmlRender={attachment.htmlRender === true}
1318 threadRef={threadRef}
1319 />
1320 ) : relativePath && isVideo && absolutePath ? (
1321 <WorkspaceVideoPreview
1322 key={`${environmentId}:${threadRef.threadId}:${absolutePath}`}
1323 environmentId={environmentId}
1324 threadRef={threadRef}
1325 draft={draft}
1326 absolutePath={absolutePath}
1327 workspaceRoot={cwd}
1328 name={relativePath}
1329 workspaceMutationId={workspaceMutationId}
1330 />
1331 ) : relativePath && isAudio && absolutePath ? (
1332 <WorkspaceAudioPreview
1333 key={`${environmentId}:${threadRef.threadId}:${absolutePath}`}
1334 environmentId={environmentId}
1335 threadRef={threadRef}
1336 draft={draft}
1337 absolutePath={absolutePath}
1338 workspaceRoot={cwd}
1339 name={relativePath}
1340 workspaceMutationId={workspaceMutationId}
1341 />
1342 ) : relativePath && isImage && absolutePath ? (
1343 <WorkspaceImagePreview
1344 key={absolutePath}
1345 environmentId={environmentId}
1346 threadRef={threadRef}
1347 draft={draft}
1348 absolutePath={absolutePath}
1349 workspaceRoot={cwd}
1350 alt={relativePath}
1351 workspaceMutationId={workspaceMutationId}
1352 />
1353 ) : relativePath && renderBrowserFile && absolutePath ? (
1354 <WorkspaceBrowserPreview
1355 key={absolutePath}
1356 environmentId={environmentId}
1357 threadRef={threadRef}
1358 draft={draft}
1359 absolutePath={absolutePath}
1360 workspaceRoot={cwd}
1361 title={relativePath}
1362 workspaceMutationId={workspaceMutationId}
1363 />
1364 ) : relativePath && file.error && file.data === null ? (
1365 <div
1366 role="alert"
1367 className="scrollbar-gutter-both flex min-h-0 flex-1 flex-col overflow-auto"
1369 <div className="my-auto flex shrink-0 flex-col gap-3 px-6 py-6 text-center text-xs leading-relaxed">
1370 <p className="text-destructive">
1371 {file.readError ? filePreviewReadErrorMessage(file.readError) : file.error}
1372 </p>
1373 {attemptedPath ? (
1374 <p className="text-muted-foreground">
1375 Attempted path
1376 <code className="block break-all font-mono text-foreground select-all">
1377 {attemptedPath}
1378 </code>
1379 </p>
1380 ) : null}
1381 {!isHostFile ? (
1382 <p className="text-muted-foreground">
1383 Workspace folder:{" "}
1384 <code className="break-all font-mono select-all">
1385 {file.readError?.cwd ?? cwd}
1386 </code>
1387 . Check the link's path or locate the file in Files.
1388 </p>
1389 ) : null}
1390 </div>
1391 </div>
1392 ) : relativePath && file.data === null ? (
1393 <div className="flex min-h-0 flex-1 items-center justify-center text-muted-foreground">
1394 <Spinner size="lg" />
1395 </div>
1396 ) : relativePath && file.data ? (
1397 isMarkdown && renderMarkdown ? (
1398 <RenderedMarkdownSurface
1399 key={relativePath}
1400 environmentId={environmentId}
1401 cwd={cwd}
1402 relativePath={relativePath}
1403 threadRef={threadRef}
1404 contents={file.data.contents}
1405 workspaceMutationId={workspaceMutationId}
1406 readOnly={isHostFile || !canWriteFiles}
1407 onPendingChange={onPendingChange}
1408 />
1409 ) : tableDelimiter && renderTable ? (
1410 <DelimitedTablePreview
1411 key={relativePath}
1412 name={relativePath}
1413 text={file.data.contents}
1414 delimiter={tableDelimiter}
1415 />
1416 ) : file.data.truncated || isHostFile || !canWriteFiles ? (
1417 <SourceFilePreview
1418 name={relativePath}
1419 text={file.data.contents}
1420 cacheKey={projectFileCacheKey(cwd, relativePath, file.data.contents)}
1421 onPostRender={onFilePostRender}
1422 />
1423 ) : (
1424 <DiffWorkerPoolProvider>
1425 <EditableFileSurface
1426 key={`${relativePath}:${resolvedTheme}`}
1427 environmentId={environmentId}
1428 cwd={cwd}
1429 relativePath={relativePath}
1430 composerDraftTarget={composerDraftTarget}
1431 contents={file.data.contents}
1432 resolvedTheme={resolvedTheme}
1433 revealRequestId={revealRequestId}
1434 wordWrap={wordWrap}
1435 onPostRender={onFilePostRender}
1436 onPendingChange={onPendingChange}
1437 />
1438 </DiffWorkerPoolProvider>
1440 ) : null}
1441 </div>
1442 {showExplorer ? (
1443 <aside
1444 className={cn(
1445 "flex min-h-0 shrink-0 bg-background",
1446 previewPath
1447 ? "w-[min(22rem,46%)] min-w-64 border-l border-border/60"
1448 : "min-w-0 flex-1",
1449 )}
1451 <FileBrowserPanel
1452 key={`${environmentId}:${hostFolderPath ?? cwd}`}
1453 environmentId={environmentId}
1454 cwd={hostFolderPath ?? cwd}
1455 projectName={hostFolderPath ?? projectName}
1456 hostFolder={hostFolderPath !== null}
1457 selectedPath={
1458 hostFolderPath === null
1459 ? relativePath
1460 : trailChildOf(hostFolderPath, breadcrumbTrail ?? hostFolderPath)
1462 selectedPathRevealId={revealRequestId}
1463 onOpenFile={onOpenFile}
1464 workspaceMutationId={workspaceMutationId}
1465 {...(previewPath && !isMedia && !isPdf
1466 ? { onRefreshSelectedFile: file.refresh }
1467 : {})}
1468 />
1469 </aside>
1470 ) : null}
1471 </div>
1472 </div>
1473 );