Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7650: attachment viewer — CSV tables, JSON/YAML tree, numbered code, HTML viewports, every kind in a new tab (#8868)
Jiayuan Zhang6dc6a0b9a2db
diff --git a/apps/web/app/[workspaceSlug]/attachments/[id]/preview/page.tsx b/apps/web/app/[workspaceSlug]/attachments/[id]/preview/page.tsxindex 6c7f785e8b..ac57617f16 100644--- a/apps/web/app/[workspaceSlug]/attachments/[id]/preview/page.tsx+++ b/apps/web/app/[workspaceSlug]/attachments/[id]/preview/page.tsx@@ -7,8 +7,8 @@ import { ErrorBoundary } from "@multica/ui/components/common/error-boundary";// Lives at /:slug/attachments/:id/preview — OUTSIDE the (dashboard) group on// purpose. The dashboard layout adds a left sidebar + top chrome; this page-// wants the full viewport for the HTML iframe. Workspace resolution still-// happens in the parent [workspaceSlug] layout so useWorkspaceId() works.+// wants the full viewport for the file. Workspace resolution still happens in+// the parent [workspaceSlug] layout so useWorkspaceId() works.export default function AttachmentPreviewWebPage({params,}: {diff --git a/packages/ui/components/ui/data-table.tsx b/packages/ui/components/ui/data-table.tsxindex 1c8c7a3fae..5d2b5d4401 100644--- a/packages/ui/components/ui/data-table.tsx+++ b/packages/ui/components/ui/data-table.tsx@@ -411,6 +411,7 @@ export function DataTable<TData>({<TableRow key={headerGroup.id} className="hover:bg-transparent">{headerGroup.headers.map((header) => {const isPinned = header.column.getIsPinned();+ const sorted = header.column.getIsSorted();const columnHasExplicitSize = hasExplicitSize(header.column.id,);@@ -425,6 +426,16 @@ export function DataTable<TData>({// Lets a drag measure every column by id instead of// pairing <th> elements with columns positionally.data-column-id={header.column.id}+ // Only a table sorted through TanStack's own sorting+ // state says so; views that order rows themselves+ // leave every header unmarked.+ aria-sort={+ sorted === "asc"+ ? "ascending"+ : sorted === "desc"+ ? "descending"+ : undefined+ }// Marks the frozen block's trailing edge for the scroll// shadow to measure against. Rendered widths differ from// configured ones under fixed table-layout, so thediff --git a/packages/views/attachments/attachment-preview-page.test.tsx b/packages/views/attachments/attachment-preview-page.test.tsxindex 617e6650ef..d875efcd22 100644--- a/packages/views/attachments/attachment-preview-page.test.tsx+++ b/packages/views/attachments/attachment-preview-page.test.tsx@@ -1,62 +1,170 @@-import { describe, expect, it, vi } from "vitest";-import { render } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { screen, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import type { ReactElement } from "react";+import type { Attachment } from "@multica/core/types";import type { ScrollRestorationAdapter } from "../platform";import { ScrollRestorationProvider } from "../platform";+import { renderWithI18n } from "../test/i18n";import { AttachmentPreviewPage } from "./attachment-preview-page";import { hashString } from "../editor/utils/hash-string";import { buildScrollBridge } from "../editor/utils/iframe-scroll-bridge";const htmlText = "<html><body><h1>Report</h1></body></html>";-vi.mock("../editor/hooks/use-attachment-html-text", () => ({- useAttachmentHtmlText: () => ({- data: { text: htmlText },- isLoading: false,- error: null,- }),+const { getAttachmentMock, getAttachmentTextContentMock } = vi.hoisted(() => ({+ getAttachmentMock: vi.fn(),+ getAttachmentTextContentMock: vi.fn(),+}));++vi.mock("@multica/core/api", () => ({+ api: {+ getAttachment: getAttachmentMock,+ getAttachmentTextContent: getAttachmentTextContentMock,+ getBaseUrl: () => "",+ },+ PreviewTooLargeError: class extends Error {},+ PreviewUnsupportedError: class extends Error {},}));-vi.mock("../i18n", () => ({- useT: () => (fn: (d: Record<string, unknown>) => string) =>- fn({ attachment: { preview_loading: "l", preview_failed: "f" } }),+vi.mock("../editor/use-download-attachment", () => ({+ useDownloadAttachment: () => vi.fn(),}));+vi.mock("@tanstack/react-virtual", () => ({+ useVirtualizer: ({ count }: { count: number }) => ({+ getVirtualItems: () =>+ Array.from({ length: count }, (_, index) => ({+ index,+ key: index,+ start: index * 37,+ end: (index + 1) * 37,+ size: 37,+ })),+ getTotalSize: () => count * 37,+ measureElement: () => {},+ }),+}));++function makeAttachment(overrides: Partial<Attachment>): Attachment {+ return {+ id: "att-1",+ workspace_id: "ws-1",+ issue_id: null,+ comment_id: null,+ chat_session_id: null,+ chat_message_id: null,+ uploader_type: "member",+ uploader_id: "u-1",+ filename: "report.html",+ url: "https://cdn.example.test/att-1",+ download_url: "https://cdn.example.test/att-1?Signature=s",+ markdown_url: "https://cdn.example.test/att-1",+ content_type: "text/html",+ size_bytes: 1024,+ created_at: "2026-05-13T00:00:00Z",+ ...overrides,+ };+}++function renderPage(ui: ReactElement) {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ return renderWithI18n(<QueryClientProvider client={client}>{ui}</QueryClientProvider>);+}++beforeEach(() => {+ getAttachmentMock.mockReset();+ getAttachmentTextContentMock.mockReset();+ getAttachmentMock.mockResolvedValue(makeAttachment({}));+ getAttachmentTextContentMock.mockResolvedValue({+ text: htmlText,+ originalContentType: "text/html",+ });+});+describe("AttachmentPreviewPage", () => {- it("injects the scroll bridge under the desktop adapter and keys the iframe on contentKey", () => {+ it("shows the viewer's bar and stage — without a close button, since the tab is the frame", async () => {+ renderPage(<AttachmentPreviewPage attachmentId="att-1" filename="report.html" />);++ expect(await screen.findByTitle("report.html")).toBeTruthy();+ expect(screen.getByText("report.html")).toBeTruthy();+ expect(screen.getByRole("button", { name: "Download" })).toBeTruthy();+ expect(screen.getByRole("button", { name: "Fit" })).toHaveAttribute("aria-pressed", "true");+ expect(screen.queryByRole("button", { name: "Close" })).toBeNull();+ expect(screen.queryByRole("button", { name: "Open in new tab" })).toBeNull();+ expect(document.title).toBe("report.html");+ });++ it("injects the scroll bridge under the desktop adapter and keys the iframe on contentKey", async () => {const adapter: ScrollRestorationAdapter = {get: () => undefined,registerExternalSource: vi.fn(),};- const { container } = render(+ renderPage(<ScrollRestorationProvider adapter={adapter}><AttachmentPreviewPage attachmentId="att-1" /></ScrollRestorationProvider>,);- const iframe = container.querySelector("iframe")!;- expect(iframe).toBeTruthy();- expect(iframe.getAttribute("srcdoc")).toContain(- buildScrollBridge(hashString(htmlText)),- );- // React only exposes `key` via the reconciled element, but we can assert- // the bridge was built for the expected token — that's the signal the- // component derived contentKey from the text.+ const iframe = await screen.findByTitle("report.html");+ expect(iframe.getAttribute("srcdoc")).toContain(buildScrollBridge(hashString(htmlText)));+ // The iframe stays inside the sandbox the viewer uses.+ expect(iframe.getAttribute("sandbox")).toBe("allow-scripts");expect(adapter.registerExternalSource).toHaveBeenCalledWith("html-iframe",expect.objectContaining({ capture: expect.any(Function) }),);});- it("does NOT inject the bridge or register a source on web (adapter without registerExternalSource)", () => {+ it("does NOT inject the bridge or register a source on web (adapter without registerExternalSource)", async () => {const webAdapter: ScrollRestorationAdapter = { get: () => undefined };- const { container } = render(+ renderPage(<ScrollRestorationProvider adapter={webAdapter}><AttachmentPreviewPage attachmentId="att-1" /></ScrollRestorationProvider>,);- const iframe = container.querySelector("iframe")!;+ const iframe = await screen.findByTitle("report.html");expect(iframe.getAttribute("srcdoc")).not.toContain("__multica");expect(iframe.getAttribute("srcdoc")).not.toContain(buildScrollBridge("x"));// Still applies the fragment-nav shim on both surfaces.expect(iframe.getAttribute("srcdoc")).toContain("scrollIntoView");});++ it("shows an image", async () => {+ getAttachmentMock.mockResolvedValue(+ makeAttachment({ filename: "shot.png", content_type: "image/png" }),+ );+ renderPage(<AttachmentPreviewPage attachmentId="att-1" />);+ const img = await screen.findByAltText("shot.png");+ expect(img.getAttribute("src")).toBe("https://cdn.example.test/att-1?Signature=s");+ });++ it("shows a CSV as a table", async () => {+ getAttachmentMock.mockResolvedValue(+ makeAttachment({ filename: "report.csv", content_type: "text/csv" }),+ );+ getAttachmentTextContentMock.mockResolvedValue({+ text: "name,count\nalpha,3\n",+ originalContentType: "text/csv",+ });+ renderPage(<AttachmentPreviewPage attachmentId="att-1" />);+ expect(await screen.findByTestId("table-preview")).toBeTruthy();+ expect(screen.getByText("alpha")).toBeTruthy();+ });++ it("titles the tab from the URL's name until the record lands", () => {+ getAttachmentMock.mockReturnValue(new Promise(() => {}));+ renderPage(<AttachmentPreviewPage attachmentId="att-1" filename="from-url.pdf" />);+ expect(screen.getByText("Loading preview…")).toBeTruthy();+ expect(document.title).toBe("from-url.pdf");+ });++ it("says the preview failed when the record cannot be loaded", async () => {+ getAttachmentMock.mockRejectedValue(new Error("404"));+ renderPage(<AttachmentPreviewPage attachmentId="att-1" />);+ await waitFor(() =>+ expect(screen.getByTestId("attachment-preview-page-error")).toHaveTextContent(+ "Couldn't load preview",+ ),+ );+ });});diff --git a/packages/views/attachments/attachment-preview-page.tsx b/packages/views/attachments/attachment-preview-page.tsxindex 6a950eeb9d..9ba1948e0a 100644--- a/packages/views/attachments/attachment-preview-page.tsx+++ b/packages/views/attachments/attachment-preview-page.tsx@@ -1,32 +1,42 @@"use client";/**- * AttachmentPreviewPage — full-page HTML attachment viewer.+ * AttachmentPreviewPage — any attachment on a page of its own.*- * Destination for "Open in new tab" in the attachment viewer's html kind. The- * viewer shows the same content inside its stage; this is the same content- * edge-to-edge so the user can resize / interact with the document at full- * size.+ * Destination for "Open in new tab" in the attachment viewer, for every kind+ * the viewer shows. It renders the viewer's own top bar and stage+ * (`AttachmentPreviewStandalone`) so a file looks and behaves the same in both+ * places — the HTML viewport switch, a table's sorting, a log's line wrapping+ * — just with the whole tab to itself.*- * Same security posture as the viewer: iframe sandbox is- * "allow-scripts" only — no allow-same-origin, no allow-top-navigation. The- * iframe runs in an opaque origin and cannot reach cookies, localStorage,- * parent, or top-level navigation.+ * The attachment record is loaded by id: the URL carries nothing else but the+ * display name (`?name=`), which titles the tab until the record lands.+ *+ * HTML keeps the viewer's security posture: iframe sandbox "allow-scripts"+ * only — no allow-same-origin, no allow-top-navigation — so the document runs+ * in an opaque origin and cannot reach cookies, localStorage, parent, or+ * top-level navigation. Here the iframe also reports its scroll position so a+ * desktop tab switch puts the reader back where they were.** The route is workspace-scoped (`/{slug}/attachments/{id}/preview`) for- * tenancy isolation; the `/api/attachments/{id}/content` proxy itself is- * already auth-checked, so the slug is purely a URL contract.+ * tenancy isolation; the attachment endpoints themselves are auth-checked, so+ * the slug is purely a URL contract.*/import { useEffect } from "react";+import { useQuery } from "@tanstack/react-query";+import { Loader2 } from "lucide-react";+import { api } from "@multica/core/api";import { useT } from "../i18n";-import { useAttachmentHtmlText } from "../editor/hooks/use-attachment-html-text";+import {+ AttachmentPreviewStandalone,+ type HtmlFrameRenderer,+} from "../editor/attachment-preview-modal";import { useHtmlPreviewScrollRestore } from "./use-html-preview-scroll-restore";interface AttachmentPreviewPageProps {attachmentId: string;- /** Optional display name. Falls back to a generic label and is only used- * for the document title — never echoed into the iframe sandbox. */+ /** Optional display name. Titles the tab until the record has loaded. */filename?: string;}@@ -35,51 +45,71 @@ export function AttachmentPreviewPage({filename,}: AttachmentPreviewPageProps) {const { t } = useT("editor");- const query = useAttachmentHtmlText(attachmentId);-- const text = query.data?.text;-- // Scroll-position restoration across desktop tab switches (multica-ai#6405).- // No-op on web (no desktop adapter). The iframe is keyed on contentKey so a- // content change (re-upload) structurally remounts a fresh document; the- // hook reports y=0 with the new key until that document scrolls, and- // messages from the previous document are dropped by token.- const { contentKey, buildSrcDoc, iframeRef, onLoad } =- useHtmlPreviewScrollRestore(text);+ const query = useQuery({+ queryKey: ["attachment-preview-page", attachmentId] as const,+ queryFn: () => api.getAttachment(attachmentId),+ // The record carries signed media URLs. Refetching would re-sign them and+ // reload a playing video or an open PDF under the reader; one fetch per+ // page view is enough.+ staleTime: Infinity,+ refetchOnWindowFocus: false,+ retry: false,+ });+ const attachment = query.data?.id ? query.data : null;// Set document.title so desktop's MutationObserver-based tab title picks// up the filename. Web shows the same string in the browser tab.+ const title = attachment?.filename || filename;useEffect(() => {- if (filename) document.title = filename;- }, [filename]);+ if (title) document.title = title;+ }, [title]);- const isLoading = query.isLoading;- const isError = !isLoading && (!!query.error || !text);+ if (attachment) {+ return (+ <AttachmentPreviewStandalone+ attachment={attachment}+ renderHtmlFrame={renderPageHtmlFrame}+ />+ );+ }return (- <div className="flex h-full w-full flex-col bg-background">- {isLoading ? (- <div className="flex flex-1 items-center justify-center text-body text-muted-foreground">+ <div className="dark flex h-full w-full items-center justify-center gap-2 bg-black/95 px-4 text-body text-muted-foreground">+ {query.isLoading ? (+ <>+ <Loader2 className="size-4 animate-spin" />{t(($) => $.attachment.preview_loading)}- </div>- ) : isError ? (- <div- className="flex flex-1 items-center justify-center px-4 text-body text-muted-foreground"- data-testid="attachment-preview-page-error"- >- {t(($) => $.attachment.preview_failed)}- </div>+ </>) : (- <iframe- key={contentKey}- ref={iframeRef}- onLoad={onLoad}- srcDoc={buildSrcDoc(text as string)}- sandbox="allow-scripts"- title={filename ?? "HTML attachment"}- className="flex-1 w-full border-0 bg-background"- />+ <span data-testid="attachment-preview-page-error">+ {t(($) => $.attachment.preview_failed)}+ </span>)}</div>);}++// Scroll-position restoration across desktop tab switches (multica-ai#6405).+// No-op on web (no desktop adapter). The iframe is keyed on contentKey so a+// content change (re-upload) structurally remounts a fresh document; the+// hook reports y=0 with the new key until that document scrolls, and+// messages from the previous document are dropped by token.+function PageHtmlFrame({ html, title }: { html: string; title: string }) {+ const { contentKey, buildSrcDoc, iframeRef, onLoad } =+ useHtmlPreviewScrollRestore(html);+ return (+ <iframe+ key={contentKey}+ ref={iframeRef}+ onLoad={onLoad}+ srcDoc={buildSrcDoc(html)}+ sandbox="allow-scripts"+ title={title}+ className="h-full w-full border-0 bg-background"+ />+ );+}++const renderPageHtmlFrame: HtmlFrameRenderer = (props) => (+ <PageHtmlFrame {...props} />+);diff --git a/packages/views/editor/attachment-preview-modal.test.tsx b/packages/views/editor/attachment-preview-modal.test.tsxindex 788b63dbb7..0f2e3f3a16 100644--- a/packages/views/editor/attachment-preview-modal.test.tsx+++ b/packages/views/editor/attachment-preview-modal.test.tsx@@ -125,6 +125,24 @@ vi.mock("../i18n", () => ({close: "Close",download_failed: "",open_in_new_tab: "Open in new tab",+ wrap_lines: "Wrap lines",+ viewport: "Viewport width",+ viewport_fill: "Fit",+ viewport_desktop: "Desktop",+ viewport_tablet: "Tablet",+ viewport_phone: "Phone",+ viewport_scale: "Scaled",+ view_source: "View source",+ view_mode: "View",+ view_tree: "Tree",+ view_raw: "Raw",+ structured_parse_failed: "Couldn't parse this file, so it's shown as text.",+ tree_show_more: "Show more",+ tree_items: "items",+ tree_keys: "keys",+ table_empty: "No rows",+ table_rows: "rows",+ table_columns: "columns",},}),}),@@ -179,6 +197,9 @@ function ClosablePreview({ attachment }: { attachment: Attachment }) {beforeEach(() => {vi.clearAllMocks();+ // Drops any body a test queued but never consumed (a media kind skips the+ // text fetch), so it cannot answer the next test's request.+ getAttachmentTextContentMock.mockReset();navState.hasOpenInNewTab = true;slugState.value = "acme";// Default to web's same-origin empty base so existing absolute-URL tests@@ -645,7 +666,7 @@ describe("AttachmentPreviewModal — URL-only source", () => {});});-describe("AttachmentPreviewModal — open-in-new-tab (HTML only)", () => {+describe("AttachmentPreviewModal — open-in-new-tab", () => {it("renders the open-in-new-tab button in the header for HTML attachments", async () => {getAttachmentTextContentMock.mockResolvedValueOnce({text: "<p>hi</p>",@@ -722,10 +743,35 @@ describe("AttachmentPreviewModal — open-in-new-tab (HTML only)", () => {expect(onClose).toHaveBeenCalledTimes(1);});- it("does not render the new-tab button for non-HTML kinds", () => {+ it.each([+ ["manual.pdf", "application/pdf"],+ ["shot.png", "image/png"],+ ["clip.mp4", "video/mp4"],+ ["report.csv", "text/csv"],+ ["data.json", "application/json"],+ ["server.log", "text/plain"],+ ])("opens %s in a new tab too — the page shows every kind", (filename, contentType) => {+ getAttachmentTextContentMock.mockResolvedValue({ text: "a", originalContentType: contentType });+ const att = makeAttachment({ filename, content_type: contentType });+ render(+ <AttachmentPreviewModal+ source={{ kind: "full", attachment: att }}+ open+ onClose={() => {}}+ />,+ );+ fireEvent.click(screen.getByTitle("Open in new tab"));+ expect(openInNewTabMock).toHaveBeenCalledWith(+ `/acme/attachments/att-1/preview?name=${filename}`,+ filename,+ { activate: true },+ );+ });++ it("does not render the new-tab button for a file the viewer cannot show", () => {const att = makeAttachment({- filename: "manual.pdf",- content_type: "application/pdf",+ filename: "archive.zip",+ content_type: "application/zip",});render(<AttachmentPreviewModal@@ -737,6 +783,17 @@ describe("AttachmentPreviewModal — open-in-new-tab (HTML only)", () => {expect(screen.queryByTitle("Open in new tab")).toBeNull();});+ it("does not render the new-tab button for a URL-only source — the page loads by id", () => {+ render(+ <AttachmentPreviewModal+ source={{ kind: "url", url: "https://cdn.example/manual.pdf", filename: "manual.pdf" }}+ open+ onClose={() => {}}+ />,+ );+ expect(screen.queryByTitle("Open in new tab")).toBeNull();+ });+it("does not render the new-tab button when there is no workspace slug", async () => {slugState.value = null;getAttachmentTextContentMock.mockResolvedValueOnce({@@ -1091,3 +1148,152 @@ describe("AttachmentPreviewModal — image zoom", () => {expect(screen.queryByRole("application")).toBeNull();});});++describe("AttachmentPreviewModal — text views", () => {+ function openText(filename: string, text: string, contentType = "text/plain") {+ getAttachmentTextContentMock.mockResolvedValue({ text, originalContentType: contentType });+ const att = makeAttachment({ filename, content_type: contentType });+ return render(+ <AttachmentPreviewModal+ source={{ kind: "full", attachment: att }}+ open+ onClose={() => {}}+ />,+ );+ }++ it("numbers the lines of a code file and leaves them unwrapped", async () => {+ openText("main.go", "package main\n\nfunc main() {}\n");+ await waitFor(() => expect(document.querySelectorAll(".code-line")).toHaveLength(3));+ expect(document.querySelector("pre.code-lines")).not.toHaveClass("code-lines-wrap");+ expect(screen.getByTitle("Wrap lines")).toHaveAttribute("aria-pressed", "false");+ });++ it("wraps a log by default and lets the reader turn it off", async () => {+ openText("server.log", "a very long line\n");+ await waitFor(() => expect(document.querySelector("pre.code-lines")).toBeTruthy());+ const pre = document.querySelector("pre.code-lines");+ expect(pre).toHaveClass("code-lines-wrap");++ fireEvent.click(screen.getByTitle("Wrap lines"));+ expect(document.querySelector("pre.code-lines")).not.toHaveClass("code-lines-wrap");+ expect(screen.getByTitle("Wrap lines")).toHaveAttribute("aria-pressed", "false");+ });++ it("keeps the reader's wrap choice when the viewer moves to another file", async () => {+ getAttachmentTextContentMock.mockResolvedValue({ text: "x\n", originalContentType: "text/plain" });+ const first = makeAttachment({ id: "att-1", filename: "a.go", content_type: "text/plain" });+ const second = makeAttachment({ id: "att-2", filename: "b.go", content_type: "text/plain" });+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ const viewer = (attachment: Attachment) => (+ <QueryClientProvider client={qc}>+ <AttachmentPreviewModal source={{ kind: "full", attachment }} open onClose={() => {}} />+ </QueryClientProvider>+ );+ const { rerender } = rtlRender(viewer(first));+ await waitFor(() => expect(document.querySelector("pre.code-lines")).toBeTruthy());+ fireEvent.click(screen.getByTitle("Wrap lines"));++ rerender(viewer(second));+ await waitFor(() => expect(document.querySelector("pre.code-lines")).toBeTruthy());+ expect(document.querySelector("pre.code-lines")).toHaveClass("code-lines-wrap");+ });+});++describe("AttachmentPreviewModal — html viewports", () => {+ function openHtml() {+ getAttachmentTextContentMock.mockResolvedValue({+ text: "<h1>Prototype</h1>",+ originalContentType: "text/html",+ });+ const att = makeAttachment({ filename: "prototype.html", content_type: "text/html" });+ render(+ <AttachmentPreviewModal source={{ kind: "full", attachment: att }} open onClose={() => {}} />,+ );+ }++ it("fills the stage by default and switches to a device width without reloading", async () => {+ openHtml();+ const iframe = await screen.findByTitle("prototype.html");+ expect(screen.getByRole("button", { name: "Fit" })).toHaveAttribute("aria-pressed", "true");+ expect(screen.getByTestId("html-viewport").style.width).toBe("100%");++ fireEvent.click(screen.getByRole("button", { name: "Phone" }));+ expect(screen.getByRole("button", { name: "Phone" })).toHaveAttribute("aria-pressed", "true");+ expect(screen.getByTestId("html-viewport").style.width).toBe("390px");+ expect(screen.getByText("390")).toBeTruthy();+ // Same element: the document keeps its state across the switch.+ expect(screen.getByTitle("prototype.html")).toBe(iframe);++ fireEvent.click(screen.getByRole("button", { name: "Desktop" }));+ expect(screen.getByTestId("html-viewport").style.width).toBe("1440px");+ });++ it("shows the source with line numbers, and holds the viewport while it does", async () => {+ openHtml();+ await screen.findByTitle("prototype.html");+ expect(screen.getByTitle("Wrap lines")).toBeDisabled();++ fireEvent.click(screen.getByTitle("View source"));+ expect(screen.getByTitle("View source")).toHaveAttribute("aria-pressed", "true");+ expect(screen.queryByTitle("prototype.html")).toBeNull();+ expect(document.querySelector(".code-line")?.textContent).toBe("<h1>Prototype</h1>");+ expect(screen.getByRole("button", { name: "Phone" })).toBeDisabled();+ expect(screen.getByTitle("Wrap lines")).toBeEnabled();+ });+});++describe("AttachmentPreviewModal — structured data", () => {+ function openData(filename: string, text: string, contentType = "application/json") {+ getAttachmentTextContentMock.mockResolvedValue({ text, originalContentType: contentType });+ const att = makeAttachment({ filename, content_type: contentType });+ render(+ <AttachmentPreviewModal source={{ kind: "full", attachment: att }} open onClose={() => {}} />,+ );+ }++ it("shows JSON as a tree, with the source one switch away", async () => {+ openData("config.json", '{"name":"web","ports":[80,443]}');+ await screen.findByText("name");+ expect(screen.getByText('"web"')).toBeTruthy();+ expect(screen.getByRole("button", { name: "Tree" })).toHaveAttribute("aria-pressed", "true");+ expect(screen.getByTitle("Wrap lines")).toBeDisabled();++ fireEvent.click(screen.getByRole("button", { name: "Raw" }));+ expect(screen.queryByText("name")).toBeNull();+ expect(document.querySelector(".code-line")?.textContent).toBe(+ '{"name":"web","ports":[80,443]}',+ );+ expect(screen.getByTitle("Wrap lines")).toBeEnabled();+ });++ it("parses YAML into the same tree", async () => {+ openData("compose.yaml", "services:\n web:\n image: nginx\n", "text/plain");+ await screen.findByText("services");+ });++ it("falls back to the source, and says why, when the file does not parse", async () => {+ openData("broken.json", '{"name": ');+ await screen.findByText("Couldn't parse this file, so it's shown as text.");+ expect(document.querySelector(".code-line")?.textContent).toBe('{"name": ');+ expect(screen.getByRole("button", { name: "Tree" })).toBeDisabled();+ expect(screen.getByRole("button", { name: "Raw" })).toHaveAttribute("aria-pressed", "true");+ expect(screen.getByTitle("Wrap lines")).toBeEnabled();+ });+});++describe("AttachmentPreviewModal — tables", () => {+ it("shows a CSV as a table", async () => {+ getAttachmentTextContentMock.mockResolvedValue({+ text: "name,count\nalpha,3\n",+ originalContentType: "text/csv",+ });+ const att = makeAttachment({ filename: "report.csv", content_type: "text/csv" });+ render(+ <AttachmentPreviewModal source={{ kind: "full", attachment: att }} open onClose={() => {}} />,+ );+ const table = await screen.findByTestId("table-preview");+ expect(table.querySelector("th[data-column-id='c0']")?.textContent).toBe("name");+ expect(table.querySelector("th[data-column-id='c1']")?.textContent).toBe("count");+ });+});diff --git a/packages/views/editor/attachment-preview-modal.tsx b/packages/views/editor/attachment-preview-modal.tsxindex 3a60864f93..b5f545f436 100644--- a/packages/views/editor/attachment-preview-modal.tsx+++ b/packages/views/editor/attachment-preview-modal.tsx@@ -11,7 +11,7 @@* rather than looked at (Markdown, text) render on a centered sheet that* keeps the app's own theme.*- * Single viewer for every previewable kind. Handles 7 PreviewKinds:+ * Single viewer for every previewable kind. Handles 9 PreviewKinds:** - image : <img> on the shared ZoomCanvas — fit on open, then wheel /* drag / pinch / double-click / keyboard zoom, same controls as@@ -31,8 +31,16 @@* JS work), but cookie / localStorage / parent access /* top-navigation / popups / forms stay blocked because* `allow-same-origin` is intentionally NOT included.+ * Laid out at a device width on demand, or shown as source.+ * - table : fetch text, parse CSV / TSV, sortable virtualized table.+ * - structured : fetch text, parse JSON / JSON Lines / YAML into a+ * collapsible tree, with the source one toggle away.* - text : fetch text, highlight with lowlight if the extension- * maps to a known hljs language; otherwise plain <pre>.+ * maps to a known hljs language, with numbered lines and a+ * wrap toggle.+ *+ * The same top bar and stage also stand alone as the "open in new tab" page+ * (`AttachmentPreviewStandalone`), so a file looks the same in both.** Media types load directly from the CloudFront signed `download_url`.* Text types go through `/api/attachments/{id}/content` to sidestep@@ -57,18 +65,26 @@ import {import {ChevronLeft,ChevronRight,+ Code,Download,ExternalLink,File,FileAudio,FileCode,+ FileSpreadsheet,FileText,FileVideo,ImageIcon,LayoutGrid,+ ListTree,Loader2,+ Maximize2,MessageSquareText,+ Monitor,PanelRight,+ Smartphone,+ Tablet,+ WrapText,X,type LucideIcon,} from "lucide-react";@@ -90,8 +106,12 @@ import {extensionToLanguage,fileTypeLabel,getPreviewKind,+ structuredFormat,+ tableDelimiter,+ wrapsByDefault,type PreviewKind,} from "./utils/preview";+import { parseStructured } from "./utils/parse-structured";import { formatBytes } from "../common/format-bytes";import { useDownloadAttachment } from "./use-download-attachment";import { useAttachmentHtmlText } from "./hooks/use-attachment-html-text";@@ -101,6 +121,13 @@ import { ZoomCanvas, ZoomControls } from "./zoom-canvas";import type { Size } from "./utils/zoom-transform";import { HtmlPreviewBody } from "./html-preview-body";import { CodeBlockStatic } from "./code-block-static";+import { TablePreview } from "./table-preview";+import { StructuredTree } from "./structured-tree";+import {+ HTML_VIEWPORTS,+ HtmlViewportFrame,+ type HtmlViewport,+} from "./html-viewport-frame";// ---------------------------------------------------------------------------// Preview source — full attachment, or URL-only (media types only)@@ -495,11 +522,10 @@ export function AttachmentPreviewModal({}};- // Open-in-new-tab: only the `html` kind has a dedicated full-page route- // (/attachments/{id}/preview).- // Gated on slug + attachmentId for the same reason — URL-only sources- // can't address the /content proxy the page relies on.- const canOpenInNewTab = kind === "html" && !!slug && !!state.attachmentId;+ // Open-in-new-tab: the full-page route (/attachments/{id}/preview) shows+ // every previewable kind, but loads the file by id — a URL-only source has+ // none, and a file the viewer cannot show gains nothing from a tab.+ const canOpenInNewTab = kind !== null && !!slug && !!state.attachmentId;const handleOpenInNewTab = () => {if (!slug || !state.attachmentId) return;const nameQuery = state.filename@@ -563,6 +589,7 @@ export function AttachmentPreviewModal({every swap, so the canvas re-fits even across a run ofsame-resolution screenshots. */}<PreviewPanel+ surface="viewer"kind={kind}source={source}state={state}@@ -595,13 +622,57 @@ const KIND_ICONS: Record<PreviewKind, LucideIcon> = {audio: FileAudio,markdown: FileText,html: FileCode,+ table: FileSpreadsheet,+ structured: FileCode,text: FileCode,};-// Top bar and stage live together because the image kind's zoom controls sit-// in the bar while the canvas they drive is on the stage: one owner for that-// shared state, mounted and destroyed with the open viewer.+type StructuredView = "tree" | "raw";++const VIEWPORT_ICONS: Record<HtmlViewport, LucideIcon> = {+ fill: Maximize2,+ desktop: Monitor,+ tablet: Tablet,+ phone: Smartphone,+};++/**+ * Renders an HTML attachment's iframe. The viewer's is plain; the full-page+ * preview's also reports its scroll position to the desktop tab restorer.+ */+export type HtmlFrameRenderer = (props: { html: string; title: string }) => ReactNode;++const renderViewerHtmlFrame: HtmlFrameRenderer = ({ html, title }) => (+ <HtmlPreviewBody+ html={html}+ title={title}+ className="h-full w-full"+ iframeClassName="rounded-none border-0"+ />+);++// The parsed body of a `structured` file. Parsed here, above the stage,+// because the top bar needs the outcome too: a file that does not parse has+// no tree to switch to. Shares the stage's query, so nothing is fetched twice.+function useStructuredParse(state: PreviewState, enabled: boolean) {+ const format = enabled ? structuredFormat(state.contentType, state.filename) : null;+ const query = useAttachmentHtmlText(format ? state.attachmentId : null);+ const text = query.data?.text;+ return useMemo(+ () => (format && text !== undefined ? parseStructured(text, format) : null),+ [format, text],+ );+}++// Top bar and stage live together because some kinds' controls sit in the+// bar while what they drive is on the stage — the image's zoom, a document's+// line wrapping, an HTML file's viewport: one owner for that shared state,+// mounted and destroyed with the open viewer.+//+// `surface` is where it is mounted: the viewer overlay, or the "open in new+// tab" page, which has no close, no sequence and no window drag region.function PreviewPanel({+ surface,kind,source,state,@@ -615,11 +686,13 @@ function PreviewPanel({info,locate,onOpenOverview,+ renderHtmlFrame = renderViewerHtmlFrame,}: {+ surface: "viewer" | "page";kind: PreviewKind | null;source: PreviewSource;state: PreviewState;- onClose: () => void;+ onClose?: () => void;onDownload: () => void;onOpenInNewTab?: () => void;sequence?: PreviewSequence;@@ -629,9 +702,32 @@ function PreviewPanel({info?: PreviewInfoPanel;locate?: PreviewLocateAction;onOpenOverview?: () => void;+ renderHtmlFrame?: HtmlFrameRenderer;}) {const { t } = useT("editor");+ // How the file is shown. Held here rather than in the stage so a choice+ // carries over as the reader pages through the sequence: the next HTML+ // file opens at the same width, the next log wraps the same way. Wrapping+ // follows the file until the reader picks.+ const [wrapChoice, setWrapChoice] = useState<boolean | null>(null);+ const wrap = wrapChoice ?? wrapsByDefault(state.filename);+ const toggleWrap = () => setWrapChoice(!wrap);+ const [htmlViewport, setHtmlViewport] = useState<HtmlViewport>("fill");+ const [htmlSource, setHtmlSource] = useState(false);+ const [structuredChoice, setStructuredChoice] = useState<StructuredView>("tree");+ const structuredParse = useStructuredParse(state, kind === "structured");+ const treeAvailable = structuredParse?.ok !== false;+ const structuredView: StructuredView = treeAvailable ? structuredChoice : "raw";+ const view: StageView = {+ wrap,+ htmlViewport,+ htmlSource,+ structuredView,+ structuredParse,+ renderHtmlFrame,+ };+// Gallery navigation hands this panel an attachment the reader never// clicked, so — unlike the click-through path, where <Attachment> had// already upgraded the URL — the viewer has to run the re-sign itself. A@@ -697,7 +793,24 @@ function PreviewPanel({// The stage's own padding — the gutters around the content — counts as// backdrop: clicking there closes, clicking the content never does.const closeOnBackdrop = (e: React.MouseEvent) => {- if (e.target === e.currentTarget) onClose();+ if (e.target === e.currentTarget) onClose?.();+ };++ const wrapButton = (enabled: boolean) => (+ <ChromeButton+ label={t(($) => $.attachment.wrap_lines)}+ pressed={enabled && wrap}+ disabled={!enabled}+ onClick={toggleWrap}+ >+ <WrapText className="size-4" />+ </ChromeButton>+ );+ const viewportLabels: Record<HtmlViewport, string> = {+ fill: t(($) => $.attachment.viewport_fill),+ desktop: t(($) => $.attachment.viewport_desktop),+ tablet: t(($) => $.attachment.viewport_tablet),+ phone: t(($) => $.attachment.viewport_phone),};return (@@ -705,8 +818,8 @@ function PreviewPanel({{/* Three columns so the counter stays centered on the window while along filename truncates before reaching it. */}<header- className="dark grid h-14 shrink-0 grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-center gap-4 pl-3 pr-2 text-foreground"- style={DRAG}+ className="dark @container grid h-14 shrink-0 grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-center gap-4 pl-3 pr-2 text-foreground"+ style={surface === "viewer" ? DRAG : undefined}><div className="flex min-w-0 items-center gap-2.5"><span className="flex size-8 shrink-0 items-center justify-center rounded-md bg-secondary text-muted-foreground">@@ -751,6 +864,62 @@ function PreviewPanel({<ChromeDivider /></>)}+ {/* View controls stay mounted, disabled where they do not apply —+ toggling the source view must not shift the button just pressed. */}+ {kind === "html" && (+ <>+ <ChromeSegmented+ label={t(($) => $.attachment.viewport)}+ value={htmlViewport}+ disabled={htmlSource}+ options={HTML_VIEWPORTS.map((viewport) => ({+ value: viewport,+ label: viewportLabels[viewport],+ icon: VIEWPORT_ICONS[viewport],+ }))}+ onChange={setHtmlViewport}+ />+ <ChromeButton+ label={t(($) => $.attachment.view_source)}+ pressed={htmlSource}+ onClick={() => setHtmlSource((shown) => !shown)}+ >+ <Code className="size-4" />+ </ChromeButton>+ {wrapButton(htmlSource)}+ <ChromeDivider />+ </>+ )}+ {kind === "structured" && (+ <>+ <ChromeSegmented+ label={t(($) => $.attachment.view_mode)}+ value={structuredView}+ disabled={!treeAvailable}+ options={[+ {+ value: "tree",+ label: t(($) => $.attachment.view_tree),+ icon: ListTree,+ },+ {+ value: "raw",+ label: t(($) => $.attachment.view_raw),+ icon: Code,+ },+ ]}+ onChange={setStructuredChoice}+ />+ {wrapButton(structuredView === "raw")}+ <ChromeDivider />+ </>+ )}+ {kind === "text" && (+ <>+ {wrapButton(true)}+ <ChromeDivider />+ </>+ )}{locate && (<ChromeButton label={locate.label} onClick={locate.onSelect}><MessageSquareText className="size-4" />@@ -787,10 +956,14 @@ function PreviewPanel({<PanelRight className="size-4" /></ChromeButton>)}- <ChromeDivider />- <ChromeButton label={t(($) => $.attachment.close)} onClick={onClose}>- <X className="size-4" />- </ChromeButton>+ {onClose && (+ <>+ <ChromeDivider />+ <ChromeButton label={t(($) => $.attachment.close)} onClick={onClose}>+ <X className="size-4" />+ </ChromeButton>+ </>+ )}</div></header><div className="flex min-h-0 flex-1">@@ -826,6 +999,7 @@ function PreviewPanel({kind={kind}source={source}state={state}+ view={view}onDownload={onDownload}onBackdropClick={closeOnBackdrop}/>@@ -870,6 +1044,7 @@ function ChromeButton({label,shortcut,pressed,+ disabled,onClick,children,}: {@@ -878,6 +1053,7 @@ function ChromeButton({shortcut?: string;/** Toggle buttons pass their state; plain actions leave it unset. */pressed?: boolean;+ disabled?: boolean;onClick: () => void;children: ReactNode;}) {@@ -885,13 +1061,14 @@ function ChromeButton({<buttontype="button"className={cn(- "flex size-8 items-center justify-center rounded-md transition-colors hover:bg-secondary hover:text-foreground",+ "flex size-8 items-center justify-center rounded-md transition-colors enabled:hover:bg-secondary enabled:hover:text-foreground disabled:opacity-40",pressed ? "bg-secondary text-foreground" : "text-muted-foreground",)}title={shortcut ? `${label} (${shortcut})` : label}aria-label={label}aria-keyshortcuts={shortcut}aria-pressed={pressed}+ disabled={disabled}onClick={onClick}>{children}@@ -899,6 +1076,52 @@ function ChromeButton({);}+// A one-of-several choice in the top bar (viewport width, tree / raw). Same+// pressed look as the toggle buttons beside it. Labels show once the bar has+// room for them; below that the icons carry the choice, named by tooltip.+function ChromeSegmented<T extends string>({+ label,+ value,+ options,+ disabled,+ onChange,+}: {+ label: string;+ value: T;+ options: ReadonlyArray<{ value: T; label: string; icon: LucideIcon }>;+ disabled?: boolean;+ onChange: (value: T) => void;+}) {+ return (+ <div role="group" aria-label={label} className="flex items-center gap-0.5">+ {options.map((option) => {+ const pressed = option.value === value;+ const Icon = option.icon;+ return (+ <button+ key={option.value}+ type="button"+ className={cn(+ "flex h-8 min-w-8 items-center justify-center gap-1.5 rounded-md px-2 text-label transition-colors enabled:hover:bg-secondary enabled:hover:text-foreground disabled:opacity-40",+ pressed ? "bg-secondary text-foreground" : "text-muted-foreground",+ )}+ title={option.label}+ aria-label={option.label}+ aria-pressed={pressed}+ disabled={disabled}+ onClick={() => onChange(option.value)}+ >+ <Icon className="size-4 shrink-0" />+ <span className="hidden @7xl:inline" aria-hidden>+ {option.label}+ </span>+ </button>+ );+ })}+ </div>+ );+}+function ChromeDivider() {return <span className="mx-1.5 h-4 w-px bg-input" aria-hidden />;}@@ -1019,24 +1242,45 @@ function ImagePreview({// Dispatch// ---------------------------------------------------------------------------+// What the top bar decided about how the file shows — see PreviewPanel.+interface StageView {+ wrap: boolean;+ htmlViewport: HtmlViewport;+ htmlSource: boolean;+ structuredView: StructuredView;+ /** The `structured` kind's parse, once its body has loaded. */+ structuredParse: ReturnType<typeof parseStructured> | null;+ renderHtmlFrame: HtmlFrameRenderer;+}++const TEXT_BACKED_KINDS: ReadonlySet<PreviewKind> = new Set<PreviewKind>([+ "markdown",+ "html",+ "table",+ "structured",+ "text",+]);+// Dispatch on PreviewKind. New cases go here; remember that the viewer frame// (top bar, close, Download CTA, ESC handling) is shared — sub-renderers only// own the stage. `image` is handled by PreviewPanel itself because its// toolbar and canvas share zoom state.//-// Layout per kind: pages (PDF, HTML) fill the stage; video letterboxes on it;-// Markdown and text scroll on a centered sheet in the app's own theme; anything-// else that sits directly on the stage wears `dark`.+// Layout per kind: pages (PDF, HTML, tables) fill the stage; video letterboxes+// on it; Markdown, code and data scroll on a centered sheet in the app's own+// theme; anything else that sits directly on the stage wears `dark`.function PreviewContent({kind,source,state,+ view,onDownload,onBackdropClick,}: {kind: Exclude<PreviewKind, "image"> | null;source: PreviewSource;state: PreviewState;+ view: StageView;onDownload: () => void;onBackdropClick: (e: React.MouseEvent) => void;}) {@@ -1056,10 +1300,7 @@ function PreviewContent({// be defensive — a direct mount of <AttachmentPreviewModal> with a URL// source whose filename later resolves to a text kind would otherwise// crash on a null id.- if (- (kind === "markdown" || kind === "html" || kind === "text") &&- !state.attachmentId- ) {+ if (TEXT_BACKED_KINDS.has(kind) && !state.attachmentId) {return (<UnsupportedFallbackmessage={t(($) => $.attachment.preview_unsupported)}@@ -1068,6 +1309,18 @@ function PreviewContent({);}+ const code = (text: string, language: string | undefined) => (+ <DocumentSheet width="code" onBackdropClick={onBackdropClick}>+ <CodeBlockStatic+ language={language}+ body={text}+ lineNumbers+ wrap={view.wrap}+ className="min-h-full"+ />+ </DocumentSheet>+ );+switch (kind) {case "pdf":return (@@ -1112,36 +1365,77 @@ function PreviewContent({/>);case "html":+ return (+ <TextBackedPreview+ attachmentId={state.attachmentId!}+ onDownload={onDownload}+ render={(text) =>+ view.htmlSource ? (+ code(text, "xml")+ ) : (+ <HtmlViewportFrame viewport={view.htmlViewport}>+ {view.renderHtmlFrame({ html: text, title: state.filename })}+ </HtmlViewportFrame>+ )+ }+ />+ );+ case "table":return (<TextBackedPreviewattachmentId={state.attachmentId!}onDownload={onDownload}render={(text) => (- <div className="h-full pb-4">- <HtmlPreviewBody- html={text}- title={state.filename}- className="h-full w-full"- iframeClassName="rounded-lg border-0"- />- </div>+ // Keyed on the file: sort order and column widths belong to it.+ <TablePreview+ key={state.attachmentId}+ text={text}+ delimiter={tableDelimiter(state.contentType, state.filename)}+ />)}/>);+ case "structured":+ return (+ <TextBackedPreview+ attachmentId={state.attachmentId!}+ onDownload={onDownload}+ render={(text) => {+ const parse = view.structuredParse;+ if (parse?.ok && view.structuredView === "tree") {+ return (+ <DocumentSheet width="code" onBackdropClick={onBackdropClick}>+ <div className="px-4 py-4">+ <StructuredTree key={state.attachmentId} value={parse.value} />+ </div>+ </DocumentSheet>+ );+ }+ return (+ <div className="flex h-full flex-col">+ {parse && !parse.ok && (+ <p+ className="dark mx-auto mb-2 w-full max-w-5xl shrink-0 text-body text-muted-foreground"+ role="status"+ >+ {t(($) => $.attachment.structured_parse_failed)}{" "}+ <span className="font-mono text-caption">{parse.message}</span>+ </p>+ )}+ <div className="min-h-0 flex-1">+ {code(text, extensionToLanguage(state.filename))}+ </div>+ </div>+ );+ }}+ />+ );case "text":return (<TextBackedPreviewattachmentId={state.attachmentId!}onDownload={onDownload}- render={(text) => (- <DocumentSheet width="code" onBackdropClick={onBackdropClick}>- <CodeBlockStatic- language={extensionToLanguage(state.filename)}- body={text}- className="px-6 py-5"- />- </DocumentSheet>- )}+ render={(text) => code(text, extensionToLanguage(state.filename))}/>);}@@ -1258,6 +1552,44 @@ function UnsupportedFallback({);}+// ---------------------------------------------------------------------------+// Standalone — the viewer's top bar and stage as a page of their own+// ---------------------------------------------------------------------------++/**+ * The "Open in new tab" destination: the same bar and stage as the viewer,+ * on the same dark ground, filling its host instead of overlaying the app.+ * No close, sequence or window drag region — the tab is the frame.+ */+export function AttachmentPreviewStandalone({+ attachment,+ renderHtmlFrame,+}: {+ attachment: Attachment;+ renderHtmlFrame?: HtmlFrameRenderer;+}) {+ const download = useDownloadAttachment();+ const source = useMemo<PreviewSource>(+ () => ({ kind: "full", attachment }),+ [attachment],+ );+ const state = normalize(source);++ return (+ <div className="flex h-full w-full flex-col bg-black/95">+ <PreviewPanel+ surface="page"+ kind={state.kind}+ source={source}+ state={state}+ onDownload={() => download(attachment.id)}+ reduceMotion+ renderHtmlFrame={renderHtmlFrame}+ />+ </div>+ );+}+// Re-export the predicate from the dispatch util so entry-point components// only need a single import to gate the Eye button.export { isPreviewable } from "./utils/preview";diff --git a/packages/views/editor/code-block-static.test.tsx b/packages/views/editor/code-block-static.test.tsxindex 8335f79f03..eb0d1cf107 100644--- a/packages/views/editor/code-block-static.test.tsx+++ b/packages/views/editor/code-block-static.test.tsx@@ -25,3 +25,70 @@ describe("CodeBlockStatic", () => {expect(code?.querySelector("span")).toBeNull();});});++describe("CodeBlockStatic with lineNumbers", () => {+ it("numbers every line, including blank ones", () => {+ const { container } = render(+ <CodeBlockStatic language="plaintext" body={"first\n\nthird\n"} lineNumbers />,+ );++ const lines = container.querySelectorAll(".code-line");+ expect(Array.from(lines, (line) => line.getAttribute("data-line"))).toEqual([+ "1",+ "2",+ "3",+ ]);+ expect(Array.from(lines, (line) => line.textContent)).toEqual([+ "first",+ "",+ "third",+ ]);+ });++ it("keeps a multi-line token highlighted on every line it spans", () => {+ const { container } = render(+ <CodeBlockStatic+ language="javascript"+ body={"/* one\ntwo */\nconst x = 1;"}+ lineNumbers+ />,+ );++ const lines = container.querySelectorAll(".code-line");+ expect(lines).toHaveLength(3);+ expect(lines[0]?.querySelector(".hljs-comment")?.textContent).toBe("/* one");+ expect(lines[1]?.querySelector(".hljs-comment")?.textContent).toBe("two */");+ expect(lines[2]?.querySelector(".hljs-keyword")?.textContent).toBe("const");+ });++ it("sizes the gutter to the widest line number", () => {+ const body = Array.from({ length: 120 }, (_, i) => `line ${i}`).join("\n");+ const { container } = render(+ <CodeBlockStatic language={undefined} body={body} lineNumbers />,+ );++ const pre = container.querySelector<HTMLElement>("pre.code-lines");+ expect(pre?.style.getPropertyValue("--line-digits")).toBe("3");+ });++ it("wraps long lines only when asked", () => {+ const { container, rerender } = render(+ <CodeBlockStatic language={undefined} body="a" lineNumbers />,+ );+ expect(container.querySelector("pre")).not.toHaveClass("code-lines-wrap");++ rerender(<CodeBlockStatic language={undefined} body="a" lineNumbers wrap />);+ expect(container.querySelector("pre")).toHaveClass("code-lines-wrap");+ });++ it("escapes markup in the source", () => {+ const { container } = render(+ <CodeBlockStatic language={undefined} body="<script>alert(1)</script>" lineNumbers />,+ );++ expect(container.querySelector("script")).toBeNull();+ expect(container.querySelector(".code-line")?.textContent).toBe(+ "<script>alert(1)</script>",+ );+ });+});diff --git a/packages/views/editor/code-block-static.tsx b/packages/views/editor/code-block-static.tsxindex 79b1974b1b..71a5c6c449 100644--- a/packages/views/editor/code-block-static.tsx+++ b/packages/views/editor/code-block-static.tsx@@ -4,7 +4,8 @@* CodeBlockStatic — read-only lowlight-highlighted code block.** Used by:- * - AttachmentPreviewModal's text-kind fallback (extracted from there).+ * - AttachmentPreviewModal's text kinds, with numbered lines and a wrap+ * toggle.* - HtmlBlockPreview's "source" toggle in ReadonlyContent.** NOT used by Tiptap's editable code-block NodeView: that path must keep@@ -13,32 +14,65 @@* the content and desync ProseMirror state from the DOM.*/-import { useMemo } from "react";+import { useMemo, type CSSProperties } from "react";import { toHtml } from "hast-util-to-html";import { cn } from "@multica/ui/lib/utils";import { highlightCode } from "./syntax-highlight";+import { highlightToLines } from "../common/task-transcript/diff-highlight";import "./styles/code.css";interface CodeBlockStaticProps {language: string | undefined;body: string;className?: string;+ /** Numbers every line in a gutter that stays put while the code scrolls. */+ lineNumbers?: boolean;+ /**+ * With `lineNumbers`: wrap long lines under their own number instead of+ * scrolling sideways. Plain blocks always wrap.+ */+ wrap?: boolean;}-export function CodeBlockStatic({ language, body, className }: CodeBlockStaticProps) {- const html = useMemo(() => {+export function CodeBlockStatic({+ language,+ body,+ className,+ lineNumbers = false,+ wrap = false,+}: CodeBlockStaticProps) {+ const { html, lineCount } = useMemo(() => {const code = body.replace(/\n$/, "");+ if (lineNumbers) {+ // Highlighted as one block, then split — a multi-line comment or+ // string keeps its colour on every line it spans.+ const lines =+ highlightToLines(code, language) ?? code.split("\n").map(escapeHtml);+ return { html: numberedLinesHtml(lines), lineCount: lines.length };+ }try {const tree = highlightCode(code, language);- return toHtml(tree) as string;+ return { html: toHtml(tree) as string, lineCount: 0 };} catch {// Keep an unexpected highlighter failure from breaking the preview.- return escapeHtml(code);+ return { html: escapeHtml(code), lineCount: 0 };}- }, [body, language]);+ }, [body, language, lineNumbers]);return (- <pre className={cn("rich-text-editor m-0 overflow-auto text-body", className)}>+ <pre+ className={cn(+ "rich-text-editor m-0 overflow-auto text-body",+ lineNumbers && "code-lines",+ lineNumbers && wrap && "code-lines-wrap",+ className,+ )}+ style={+ lineNumbers+ ? ({ "--line-digits": String(lineCount).length } as CSSProperties)+ : undefined+ }+ ><codeclassName={cn("hljs", language && `language-${language}`)}dangerouslySetInnerHTML={{ __html: html }}@@ -47,6 +81,18 @@ export function CodeBlockStatic({ language, body, className }: CodeBlockStaticPr);}+// One element per line, numbered through a data attribute: the number is a+// pseudo-element, so selecting and copying the code never picks it up. Built+// as one string and set once — a log file can run to tens of thousands of+// lines, far too many to hand React as elements.+function numberedLinesHtml(lines: string[]): string {+ let html = "";+ for (let i = 0; i < lines.length; i++) {+ html += `<span class="code-line" data-line="${i + 1}"><span class="code-text">${lines[i]}</span></span>`;+ }+ return html;+}+function escapeHtml(s: string): string {return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");}diff --git a/packages/views/editor/html-viewport-frame.test.tsx b/packages/views/editor/html-viewport-frame.test.tsxnew file mode 100644index 0000000000..2869f9254a--- /dev/null+++ b/packages/views/editor/html-viewport-frame.test.tsx@@ -0,0 +1,69 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { screen } from "@testing-library/react";+import { renderWithI18n } from "../test/i18n";+import { fitViewport, HtmlViewportFrame } from "./html-viewport-frame";++describe("fitViewport", () => {+ it("keeps the device width and scales it down into a narrower area", () => {+ expect(fitViewport({ width: 1100, height: 800 }, 1440)).toEqual({+ width: 1440,+ height: 1047,+ scale: 1100 / 1440,+ });+ });++ it("never scales up past the device's own size", () => {+ expect(fitViewport({ width: 1600, height: 900 }, 390)).toEqual({+ width: 390,+ height: 900,+ scale: 1,+ });+ });+});++describe("HtmlViewportFrame", () => {+ // jsdom has no layout: give every element the stage area's layout box.+ beforeEach(() => {+ vi.spyOn(HTMLElement.prototype, "offsetWidth", "get").mockReturnValue(1100);+ vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockReturnValue(800);+ });+ afterEach(() => {+ vi.restoreAllMocks();+ });++ const frame = <iframe title="doc" className="h-full w-full" />;++ it("fills the area with no caption by default", () => {+ renderWithI18n(<HtmlViewportFrame viewport="fill">{frame}</HtmlViewportFrame>);+ expect(screen.getByTestId("html-viewport").style.width).toBe("100%");+ expect(screen.queryByText(/×/)).toBeNull();+ });++ it("lays a wider device out at full size and scales it to fit, saying by how much", () => {+ renderWithI18n(<HtmlViewportFrame viewport="desktop">{frame}</HtmlViewportFrame>);++ const box = screen.getByTestId("html-viewport");+ expect(box.style.width).toBe("1100px");+ const layout = screen.getByTitle("doc").parentElement!;+ expect(layout.style.width).toBe("1440px");+ expect(layout.style.height).toBe("1047px");+ expect(layout.style.transform).toBe(`scale(${1100 / 1440})`);+ expect(screen.getByText(/1440 × 1047/)).toHaveTextContent("1440 × 1047 · Scaled to 76%");+ });++ it("shows a device that fits at its own size", () => {+ renderWithI18n(<HtmlViewportFrame viewport="phone">{frame}</HtmlViewportFrame>);++ expect(screen.getByTestId("html-viewport").style.width).toBe("390px");+ const layout = screen.getByTitle("doc").parentElement!;+ expect(layout.style.transform).toBe("");+ expect(screen.getByText("390 × 800")).toBeTruthy();+ });++ it("localizes the scale", () => {+ renderWithI18n(<HtmlViewportFrame viewport="desktop">{frame}</HtmlViewportFrame>, {+ locale: "zh-Hans",+ });+ expect(screen.getByText(/缩放/)).toHaveTextContent("1440 × 1047 · 缩放 76%");+ });+});diff --git a/packages/views/editor/html-viewport-frame.tsx b/packages/views/editor/html-viewport-frame.tsxnew file mode 100644index 0000000000..e5efbe02c2--- /dev/null+++ b/packages/views/editor/html-viewport-frame.tsx@@ -0,0 +1,152 @@+"use client";++/**+ * HtmlViewportFrame — lays an HTML attachment's iframe out at a chosen+ * viewport width, for the viewer's html kind.+ *+ * - fill : the iframe takes the whole stage, as the page would in a+ * browser window that size. The default.+ * - desktop / tablet / phone : the iframe is exactly 1440 / 768 / 390 CSS px+ * wide, so the document's media queries see that device. When+ * the stage is narrower the frame scales down to fit — layout+ * stays at the device width, only the pixels shrink — and the+ * caption says by how much. Height always fills the stage.+ *+ * The iframe itself is the caller's: the viewer and the full-page preview+ * wire different ones, and this only owns the box around it.+ */++import { useLayoutEffect, useState, type ReactNode } from "react";+import { cn } from "@multica/ui/lib/utils";+import { useT } from "../i18n";++export type HtmlViewport = "fill" | "desktop" | "tablet" | "phone";++export const HTML_VIEWPORTS: readonly HtmlViewport[] = [+ "fill",+ "desktop",+ "tablet",+ "phone",+];++export const VIEWPORT_WIDTHS: Record<Exclude<HtmlViewport, "fill">, number> = {+ desktop: 1440,+ tablet: 768,+ phone: 390,+};++export interface ViewportFit {+ /** CSS px the document lays out in. */+ width: number;+ height: number;+ /** ≤ 1 — never scaled up past the device's own size. */+ scale: number;+}++/** Fits a device `width` into `area`: scale by width, fill the height. */+export function fitViewport(+ area: { width: number; height: number },+ width: number,+): ViewportFit {+ const scale = Math.min(1, area.width / width);+ return { width, height: Math.round(area.height / scale), scale };+}++// The untransformed layout box (offsetWidth / offsetHeight), not a client+// rect: the viewer's stage scales in on open, and a rect measured mid-+// animation would fit against a box a few percent too small.+function useLayoutSize(node: HTMLElement | null) {+ const [size, setSize] = useState<{ width: number; height: number } | null>(null);+ useLayoutEffect(() => {+ if (!node) return;+ const measure = () => {+ const width = node.offsetWidth;+ const height = node.offsetHeight;+ setSize((previous) =>+ previous?.width === width && previous.height === height+ ? previous+ : { width, height },+ );+ };+ measure();+ if (typeof ResizeObserver === "undefined") return;+ const observer = new ResizeObserver(measure);+ observer.observe(node);+ return () => observer.disconnect();+ }, [node]);+ return size;+}++export function HtmlViewportFrame({+ viewport,+ children,+}: {+ viewport: HtmlViewport;+ /** The iframe, sized `h-full w-full`. */+ children: ReactNode;+}) {+ const { t } = useT("editor");+ const [area, setArea] = useState<HTMLDivElement | null>(null);+ const size = useLayoutSize(area);++ const deviceWidth = viewport === "fill" ? null : VIEWPORT_WIDTHS[viewport];+ // Until the area has a size (first layout, or a host without layout such+ // as a test DOM) a device frame shows unscaled at full height.+ const fit =+ deviceWidth !== null && size && size.width > 0+ ? fitViewport(size, deviceWidth)+ : null;+ const percent = fit ? Math.round(fit.scale * 100) : 100;++ // One element tree for every viewport, so switching only resizes the+ // iframe — it never remounts, and the document keeps its state.+ return (+ <div className={cn("flex h-full flex-col", deviceWidth === null ? "pb-4" : "pb-2")}>+ <div ref={setArea} className="relative min-h-0 flex-1">+ {/* The visible box is the scaled size; inside it the frame lays out+ at full device size and a transform shrinks it to fit. */}+ <div+ className="mx-auto h-full max-w-full overflow-hidden rounded-lg"+ style={{+ width:+ deviceWidth === null+ ? "100%"+ : fit+ ? deviceWidth * fit.scale+ : deviceWidth,+ }}+ data-testid="html-viewport"+ >+ <div+ className="h-full w-full"+ style={+ deviceWidth === null+ ? undefined+ : fit+ ? {+ width: fit.width,+ height: fit.height,+ transform: fit.scale < 1 ? `scale(${fit.scale})` : undefined,+ transformOrigin: "top left",+ }+ : { width: deviceWidth }+ }+ >+ {children}+ </div>+ </div>+ </div>+ {deviceWidth !== null && (+ <p className="dark shrink-0 pt-2 text-center text-caption tabular-nums text-muted-foreground">+ {fit ? `${fit.width} × ${fit.height}` : deviceWidth}+ {percent < 100 && (+ <>+ {" · "}+ {t(($) => $.attachment.viewport_scale, { percent })}+ </>+ )}+ </p>+ )}+ </div>+ );+}diff --git a/packages/views/editor/structured-tree.test.tsx b/packages/views/editor/structured-tree.test.tsxnew file mode 100644index 0000000000..c1eee7e54a--- /dev/null+++ b/packages/views/editor/structured-tree.test.tsx@@ -0,0 +1,85 @@+import { describe, expect, it } from "vitest";+import { fireEvent, screen } from "@testing-library/react";+import { renderWithI18n } from "../test/i18n";+import { previewOf, StructuredTree } from "./structured-tree";++function disclosure(name: RegExp): HTMLElement {+ return screen.getByRole("button", { name });+}++describe("StructuredTree", () => {+ it("opens an object root one level deep and colours values by type", () => {+ renderWithI18n(+ <StructuredTree+ value={{ name: "web", replicas: 3, debug: false, owner: null, env: { PORT: "80" } }}+ />,+ );++ expect(screen.getByText('"web"')).toHaveClass("hljs-string");+ expect(screen.getByText("3")).toHaveClass("hljs-number");+ expect(screen.getByText("false")).toHaveClass("hljs-literal");+ expect(screen.getByText("null")).toHaveClass("hljs-literal");+ // A small second-level object is already open.+ expect(disclosure(/^env/)).toHaveAttribute("aria-expanded", "true");+ expect(screen.getByText('"80"')).toBeTruthy();+ });++ it("keeps the records of an array root collapsed, each with a preview", () => {+ renderWithI18n(+ <StructuredTree value={[{ id: 1, name: "a" }, { id: 2, name: "b" }]} />,+ );++ const first = disclosure(/^0/);+ expect(first).toHaveAttribute("aria-expanded", "false");+ expect(first).toHaveTextContent('{ id: 1, name: "a" }');++ fireEvent.click(first);+ expect(first).toHaveAttribute("aria-expanded", "true");+ expect(first).toHaveTextContent("2 keys");+ expect(screen.getByText('"a"')).toBeTruthy();++ fireEvent.click(first);+ expect(screen.queryByText('"a"')).toBeNull();+ });++ it("pages through a long list instead of rendering it all", () => {+ const value = Array.from({ length: 250 }, (_, i) => `item-${i}`);+ renderWithI18n(<StructuredTree value={value} />);++ expect(screen.getByText('"item-99"')).toBeTruthy();+ expect(screen.queryByText('"item-100"')).toBeNull();++ fireEvent.click(screen.getByRole("button", { name: "Show more (150 left)" }));+ expect(screen.getByText('"item-199"')).toBeTruthy();+ expect(screen.queryByText('"item-200"')).toBeNull();+ expect(screen.getByRole("button", { name: "Show more (50 left)" })).toBeTruthy();+ });++ it("shows empty containers inline, not as disclosures", () => {+ renderWithI18n(<StructuredTree value={{ tags: [], meta: {} }} />);+ expect(screen.getByText(": []")).toBeTruthy();+ expect(screen.getByText(": {}")).toBeTruthy();+ expect(screen.queryByRole("button")).toBeNull();+ });++ it("quotes keys that would read ambiguously bare", () => {+ renderWithI18n(<StructuredTree value={{ "two words": 1, "": 2, plain_key: 3 }} />);+ expect(screen.getByText('"two words"')).toHaveClass("hljs-attr");+ expect(screen.getByText('""')).toHaveClass("hljs-attr");+ expect(screen.getByText("plain_key")).toHaveClass("hljs-attr");+ });++ it("renders a bare value", () => {+ renderWithI18n(<StructuredTree value="just text" />);+ expect(screen.getByText('"just text"')).toHaveClass("hljs-string");+ });+});++describe("previewOf", () => {+ it("shrinks nested containers and stops at the budget", () => {+ expect(previewOf({ a: 1, b: [1, 2], c: { d: 1 } })).toBe("{ a: 1, b: […], c: {…} }");+ const long = previewOf(Array.from({ length: 40 }, (_, i) => i * 1000));+ expect(long.endsWith(", …]")).toBe(true);+ expect(long.length).toBeLessThan(100);+ });+});diff --git a/packages/views/editor/structured-tree.tsx b/packages/views/editor/structured-tree.tsxnew file mode 100644index 0000000000..fa5db55b0d--- /dev/null+++ b/packages/views/editor/structured-tree.tsx@@ -0,0 +1,242 @@+"use client";++/**+ * StructuredTree — parsed JSON / YAML as a collapsible tree, for the viewer's+ * `structured` kind.+ *+ * Every object and array is a disclosure: its row toggles it, and a collapsed+ * one previews its first entries inline (`{ id: 1, name: "a", … }`) so a list+ * of records can be scanned without opening each. The root is always open.+ * One more level opens by default under an object root — a config reads+ * top-down — but not under an array root, where the previews are the view.+ *+ * Large collections render their children a page at a time, so a 50 000-item+ * array costs what its first page costs.+ */++import { useState, type ReactNode } from "react";+import { ChevronRight } from "lucide-react";+import { cn } from "@multica/ui/lib/utils";+import { useT } from "../i18n";+import "./styles/code.css";++const PAGE_SIZE = 100;+// Children count up to which a second-level object opens on its own.+const AUTO_OPEN_LIMIT = 50;+const PREVIEW_BUDGET = 80;++type Container = Record<string, unknown> | unknown[];++function isContainer(value: unknown): value is Container {+ return typeof value === "object" && value !== null;+}++function entriesOf(value: Container): Array<[string, unknown]> {+ return Array.isArray(value)+ ? value.map((item, index) => [String(index), item])+ : Object.entries(value);+}++// A key that would read ambiguously bare (empty, spaces, punctuation) is+// quoted, the way a devtools console shows it.+function formatKey(key: string): string {+ return /^[\p{L}\p{N}_$-]+$/u.test(key) ? key : JSON.stringify(key);+}++function primitiveText(value: unknown): string {+ if (typeof value === "string") return JSON.stringify(value);+ if (value instanceof Date) return value.toISOString();+ return String(value);+}++function primitiveClass(value: unknown): string {+ if (typeof value === "string" || value instanceof Date) return "hljs-string";+ if (typeof value === "number" || typeof value === "bigint") return "hljs-number";+ return "hljs-literal";+}++// `{ id: 1, name: "a", … }` — nested containers shrink to `{…}` / `[…]`.+export function previewOf(value: Container): string {+ const isArray = Array.isArray(value);+ const parts: string[] = [];+ let used = 0;+ let truncated = false;+ for (const [key, item] of entriesOf(value)) {+ const shown = isContainer(item)+ ? Array.isArray(item)+ ? "[…]"+ : "{…}"+ : primitiveText(item);+ const part = isArray ? shown : `${formatKey(key)}: ${shown}`;+ if (parts.length > 0 && used + part.length > PREVIEW_BUDGET) {+ truncated = true;+ break;+ }+ parts.push(part);+ used += part.length + 2;+ }+ const body = parts.join(", ") + (truncated ? ", …" : "");+ return isArray ? `[${body}]` : `{ ${body} }`;+}++export function StructuredTree({ value }: { value: unknown }) {+ return (+ <div className="structured-tree font-mono text-label leading-6">+ {isContainer(value) ? (+ <Children value={value} depth={1} parentIsArray={Array.isArray(value)} />+ ) : (+ <Primitive value={value} />+ )}+ </div>+ );+}++function Children({+ value,+ depth,+ parentIsArray,+}: {+ value: Container;+ depth: number;+ parentIsArray: boolean;+}) {+ const { t } = useT("editor");+ const entries = entriesOf(value);+ const [shown, setShown] = useState(PAGE_SIZE);+ const remaining = entries.length - shown;++ return (+ <ul className={cn(depth > 1 && "ml-[7px] border-l border-border pl-3")}>+ {entries.slice(0, shown).map(([key, item]) => (+ <Node+ key={key}+ name={key}+ value={item}+ depth={depth}+ parentIsArray={parentIsArray}+ />+ ))}+ {remaining > 0 && (+ <li>+ <button+ type="button"+ className="ml-5 rounded-sm px-1 text-muted-foreground hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"+ onClick={() => setShown((count) => count + PAGE_SIZE)}+ >+ {t(($) => $.attachment.tree_show_more, { count: remaining })}+ </button>+ </li>+ )}+ </ul>+ );+}++function Node({+ name,+ value,+ depth,+ parentIsArray,+}: {+ name: string;+ value: unknown;+ depth: number;+ parentIsArray: boolean;+}) {+ const label = (+ <span className={parentIsArray ? "text-muted-foreground" : "hljs-attr"}>+ {parentIsArray ? name : formatKey(name)}+ </span>+ );++ if (!isContainer(value)) {+ return (+ <li className="flex min-w-0 gap-1 pl-5">+ <span className="shrink-0">+ {label}+ <span className="text-muted-foreground">:</span>+ </span>+ <Primitive value={value} />+ </li>+ );+ }++ return (+ <ContainerNode+ label={label}+ value={value}+ depth={depth}+ defaultOpen={+ depth === 1 && !parentIsArray && entriesOf(value).length <= AUTO_OPEN_LIMIT+ }+ />+ );+}++function ContainerNode({+ label,+ value,+ depth,+ defaultOpen,+}: {+ label: ReactNode;+ value: Container;+ depth: number;+ defaultOpen: boolean;+}) {+ const { t } = useT("editor");+ const isArray = Array.isArray(value);+ const count = isArray ? value.length : Object.keys(value).length;+ const [open, setOpen] = useState(defaultOpen);++ if (count === 0) {+ return (+ <li className="pl-5">+ {label}+ <span className="text-muted-foreground">: {isArray ? "[]" : "{}"}</span>+ </li>+ );+ }++ return (+ <li>+ <button+ type="button"+ aria-expanded={open}+ className="flex w-full min-w-0 items-center gap-1 rounded-sm text-left hover:bg-muted/60 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"+ onClick={() => setOpen((next) => !next)}+ >+ <ChevronRight+ aria-hidden+ className={cn(+ "size-4 shrink-0 text-muted-foreground transition-transform duration-100",+ open && "rotate-90",+ )}+ />+ <span className="shrink-0">+ {label}+ <span className="text-muted-foreground">:</span>+ </span>+ {open ? (+ <span className="shrink-0 text-muted-foreground">+ {isArray+ ? t(($) => $.attachment.tree_items, { count })+ : t(($) => $.attachment.tree_keys, { count })}+ </span>+ ) : (+ <span className="min-w-0 truncate text-muted-foreground">+ {previewOf(value)}+ </span>+ )}+ </button>+ {open && <Children value={value} depth={depth + 1} parentIsArray={isArray} />}+ </li>+ );+}++function Primitive({ value }: { value: unknown }) {+ return (+ <span className={cn("min-w-0 [overflow-wrap:anywhere]", primitiveClass(value))}>+ {primitiveText(value)}+ </span>+ );+}diff --git a/packages/views/editor/styles/code.css b/packages/views/editor/styles/code.cssindex 7091391488..a3b29a2dd2 100644--- a/packages/views/editor/styles/code.css+++ b/packages/views/editor/styles/code.css@@ -52,69 +52,128 @@ pre.rich-text-editor code {line-height: 1.6;}-/* Syntax highlighting — lowlight (hljs). Scoped to the editor surface and to- the task transcript, which highlights file bodies with the same engine so a- file reads identically in a comment and in an execution trace. */-:is(.rich-text-editor, .transcript-code) .hljs-keyword,-:is(.rich-text-editor, .transcript-code) .hljs-selector-tag,-:is(.rich-text-editor, .transcript-code) .hljs-built_in { color: oklch(0.55 0.16 255); }+/* Syntax highlighting — lowlight (hljs). Scoped to the editor surface, to the+ task transcript, which highlights file bodies with the same engine so a+ file reads identically in a comment and in an execution trace, and to the+ attachment viewer's data tree, whose keys and values borrow the same token+ colours as the file's source. */+:is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-keyword,+:is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-selector-tag,+:is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-built_in { color: oklch(0.55 0.16 255); }-:is(.rich-text-editor, .transcript-code) .hljs-string,-:is(.rich-text-editor, .transcript-code) .hljs-addition { color: oklch(0.55 0.14 155); }+:is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-string,+:is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-addition { color: oklch(0.55 0.14 155); }-:is(.rich-text-editor, .transcript-code) .hljs-comment,-:is(.rich-text-editor, .transcript-code) .hljs-quote { color: var(--muted-foreground); font-style: italic; }+:is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-comment,+:is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-quote { color: var(--muted-foreground); font-style: italic; }-:is(.rich-text-editor, .transcript-code) .hljs-number,-:is(.rich-text-editor, .transcript-code) .hljs-literal { color: oklch(0.58 0.16 30); }+:is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-number,+:is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-literal { color: oklch(0.58 0.16 30); }-:is(.rich-text-editor, .transcript-code) .hljs-title,-:is(.rich-text-editor, .transcript-code) .hljs-section,-:is(.rich-text-editor, .transcript-code) .hljs-title\.function_ { color: oklch(0.55 0.14 280); }+:is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-title,+:is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-section,+:is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-title\.function_ { color: oklch(0.55 0.14 280); }-:is(.rich-text-editor, .transcript-code) .hljs-attr,-:is(.rich-text-editor, .transcript-code) .hljs-attribute { color: oklch(0.58 0.12 60); }+:is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-attr,+:is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-attribute { color: oklch(0.58 0.12 60); }-:is(.rich-text-editor, .transcript-code) .hljs-variable,-:is(.rich-text-editor, .transcript-code) .hljs-template-variable { color: oklch(0.58 0.14 20); }+:is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-variable,+:is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-template-variable { color: oklch(0.58 0.14 20); }-:is(.rich-text-editor, .transcript-code) .hljs-type,-:is(.rich-text-editor, .transcript-code) .hljs-title\.class_ { color: oklch(0.55 0.14 200); }+:is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-type,+:is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-title\.class_ { color: oklch(0.55 0.14 200); }-:is(.rich-text-editor, .transcript-code) .hljs-deletion { color: oklch(0.55 0.2 25); }+:is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-deletion { color: oklch(0.55 0.2 25); }-:is(.rich-text-editor, .transcript-code) .hljs-meta { color: var(--muted-foreground); }+:is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-meta { color: var(--muted-foreground); }/* XML / HTML — lowlight emits .hljs-tag for `<` `>` brackets and .hljs-namefor the element name. Without these rules, HTML source renders mostly inthe default text color and looks unhighlighted. */-:is(.rich-text-editor, .transcript-code) .hljs-tag { color: var(--muted-foreground); }-:is(.rich-text-editor, .transcript-code) .hljs-name { color: oklch(0.55 0.16 255); }+:is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-tag { color: var(--muted-foreground); }+:is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-name { color: oklch(0.55 0.16 255); }/* Dark mode overrides */-.dark :is(.rich-text-editor, .transcript-code) .hljs-keyword,-.dark :is(.rich-text-editor, .transcript-code) .hljs-selector-tag,-.dark :is(.rich-text-editor, .transcript-code) .hljs-built_in { color: oklch(0.7 0.14 255); }--.dark :is(.rich-text-editor, .transcript-code) .hljs-string,-.dark :is(.rich-text-editor, .transcript-code) .hljs-addition { color: oklch(0.7 0.14 155); }--.dark :is(.rich-text-editor, .transcript-code) .hljs-number,-.dark :is(.rich-text-editor, .transcript-code) .hljs-literal { color: oklch(0.72 0.14 30); }+.dark :is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-keyword,+.dark :is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-selector-tag,+.dark :is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-built_in { color: oklch(0.7 0.14 255); }++.dark :is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-string,+.dark :is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-addition { color: oklch(0.7 0.14 155); }++.dark :is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-number,+.dark :is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-literal { color: oklch(0.72 0.14 30); }++.dark :is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-title,+.dark :is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-section,+.dark :is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-title\.function_ { color: oklch(0.72 0.12 280); }++.dark :is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-attr,+.dark :is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-attribute { color: oklch(0.72 0.1 60); }++.dark :is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-variable,+.dark :is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-template-variable { color: oklch(0.72 0.12 20); }++.dark :is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-type,+.dark :is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-title\.class_ { color: oklch(0.72 0.12 200); }++.dark :is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-deletion { color: oklch(0.7 0.18 25); }++.dark :is(.rich-text-editor, .transcript-code, .structured-tree) .hljs-name { color: oklch(0.72 0.14 255); }++/* Numbered lines — CodeBlockStatic with `lineNumbers` (the attachment viewer's+ code, text and log files). A whole document rather than a block inside+ prose: no margin, no rounded panel, just the page it sits on. Each line is a+ flex row: a gutter pseudo-element carrying `data-line`, then the code. Lines+ keep their shape and the block scrolls sideways; `.code-lines-wrap` wraps+ them under their own number instead. The gutter is sticky so numbers stay+ in view while scrolling sideways, and opaque so code passing beneath it+ never shows through — a host on another surface sets `--code-gutter-bg`. */+pre.code-lines {+ margin: 0;+ border-radius: 0;+ background: transparent;+ padding: 1rem 0;+ white-space: pre;+}-.dark :is(.rich-text-editor, .transcript-code) .hljs-title,-.dark :is(.rich-text-editor, .transcript-code) .hljs-section,-.dark :is(.rich-text-editor, .transcript-code) .hljs-title\.function_ { color: oklch(0.72 0.12 280); }+pre.code-lines code {+ display: block;+ width: max-content;+ min-width: 100%;+}-.dark :is(.rich-text-editor, .transcript-code) .hljs-attr,-.dark :is(.rich-text-editor, .transcript-code) .hljs-attribute { color: oklch(0.72 0.1 60); }+pre.code-lines.code-lines-wrap code {+ width: auto;+}-.dark :is(.rich-text-editor, .transcript-code) .hljs-variable,-.dark :is(.rich-text-editor, .transcript-code) .hljs-template-variable { color: oklch(0.72 0.12 20); }+pre.code-lines .code-line {+ display: flex;+}-.dark :is(.rich-text-editor, .transcript-code) .hljs-type,-.dark :is(.rich-text-editor, .transcript-code) .hljs-title\.class_ { color: oklch(0.72 0.12 200); }+pre.code-lines .code-line::before {+ content: attr(data-line);+ position: sticky;+ left: 0;+ flex: none;+ box-sizing: content-box;+ width: calc(var(--line-digits, 1) * 1ch);+ padding-inline: 1rem 1.25rem;+ text-align: right;+ color: color-mix(in srgb, var(--muted-foreground) 70%, transparent);+ background: var(--code-gutter-bg, var(--background));+ user-select: none;+}-.dark :is(.rich-text-editor, .transcript-code) .hljs-deletion { color: oklch(0.7 0.18 25); }+pre.code-lines .code-text {+ flex: 1 0 auto;+ padding-right: 1.5rem;+ white-space: pre;+}-.dark :is(.rich-text-editor, .transcript-code) .hljs-name { color: oklch(0.72 0.14 255); }+pre.code-lines.code-lines-wrap .code-text {+ flex: 1 1 0;+ min-width: 0;+ white-space: pre-wrap;+ overflow-wrap: anywhere;+}diff --git a/packages/views/editor/table-preview.test.tsx b/packages/views/editor/table-preview.test.tsxnew file mode 100644index 0000000000..ace2675fa5--- /dev/null+++ b/packages/views/editor/table-preview.test.tsx@@ -0,0 +1,119 @@+import { describe, expect, it, vi } from "vitest";+import { fireEvent, screen, within } from "@testing-library/react";+import { renderWithI18n } from "../test/i18n";+import { compareCells, TablePreview } from "./table-preview";++// The body virtualizes; render every row so DOM order reflects sort order.+vi.mock("@tanstack/react-virtual", () => ({+ useVirtualizer: ({ count }: { count: number }) => ({+ getVirtualItems: () =>+ Array.from({ length: count }, (_, index) => ({+ index,+ key: index,+ start: index * 37,+ end: (index + 1) * 37,+ size: 37,+ })),+ getTotalSize: () => count * 37,+ measureElement: () => {},+ }),+}));++function columnValues(columnId: string): string[] {+ return Array.from(+ document.querySelectorAll(`tbody td[data-column-id='${columnId}']`),+ (cell) => cell.textContent ?? "",+ );+}++function header(name: string): HTMLElement {+ return screen.getByRole("button", { name });+}++describe("TablePreview", () => {+ it("takes the first record as the header and numbers the rows", () => {+ renderWithI18n(<TablePreview text={"name,count\nalpha,3\nbeta,10\n"} delimiter="," />);++ expect(header("name")).toBeTruthy();+ expect(header("count")).toBeTruthy();+ expect(columnValues("c0")).toEqual(["alpha", "beta"]);+ expect(columnValues("__row")).toEqual(["1", "2"]);+ expect(screen.getByText(/2 rows/)).toHaveTextContent("2 rows · 2 columns");+ });++ it("sorts numbers as numbers, then descending, then back to file order", () => {+ renderWithI18n(+ <TablePreview text={"item,qty\na,10\nb,9\nc,\nd,100\n"} delimiter="," />,+ );+ const th = () => document.querySelector("th[data-column-id='c1']");++ fireEvent.click(header("qty"));+ expect(columnValues("c1")).toEqual(["9", "10", "100", ""]);+ expect(th()).toHaveAttribute("aria-sort", "ascending");++ fireEvent.click(header("qty"));+ // Empty cells stay last whichever way the column sorts.+ expect(columnValues("c1")).toEqual(["100", "10", "9", ""]);+ expect(th()).toHaveAttribute("aria-sort", "descending");++ fireEvent.click(header("qty"));+ expect(columnValues("c1")).toEqual(["10", "9", "", "100"]);+ expect(th()).not.toHaveAttribute("aria-sort");+ });++ it("keeps each row's file position in the row-number column while sorted", () => {+ renderWithI18n(<TablePreview text={"k\nb\na\n"} delimiter="," />);+ fireEvent.click(header("k"));+ expect(columnValues("c0")).toEqual(["a", "b"]);+ expect(columnValues("__row")).toEqual(["2", "1"]);+ });++ it("right-aligns an all-number column", () => {+ renderWithI18n(<TablePreview text={"name,qty\na,1\nb,2.5\n"} delimiter="," />);+ const qty = document.querySelector("tbody td[data-column-id='c1'] span");+ const name = document.querySelector("tbody td[data-column-id='c0'] span");+ expect(qty).toHaveClass("text-right");+ expect(name).not.toHaveClass("text-right");+ });++ it("reads a semicolon-separated CSV and a TSV", () => {+ const { unmount } = renderWithI18n(<TablePreview text={"a;b\n1;2\n"} delimiter="," />);+ expect(columnValues("c1")).toEqual(["2"]);+ unmount();++ renderWithI18n(<TablePreview text={"a\tb,c\n1\t2,3\n"} delimiter={"\t"} />);+ expect(header("b,c")).toBeTruthy();+ expect(columnValues("c1")).toEqual(["2,3"]);+ });++ it("shows the file's column names as written", () => {+ renderWithI18n(<TablePreview text={"userId,created_at\n1,2\n"} delimiter="," />);+ const title = within(header("userId")).getByText("userId");+ expect(title.closest("button")).toHaveClass("normal-case");+ });++ it("says so when there are no rows", () => {+ renderWithI18n(<TablePreview text={"only,a,header\n"} delimiter="," />);+ expect(screen.getByText("No rows")).toBeTruthy();+ expect(screen.getByText(/0 rows/)).toHaveTextContent("0 rows · 3 columns");+ });++ it("uses the localized counts", () => {+ renderWithI18n(<TablePreview text={"a,b\n1,2\n"} delimiter="," />, { locale: "zh-Hans" });+ expect(screen.getByText(/1 行/)).toHaveTextContent("1 行 · 2 列");+ });+});++describe("compareCells", () => {+ it("orders numbers numerically and ahead of text", () => {+ expect(["b", "10", "9", "a"].sort(compareCells)).toEqual(["9", "10", "a", "b"]);+ });++ it("orders text naturally and case-insensitively", () => {+ expect(["file10", "File2", "file1"].sort(compareCells)).toEqual([+ "file1",+ "File2",+ "file10",+ ]);+ });+});diff --git a/packages/views/editor/table-preview.tsx b/packages/views/editor/table-preview.tsxnew file mode 100644index 0000000000..252df94b8a--- /dev/null+++ b/packages/views/editor/table-preview.tsx@@ -0,0 +1,270 @@+"use client";++/**+ * TablePreview — a CSV / TSV attachment as a table, for the viewer's `table`+ * kind.+ *+ * Rendered by the shared DataTable, so the header stays pinned while the body+ * scrolls, rows virtualize (a 2 MB export is tens of thousands of them), and+ * columns resize by dragging their edge. Clicking a header sorts by that+ * column: ascending, descending, then back to file order. The row-number+ * column is frozen on the left and keeps each row's position in the file, so+ * a sorted row can still be found in the source.+ *+ * The first record is the header, as in every spreadsheet import.+ */++import { useMemo, useState } from "react";+import {+ getCoreRowModel,+ getSortedRowModel,+ useReactTable,+ type ColumnDef,+ type Row,+ type SortingState,+} from "@tanstack/react-table";+import { ArrowDown, ArrowUp, ArrowUpDown } from "lucide-react";+import { DataTable } from "@multica/ui/components/ui/data-table";+import { cn } from "@multica/ui/lib/utils";+import { useT } from "../i18n";+import {+ parseDelimited,+ sniffDelimiter,+ toTable,+ type CellDelimiter,+} from "./utils/parse-delimited";++const ROW_NUMBER_COLUMN = "__row";++// Column widths come from the content, not a flat default: an `id` column+// and a `description` column should not start out the same size. Estimated+// from a sample of rows, then clamped so one long value cannot claim the+// whole table — the user can widen any column by dragging.+const SAMPLE_ROWS = 200;+const BODY_FONT_PX = 14;+const HEADER_FONT_PX = 12;+const CELL_PADDING = 32;+// The sort arrow and its gap beside a header's name.+const SORT_ICON_ROOM = 18;+const MIN_COLUMN_WIDTH = 72;+const MAX_COLUMN_WIDTH = 320;+const ROW_HEIGHT = 37;+const SCROLLBAR_SLACK = 16;++// Rendered width of `value` at `fontPx`, in em-fractions per character class+// of a proportional UI face: figures and capitals run wide (and figures are+// tabular), lowercase and punctuation narrower, CJK glyphs a full em.+function textWidth(value: string, fontPx: number): number {+ let ems = 0;+ for (const char of value) {+ if ((char.codePointAt(0) ?? 0) > 0x2e80) ems += 1;+ else if (/[0-9A-Z]/.test(char)) ems += 0.64;+ else ems += 0.54;+ }+ return ems * fontPx;+}++function toNumber(value: string): number | null {+ const trimmed = value.trim();+ if (trimmed === "") return null;+ const number = Number(trimmed);+ return Number.isFinite(number) ? number : null;+}++const collator = new Intl.Collator(undefined, {+ numeric: true,+ sensitivity: "base",+});++// Numbers compare as numbers (so 9 < 10), and sort ahead of text in a mixed+// column. Empty cells never reach here — `sortUndefined: "last"` keeps them at+// the bottom in both directions.+export function compareCells(a: string, b: string): number {+ const x = toNumber(a);+ const y = toNumber(b);+ if (x !== null && y !== null) return x - y;+ if (x !== null) return -1;+ if (y !== null) return 1;+ return collator.compare(a, b);+}++interface ColumnInfo {+ width: number;+ numeric: boolean;+}++function describeColumns(header: string[], rows: string[][]): ColumnInfo[] {+ const sample = rows.slice(0, SAMPLE_ROWS);+ return header.map((title, index) => {+ let widest = textWidth(title, HEADER_FONT_PX) + SORT_ICON_ROOM;+ let numbers = 0;+ let filled = 0;+ for (const row of sample) {+ const value = row[index] ?? "";+ widest = Math.max(widest, textWidth(value, BODY_FONT_PX));+ if (value.trim() === "") continue;+ filled += 1;+ if (toNumber(value) !== null) numbers += 1;+ }+ const width = Math.ceil(widest + CELL_PADDING);+ return {+ width: Math.min(MAX_COLUMN_WIDTH, Math.max(MIN_COLUMN_WIDTH, width)),+ numeric: filled > 0 && numbers === filled,+ };+ });+}++function sortByCell(rowA: Row<string[]>, rowB: Row<string[]>, columnId: string) {+ return compareCells(+ rowA.getValue<string>(columnId),+ rowB.getValue<string>(columnId),+ );+}++interface TablePreviewProps {+ text: string;+ /** `\t` for TSV. A CSV's delimiter is sniffed — `;` exports are common. */+ delimiter: "," | "\t";+}++export function TablePreview({ text, delimiter }: TablePreviewProps) {+ const { t } = useT("editor");+ const [sorting, setSorting] = useState<SortingState>([]);++ const table = useMemo(() => {+ const cellDelimiter: CellDelimiter =+ delimiter === "\t" ? "\t" : sniffDelimiter(text);+ return toTable(parseDelimited(text, cellDelimiter));+ }, [text, delimiter]);++ const columnInfo = useMemo(+ () => describeColumns(table.header, table.rows),+ [table],+ );++ const columns = useMemo<ColumnDef<string[]>[]>(() => {+ const digits = String(table.rows.length).length;+ const rowNumber: ColumnDef<string[]> = {+ id: ROW_NUMBER_COLUMN,+ header: "#",+ cell: ({ row }) => (+ <span className="block text-right tabular-nums text-muted-foreground">+ {row.index + 1}+ </span>+ ),+ size: Math.max(48, Math.ceil(digits * 0.64 * BODY_FONT_PX) + CELL_PADDING),+ enableSorting: false,+ enableResizing: false,+ };+ return [+ rowNumber,+ ...table.header.map<ColumnDef<string[]>>((title, index) => ({+ id: `c${index}`,+ // Empty cells read as "no value" so they can sort last.+ accessorFn: (row) => (row[index] === "" ? undefined : row[index]),+ header: ({ column }) => (+ <SortHeader+ title={title}+ numeric={columnInfo[index]?.numeric ?? false}+ sorted={column.getIsSorted()}+ onToggle={column.getToggleSortingHandler()}+ />+ ),+ cell: ({ getValue }) => {+ const value = getValue<string | undefined>() ?? "";+ return (+ <span+ className={cn(+ "block truncate",+ columnInfo[index]?.numeric && "text-right tabular-nums",+ )}+ title={value}+ >+ {value}+ </span>+ );+ },+ size: columnInfo[index]?.width ?? MIN_COLUMN_WIDTH,+ minSize: 48,+ sortingFn: sortByCell,+ sortUndefined: "last",+ })),+ ];+ }, [table, columnInfo]);++ const reactTable = useReactTable({+ data: table.rows,+ columns,+ state: { sorting },+ onSortingChange: setSorting,+ getCoreRowModel: getCoreRowModel(),+ getSortedRowModel: getSortedRowModel(),+ initialState: { columnPinning: { left: [ROW_NUMBER_COLUMN] } },+ columnResizeMode: "onChange",+ });++ return (+ <div className="flex h-full flex-col pb-4">+ {/* As wide as the columns need, up to the stage: a three-column file+ reads as a sheet, a wide export uses every pixel and scrolls. The+ slack is a classic scrollbar's width, so one never forces a+ sideways scroll on its own. */}+ <div+ className="mx-auto flex min-h-0 w-full flex-1 flex-col overflow-hidden rounded-lg bg-background text-foreground"+ style={{ maxWidth: reactTable.getTotalSize() + SCROLLBAR_SLACK }}+ data-testid="table-preview"+ >+ <DataTable+ table={reactTable}+ virtualizeRows+ virtualRowHeight={ROW_HEIGHT}+ emptyMessage={t(($) => $.attachment.table_empty)}+ />+ <p className="shrink-0 border-t border-border px-4 py-1.5 text-caption tabular-nums text-muted-foreground">+ {t(($) => $.attachment.table_rows, { count: table.rows.length })}+ {" · "}+ {t(($) => $.attachment.table_columns, { count: table.columnCount })}+ </p>+ </div>+ </div>+ );+}++function SortHeader({+ title,+ numeric,+ sorted,+ onToggle,+}: {+ title: string;+ numeric: boolean;+ sorted: false | "asc" | "desc";+ onToggle: ((event: unknown) => void) | undefined;+}) {+ const Icon = sorted === "asc" ? ArrowUp : sorted === "desc" ? ArrowDown : ArrowUpDown;+ return (+ <button+ type="button"+ onClick={onToggle}+ className={cn(+ // The table header's spreadsheet casing is for labels the app wrote;+ // these are the file's own column names and show as written.+ "group/sort flex w-full min-w-0 items-center gap-1 rounded-sm normal-case tracking-normal text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring",+ numeric && "flex-row-reverse",+ )}+ >+ <span className="truncate font-medium" title={title}>+ {title}+ </span>+ <Icon+ aria-hidden+ className={cn(+ "size-3.5 shrink-0",+ sorted+ ? "text-foreground"+ : "text-muted-foreground opacity-0 transition-opacity group-hover/sort:opacity-100 group-focus-visible/sort:opacity-100",+ )}+ />+ </button>+ );+}diff --git a/packages/views/editor/utils/file-icon.ts b/packages/views/editor/utils/file-icon.tsindex 3d1818bcdf..f7d35db3bd 100644--- a/packages/views/editor/utils/file-icon.ts+++ b/packages/views/editor/utils/file-icon.ts@@ -54,7 +54,10 @@ export function fileIcon(contentType: string, filename: string): LucideIcon {case "pdf":case "markdown":return FileText;+ case "table":+ return FileSpreadsheet;case "html":+ case "structured":case "text":return FileCode;default:diff --git a/packages/views/editor/utils/parse-delimited.test.ts b/packages/views/editor/utils/parse-delimited.test.tsnew file mode 100644index 0000000000..20f62845d3--- /dev/null+++ b/packages/views/editor/utils/parse-delimited.test.ts@@ -0,0 +1,86 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import { parseDelimited, sniffDelimiter, toTable } from "./parse-delimited";++describe("parseDelimited", () => {+ it("splits records and fields", () => {+ expect(parseDelimited("a,b\n1,2\n", ",")).toEqual([+ ["a", "b"],+ ["1", "2"],+ ]);+ });++ it("keeps delimiters, quotes and line breaks inside quoted fields", () => {+ const text = 'name,note\n"Doe, Jane","said ""hi""\nthen left"\n';+ expect(parseDelimited(text, ",")).toEqual([+ ["name", "note"],+ ["Doe, Jane", 'said "hi"\nthen left'],+ ]);+ });++ it("accepts CRLF and CR line endings and a missing final newline", () => {+ expect(parseDelimited("a,b\r\n1,2\r3,4", ",")).toEqual([+ ["a", "b"],+ ["1", "2"],+ ["3", "4"],+ ]);+ });++ it("strips a UTF-8 byte order mark", () => {+ expect(parseDelimited("id,name\n1,x", ",")[0]).toEqual(["id", "name"]);+ });++ it("keeps empty fields but skips blank lines", () => {+ expect(parseDelimited("a,,c\n\n,,\n", ",")).toEqual([+ ["a", "", "c"],+ ["", "", ""],+ ]);+ });++ it("treats a quote that does not open a field as text", () => {+ expect(parseDelimited('5" screen,ok\n"x"y,z', ",")).toEqual([+ ['5" screen', "ok"],+ ["xy", "z"],+ ]);+ });++ it("splits TSV on tabs only", () => {+ expect(parseDelimited("a\tb,c\n1\t2", "\t")).toEqual([+ ["a", "b,c"],+ ["1", "2"],+ ]);+ });++ it("returns nothing for an empty file", () => {+ expect(parseDelimited("", ",")).toEqual([]);+ });+});++describe("sniffDelimiter", () => {+ it("picks whichever candidate splits the first line most", () => {+ expect(sniffDelimiter("a,b,c\n1,2,3")).toBe(",");+ expect(sniffDelimiter("a;b;c\n1,5;2,5;3")).toBe(";");+ expect(sniffDelimiter("a\tb\tc")).toBe("\t");+ });++ it("defaults to a comma for a single column", () => {+ expect(sniffDelimiter("only\n1\n2")).toBe(",");+ });+});++describe("toTable", () => {+ it("pads ragged records to the widest one", () => {+ expect(toTable([["a", "b"], ["1"], ["1", "2", "3"]])).toEqual({+ header: ["a", "b", ""],+ rows: [+ ["1", "", ""],+ ["1", "2", "3"],+ ],+ columnCount: 3,+ });+ });++ it("handles no records at all", () => {+ expect(toTable([])).toEqual({ header: [], rows: [], columnCount: 0 });+ });+});diff --git a/packages/views/editor/utils/parse-delimited.ts b/packages/views/editor/utils/parse-delimited.tsnew file mode 100644index 0000000000..9e41b304e3--- /dev/null+++ b/packages/views/editor/utils/parse-delimited.ts@@ -0,0 +1,112 @@+/**+ * CSV / TSV parsing for the attachment viewer's table.+ *+ * RFC 4180 with the usual leniency: a quote is only special at the start of a+ * field, `""` inside a quoted field is a literal quote, quoted fields may hold+ * delimiters and line breaks, and CRLF / LF / CR all end a record. Anything a+ * strict parser would reject (text after a closing quote, an unterminated+ * quote) is kept as text instead — a preview shows what is in the file rather+ * than refusing it.+ */++export type CellDelimiter = "," | ";" | "\t";++export interface ParsedTable {+ /** The first record. Padded to `columnCount`. */+ header: string[];+ /** Every later record, each padded to `columnCount`. */+ rows: string[][];+ /** The widest record's field count — ragged files keep every value. */+ columnCount: number;+}++const CANDIDATES: readonly CellDelimiter[] = [",", ";", "\t"];++/**+ * The delimiter a `.csv` file actually uses. Spreadsheets in locales with a+ * decimal comma export `;`, and a mislabeled TSV is common. Read off the first+ * record: whichever candidate splits it most wins, a comma on ties.+ */+export function sniffDelimiter(text: string): CellDelimiter {+ let end = text.search(/\r|\n/);+ if (end < 0) end = text.length;+ const firstLine = text.slice(0, end);+ let best: CellDelimiter = ",";+ let bestCount = 0;+ for (const candidate of CANDIDATES) {+ const count = firstLine.split(candidate).length - 1;+ if (count > bestCount) {+ best = candidate;+ bestCount = count;+ }+ }+ return best;+}++export function parseDelimited(text: string, delimiter: CellDelimiter): string[][] {+ const records: string[][] = [];+ let record: string[] = [];+ let field = "";+ let i = text.charCodeAt(0) === 0xfeff ? 1 : 0;+ const length = text.length;++ const endField = () => {+ record.push(field);+ field = "";+ };+ const endRecord = () => {+ endField();+ // A blank line is spacing, not a row of one empty cell.+ if (record.length > 1 || record[0] !== "") records.push(record);+ record = [];+ };++ while (i < length) {+ const char = text[i];++ if (char === '"' && field === "") {+ // Quoted field: read to the closing quote, unescaping `""`.+ i += 1;+ while (i < length) {+ if (text[i] === '"') {+ if (text[i + 1] === '"') {+ field += '"';+ i += 2;+ continue;+ }+ i += 1;+ break;+ }+ field += text[i];+ i += 1;+ }+ continue;+ }++ if (char === delimiter) {+ endField();+ i += 1;+ } else if (char === "\r" || char === "\n") {+ endRecord();+ i += char === "\r" && text[i + 1] === "\n" ? 2 : 1;+ } else {+ field += char;+ i += 1;+ }+ }++ // The last record, unless the file simply ended with a line break.+ if (field !== "" || record.length > 0) endRecord();+ return records;+}++/** Splits parsed records into a header and padded rows. */+export function toTable(records: string[][]): ParsedTable {+ const columnCount = records.reduce((max, r) => Math.max(max, r.length), 0);+ const pad = (record: string[]) =>+ record.length === columnCount+ ? record+ : [...record, ...Array<string>(columnCount - record.length).fill("")];+ const [header = [], ...rows] = records;+ return { header: pad(header), rows: rows.map(pad), columnCount };+}diff --git a/packages/views/editor/utils/parse-structured.test.ts b/packages/views/editor/utils/parse-structured.test.tsnew file mode 100644index 0000000000..bd498b3d39--- /dev/null+++ b/packages/views/editor/utils/parse-structured.test.ts@@ -0,0 +1,65 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import { parseStructured } from "./parse-structured";++describe("parseStructured", () => {+ it("parses JSON", () => {+ expect(parseStructured('{"a":[1,true,null]}', "json")).toEqual({+ ok: true,+ value: { a: [1, true, null] },+ });+ });++ it("reports why JSON failed", () => {+ const result = parseStructured('{"a":', "json");+ expect(result.ok).toBe(false);+ expect(!result.ok && result.message).toBeTruthy();+ });++ it("parses JSON Lines into a list, skipping blank lines", () => {+ expect(parseStructured('{"n":1}\n\n{"n":2}\r\n', "jsonl")).toEqual({+ ok: true,+ value: [{ n: 1 }, { n: 2 }],+ });+ });++ it("names the JSON Lines line that failed", () => {+ const result = parseStructured('{"n":1}\n{oops}\n', "jsonl");+ expect(result.ok).toBe(false);+ expect(!result.ok && result.message).toMatch(/^Line 2: /);+ });++ it("parses YAML", () => {+ expect(parseStructured("name: web\nports:\n - 80\n - 443\n", "yaml")).toEqual({+ ok: true,+ value: { name: "web", ports: [80, 443] },+ });+ });++ it("shows a multi-document YAML stream as a list of documents", () => {+ expect(parseStructured("kind: A\n---\nkind: B\n", "yaml")).toEqual({+ ok: true,+ value: [{ kind: "A" }, { kind: "B" }],+ });+ });++ it("treats an empty YAML file as null", () => {+ expect(parseStructured("", "yaml")).toEqual({ ok: true, value: null });+ });++ it("reports YAML syntax errors", () => {+ const result = parseStructured("a: [1, 2\nb: 3", "yaml");+ expect(result.ok).toBe(false);+ });++ it("refuses runaway alias expansion instead of hanging", () => {+ const bomb = [+ "a: &a [x, x, x, x, x, x, x, x, x]",+ "b: &b [*a, *a, *a, *a, *a, *a, *a, *a, *a]",+ "c: &c [*b, *b, *b, *b, *b, *b, *b, *b, *b]",+ "d: &d [*c, *c, *c, *c, *c, *c, *c, *c, *c]",+ "e: [*d, *d, *d, *d, *d, *d, *d, *d, *d]",+ ].join("\n");+ expect(parseStructured(bomb, "yaml").ok).toBe(false);+ });+});diff --git a/packages/views/editor/utils/parse-structured.ts b/packages/views/editor/utils/parse-structured.tsnew file mode 100644index 0000000000..22ea0bc9f9--- /dev/null+++ b/packages/views/editor/utils/parse-structured.ts@@ -0,0 +1,65 @@+/**+ * Parses a `structured` attachment (JSON, JSON Lines, YAML) for the viewer's+ * tree. A failure carries the parser's own message — it names the line — so+ * the viewer can say why it fell back to the source.+ */++import { parseAllDocuments } from "yaml";+import type { StructuredFormat } from "./preview";++export type StructuredParse =+ | { ok: true; value: unknown }+ | { ok: false; message: string };++function errorMessage(error: unknown): string {+ return error instanceof Error ? error.message : String(error);+}++function parseJsonLines(text: string): StructuredParse {+ const values: unknown[] = [];+ const lines = text.split(/\r\n|\n|\r/);+ for (let i = 0; i < lines.length; i++) {+ const line = lines[i]!;+ if (line.trim() === "") continue;+ try {+ values.push(JSON.parse(line));+ } catch (error) {+ return { ok: false, message: `Line ${i + 1}: ${errorMessage(error)}` };+ }+ }+ return { ok: true, value: values };+}++function parseYaml(text: string): StructuredParse {+ // Every document in the stream: a multi-document file (`---` separated,+ // e.g. Kubernetes manifests) shows as a list of its documents.+ const documents = parseAllDocuments(text);+ const values: unknown[] = [];+ for (const document of documents) {+ const [firstError] = document.errors;+ if (firstError) return { ok: false, message: firstError.message };+ // toJS enforces yaml's alias expansion cap, so a "billion laughs" file+ // throws here instead of exhausting memory.+ values.push(document.toJS());+ }+ if (values.length === 0) return { ok: true, value: null };+ return { ok: true, value: values.length === 1 ? values[0] : values };+}++export function parseStructured(+ text: string,+ format: StructuredFormat,+): StructuredParse {+ try {+ switch (format) {+ case "json":+ return { ok: true, value: JSON.parse(text) };+ case "jsonl":+ return parseJsonLines(text);+ case "yaml":+ return parseYaml(text);+ }+ } catch (error) {+ return { ok: false, message: errorMessage(error) };+ }+}diff --git a/packages/views/editor/utils/preview.test.ts b/packages/views/editor/utils/preview.test.tsindex 9439c2a015..23bd802da4 100644--- a/packages/views/editor/utils/preview.test.ts+++ b/packages/views/editor/utils/preview.test.ts@@ -4,6 +4,9 @@ import {extensionToLanguage,getPreviewKind,isPreviewable,+ structuredFormat,+ tableDelimiter,+ wrapsByDefault,type PreviewKind,} from "./preview";@@ -26,9 +29,21 @@ describe("getPreviewKind", () => {// Code / config — fallback to text after sniffer guesses "text/plain"["text/plain", "main.go", "text"],["application/octet-stream", "main.go", "text"],- ["text/plain", "config.yml", "text"],["application/javascript", "bundle.js", "text"],- ["application/json", "data.json", "text"],++ // Tables — the sniffer usually says text/plain, so the extension decides+ ["text/csv", "report.csv", "table"],+ ["text/plain", "report.csv", "table"],+ ["application/octet-stream", "export.tsv", "table"],+ ["text/tab-separated-values", "export", "table"],++ // Structured data — tree view+ ["application/json", "data.json", "structured"],+ ["text/plain", "config.yml", "structured"],+ ["application/octet-stream", "compose.yaml", "structured"],+ ["text/plain", "events.jsonl", "structured"],+ ["application/octet-stream", "events.ndjson", "structured"],+ ["application/x-yaml", "values", "structured"],// Plain text["text/plain", "log.txt", "text"],@@ -59,6 +74,39 @@ describe("getPreviewKind", () => {});});+describe("structuredFormat", () => {+ it("reads the format from the extension first", () => {+ expect(structuredFormat("text/plain", "a.json")).toBe("json");+ expect(structuredFormat("application/json", "a.jsonl")).toBe("jsonl");+ expect(structuredFormat("text/plain", "a.ndjson")).toBe("jsonl");+ expect(structuredFormat("text/plain", "a.yml")).toBe("yaml");+ });++ it("falls back to the content type for extension-less files", () => {+ expect(structuredFormat("application/json; charset=utf-8", "payload")).toBe("json");+ expect(structuredFormat("application/yaml", "values")).toBe("yaml");+ expect(structuredFormat("text/plain", "notes.txt")).toBeNull();+ });+});++describe("tableDelimiter", () => {+ it("is a tab for TSV and a comma otherwise", () => {+ expect(tableDelimiter("text/plain", "export.tsv")).toBe("\t");+ expect(tableDelimiter("text/tab-separated-values", "export")).toBe("\t");+ expect(tableDelimiter("text/csv", "report.csv")).toBe(",");+ });+});++describe("wrapsByDefault", () => {+ it("wraps prose and logs, keeps code lines intact", () => {+ expect(wrapsByDefault("server.log")).toBe(true);+ expect(wrapsByDefault("notes.txt")).toBe(true);+ expect(wrapsByDefault("LICENSE")).toBe(true);+ expect(wrapsByDefault("main.go")).toBe(false);+ expect(wrapsByDefault("page.html")).toBe(false);+ });+});+describe("isPreviewable", () => {it("is true for any non-null PreviewKind", () => {expect(isPreviewable("application/pdf", "x.pdf")).toBe(true);@@ -101,3 +149,50 @@ describe("extensionToLanguage", () => {expect(extensionToLanguage("noextension")).toBeUndefined();});});++// Mirror of TestIsTextPreviewable in server/internal/handler/file_test.go,+// the text proxy's whitelist. Keep the two tables identical: a type only the+// client accepts opens to a 415, one only the server accepts never opens.+describe("text preview whitelist (mirrors the server)", () => {+ const TEXT_BACKED = new Set<PreviewKind>(["markdown", "html", "table", "structured", "text"]);+ const cases: Array<[string, string, string, boolean]> = [+ ["markdown by ext", "application/octet-stream", "README.md", true],+ ["markdown by mime", "text/markdown", "README", true],+ ["plain text", "text/plain", "log.txt", true],+ ["json by mime", "application/json", "data.json", true],+ ["yaml by ext", "application/octet-stream", "config.yml", true],+ ["csv by ext", "application/octet-stream", "report.csv", true],+ ["tsv by ext", "application/octet-stream", "export.tsv", true],+ ["json lines by ext", "application/octet-stream", "events.jsonl", true],+ ["ndjson by ext", "application/octet-stream", "events.ndjson", true],+ ["ndjson by mime", "application/x-ndjson", "events", true],+ ["log by ext", "application/octet-stream", "server.log", true],+ ["go source", "text/plain", "main.go", true],+ ["typescript", "application/octet-stream", "index.ts", true],+ ["html", "text/html", "page.html", true],+ ["dockerfile no ext", "application/octet-stream", "Dockerfile", true],+ ["makefile no ext", "application/octet-stream", "Makefile", true],+ ["env dotfile", "application/octet-stream", ".env", true],+ ["gitignore dotfile", "application/octet-stream", ".gitignore", true],+ ["dockerfile extension", "application/octet-stream", "service.dockerfile", true],+ ["makefile extension", "application/octet-stream", "rules.makefile", true],++ ["pdf rejected", "application/pdf", "doc.pdf", false],+ ["png rejected", "image/png", "shot.png", false],+ ["video rejected", "video/mp4", "clip.mp4", false],+ ["binary fallthrough", "application/octet-stream", "blob.bin", false],+ [+ "docx rejected",+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",+ "report.docx",+ false,+ ],+ ];++ for (const [name, contentType, filename, want] of cases) {+ it(name, () => {+ const kind = getPreviewKind(contentType, filename);+ expect(kind !== null && TEXT_BACKED.has(kind)).toBe(want);+ });+ }+});diff --git a/packages/views/editor/utils/preview.ts b/packages/views/editor/utils/preview.tsindex bda8954e47..9c69854b54 100644--- a/packages/views/editor/utils/preview.ts+++ b/packages/views/editor/utils/preview.ts@@ -5,7 +5,9 @@* 1. Add a new branch returning a new PreviewKind literal.* 2. Add the corresponding renderer in attachment-preview-modal.tsx's dispatch.* 3. If the renderer needs the file body as text, also extend isTextPreviewable- * in server/internal/handler/file.go so the proxy endpoint accepts it.+ * in server/internal/handler/file.go so the proxy endpoint accepts it, and+ * add the type to the case table both sides test (preview.test.ts and+ * TestIsTextPreviewable in file_test.go).* 4. If the renderer fetches a binary, decide whether to use download_url* (CloudFront, no auth on the client side) or a new authenticated proxy.*/@@ -19,8 +21,16 @@ export type PreviewKind =| "audio"| "markdown"| "html"+ // CSV / TSV — a sortable table.+ | "table"+ // JSON / JSON Lines / YAML — a collapsible tree, with the source one toggle+ // away.+ | "structured"| "text";+/** How a `structured` file's body parses. */+export type StructuredFormat = "json" | "jsonl" | "yaml";+const EXT_LANGUAGE_MAP: Record<string, string> = {// Markdownmd: "markdown",@@ -40,6 +50,8 @@ const EXT_LANGUAGE_MAP: Record<string, string> = {less: "less",// Config / datajson: "json",+ jsonl: "json",+ ndjson: "json",yml: "yaml",yaml: "yaml",toml: "ini",@@ -97,7 +109,7 @@ const BASENAME_LANGUAGE_MAP: Record<string, string> = {// (mirror reserved-slugs pattern in server/internal/handler/reserved_slugs.json).const TEXT_EXTENSIONS = new Set<string>(["md", "markdown", "txt", "log", "csv", "tsv",- "html", "htm", "json", "xml",+ "html", "htm", "json", "jsonl", "ndjson", "xml","yml", "yaml", "toml", "ini", "conf","dockerfile", "makefile", "gitignore","sh", "bash", "zsh",@@ -112,6 +124,7 @@ const TEXT_EXTENSIONS = new Set<string>([const TEXT_CONTENT_TYPES = new Set<string>(["application/json",+ "application/x-ndjson","application/javascript","application/xml","application/x-yaml",@@ -128,6 +141,28 @@ const TEXT_BASENAMES = new Set<string>([".gitignore",]);+const TABLE_CONTENT_TYPES = new Set<string>([+ "text/csv",+ "text/tab-separated-values",+]);++const STRUCTURED_EXT_FORMATS: Record<string, StructuredFormat> = {+ json: "json",+ jsonl: "jsonl",+ ndjson: "jsonl",+ yml: "yaml",+ yaml: "yaml",+};++const STRUCTURED_CONTENT_TYPE_FORMATS: Record<string, StructuredFormat> = {+ "application/json": "json",+ "application/x-ndjson": "jsonl",+ "application/yaml": "yaml",+ "application/x-yaml": "yaml",+ "text/yaml": "yaml",+ "text/x-yaml": "yaml",+};+// Extension fallbacks for media kinds — used when contentType is empty// (URL-only preview source, no server-side metadata available).const VIDEO_EXTS = new Set<string>([@@ -194,11 +229,37 @@ export function getPreviewKind(if (ct === "text/html" || ext === "html" || ext === "htm") {return "html";}+ if (TABLE_CONTENT_TYPES.has(ct) || ext === "csv" || ext === "tsv") {+ return "table";+ }+ if (structuredFormat(contentType, filename)) return "structured";if (isTextLike(contentType, filename)) return "text";return null;}+/**+ * The parser a `structured` file needs, or null when it is not one. The+ * extension wins over the content type: a sniffer labels most of these+ * `text/plain`, and a `.jsonl` uploaded as `application/json` is still lines.+ */+export function structuredFormat(+ contentType: string,+ filename: string,+): StructuredFormat | null {+ const ext = extOf(filename);+ if (ext && STRUCTURED_EXT_FORMATS[ext]) return STRUCTURED_EXT_FORMATS[ext];+ return STRUCTURED_CONTENT_TYPE_FORMATS[normalizeContentType(contentType)] ?? null;+}++/** The cell separator of a `table` file: tab for TSV, comma otherwise. */+export function tableDelimiter(contentType: string, filename: string): "," | "\t" {+ return extOf(filename) === "tsv" ||+ normalizeContentType(contentType) === "text/tab-separated-values"+ ? "\t"+ : ",";+}+/** Short type label for metadata lines — the extension, upper-cased (`PNG`). */export function fileTypeLabel(filename: string): string {return extOf(filename).toUpperCase();@@ -226,6 +287,16 @@ export function canOpenPreview(return kind !== null && (hasRecord || URL_PREVIEWABLE_KINDS.has(kind));}+/**+ * Whether a file reads better with long lines wrapped. Prose and logs do —+ * their lines are paragraphs and messages; code keeps its lines intact so+ * indentation stays readable, and scrolls sideways instead.+ */+export function wrapsByDefault(filename: string): boolean {+ const language = extensionToLanguage(filename);+ return language === undefined || language === "plaintext";+}+// Pick the hljs language token for a file. Returns undefined when the file// doesn't have a recognizable extension — callers can fall back to a plain// `<pre>` render. Kept tiny and ext-driven on purpose: lowlight's `common`diff --git a/packages/views/locales/en/editor.json b/packages/views/locales/en/editor.jsonindex f8f232a258..fe566a44e4 100644--- a/packages/views/locales/en/editor.json+++ b/packages/views/locales/en/editor.json@@ -63,7 +63,29 @@"next": "Next","sequence_position": "{{index}} / {{total}}","overview": "All deliverables",- "info": "Info"+ "info": "Info",+ "wrap_lines": "Wrap lines",+ "viewport": "Viewport width",+ "viewport_fill": "Fit",+ "viewport_desktop": "Desktop",+ "viewport_tablet": "Tablet",+ "viewport_phone": "Phone",+ "viewport_scale": "Scaled to {{percent}}%",+ "view_source": "View source",+ "view_mode": "View",+ "view_tree": "Tree",+ "view_raw": "Raw",+ "structured_parse_failed": "Couldn't parse this file, so it's shown as text.",+ "tree_show_more": "Show more ({{count}} left)",+ "tree_items_one": "{{count}} item",+ "tree_items_other": "{{count}} items",+ "tree_keys_one": "{{count}} key",+ "tree_keys_other": "{{count}} keys",+ "table_empty": "No rows",+ "table_rows_one": "{{count}} row",+ "table_rows_other": "{{count}} rows",+ "table_columns_one": "{{count}} column",+ "table_columns_other": "{{count}} columns"},"link_hover": {"copy_link": "Copy link",diff --git a/packages/views/locales/fr/editor.json b/packages/views/locales/fr/editor.jsonindex 1caf00b71d..f5afd8d7db 100644--- a/packages/views/locales/fr/editor.json+++ b/packages/views/locales/fr/editor.json@@ -63,7 +63,29 @@"next": "Suivant","sequence_position": "{{index}} / {{total}}","overview": "Tous les livrables",- "info": "Informations"+ "info": "Informations",+ "wrap_lines": "Retour à la ligne",+ "viewport": "Largeur d'affichage",+ "viewport_fill": "Ajusté",+ "viewport_desktop": "Ordinateur",+ "viewport_tablet": "Tablette",+ "viewport_phone": "Téléphone",+ "viewport_scale": "Réduit à {{percent}} %",+ "view_source": "Voir la source",+ "view_mode": "Affichage",+ "view_tree": "Arborescence",+ "view_raw": "Brut",+ "structured_parse_failed": "Impossible d'analyser ce fichier, il est affiché en texte.",+ "tree_show_more": "Afficher la suite ({{count}})",+ "tree_items_one": "{{count}} élément",+ "tree_items_other": "{{count}} éléments",+ "tree_keys_one": "{{count}} clé",+ "tree_keys_other": "{{count}} clés",+ "table_empty": "Aucune ligne",+ "table_rows_one": "{{count}} ligne",+ "table_rows_other": "{{count}} lignes",+ "table_columns_one": "{{count}} colonne",+ "table_columns_other": "{{count}} colonnes"},"link_hover": {"copy_link": "Copier le lien",diff --git a/packages/views/locales/ja/editor.json b/packages/views/locales/ja/editor.jsonindex 0d0a8cf0bf..aeb8f94a60 100644--- a/packages/views/locales/ja/editor.json+++ b/packages/views/locales/ja/editor.json@@ -63,7 +63,25 @@"next": "次へ","sequence_position": "{{index}} / {{total}}","overview": "すべての成果物",- "info": "情報"+ "info": "情報",+ "wrap_lines": "折り返し",+ "viewport": "ビューポート幅",+ "viewport_fill": "フィット",+ "viewport_desktop": "デスクトップ",+ "viewport_tablet": "タブレット",+ "viewport_phone": "スマートフォン",+ "viewport_scale": "{{percent}}% に縮小",+ "view_source": "ソースを表示",+ "view_mode": "表示",+ "view_tree": "ツリー",+ "view_raw": "原文",+ "structured_parse_failed": "このファイルを解析できなかったため、テキストとして表示しています。",+ "tree_show_more": "さらに表示(残り {{count}} 件)",+ "tree_items_other": "{{count}} 件",+ "tree_keys_other": "{{count}} 個のキー",+ "table_empty": "行がありません",+ "table_rows_other": "{{count}} 行",+ "table_columns_other": "{{count}} 列"},"link_hover": {"copy_link": "リンクをコピー",diff --git a/packages/views/locales/ko/editor.json b/packages/views/locales/ko/editor.jsonindex dd44211bff..058c9ee68a 100644--- a/packages/views/locales/ko/editor.json+++ b/packages/views/locales/ko/editor.json@@ -63,7 +63,25 @@"next": "다음","sequence_position": "{{index}} / {{total}}","overview": "모든 산출물",- "info": "정보"+ "info": "정보",+ "wrap_lines": "줄 바꿈",+ "viewport": "뷰포트 너비",+ "viewport_fill": "맞춤",+ "viewport_desktop": "데스크톱",+ "viewport_tablet": "태블릿",+ "viewport_phone": "휴대폰",+ "viewport_scale": "{{percent}}%로 축소",+ "view_source": "소스 보기",+ "view_mode": "보기",+ "view_tree": "트리",+ "view_raw": "원문",+ "structured_parse_failed": "이 파일을 해석할 수 없어 텍스트로 표시합니다.",+ "tree_show_more": "더 보기 ({{count}}개 남음)",+ "tree_items_other": "항목 {{count}}개",+ "tree_keys_other": "키 {{count}}개",+ "table_empty": "행이 없습니다",+ "table_rows_other": "{{count}}행",+ "table_columns_other": "{{count}}열"},"link_hover": {"copy_link": "링크 복사",diff --git a/packages/views/locales/zh-Hans/editor.json b/packages/views/locales/zh-Hans/editor.jsonindex 8b80226744..9c1851e44c 100644--- a/packages/views/locales/zh-Hans/editor.json+++ b/packages/views/locales/zh-Hans/editor.json@@ -63,7 +63,25 @@"next": "下一个","sequence_position": "{{index}} / {{total}}","overview": "全部产物",- "info": "信息"+ "info": "信息",+ "wrap_lines": "自动换行",+ "viewport": "视口宽度",+ "viewport_fill": "自适应",+ "viewport_desktop": "桌面",+ "viewport_tablet": "平板",+ "viewport_phone": "手机",+ "viewport_scale": "缩放 {{percent}}%",+ "view_source": "查看源码",+ "view_mode": "视图",+ "view_tree": "树形",+ "view_raw": "原文",+ "structured_parse_failed": "无法解析这个文件,已按原文显示。",+ "tree_show_more": "显示更多(还有 {{count}} 项)",+ "tree_items_other": "{{count}} 项",+ "tree_keys_other": "{{count}} 个键",+ "table_empty": "没有数据行",+ "table_rows_other": "{{count}} 行",+ "table_columns_other": "{{count}} 列"},"link_hover": {"copy_link": "复制链接",diff --git a/packages/views/package.json b/packages/views/package.jsonindex 212cc03db9..865d0f73e0 100644--- a/packages/views/package.json+++ b/packages/views/package.json@@ -118,7 +118,8 @@"remark-gfm": "^4.0.1","remark-math": "catalog:","sonner": "^2.0.7",- "unist-util-visit": "^5.1.0"+ "unist-util-visit": "^5.1.0",+ "yaml": "catalog:"},"peerDependencies": {"@tanstack/react-query": "catalog:",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex a7e2c0d296..bf8687d1f5 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1113,6 +1113,9 @@ importers:unist-util-visit:specifier: ^5.1.0version: 5.1.0+ yaml:+ specifier: 'catalog:'+ version: 2.9.0zustand:specifier: 'catalog:'version: 5.0.12(@types/[email protected])([email protected])([email protected])([email protected]([email protected]))diff --git a/server/internal/handler/file.go b/server/internal/handler/file.goindex 7efaf6cefa..cac6a7b315 100644--- a/server/internal/handler/file.go+++ b/server/internal/handler/file.go@@ -1368,6 +1368,7 @@ func isTextPreviewable(contentType, filename string) bool {}switch ct {case "application/json",+ "application/x-ndjson","application/javascript","application/xml","application/x-yaml",@@ -1384,7 +1385,7 @@ func isTextPreviewable(contentType, filename string) bool {".txt", ".log",".csv", ".tsv",".html", ".htm",- ".json", ".xml",+ ".json", ".jsonl", ".ndjson", ".xml",".yml", ".yaml", ".toml", ".ini", ".conf",".sh", ".bash", ".zsh",".py", ".rb", ".go", ".rs",diff --git a/server/internal/handler/file_test.go b/server/internal/handler/file_test.goindex 9fd246ee49..6f5a40c496 100644--- a/server/internal/handler/file_test.go+++ b/server/internal/handler/file_test.go@@ -1637,7 +1637,8 @@ func TestGetAttachmentContent_NotFound(t *testing.T) {// isTextPreviewable is the whitelist linkpin between the proxy and the// client-side dispatcher. Regress against the most common content types so-// drifting one of the lists alone fails loud.+// drifting one of the lists alone fails loud. The same table runs against the+// client in packages/views/editor/utils/preview.test.ts — change both.func TestIsTextPreviewable(t *testing.T) {t.Helper()cases := []struct {@@ -1651,6 +1652,12 @@ func TestIsTextPreviewable(t *testing.T) {{"plain text", "text/plain", "log.txt", true},{"json by mime", "application/json", "data.json", true},{"yaml by ext", "application/octet-stream", "config.yml", true},+ {"csv by ext", "application/octet-stream", "report.csv", true},+ {"tsv by ext", "application/octet-stream", "export.tsv", true},+ {"json lines by ext", "application/octet-stream", "events.jsonl", true},+ {"ndjson by ext", "application/octet-stream", "events.ndjson", true},+ {"ndjson by mime", "application/x-ndjson", "events", true},+ {"log by ext", "application/octet-stream", "server.log", true},{"go source", "text/plain", "main.go", true},{"typescript", "application/octet-stream", "index.ts", true},{"html", "text/html", "page.html", true},