/** * FilePreview – renders a non-code file in the editor area. * * Supported types (auto-detected by extension): * • image – PNG / JPG / GIF / WebP / SVG / ICO / BMP * • pdf – inline * • markdown – react-markdown with GFM * • html – read-only sandboxed document * • csv – parsed table */ import { ExternalLink, FileWarning, LoaderCircle } from "lucide-react"; import { useEffect, useMemo, useState } from "react"; import { useTranslation } from "react-i18next"; import ReactMarkdown from "react-markdown"; import remarkGfm from "remark-gfm"; import { workspaceApi } from "../../api/modules/workspace"; import { buildAuthHeaders } from "../../api/authHeaders"; import { RenderableCodeBlock } from "../../components/RenderableCodeBlock"; import type { WorkspaceRoot } from "../../features/files-workspace/types"; import { ExternalMarkdownLink } from "../../components/Markdown/externalLinkComponents"; import { useAgentStore } from "../../stores/agentStore"; import { openHtmlFile } from "../../utils/openHtmlFile"; import { parseMarkdownFrontmatter } from "../../utils/markdown"; import styles from "./FilePreview.module.less"; // --------------------------------------------------------------------------- // Type detection // --------------------------------------------------------------------------- const IMAGE_EXTS = new Set([ "png", "jpg", "jpeg", "gif", "webp", "svg", "ico", "bmp", ]); export type PreviewType = | "image" | "pdf" | "markdown" | "html" | "csv" | "none"; export function getPreviewType(filePath: string): PreviewType { const ext = filePath.split(".").pop()?.toLowerCase() ?? ""; if (IMAGE_EXTS.has(ext)) return "image"; if (ext === "pdf") return "pdf"; if (ext === "md" || ext === "mdx") return "markdown"; if (ext === "html" || ext === "htm") return "html"; if (ext === "csv") return "csv"; return "none"; } export function isPreviewable(filePath: string): boolean { return getPreviewType(filePath) !== "none"; } // --------------------------------------------------------------------------- // CSV parser (no external dep) // --------------------------------------------------------------------------- function parseCsv(raw: string): string[][] { const lines = raw.trimEnd().split(/\r?\n/); return lines.map((line) => { const cells: string[] = []; let cur = ""; let inQuote = false; for (let i = 0; i < line.length; i++) { const ch = line[i]; if (ch === '"') { if (inQuote && line[i + 1] === '"') { cur += '"'; i++; } else { inQuote = !inQuote; } } else if (ch === "," && !inQuote) { cells.push(cur); cur = ""; } else { cur += ch; } } cells.push(cur); return cells; }); } // --------------------------------------------------------------------------- // Authenticated blob loader — browser-native / won't send // X-Agent-Id, so we fetch with headers and create an object URL. // // --------------------------------------------------------------------------- function useAuthBlobUrl( filePath: string, chatId?: string, binaryUrl?: string, root?: WorkspaceRoot, ): { blobUrl: string | null; loading: boolean; failed: boolean; } { const [blobUrl, setBlobUrl] = useState(null); const [loading, setLoading] = useState(true); const [failed, setFailed] = useState(false); const selectedAgent = useAgentStore((state) => state.selectedAgent); useEffect(() => { let revoked = false; setLoading(true); setFailed(false); const loadBlob = async (): Promise => { const url = binaryUrl ?? workspaceApi.getFileDownloadUrl(filePath, root); const res = await fetch(url, { headers: { ...buildAuthHeaders(), ...(chatId ? { "X-Chat-Id": chatId } : {}), }, }); if (!res.ok) throw new Error(`${res.status}`); return res.blob(); }; loadBlob() .then((blob) => { if (revoked || !blob) return; setBlobUrl(URL.createObjectURL(blob)); setLoading(false); }) .catch(() => { if (!revoked) { setBlobUrl(null); setLoading(false); setFailed(true); } }); return () => { revoked = true; setBlobUrl((prev) => { if (prev) URL.revokeObjectURL(prev); return null; }); }; }, [binaryUrl, chatId, filePath, root, selectedAgent]); return { blobUrl, loading, failed }; } // --------------------------------------------------------------------------- // Sub-renderers // --------------------------------------------------------------------------- function ImagePreview({ filePath, chatId, binaryUrl, root, }: { filePath: string; chatId?: string; binaryUrl?: string; root?: WorkspaceRoot; }) { const { t } = useTranslation(); const { blobUrl, loading, failed } = useAuthBlobUrl( filePath, chatId, binaryUrl, root, ); if (loading) { return ( } spinning> {t("common.loading")} ); } if (failed || !blobUrl) { return ( }> {t("files.loadFailed")} ); } return (
{filePath.split("/").pop()}
); } function PdfPreview({ filePath, chatId, binaryUrl, root, }: { filePath: string; chatId?: string; binaryUrl?: string; root?: WorkspaceRoot; }) { const { t } = useTranslation(); const { blobUrl, loading, failed } = useAuthBlobUrl( filePath, chatId, binaryUrl, root, ); if (loading) { return ( } spinning> {t("common.loading")} ); } if (failed || !blobUrl) { return ( }> {t("files.loadFailed")} ); } return ( ); } function PreviewStatus({ children, icon, spinning = false, }: { children: React.ReactNode; icon: React.ReactNode; spinning?: boolean; }) { return (
{icon} {children}
); } const markdownComponents = { a: ExternalMarkdownLink, pre({ children }: { children?: React.ReactNode }) { return <>{children}; }, code({ node, inline, className, children, ...rest }: React.ComponentPropsWithoutRef<"code"> & { node?: unknown; inline?: boolean; }) { void node; void inline; const match = /language-([\w-]+)/.exec(className || ""); return ( {children} ); }, }; function MarkdownPreview({ content }: { content: string }) { const { body, entries } = useMemo( () => parseMarkdownFrontmatter(content), [content], ); return (
{entries.length > 0 && (
{entries.map(({ key, value }, index) => (
{key}
{value}
))}
)} {body}
); } function buildReadOnlyHtml(content: string): string { const document = new DOMParser().parseFromString(content, "text/html"); document .querySelectorAll("script, meta[http-equiv='refresh']") .forEach((element) => element.remove()); document.querySelectorAll("*").forEach((element) => { Array.from(element.attributes).forEach((attribute) => { if (attribute.name.toLowerCase().startsWith("on")) { element.removeAttribute(attribute.name); } }); element.removeAttribute("contenteditable"); }); document.querySelectorAll("a").forEach((element) => { element.removeAttribute("href"); element.removeAttribute("target"); element.removeAttribute("download"); }); document.querySelectorAll("form").forEach((element) => { element.removeAttribute("action"); element.removeAttribute("method"); }); document .querySelectorAll("button, input, select, textarea") .forEach((element) => element.setAttribute("disabled", "")); const style = document.createElement("style"); style.textContent = [ "a, button, input, select, textarea, form, iframe, object, embed,", "audio, video, [contenteditable] { pointer-events: none !important; }", ].join(" "); document.head.appendChild(style); return `\n${document.documentElement.outerHTML}`; } function HtmlPreview({ content, filePath, chatId, projectDirOverride, root, workspaceBacked, }: FilePreviewProps) { const { t } = useTranslation(); const readOnlyHtml = useMemo(() => buildReadOnlyHtml(content), [content]); return (