Files
t3code/apps/web/src/components/files/FilePreviewPanel.tsx
T

1509 lines
55 KiB
TypeScript

import { Spinner } from "~/components/ui/spinner";
import {
AuthPreviewOperateScope,
type EditorId,
type EnvironmentId,
type ResolvedKeybindingsConfig,
type ScopedThreadRef,
} from "@t3tools/contracts";
import { filePreviewDelimiter } from "@t3tools/shared/delimitedPreview";
import { AuthFilesystemWriteScope } from "@t3tools/contracts";
import {
isWorkspaceAudioPreviewPath,
isWorkspaceImagePreviewPath,
isWorkspaceVideoPreviewPath,
} from "@t3tools/shared/filePreview";
import {
DEFAULT_TOKENIZE_MAX_LENGTH,
VirtualizedFile,
getFiletypeFromFileName,
type File as FileInstance,
type FileContents,
type PostRenderPhase,
type SelectedLineRange,
} from "@pierre/diffs";
import {
Editor,
type EditorChangeEvent,
type EditorFactory,
type EditorOptions,
} from "@pierre/diffs/edit";
import type { WorkerPoolManager } from "@pierre/diffs/worker";
import { EditProvider, File, Virtualizer, useWorkerPool } from "@pierre/diffs/react";
import { DiffWorkerPoolProvider } from "../DiffWorkerPoolProvider";
import { useFilesystemReadAccess } from "~/state/filesystem";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { mediaFileReference } from "@t3tools/client-runtime/media-reference";
import { FolderTree, Globe2, WrapTextIcon } from "lucide-react";
import { Code2, Eye, Table2 } from "lucide";
import * as Schema from "effect/Schema";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { isBrowserPreviewFile, openFileInPreview } from "~/browser/openFileInPreview";
import { useAssetUrlRefresh, useAssetUrlState } from "~/assets/assetUrls";
import { OpenInPicker } from "~/components/chat/OpenInPicker";
import { MediaVideoPlayer } from "~/components/media/MediaVideoPlayer";
import { MediaActions, type MediaActionSource } from "~/components/media/MediaActions";
import { MorphIcon } from "~/components/MorphIcon";
import { useRemoteOpenState } from "~/remoteOpen";
import { useClientSettings, useUpdateClientSettings } from "~/hooks/useSettings";
import { useTheme } from "~/hooks/useTheme";
import { getLocalStorageItem, setLocalStorageItem, useLocalStorage } from "~/hooks/useLocalStorage";
import { useWorkspaceMutationRefresh } from "~/hooks/useWorkspaceMutationRefresh";
import { resolveDiffThemeName } from "~/lib/diffRendering";
import { PREFERRED_HIGHLIGHTER } from "~/lib/syntaxHighlighting";
import { cn } from "~/lib/utils";
import type { ChatFileAttachment } from "~/types";
import { isAbsolutePath } from "@t3tools/shared/path";
import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks";
import { ScrollArea } from "~/components/ui/scroll-area";
import { stackedThreadToast, toastManager } from "~/components/ui/toast";
import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
import { buildFileReviewComment } from "~/reviewCommentContext";
import { assetEnvironment } from "~/state/assets";
import { usePreviewAvailable } from "~/browser/previewRuntime";
import { useEnvironmentHttpBaseUrl, usePrimaryEnvironmentId } from "~/state/environments";
import { previewEnvironment } from "~/state/preview";
import { useEnvironmentScope } from "~/state/session";
import { useAtomCommand } from "~/state/use-atom-command";
import { useAtomQueryRunner } from "~/state/use-atom-query-runner";
import { AttachmentFilePreview } from "./AttachmentFilePreview";
import { AudioPreview } from "./AudioPreview";
import { BrowserDocumentFrame, isPdfPreviewFile } from "./BrowserDocumentFrame";
import { DelimitedTablePreview } from "./DelimitedTablePreview";
import FileBrowserPanel from "./FileBrowserPanel";
import { FileBreadcrumbs } from "./FileBreadcrumbs";
import { FileMarkdownPreview } from "./FileMarkdownPreview";
import {
type FileCommentAnnotationEntry,
type FileCommentAnnotationGroup,
type FileCommentLineAnnotation,
formatFileCommentRange,
nextFileCommentId,
normalizeFileCommentRange,
remapFileCommentAnnotations,
} from "./fileCommentAnnotations";
import { installFileEditorDismissal } from "./fileEditorDismissal";
import {
FILE_LINK_REVEAL_ATTRIBUTE,
FILE_LINK_REVEAL_UNSAFE_CSS,
FILE_SURFACE_SUBHEADER_CLASS,
FileSurfaceAction,
FileSurfaceFailure,
FileSurfaceLoading,
} from "./fileSurfaceChrome";
import SourceFilePreview from "./ReadOnlySourcePreview";
import { resolveCenteredFileLineScrollTop } from "./fileLineReveal";
import { DiffCommentAnnotation } from "../diffs/DiffCommentAnnotation";
import { projectFileCacheKey } from "./fileContentRevision";
import {
filePreviewReadErrorMessage,
isMarkdownPreviewFile,
resolveFilePreviewPath,
setMarkdownTaskChecked,
shouldShowFileExplorer,
workspaceAssetResource,
} from "./filePreviewMode";
import { useFileSaveCoordinator } from "./useFileSaveCoordinator";
import {
getOptimisticProjectFileQueryData,
getProjectFileContents,
setProjectFileQueryData,
useProjectFileQuery,
} from "./projectFilesQueryState";
interface FilePreviewPanelProps {
environmentId: EnvironmentId;
cwd: string;
projectName: string;
relativePath: string | null;
attachment?: ChatFileAttachment;
threadRef: ScopedThreadRef;
composerDraftTarget: ScopedThreadRef | DraftId;
keybindings: ResolvedKeybindingsConfig;
availableEditors: ReadonlyArray<EditorId>;
revealLine: number | null;
revealRequestId: number;
onOpenFile: (relativePath: string) => void;
onPendingChange: (relativePath: string, pending: boolean) => void;
selectedFilePending: boolean;
workspaceMutationId: string | null;
}
const FILE_EXPLORER_STORAGE_KEY = "t3code.fileExplorerOpen";
const RENDER_MARKDOWN_STORAGE_KEY = "t3code.renderMarkdown";
const RENDER_BROWSER_FILE_STORAGE_KEY = "t3code.renderBrowserFile";
const RENDER_TABLE_STORAGE_KEY = "t3code.renderTable";
// Shared by the read-only and annotated surfaces, so it is generic over annotation metadata.
type FilePostRender = <LAnnotation>(
fileContainer: HTMLElement,
instance: FileInstance<LAnnotation, undefined>,
phase: PostRenderPhase,
) => void;
function WorkspaceImagePreview(props: {
readonly environmentId: EnvironmentId;
readonly threadRef: ScopedThreadRef;
/** The thread is a draft the server does not know yet. */
readonly draft: boolean;
readonly absolutePath: string;
readonly workspaceRoot: string;
readonly alt: string;
readonly workspaceMutationId: string | null;
}) {
const resource = useMemo(
() =>
workspaceAssetResource({
kind: "workspace-file",
threadRef: props.threadRef,
draft: props.draft,
workspaceRoot: props.workspaceRoot,
absolutePath: props.absolutePath,
}),
[props.threadRef, props.draft, props.workspaceRoot, props.absolutePath],
);
const assetUrl = useAssetUrlState(props.environmentId, resource);
const [failedUrl, setFailedUrl] = useState<string | null>(null);
const revisionSuffix =
props.workspaceMutationId === null
? ""
: `${assetUrl._tag === "Success" && assetUrl.url.includes("?") ? "&" : "?"}workspace-revision=${encodeURIComponent(props.workspaceMutationId)}`;
const imageUrl = assetUrl._tag === "Success" ? `${assetUrl.url}${revisionSuffix}` : null;
const actionsSource: MediaActionSource = {
kind: "image",
name: props.alt,
src: imageUrl,
reference: mediaFileReference(props.absolutePath, props.workspaceRoot),
asset: { environmentId: props.environmentId, resource },
};
if (assetUrl._tag === "Failure" || (imageUrl !== null && failedUrl === imageUrl)) {
return (
<MediaActions source={actionsSource}>
<div className="flex min-h-0 flex-1 items-center justify-center px-6 text-center text-xs leading-relaxed text-destructive">
Unable to load workspace image.
</div>
</MediaActions>
);
}
return assetUrl._tag === "Success" && imageUrl !== null ? (
// oxlint-disable-next-line t3code/require-centered-scroll-gutter -- The image is capped at max-h-full max-w-full, so this never scrolls.
<div className="flex min-h-0 flex-1 items-center justify-center overflow-auto p-4">
<MediaActions source={actionsSource}>
<img
className="max-h-full max-w-full object-contain"
src={imageUrl}
alt={props.alt}
onError={() => setFailedUrl(imageUrl)}
/>
</MediaActions>
</div>
) : (
<div className="flex min-h-0 flex-1 items-center justify-center text-muted-foreground">
<Spinner size="lg" />
</div>
);
}
/**
* Renders an HTML or PDF file in place from its signed asset URL. HTML runs in
* a sandboxed frame with an opaque origin, so a page cannot reach the app's
* session or storage. A file inside the workspace may load sibling assets; a
* host file outside it is served on its own.
*/
function WorkspaceBrowserPreview(props: {
readonly environmentId: EnvironmentId;
readonly threadRef: ScopedThreadRef;
/** The thread is a draft the server does not know yet. */
readonly draft: boolean;
readonly absolutePath: string;
readonly workspaceRoot: string;
readonly title: string;
readonly workspaceMutationId: string | null;
}) {
const insideWorkspace =
mediaFileReference(props.absolutePath, props.workspaceRoot).relativePath !== undefined;
const resource = useMemo(
() =>
workspaceAssetResource({
kind: insideWorkspace ? "workspace-file" : "media-file",
threadRef: props.threadRef,
draft: props.draft,
workspaceRoot: props.workspaceRoot,
absolutePath: props.absolutePath,
}),
[insideWorkspace, props.threadRef, props.draft, props.workspaceRoot, props.absolutePath],
);
const assetUrl = useAssetUrlState(props.environmentId, resource);
const revisionSuffix =
props.workspaceMutationId === null
? ""
: `${assetUrl._tag === "Success" && assetUrl.url.includes("?") ? "&" : "?"}workspace-revision=${encodeURIComponent(props.workspaceMutationId)}`;
if (assetUrl._tag === "Failure") {
return (
<div className="flex min-h-0 flex-1 items-center justify-center px-6 text-center text-xs leading-relaxed text-destructive">
Unable to load file preview.
</div>
);
}
if (assetUrl._tag !== "Success") {
return (
<div className="flex min-h-0 flex-1 items-center justify-center text-muted-foreground">
<Spinner size="lg" />
</div>
);
}
return (
<BrowserDocumentFrame
src={`${assetUrl.url}${revisionSuffix}`}
title={props.title}
pdf={isPdfPreviewFile(props.absolutePath)}
/>
);
}
function WorkspaceVideoPreview(props: {
readonly environmentId: EnvironmentId;
readonly threadRef: ScopedThreadRef;
/** The thread is a draft the server does not know yet. */
readonly draft: boolean;
readonly absolutePath: string;
readonly workspaceRoot: string;
readonly name: string;
readonly workspaceMutationId: string | null;
}) {
const resource = useMemo(
() =>
workspaceAssetResource({
kind: "media-file",
threadRef: props.threadRef,
draft: props.draft,
workspaceRoot: props.workspaceRoot,
absolutePath: props.absolutePath,
}),
[props.threadRef, props.draft, props.workspaceRoot, props.absolutePath],
);
const assetUrl = useAssetUrlState(props.environmentId, resource);
const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, resource);
useWorkspaceMutationRefresh({
mutationId: props.workspaceMutationId,
resourceKey: JSON.stringify([props.environmentId, resource]),
refresh: () => {
// Failed refreshes flow through assetUrl and can be retried from the player.
void refreshAssetUrl().catch(() => undefined);
},
});
const revisionSuffix =
props.workspaceMutationId === null
? ""
: `${assetUrl._tag === "Success" && assetUrl.url.includes("?") ? "&" : "?"}workspace-revision=${encodeURIComponent(props.workspaceMutationId)}`;
const latestUrl = assetUrl._tag === "Success" ? `${assetUrl.url}${revisionSuffix}` : null;
return (
<div className="flex min-h-0 flex-1 items-center justify-center overflow-hidden p-4">
<MediaVideoPlayer
src={latestUrl}
sourceFailed={assetUrl._tag === "Failure"}
label={props.name}
revision={props.workspaceMutationId}
preload="metadata"
className="flex h-full min-h-0 w-full max-w-5xl items-center justify-center"
onRetry={refreshAssetUrl}
actionsSource={{
kind: "video",
name: props.name,
src: latestUrl,
reference: mediaFileReference(props.absolutePath, props.workspaceRoot),
asset: { environmentId: props.environmentId, resource },
}}
/>
</div>
);
}
function WorkspaceAudioPreview(props: {
readonly environmentId: EnvironmentId;
readonly threadRef: ScopedThreadRef;
/** The thread is a draft the server does not know yet. */
readonly draft: boolean;
readonly absolutePath: string;
readonly workspaceRoot: string;
readonly name: string;
readonly workspaceMutationId: string | null;
}) {
const resource = useMemo(
() =>
workspaceAssetResource({
kind: "media-file",
threadRef: props.threadRef,
draft: props.draft,
workspaceRoot: props.workspaceRoot,
absolutePath: props.absolutePath,
}),
[props.threadRef, props.draft, props.workspaceRoot, props.absolutePath],
);
const assetUrl = useAssetUrlState(props.environmentId, resource);
const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, resource);
const [failedUrl, setFailedUrl] = useState<string | null>(null);
useWorkspaceMutationRefresh({
mutationId: props.workspaceMutationId,
resourceKey: JSON.stringify([props.environmentId, resource]),
refresh: () => {
void refreshAssetUrl().catch(() => undefined);
},
});
const revisionSuffix =
props.workspaceMutationId === null
? ""
: `${assetUrl._tag === "Success" && assetUrl.url.includes("?") ? "&" : "?"}workspace-revision=${encodeURIComponent(props.workspaceMutationId)}`;
const url = assetUrl._tag === "Success" ? `${assetUrl.url}${revisionSuffix}` : null;
if (assetUrl._tag === "Failure" || (url !== null && failedUrl === url)) {
return (
<FileSurfaceFailure
message="Unable to load audio."
onRetry={() => {
setFailedUrl(null);
void refreshAssetUrl().catch(() => undefined);
}}
/>
);
}
if (url === null) return <FileSurfaceLoading />;
return <AudioPreview src={url} name={props.name} onError={() => setFailedUrl(url)} />;
}
function clampFileLine(contents: string, requestedLine: number): number {
let lineCount = 1;
for (let index = 0; index < contents.length; index += 1) {
const character = contents.charCodeAt(index);
if (character === 10) {
lineCount += 1;
} else if (character === 13) {
lineCount += 1;
if (contents.charCodeAt(index + 1) === 10) index += 1;
}
}
return Math.min(Math.max(1, requestedLine), lineCount);
}
function updateFileLinkReveal(fileContainer: HTMLElement, line: number | null): void {
const root = fileContainer.shadowRoot ?? fileContainer;
for (const element of root.querySelectorAll<HTMLElement>(`[${FILE_LINK_REVEAL_ATTRIBUTE}]`)) {
element.removeAttribute(FILE_LINK_REVEAL_ATTRIBUTE);
}
if (line === null) return;
root
.querySelector<HTMLElement>(`[data-line="${line}"]`)
?.setAttribute(FILE_LINK_REVEAL_ATTRIBUTE, "");
root
.querySelector<HTMLElement>(`[data-column-number="${line}"]`)
?.setAttribute(FILE_LINK_REVEAL_ATTRIBUTE, "");
}
/**
* Frames to keep retrying while the file contents or line metrics are not
* available yet (fresh mounts hydrate asynchronously).
*/
const REVEAL_MAX_ATTEMPTS = 30;
/**
* After scrolling to the target, hold it for a short window so late
* programmatic scroll resets (editable-editor focus and state restoration)
* cannot silently snap the file back to the top. Real user input cancels the
* guard immediately.
*/
const REVEAL_GUARD_FRAMES = 20;
const REVEAL_GUARD_TOLERANCE_PX = 2;
interface FileRevealState {
frameId: number | null;
cancelGuard: (() => void) | null;
handledRequestId: number | null;
latestRequestId: number | null;
}
function useFileLineReveal(
relativePath: string | null,
revealLine: number | null,
revealRequestId: number,
): FilePostRender {
const [revealStatesByPath] = useState(() => new Map<string, FileRevealState>());
return useCallback<FilePostRender>(
(fileContainer, instance, phase) => {
if (relativePath === null) return;
const existingState = revealStatesByPath.get(relativePath);
const state: FileRevealState = existingState ?? {
frameId: null,
cancelGuard: null,
handledRequestId: null,
latestRequestId: null,
};
if (!existingState) revealStatesByPath.set(relativePath, state);
const cancelPendingReveal = () => {
if (state.frameId !== null) {
cancelAnimationFrame(state.frameId);
state.frameId = null;
}
state.cancelGuard?.();
};
if (phase === "unmount") {
cancelPendingReveal();
return;
}
const contents = instance.file?.contents;
const targetLine =
revealLine === null || contents === undefined ? null : clampFileLine(contents, revealLine);
updateFileLinkReveal(fileContainer, targetLine);
if (!(instance instanceof VirtualizedFile)) return;
if (state.latestRequestId !== revealRequestId) {
cancelPendingReveal();
state.latestRequestId = revealRequestId;
state.handledRequestId = null;
}
if (revealLine === null) {
fileContainer.style.minHeight = "";
return;
}
const scrollContainer = fileContainer.closest<HTMLElement>(".file-preview-virtualizer");
if (!scrollContainer) return;
fileContainer.style.minHeight = `${Math.ceil(
Math.max(instance.height, scrollContainer.clientHeight),
)}px`;
if (state.handledRequestId === revealRequestId || state.frameId !== null) {
return;
}
const resolveScrollTarget = (line: number): number | null => {
const linePosition = instance.getLinePosition(line);
if (!linePosition) return null;
const scrollContainerRect = scrollContainer.getBoundingClientRect();
const fileTop =
scrollContainer.scrollTop +
fileContainer.getBoundingClientRect().top -
scrollContainerRect.top;
const root = fileContainer.shadowRoot ?? fileContainer;
const renderedLineElement = root.querySelector<HTMLElement>(`[data-line="${line}"]`);
const renderedLineRect = renderedLineElement?.getBoundingClientRect();
return resolveCenteredFileLineScrollTop({
scrollTop: scrollContainer.scrollTop,
scrollHeight: scrollContainer.scrollHeight,
viewportTop: scrollContainerRect.top,
viewportHeight: scrollContainer.clientHeight,
fileTop,
estimatedLine: linePosition,
...(renderedLineRect && renderedLineRect.height > 0
? {
renderedLine: {
top: renderedLineRect.top,
height: renderedLineRect.height,
},
}
: {}),
});
};
const guardScrollTarget = (line: number) => {
let framesLeft = REVEAL_GUARD_FRAMES;
let guardFrameId: number | null = null;
const cancelGuard = () => {
if (guardFrameId !== null) {
cancelAnimationFrame(guardFrameId);
guardFrameId = null;
}
scrollContainer.removeEventListener("wheel", cancelGuard);
scrollContainer.removeEventListener("touchstart", cancelGuard);
scrollContainer.removeEventListener("pointerdown", cancelGuard, true);
window.removeEventListener("keydown", cancelGuard, true);
if (state.cancelGuard === cancelGuard) state.cancelGuard = null;
};
scrollContainer.addEventListener("wheel", cancelGuard, { passive: true });
scrollContainer.addEventListener("touchstart", cancelGuard, { passive: true });
// Pierre stops gutter pointer events from bubbling. Listen in capture
// so starting a comment cancels the reveal guard before the row expands.
scrollContainer.addEventListener("pointerdown", cancelGuard, {
passive: true,
capture: true,
});
window.addEventListener("keydown", cancelGuard, true);
const holdTarget = () => {
guardFrameId = null;
framesLeft -= 1;
if (framesLeft <= 0 || !scrollContainer.isConnected) {
cancelGuard();
return;
}
const targetTop = resolveScrollTarget(line);
if (
targetTop !== null &&
Math.abs(scrollContainer.scrollTop - targetTop) > REVEAL_GUARD_TOLERANCE_PX
) {
scrollContainer.scrollTop = targetTop;
}
guardFrameId = requestAnimationFrame(holdTarget);
};
guardFrameId = requestAnimationFrame(holdTarget);
state.cancelGuard = cancelGuard;
};
const scheduleReveal = (attempt: number) => {
state.frameId = requestAnimationFrame(() => {
state.frameId = null;
if (state.latestRequestId !== revealRequestId || !fileContainer.isConnected) {
return;
}
// Contents and line metrics can lag the first post-render on fresh
// mounts; clamping against missing contents would scroll to line 1
// and wrongly mark the request handled.
const currentContents = instance.file?.contents;
const line =
currentContents === undefined ? null : clampFileLine(currentContents, revealLine);
const targetTop = line === null ? null : resolveScrollTarget(line);
if (line === null || targetTop === null) {
if (attempt < REVEAL_MAX_ATTEMPTS) scheduleReveal(attempt + 1);
return;
}
updateFileLinkReveal(fileContainer, line);
scrollContainer.scrollTop = targetTop;
state.handledRequestId = revealRequestId;
guardScrollTarget(line);
});
};
scheduleReveal(0);
},
[revealStatesByPath, relativePath, revealLine, revealRequestId],
);
}
const createFileEditor: EditorFactory<FileCommentAnnotationGroup, undefined> = (
editorType,
options,
editStateKey,
) => new Editor(editorType, options, editStateKey);
function editableFileContents(
environmentId: EnvironmentId,
cwd: string,
relativePath: string,
contents: string,
): FileContents {
return {
name: relativePath,
contents,
cacheKey: `editor:${environmentId}:${projectFileCacheKey(cwd, relativePath, contents)}`,
};
}
function needsWorkerHighlight(workerPool: WorkerPoolManager | undefined, file: FileContents) {
if (workerPool?.isWorkingPool() !== true) return false;
if ((file.lang ?? getFiletypeFromFileName(file.name)) === "text") return false;
let lines = 1;
for (
let index = file.contents.indexOf("\n");
index !== -1;
index = file.contents.indexOf("\n", index + 1)
) {
lines += 1;
}
return lines <= DEFAULT_TOKENIZE_MAX_LENGTH;
}
/**
* Pierre highlights an active edit session on the main thread, so each version
* of the file becomes editable only once it has rendered the worker's
* highlight. A failed worker highlight falls back to main-thread highlighting.
*/
function useEditableAfterHighlight(file: FileContents) {
const workerPool = useWorkerPool();
const [highlightedFile, setHighlightedFile] = useState<FileContents | null>(null);
const needsHighlight = useMemo(() => needsWorkerHighlight(workerPool, file), [file, workerPool]);
const ready = !needsHighlight || highlightedFile === file;
useEffect(() => {
if (ready || workerPool === undefined) return;
workerPool.primeFileHighlightCache(file).catch(() => setHighlightedFile(file));
}, [file, ready, workerPool]);
const onPostRender = useCallback(
(renderedFile: FileContents | undefined, phase: PostRenderPhase) => {
if (ready || phase === "unmount" || renderedFile?.cacheKey !== file.cacheKey) return;
// The pool caches a result just before the instance renders it, so a
// render that sees the cache has painted highlighted rows.
if (workerPool?.getFileResultCache(file) !== undefined) setHighlightedFile(file);
},
[file, ready, workerPool],
);
return { ready, onPostRender };
}
interface EditableFileSurfaceProps {
environmentId: EnvironmentId;
cwd: string;
relativePath: string;
composerDraftTarget: ScopedThreadRef | DraftId;
contents: string;
resolvedTheme: "light" | "dark";
revealRequestId: number;
wordWrap: boolean;
onPostRender: FilePostRender;
onPendingChange: (relativePath: string, pending: boolean) => void;
}
interface FileSelectionOverride {
revealRequestId: number;
range: SelectedLineRange | null;
}
function EditableFileSurface({
environmentId,
cwd,
relativePath,
composerDraftTarget,
contents,
resolvedTheme,
revealRequestId,
wordWrap,
onPostRender,
onPendingChange,
}: EditableFileSurfaceProps) {
const addReviewComment = useComposerDraftStore((store) => store.addReviewComment);
const removeReviewComment = useComposerDraftStore((store) => store.removeReviewComment);
const [lineAnnotations, setLineAnnotations] = useState<FileCommentLineAnnotation[]>([]);
const [selectionOverride, setSelectionOverride] = useState<FileSelectionOverride | null>(null);
const selectedRange =
selectionOverride?.revealRequestId === revealRequestId ? selectionOverride.range : null;
const setSelectedRange = useCallback(
(range: SelectedLineRange | null) => {
setSelectionOverride({ revealRequestId, range });
},
[revealRequestId],
);
const surfaceRef = useRef<HTMLDivElement>(null);
const selectionFrameRef = useRef<number | null>(null);
const saveCoordinator = useFileSaveCoordinator({
environmentId,
cwd,
relativePath,
onPendingChange,
});
// The editor owns the draft, so its own edits echoing back through the file
// query keep the file identity. Only a change from elsewhere replaces it.
const [externalFile, setExternalFile] = useState(() =>
editableFileContents(environmentId, cwd, relativePath, contents),
);
const [editedContents, setEditedContents] = useState<string | null>(null);
if (contents !== (editedContents ?? externalFile.contents)) {
setExternalFile(editableFileContents(environmentId, cwd, relativePath, contents));
setEditedContents(null);
}
const { ready: editable, onPostRender: onEditablePostRender } =
useEditableAfterHighlight(externalFile);
const editorRef = useRef<Editor<"file", FileCommentAnnotationGroup, undefined> | null>(null);
const editorOptions = useMemo<EditorOptions<"file", FileCommentAnnotationGroup, undefined>>(
() => ({
onAttach: (editor) => {
editorRef.current = editor;
},
onComplete: () => {
editorRef.current = null;
},
}),
[],
);
// Mirrors the draft out to the save queue, the optimistic file query and the
// composer's review comments.
const handleEditChange = useCallback(
({
file,
lineAnnotations: nextLineAnnotations,
}: EditorChangeEvent<"file", FileCommentAnnotationGroup, undefined>) => {
// Adopting an external change reports it as an edit; it is already on disk.
if (file.contents === getProjectFileContents(environmentId, cwd, relativePath)) return;
setEditedContents(file.contents);
setProjectFileQueryData(environmentId, cwd, relativePath, file.contents);
saveCoordinator.change(file.contents);
if (!nextLineAnnotations) return;
const remapped = remapFileCommentAnnotations(nextLineAnnotations);
// The editor hands back the array it was given until an edit moves an annotation.
setLineAnnotations((current) => (current === nextLineAnnotations ? current : remapped));
for (const annotation of remapped) {
for (const entry of annotation.metadata.entries) {
if (entry.kind !== "comment") continue;
addReviewComment(
composerDraftTarget,
buildFileReviewComment({
id: entry.id,
filePath: relativePath,
startLine: entry.startLine,
endLine: entry.endLine,
text: entry.text,
contents: file.contents,
}),
);
}
}
},
[addReviewComment, composerDraftTarget, cwd, environmentId, relativePath, saveCoordinator],
);
const removeAnnotationEntry = useCallback(
(entryId: string) => {
setSelectedRange(null);
removeReviewComment(composerDraftTarget, entryId);
setLineAnnotations((current) => {
return current.flatMap((annotation) => {
const entries = annotation.metadata.entries.filter((entry) => entry.id !== entryId);
return entries.length > 0 ? [{ ...annotation, metadata: { entries } }] : [];
});
});
},
[composerDraftTarget, removeReviewComment, setSelectedRange],
);
const submitAnnotationEntry = useCallback(
(entryId: string, text: string) => {
setSelectedRange(null);
const entry = lineAnnotations
.flatMap((annotation) => annotation.metadata.entries)
.find((candidate) => candidate.id === entryId);
if (entry) {
addReviewComment(
composerDraftTarget,
buildFileReviewComment({
id: entry.id,
filePath: relativePath,
startLine: entry.startLine,
endLine: entry.endLine,
text,
contents,
}),
);
}
setLineAnnotations((current) =>
current.map((annotation) => ({
...annotation,
metadata: {
entries: annotation.metadata.entries.map((annotationEntry) =>
annotationEntry.id === entryId
? { ...annotationEntry, kind: "comment", text }
: annotationEntry,
),
},
})),
);
},
[
addReviewComment,
composerDraftTarget,
contents,
lineAnnotations,
relativePath,
setSelectedRange,
],
);
const beginComment = useCallback((range: SelectedLineRange) => {
editorRef.current?.setSelections([]);
editorRef.current?.blur();
const { startLine, endLine } = normalizeFileCommentRange(range);
const draftEntry: FileCommentAnnotationEntry = {
id: nextFileCommentId(),
kind: "draft",
startLine,
endLine,
text: "",
};
setLineAnnotations((current) => {
const withoutDraft = current.flatMap((annotation) => {
const entries = annotation.metadata.entries.filter((entry) => entry.kind !== "draft");
return entries.length > 0 ? [{ ...annotation, metadata: { entries } }] : [];
});
const existingIndex = withoutDraft.findIndex(
(annotation) => annotation.lineNumber === endLine,
);
if (existingIndex < 0) {
return [
...withoutDraft,
{
lineNumber: endLine,
metadata: { entries: [draftEntry] },
},
];
}
return withoutDraft.map((annotation, index) =>
index === existingIndex
? {
...annotation,
metadata: { entries: [...annotation.metadata.entries, draftEntry] },
}
: annotation,
);
});
}, []);
const hasOpenCommentForm = lineAnnotations.some((annotation) =>
annotation.metadata.entries.some((entry) => entry.kind === "draft"),
);
useEffect(() => {
const root = surfaceRef.current;
if (!root) return;
return installFileEditorDismissal({
root,
editor: { setSelections: (selections) => editorRef.current?.setSelections(selections) },
isBlocked: () => hasOpenCommentForm,
onDismiss: () => setSelectedRange(null),
});
}, [hasOpenCommentForm, setSelectedRange]);
const handleLineSelectionEnd = useCallback(
(range: SelectedLineRange | null) => {
setSelectedRange(range);
if (range) {
beginComment(range);
}
},
[beginComment, setSelectedRange],
);
const handlePostRender = useCallback<FilePostRender>(
(fileContainer, instance, phase) => {
onPostRender(fileContainer, instance, phase);
onEditablePostRender(instance.file, phase);
if (selectionFrameRef.current !== null) {
cancelAnimationFrame(selectionFrameRef.current);
selectionFrameRef.current = null;
}
if (phase === "unmount") return;
selectionFrameRef.current = requestAnimationFrame(() => {
selectionFrameRef.current = null;
if (!fileContainer.isConnected) return;
instance.setSelectedLines(selectedRange, { notify: false });
});
},
[onEditablePostRender, onPostRender, selectedRange],
);
return (
<EditProvider createEditor={createFileEditor}>
<div ref={surfaceRef} className="flex min-h-0 flex-1">
<Virtualizer
className="file-preview-virtualizer min-h-0 flex-1 overflow-auto"
config={{
overscrollSize: 600,
intersectionObserverMargin: 1200,
}}
>
<File<FileCommentAnnotationGroup>
file={externalFile}
edit={editable}
editorOptions={editorOptions}
onEditChange={handleEditChange}
options={{
disableFileHeader: true,
enableGutterUtility: !hasOpenCommentForm,
enableLineSelection: !hasOpenCommentForm,
onGutterUtilityClick: setSelectedRange,
onLineSelectionChange: setSelectedRange,
onLineSelectionEnd: handleLineSelectionEnd,
overflow: wordWrap ? "wrap" : "scroll",
theme: resolveDiffThemeName(resolvedTheme),
preferredHighlighter: PREFERRED_HIGHLIGHTER,
themeType: resolvedTheme,
unsafeCSS: FILE_LINK_REVEAL_UNSAFE_CSS,
onPostRender: handlePostRender,
}}
selectedLines={selectedRange}
lineAnnotations={lineAnnotations}
renderAnnotation={(annotation) => (
<div className="py-1">
{annotation.metadata.entries.map((entry) => (
<DiffCommentAnnotation
key={entry.id}
kind={entry.kind}
rangeLabel={formatFileCommentRange(entry.startLine, entry.endLine)}
text={entry.text}
onCancel={() => removeAnnotationEntry(entry.id)}
onComment={(text) => submitAnnotationEntry(entry.id, text)}
onDelete={() => removeAnnotationEntry(entry.id)}
/>
))}
</div>
)}
className="min-h-full"
/>
</Virtualizer>
</div>
</EditProvider>
);
}
function RenderedMarkdownSurface({
environmentId,
cwd,
relativePath,
contents,
threadRef,
readOnly,
onPendingChange,
}: Omit<
EditableFileSurfaceProps,
| "resolvedTheme"
| "composerDraftTarget"
| "revealLine"
| "revealRequestId"
| "wordWrap"
| "onPostRender"
> & {
threadRef: ScopedThreadRef;
readOnly: boolean;
}) {
const saveCoordinator = useFileSaveCoordinator({
environmentId,
cwd,
relativePath,
onPendingChange,
});
return (
<ScrollArea className="min-h-0 flex-1">
<FileMarkdownPreview
text={contents}
cwd={cwd}
relativePath={relativePath}
threadRef={threadRef}
onTaskListChange={
readOnly
? undefined
: ({ markerOffset, checked }) => {
const currentContents =
getOptimisticProjectFileQueryData(environmentId, cwd, relativePath)?.contents ??
contents;
const nextContents = setMarkdownTaskChecked(currentContents, markerOffset, checked);
if (nextContents === currentContents) return;
setProjectFileQueryData(environmentId, cwd, relativePath, nextContents);
saveCoordinator.change(nextContents);
}
}
/>
</ScrollArea>
);
}
function renderedToggleLabel(mode: "markdown" | "html" | "table", rendered: boolean): string {
if (mode === "markdown") return rendered ? "Show markdown source" : "Show rendered markdown";
if (mode === "table") return rendered ? "Show source" : "Show table";
return rendered ? "Show HTML source" : "Show rendered page";
}
function initialExplorerOpen(): boolean {
try {
return getLocalStorageItem(FILE_EXPLORER_STORAGE_KEY, Schema.Boolean) ?? true;
} catch (error) {
console.error(error);
return true;
}
}
export default function FilePreviewPanel({
environmentId,
cwd,
projectName,
relativePath: requestedPath,
attachment,
threadRef,
composerDraftTarget,
keybindings,
availableEditors,
revealLine,
revealRequestId,
onOpenFile,
onPendingChange,
selectedFilePending,
workspaceMutationId,
}: FilePreviewPanelProps) {
const relativePath =
attachment === undefined ? resolveFilePreviewPath(requestedPath, cwd) : requestedPath;
// A draft's composer target is its draft id; a thread the server knows is a ref.
const draft = typeof composerDraftTarget === "string";
const { resolvedTheme } = useTheme();
const wordWrap = useClientSettings((settings) => settings.wordWrap);
const canOperatePreview = useEnvironmentScope(environmentId, AuthPreviewOperateScope);
const primaryEnvironmentId = usePrimaryEnvironmentId();
const remoteOpenState = useRemoteOpenState(environmentId);
const environmentHttpBaseUrl = useEnvironmentHttpBaseUrl(environmentId);
const previewAvailable = usePreviewAvailable(environmentId);
const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
reportFailure: false,
});
const openPreview = useAtomCommand(previewEnvironment.open, {
reportFailure: false,
});
const isVideo = relativePath !== null && isWorkspaceVideoPreviewPath(relativePath);
const isAudio = relativePath !== null && !isVideo && isWorkspaceAudioPreviewPath(relativePath);
const isImage = relativePath !== null && !isVideo && isWorkspaceImagePreviewPath(relativePath);
const isMedia = isImage || isVideo || isAudio;
// PDFs have no text to show; HTML has, and can toggle between page and source.
const isPdf = relativePath !== null && isPdfPreviewFile(relativePath);
const isHtml = relativePath !== null && !isPdf && isBrowserPreviewFile(relativePath);
// A file outside the workspace (an absolute path) is shown, never edited.
const isHostFile =
attachment !== undefined || (relativePath !== null && isAbsolutePath(relativePath));
const fileAccess = useFilesystemReadAccess(environmentId);
const { canReadFiles } = fileAccess;
const canWriteFiles = useEnvironmentScope(environmentId, AuthFilesystemWriteScope);
// Media and PDFs render from their absolute path, so their contents are never
// shown. The read still runs: a folder named `assets.png` is only knowable as a
// folder from the read failure, and the server stats before reading, so a folder
// costs an open and a stat and returns no body.
const file = useProjectFileQuery(
environmentId,
cwd,
relativePath,
attachment === undefined && relativePath !== null,
);
const attemptedPath = file.readError?.resolvedPath ?? file.readError?.operationPath;
// A chat link cannot tell a folder from a file, so a folder arrives here as
// a file surface and the read fails. Keep the breadcrumbs, drop the preview
// pane, and let the tree fill the surface with the folder revealed. Mutation
// refresh stays on so the surface notices if the path becomes a file. A host
// path cannot be revealed in the workspace tree, so it keeps the read error.
const isDirectory = file.isNotFile && !isHostFile;
// Everything preview-related keys off previewPath; a folder has no preview.
const previewPath = isDirectory ? null : relativePath;
const [explorerOpen, setExplorerOpen] = useState(initialExplorerOpen);
const showExplorer = shouldShowFileExplorer({
relativePath: previewPath,
explorerOpen,
attachmentOpen: attachment !== undefined,
});
// Reading markdown rendered is a preference, not a property of one file. Keeping
// it on the panel meant a thread switch dropped it and forced source back.
const [renderMarkdownPreferred, setRenderMarkdownPreferred] = useLocalStorage(
RENDER_MARKDOWN_STORAGE_KEY,
false,
Schema.Boolean,
);
const [renderBrowserFilePreferred, setRenderBrowserFilePreferred] = useLocalStorage(
RENDER_BROWSER_FILE_STORAGE_KEY,
true,
Schema.Boolean,
);
const [renderTablePreferred, setRenderTablePreferred] = useLocalStorage(
RENDER_TABLE_STORAGE_KEY,
true,
Schema.Boolean,
);
// Paired with the path on purpose: each file surface counts its reveals from
// one, so a bare id would let a dismissed reveal on one file swallow the first
// reveal on the next.
const [handledReveal, setHandledReveal] = useState<{ path: string; requestId: number } | null>(
null,
);
const breadcrumbRef = useRef<HTMLDivElement>(null);
const isMarkdown = previewPath ? isMarkdownPreviewFile(previewPath) : false;
const tableDelimiter =
previewPath && attachment === undefined ? filePreviewDelimiter({ name: previewPath }) : null;
// A reveal still wins over the preference: the line only exists in the source.
const revealHandled =
revealLine === null ||
(handledReveal?.path === relativePath && handledReveal.requestId === revealRequestId);
const renderMarkdown = isMarkdown && renderMarkdownPreferred && revealHandled;
const renderBrowserFile = isPdf || (isHtml && renderBrowserFilePreferred && revealHandled);
const renderTable = tableDelimiter !== null && renderTablePreferred && revealHandled;
const renderedMode = isMarkdown
? ("markdown" as const)
: tableDelimiter
? ("table" as const)
: isHtml
? ("html" as const)
: null;
const canToggleRendered =
previewPath !== null && attachment === undefined && renderedMode !== null;
const updateClientSettings = useUpdateClientSettings();
// Word wrap only reaches the text bodies. A rendered Markdown document, a table and the
// browser frame all lay themselves out, so the toggle stays hidden rather than inert.
const showsRawText =
previewPath !== null &&
file.data !== null &&
!(isMarkdown && renderMarkdown) &&
!(tableDelimiter && renderTable) &&
!renderBrowserFile;
const rendered = isMarkdown ? renderMarkdown : tableDelimiter ? renderTable : renderBrowserFile;
const setRenderedPreferred = isMarkdown
? setRenderMarkdownPreferred
: tableDelimiter
? setRenderTablePreferred
: setRenderBrowserFilePreferred;
const canOpenInBrowser =
canOperatePreview &&
previewPath !== null &&
attachment === undefined &&
!isVideo &&
previewAvailable &&
isBrowserPreviewFile(previewPath);
const absolutePath =
relativePath && attachment === undefined ? resolvePathLinkTarget(relativePath, cwd) : null;
const onFilePostRender = useFileLineReveal(relativePath, revealLine, revealRequestId);
useWorkspaceMutationRefresh({
enabled:
attachment === undefined &&
relativePath !== null &&
// Media and PDFs never show their contents, so re-reading them on every
// workspace mutation is waste. A folder named like one still re-reads, so
// it notices when the path becomes a file.
(isDirectory || (!isMedia && !isPdf)) &&
!selectedFilePending,
mutationId: workspaceMutationId,
refresh: file.refresh,
resourceKey: `file:${environmentId}:${cwd}:${relativePath ?? ""}`,
});
useEffect(() => {
const currentCrumb = breadcrumbRef.current?.querySelector<HTMLElement>(
"[data-current-file-crumb='true']",
);
currentCrumb?.scrollIntoView({ block: "nearest", inline: "end" });
}, [relativePath]);
const toggleExplorer = () => {
setExplorerOpen((current) => {
const next = !current;
try {
setLocalStorageItem(FILE_EXPLORER_STORAGE_KEY, next, Schema.Boolean);
} catch (error) {
console.error(error);
}
return next;
});
};
const handleOpenInBrowser = useCallback(() => {
if (!canReadFiles || !canOperatePreview || !absolutePath || !environmentHttpBaseUrl) return;
void (async () => {
const result = await openFileInPreview({
threadRef,
filePath: absolutePath,
workspaceRoot: cwd,
httpBaseUrl: environmentHttpBaseUrl,
createAssetUrl,
openPreview,
});
if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
return;
}
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Unable to open file in browser",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
})();
}, [
absolutePath,
canReadFiles,
canOperatePreview,
createAssetUrl,
cwd,
environmentHttpBaseUrl,
openPreview,
threadRef,
]);
if (attachment === undefined && !canReadFiles) {
if (fileAccess.isPending) {
return (
<div className="flex min-h-0 flex-1 items-center justify-center gap-2 text-sm text-muted-foreground">
<Spinner className="size-4" />
Checking file access...
</div>
);
}
return (
<div className="p-4 text-sm text-muted-foreground">
{fileAccess.error ?? "This connection cannot read host files."}
</div>
);
}
return (
<div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-background">
{relativePath && attachment === undefined ? (
<div className={FILE_SURFACE_SUBHEADER_CLASS} data-surface-subheader>
<ScrollArea
radius="none"
ref={breadcrumbRef}
hideScrollbars
scrollFade
className="min-w-0 flex-1"
data-file-breadcrumbs
>
<div className="flex h-full w-max min-w-full items-center text-xs">
<FileBreadcrumbs
cwd={cwd}
environmentId={environmentId}
onOpenFile={onOpenFile}
projectName={projectName}
relativePath={relativePath}
workspaceMutationId={workspaceMutationId}
/>
</div>
</ScrollArea>
{absolutePath &&
(environmentId === primaryEnvironmentId || remoteOpenState.mode !== "local-exec") ? (
<OpenInPicker
environmentId={environmentId}
keybindings={keybindings}
availableEditors={availableEditors}
openInCwd={absolutePath}
compact
/>
) : null}
{canToggleRendered && renderedMode ? (
<FileSurfaceAction
label={renderedToggleLabel(renderedMode, rendered)}
pressed={rendered}
onPress={() => {
const pressed = !rendered;
setRenderedPreferred(pressed);
setHandledReveal(
pressed && relativePath !== null
? { path: relativePath, requestId: revealRequestId }
: null,
);
}}
>
<MorphIcon
className="size-3.5"
icon={rendered ? Code2 : renderedMode === "table" ? Table2 : Eye}
/>
</FileSurfaceAction>
) : null}
{showsRawText ? (
<FileSurfaceAction
label={wordWrap ? "Disable word wrap" : "Enable word wrap"}
pressed={wordWrap}
onPress={() => updateClientSettings({ wordWrap: !wordWrap })}
>
<WrapTextIcon className="size-3.5" />
</FileSurfaceAction>
) : null}
{canOpenInBrowser ? (
<FileSurfaceAction label="Open file in preview browser" onPress={handleOpenInBrowser}>
<Globe2 className="size-3.5" />
</FileSurfaceAction>
) : null}
{!isHostFile && previewPath !== null ? (
<FileSurfaceAction
label={explorerOpen ? "Hide file explorer" : "Show file explorer"}
pressed={explorerOpen}
onPress={toggleExplorer}
>
<FolderTree className="size-3.5" />
</FileSurfaceAction>
) : null}
</div>
) : null}
{relativePath && !attachment && !isHostFile && !canWriteFiles && !fileAccess.isPending ? (
<div className="shrink-0 border-b px-3 py-1.5 text-2xs text-muted-foreground">
Read-only connection. Unsaved edits are kept until write access returns.
</div>
) : null}
{previewPath &&
attachment === undefined &&
!isMedia &&
!renderBrowserFile &&
file.data?.truncated ? (
<div className="shrink-0 border-b border-warning/20 bg-warning-surface px-3 py-1.5 text-2xs text-warning-foreground">
Preview limited to the first 1 MB of a {file.data.byteLength.toLocaleString()} byte file.
</div>
) : null}
<div className="flex min-h-0 flex-1 overflow-hidden">
<div
className={cn("min-w-0 flex-1 flex-col overflow-hidden", previewPath ? "flex" : "hidden")}
>
{isDirectory ? null : relativePath && attachment ? (
<AttachmentFilePreview
key={`${environmentId}:${attachment.id}`}
name={attachment.name}
mimeType={attachment.mimeType}
sizeBytes={attachment.sizeBytes}
asset={{ environmentId, attachmentId: attachment.id }}
htmlRender={attachment.htmlRender === true}
threadRef={threadRef}
/>
) : relativePath && isVideo && absolutePath ? (
<WorkspaceVideoPreview
key={`${environmentId}:${threadRef.threadId}:${absolutePath}`}
environmentId={environmentId}
threadRef={threadRef}
draft={draft}
absolutePath={absolutePath}
workspaceRoot={cwd}
name={relativePath}
workspaceMutationId={workspaceMutationId}
/>
) : relativePath && isAudio && absolutePath ? (
<WorkspaceAudioPreview
key={`${environmentId}:${threadRef.threadId}:${absolutePath}`}
environmentId={environmentId}
threadRef={threadRef}
draft={draft}
absolutePath={absolutePath}
workspaceRoot={cwd}
name={relativePath}
workspaceMutationId={workspaceMutationId}
/>
) : relativePath && isImage && absolutePath ? (
<WorkspaceImagePreview
key={absolutePath}
environmentId={environmentId}
threadRef={threadRef}
draft={draft}
absolutePath={absolutePath}
workspaceRoot={cwd}
alt={relativePath}
workspaceMutationId={workspaceMutationId}
/>
) : relativePath && renderBrowserFile && absolutePath ? (
<WorkspaceBrowserPreview
key={absolutePath}
environmentId={environmentId}
threadRef={threadRef}
draft={draft}
absolutePath={absolutePath}
workspaceRoot={cwd}
title={relativePath}
workspaceMutationId={workspaceMutationId}
/>
) : relativePath && file.error && file.data === null ? (
<div
role="alert"
className="scrollbar-gutter-both flex min-h-0 flex-1 flex-col overflow-auto"
>
<div className="my-auto flex shrink-0 flex-col gap-3 px-6 py-6 text-center text-xs leading-relaxed">
<p className="text-destructive">
{file.readError ? filePreviewReadErrorMessage(file.readError) : file.error}
</p>
{attemptedPath ? (
<p className="text-muted-foreground">
Attempted path
<code className="block break-all font-mono text-foreground select-all">
{attemptedPath}
</code>
</p>
) : null}
{!isHostFile ? (
<p className="text-muted-foreground">
Workspace folder:{" "}
<code className="break-all font-mono select-all">
{file.readError?.cwd ?? cwd}
</code>
. Check the link's path or locate the file in Files.
</p>
) : null}
</div>
</div>
) : relativePath && file.data === null ? (
<div className="flex min-h-0 flex-1 items-center justify-center text-muted-foreground">
<Spinner size="lg" />
</div>
) : relativePath && file.data ? (
isMarkdown && renderMarkdown ? (
// Markdown reconciles in place across text updates, so a file
// switch needs a new key or the previous file's disclosure and
// wrap state carries into the next document.
<RenderedMarkdownSurface
key={relativePath}
environmentId={environmentId}
cwd={cwd}
relativePath={relativePath}
threadRef={threadRef}
contents={file.data.contents}
readOnly={isHostFile || !canWriteFiles}
onPendingChange={onPendingChange}
/>
) : tableDelimiter && renderTable ? (
<DelimitedTablePreview
key={relativePath}
name={relativePath}
text={file.data.contents}
delimiter={tableDelimiter}
/>
) : file.data.truncated || isHostFile || !canWriteFiles ? (
<SourceFilePreview
name={relativePath}
text={file.data.contents}
cacheKey={projectFileCacheKey(cwd, relativePath, file.data.contents)}
onPostRender={onFilePostRender}
/>
) : (
<DiffWorkerPoolProvider>
<EditableFileSurface
key={`${relativePath}:${resolvedTheme}`}
environmentId={environmentId}
cwd={cwd}
relativePath={relativePath}
composerDraftTarget={composerDraftTarget}
contents={file.data.contents}
resolvedTheme={resolvedTheme}
revealRequestId={revealRequestId}
wordWrap={wordWrap}
onPostRender={onFilePostRender}
onPendingChange={onPendingChange}
/>
</DiffWorkerPoolProvider>
)
) : null}
</div>
{showExplorer ? (
<aside
className={cn(
"flex min-h-0 shrink-0 bg-background",
previewPath
? "w-[min(22rem,46%)] min-w-64 border-l border-border/60"
: "min-w-0 flex-1",
)}
>
<FileBrowserPanel
key={`${environmentId}:${cwd}`}
environmentId={environmentId}
cwd={cwd}
projectName={projectName}
selectedPath={relativePath}
selectedPathRevealId={revealRequestId}
onOpenFile={onOpenFile}
workspaceMutationId={workspaceMutationId}
{...(previewPath && !isMedia && !isPdf
? { onRefreshSelectedFile: file.refresh }
: {})}
/>
</aside>
) : null}
</div>
</div>
);
}