Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(editor): inline HTML attachment preview + ```html block render (MUL-2345) (#2790)

Naiyuan Qingceb967aefae0
diff --git a/packages/views/editor/attachment-card.test.tsx b/packages/views/editor/attachment-card.test.tsx
new file mode 100644
index 0000000000..fe722e1204
--- /dev/null
+++ b/packages/views/editor/attachment-card.test.tsx
@@ -0,0 +1,209 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { fireEvent, render as rtlRender, screen, waitFor } from "@testing-library/react";
+import type { ReactElement } from "react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+
+// vi.hoisted lets us reference the mock from inside the vi.mock factory
+// even though the factory hoists above the file's top-level statements.
+const { getAttachmentTextContentMock } = vi.hoisted(() => ({
+ getAttachmentTextContentMock: vi.fn(),
+}));
+
+vi.mock("@multica/core/api", () => ({
+ api: { getAttachmentTextContent: getAttachmentTextContentMock },
+ PreviewTooLargeError: class extends Error {},
+ PreviewUnsupportedError: class extends Error {},
+}));
+
+vi.mock("../i18n", () => ({
+ useT: () => ({
+ t: (sel: (s: Record<string, Record<string, string>>) => string) =>
+ sel({
+ image: { download: "Download" },
+ attachment: {
+ preview: "Preview",
+ preview_loading: "Loading preview…",
+ },
+ file_card: { uploading: "Uploading {{filename}}" },
+ }),
+ }),
+}));
+
+import { AttachmentCard } from "./attachment-card";
+
+function render(ui: ReactElement) {
+ const qc = new QueryClient({
+ defaultOptions: { queries: { retry: false, gcTime: 0 } },
+ });
+ return rtlRender(<QueryClientProvider client={qc}>{ui}</QueryClientProvider>);
+}
+
+beforeEach(() => vi.clearAllMocks());
+afterEach(() => vi.restoreAllMocks());
+
+describe("AttachmentCard — kind dispatch", () => {
+ it("renders chrome only for non-html kinds (image, video, other)", () => {
+ render(
+ <AttachmentCard
+ filename="snapshot.png"
+ contentType="image/png"
+ attachmentId="att-1"
+ href="https://cdn.example/snapshot.png"
+ onPreview={() => {}}
+ onDownload={() => {}}
+ />,
+ );
+ expect(screen.getByText("snapshot.png")).toBeTruthy();
+ // No inline iframe for an image-kind attachment.
+ expect(document.querySelector("iframe")).toBeNull();
+ });
+
+ it("renders chrome only for an html URL-only source (no attachmentId)", () => {
+ render(
+ <AttachmentCard
+ filename="report.html"
+ contentType="text/html"
+ href="https://cdn.example/report.html"
+ onPreview={() => {}}
+ onDownload={() => {}}
+ />,
+ );
+ // Without an attachment id we cannot hit the ID-keyed /content proxy,
+ // so the card must fall back to chrome-only.
+ expect(document.querySelector("iframe")).toBeNull();
+ expect(screen.getByText("report.html")).toBeTruthy();
+ });
+
+ it("hides the Eye button for an html URL-only source (the modal's /content proxy is ID-keyed)", () => {
+ // Regression: a cross-comment / copy-pasted `!file[report.html](url)`
+ // used to surface a dead Eye button — the AttachmentCard allowed
+ // preview when `previewableFromUrl` was true even without an
+ // attachmentId, but the modal's tryOpen rejects URL-only text kinds
+ // and the click became a silent no-op.
+ render(
+ <AttachmentCard
+ filename="report.html"
+ contentType="text/html"
+ href="https://cdn.example/report.html"
+ onPreview={() => {}}
+ onDownload={() => {}}
+ />,
+ );
+ expect(screen.queryByTitle("Preview")).toBeNull();
+ // Download stays available — the underlying URL is still reachable.
+ expect(screen.getByTitle("Download")).toBeTruthy();
+ });
+
+ it("still shows the Eye button for an html source when an attachmentId is available", () => {
+ getAttachmentTextContentMock.mockResolvedValueOnce({
+ text: "<p>ok</p>",
+ originalContentType: "text/html",
+ });
+ render(
+ <AttachmentCard
+ filename="report.html"
+ contentType="text/html"
+ attachmentId="att-1"
+ href="https://cdn.example/report.html"
+ onPreview={() => {}}
+ onDownload={() => {}}
+ />,
+ );
+ expect(screen.getByTitle("Preview")).toBeTruthy();
+ });
+
+ it("shows the Eye button for a URL-only pdf source (modal renders pdfs directly from URL)", () => {
+ // Counterpart to the html regression: media kinds (pdf/video/audio)
+ // ARE URL-previewable because the modal renders them via
+ // <iframe src=url>/<video>/<audio>, not via the /content proxy.
+ render(
+ <AttachmentCard
+ filename="manual.pdf"
+ contentType="application/pdf"
+ href="https://cdn.example/manual.pdf"
+ onPreview={() => {}}
+ onDownload={() => {}}
+ />,
+ );
+ expect(screen.getByTitle("Preview")).toBeTruthy();
+ });
+
+ it("renders an inline iframe with sandbox='allow-scripts' for an HTML attachment", async () => {
+ getAttachmentTextContentMock.mockResolvedValueOnce({
+ text: "<p>chart goes here</p>",
+ originalContentType: "text/html",
+ });
+ render(
+ <AttachmentCard
+ filename="report.html"
+ contentType="text/html"
+ attachmentId="att-1"
+ href="https://cdn.example/report.html"
+ onPreview={() => {}}
+ onDownload={() => {}}
+ />,
+ );
+ await waitFor(() => {
+ const frame = document.querySelector("iframe") as HTMLIFrameElement | null;
+ expect(frame).toBeTruthy();
+ expect(frame?.getAttribute("sandbox")).toBe("allow-scripts");
+ expect(frame?.getAttribute("srcdoc")).toBe("<p>chart goes here</p>");
+ });
+ });
+});
+
+describe("AttachmentCard — Eye / Download buttons", () => {
+ it("invokes onPreview when Eye is clicked", () => {
+ const onPreview = vi.fn();
+ render(
+ <AttachmentCard
+ filename="manual.pdf"
+ contentType="application/pdf"
+ attachmentId="att-1"
+ href="https://cdn.example/manual.pdf"
+ onPreview={onPreview}
+ onDownload={() => {}}
+ />,
+ );
+ fireEvent.mouseDown(screen.getByTitle("Preview"));
+ expect(onPreview).toHaveBeenCalled();
+ });
+
+ it("invokes onDownload when Download is clicked", () => {
+ const onDownload = vi.fn();
+ render(
+ <AttachmentCard
+ filename="manual.pdf"
+ contentType="application/pdf"
+ attachmentId="att-1"
+ href="https://cdn.example/manual.pdf"
+ onPreview={() => {}}
+ onDownload={onDownload}
+ />,
+ );
+ fireEvent.mouseDown(screen.getByTitle("Download"));
+ expect(onDownload).toHaveBeenCalled();
+ });
+
+ it("hides the Eye button while uploading and skips the inline HTML preview", () => {
+ render(
+ <AttachmentCard
+ filename="report.html"
+ contentType="text/html"
+ attachmentId="att-1"
+ href="https://cdn.example/report.html"
+ uploading
+ onPreview={() => {}}
+ onDownload={() => {}}
+ />,
+ );
+ expect(screen.queryByTitle("Preview")).toBeNull();
+ expect(screen.queryByTitle("Download")).toBeNull();
+ expect(document.querySelector("iframe")).toBeNull();
+ // The mock `t()` returns the i18n template as-is; the production t-fn
+ // interpolates {{filename}} → "report.html". Asserting the template
+ // proves the uploading branch was selected without depending on the
+ // interpolation behavior of the mock.
+ expect(screen.getByText("Uploading {{filename}}")).toBeTruthy();
+ });
+});
diff --git a/packages/views/editor/attachment-card.tsx b/packages/views/editor/attachment-card.tsx
new file mode 100644
index 0000000000..f304983caf
--- /dev/null
+++ b/packages/views/editor/attachment-card.tsx
@@ -0,0 +1,228 @@
+"use client";
+
+/**
+ * AttachmentCard — shared attachment row UI used by every entry point that
+ * renders a non-image attachment in the editor surface.
+ *
+ * Three call sites:
+ * 1. `extensions/file-card.tsx` — Tiptap NodeView for `!file[name](url)`
+ * inline in markdown.
+ * 2. `readonly-content.tsx` — readonly file-card `<div data-type="fileCard">`
+ * branch, rendered through preprocessMarkdown.
+ * 3. `comment-card.tsx` `AttachmentList` — standalone attachments that were
+ * not referenced by URL inside the markdown body.
+ *
+ * Centralizing this avoids the third-instance trap: every previous attempt to
+ * add a feature here had to be added in three places, and dropping one
+ * silently re-introduced the bug — MUL-2330's HTML chart was a standalone
+ * attachment, so the inline HTML preview only works if THIS path is covered.
+ *
+ * HTML kind extension:
+ * - When the attachment is HTML and the caller can provide an
+ * `attachmentId` (i.e. the attachment record is known — required for the
+ * ID-keyed `/api/attachments/{id}/content` proxy), the card mounts an
+ * inline `CodeBlockIframe` underneath the row to render the HTML body
+ * directly. Loading errors and 413/415 cases collapse back to the bare
+ * row + Eye/Download buttons.
+ * - For non-HTML kinds (or HTML where we only have a URL), the card looks
+ * and behaves exactly like the previous handwritten rows.
+ */
+
+import { Download, Eye, FileText, Loader2 } from "lucide-react";
+import { useT } from "../i18n";
+import { getPreviewKind } from "./utils/preview";
+import { CodeBlockIframe } from "./code-block-iframe";
+import { useAttachmentHtmlText } from "./hooks/use-attachment-html-text";
+
+// ---------------------------------------------------------------------------
+// Inline HTML preview body
+// ---------------------------------------------------------------------------
+
+// Fixed height per the V2 plan; auto-resize via postMessage handshake is
+// explicitly out of scope for V1.
+const INLINE_HTML_HEIGHT = "h-[480px]";
+
+function InlineHtmlIframe({
+ attachmentId,
+ filename,
+}: {
+ attachmentId: string;
+ filename: string;
+}) {
+ const { t } = useT("editor");
+ const query = useAttachmentHtmlText(attachmentId);
+
+ if (query.isLoading) {
+ return (
+ <div className="mt-1 flex h-[480px] items-center justify-center gap-2 rounded-md border border-border bg-muted/30 text-xs text-muted-foreground">
+ <Loader2 className="size-3.5 animate-spin" />
+ {t(($) => $.attachment.preview_loading)}
+ </div>
+ );
+ }
+ // Any error path (413 / 415 / transport) — fall back silently. The
+ // surrounding card still offers Eye → modal (which surfaces the typed
+ // error) and Download as escape hatches.
+ if (query.error || !query.data) return null;
+
+ return (
+ <div className="mt-1">
+ <CodeBlockIframe
+ html={query.data.text}
+ title={filename}
+ heightClassName={INLINE_HTML_HEIGHT}
+ />
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Card chrome — icon + filename + optional Eye + Download
+// ---------------------------------------------------------------------------
+
+interface AttachmentCardChromeProps {
+ filename: string;
+ uploading?: boolean;
+ canPreview: boolean;
+ canDownload: boolean;
+ onPreview: () => void;
+ onDownload: () => void;
+}
+
+function AttachmentCardChrome({
+ filename,
+ uploading,
+ canPreview,
+ canDownload,
+ onPreview,
+ onDownload,
+}: AttachmentCardChromeProps) {
+ const { t } = useT("editor");
+ return (
+ <div
+ className="flex items-center gap-2 rounded-md border border-border bg-muted/50 px-2.5 py-1 transition-colors hover:bg-muted"
+ onMouseDown={(e) => e.stopPropagation()}
+ >
+ {uploading ? (
+ <Loader2 className="size-4 shrink-0 animate-spin text-muted-foreground" />
+ ) : (
+ <FileText className="size-4 shrink-0 text-muted-foreground" />
+ )}
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-sm">
+ {uploading
+ ? t(($) => $.file_card.uploading, { filename })
+ : filename}
+ </p>
+ </div>
+ {!uploading && canPreview && (
+ <button
+ type="button"
+ className="shrink-0 rounded-md p-1 text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"
+ title={t(($) => $.attachment.preview)}
+ aria-label={t(($) => $.attachment.preview)}
+ onMouseDown={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ onPreview();
+ }}
+ >
+ <Eye className="size-3.5" />
+ </button>
+ )}
+ {!uploading && canDownload && (
+ <button
+ type="button"
+ className="shrink-0 rounded-md p-1 text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"
+ title={t(($) => $.image.download)}
+ aria-label={t(($) => $.image.download)}
+ onMouseDown={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ onDownload();
+ }}
+ >
+ <Download className="size-3.5" />
+ </button>
+ )}
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// AttachmentCard — public component
+// ---------------------------------------------------------------------------
+
+export interface AttachmentCardProps {
+ /** Filename used for icon label and previewable-kind detection. */
+ filename: string;
+ /** Content type used in addition to filename for previewable-kind detection. */
+ contentType?: string;
+ /**
+ * Attachment id — required for HTML inline rendering (the `/content`
+ * proxy is ID-keyed). Undefined means we only have a URL (e.g. a
+ * cross-comment `!file[]()` reference) — the card still renders, the
+ * HTML iframe just doesn't expand.
+ */
+ attachmentId?: string;
+ /** Download URL — used purely as a non-null sentinel for the download button. */
+ href?: string;
+ /** True while a synchronous upload is in flight (file-card NodeView only). */
+ uploading?: boolean;
+ /** Pressed when the Eye button is clicked. */
+ onPreview: () => void;
+ /** Pressed when the Download button is clicked. */
+ onDownload: () => void;
+ /**
+ * Set to false to disable the HTML inline preview branch (and behave like
+ * the legacy chrome-only card). Useful for editor NodeViews while a draft
+ * upload is still in flight.
+ */
+ inlineHtmlEnabled?: boolean;
+}
+
+export function AttachmentCard({
+ filename,
+ contentType = "",
+ attachmentId,
+ href,
+ uploading,
+ onPreview,
+ onDownload,
+ inlineHtmlEnabled = true,
+}: AttachmentCardProps) {
+ const kind = filename ? getPreviewKind(contentType, filename) : null;
+ // Media kinds (pdf/video/audio) are previewable from a URL alone — the
+ // modal renders them as <video>/<audio>/<iframe src=url>. Text kinds
+ // (markdown/html/text) need the ID-keyed `/api/attachments/{id}/content`
+ // proxy, so they only preview when we have an attachmentId — otherwise
+ // the Eye button would call tryOpen, get rejected, and do nothing.
+ const isUrlPreviewableKind =
+ kind === "pdf" || kind === "video" || kind === "audio";
+ const canPreview =
+ !!href && kind !== null && (!!attachmentId || isUrlPreviewableKind);
+
+ // Mount the inline iframe only when we can hit the /content proxy
+ // (attachmentId present) AND kind is HTML AND no upload is in flight.
+ const showInlineHtml =
+ inlineHtmlEnabled &&
+ !uploading &&
+ kind === "html" &&
+ !!attachmentId;
+
+ return (
+ <div className="my-1">
+ <AttachmentCardChrome
+ filename={filename}
+ uploading={uploading}
+ canPreview={canPreview}
+ canDownload={!!href}
+ onPreview={onPreview}
+ onDownload={onDownload}
+ />
+ {showInlineHtml && (
+ <InlineHtmlIframe attachmentId={attachmentId!} filename={filename} />
+ )}
+ </div>
+ );
+}
diff --git a/packages/views/editor/attachment-preview-modal.test.tsx b/packages/views/editor/attachment-preview-modal.test.tsx
index cd051010ef..0f74568137 100644
--- a/packages/views/editor/attachment-preview-modal.test.tsx
+++ b/packages/views/editor/attachment-preview-modal.test.tsx
@@ -159,7 +159,7 @@ describe("AttachmentPreviewModal — dispatch", () => {
expect(screen.getByTestId("readonly-content").textContent).toContain("# heading");
});
- it("renders an iframe with srcdoc + sandbox='' for HTML", async () => {
+ it("renders an iframe with srcdoc + sandbox='allow-scripts' for HTML", async () => {
getAttachmentTextContentMock.mockResolvedValueOnce({
text: "<p>hi</p>",
originalContentType: "text/html",
@@ -170,7 +170,10 @@ describe("AttachmentPreviewModal — dispatch", () => {
await waitFor(() => {
const frame = document.querySelector("iframe[sandbox]") as HTMLIFrameElement | null;
expect(frame).toBeTruthy();
- expect(frame?.getAttribute("sandbox")).toBe("");
+ // `allow-scripts` is required so vanilla-JS chart libraries render
+ // (MUL-2330). The combination with `allow-same-origin` would defeat
+ // the sandbox, so this assertion must stay exact.
+ expect(frame?.getAttribute("sandbox")).toBe("allow-scripts");
expect(frame?.getAttribute("srcdoc")).toBe("<p>hi</p>");
});
});
diff --git a/packages/views/editor/attachment-preview-modal.tsx b/packages/views/editor/attachment-preview-modal.tsx
index 47b71a6a8a..8b57e36ad3 100644
--- a/packages/views/editor/attachment-preview-modal.tsx
+++ b/packages/views/editor/attachment-preview-modal.tsx
@@ -15,10 +15,12 @@
* - markdown : fetch text via api.getAttachmentTextContent, render via
* the existing ReadonlyContent (full mention/mermaid/katex
* pipeline included).
- * - html : fetch text, hand to <iframe srcdoc={text} sandbox="">.
- * Empty sandbox attribute = max restriction (no scripts,
- * no forms, no top-nav, no popups, no same-origin) — the
- * recommended pattern for previewing untrusted HTML.
+ * - html : fetch text, hand to <iframe srcdoc={text}
+ * sandbox="allow-scripts">. The iframe runs in an opaque
+ * origin: scripts execute (chart libraries / vanilla SVG
+ * JS work), but cookie / localStorage / parent access /
+ * top-navigation / popups / forms stay blocked because
+ * `allow-same-origin` is intentionally NOT included.
* - text : fetch text, highlight with lowlight if the extension
* maps to a known hljs language; otherwise plain <pre>.
*
@@ -35,17 +37,11 @@ import {
type ReactNode,
} from "react";
import { createPortal } from "react-dom";
-import { useQuery } from "@tanstack/react-query";
-import { Download, FileText, Loader2, X } from "lucide-react";
-import { createLowlight, common } from "lowlight";
-// @ts-expect-error -- hast-util-to-html has no bundled type declarations
-import { toHtml } from "hast-util-to-html";
-import { cn } from "@multica/ui/lib/utils";
import {
- api,
PreviewTooLargeError,
PreviewUnsupportedError,
} from "@multica/core/api";
+import { Download, FileText, Loader2, X } from "lucide-react";
import type { Attachment } from "@multica/core/types";
import { useT } from "../i18n";
import { openExternal } from "../platform";
@@ -56,6 +52,8 @@ import {
type PreviewKind,
} from "./utils/preview";
import { useDownloadAttachment } from "./use-download-attachment";
+import { useAttachmentHtmlText } from "./hooks/use-attachment-html-text";
+import { CodeBlockStatic } from "./code-block-static";
// ---------------------------------------------------------------------------
// Preview source — full attachment, or URL-only (media types only)
@@ -355,7 +353,12 @@ function PreviewContent({
render={(text) => (
<iframe
srcDoc={text}
- sandbox=""
+ // `allow-scripts` without `allow-same-origin` — scripts run
+ // in an opaque origin and cannot read cookies / localStorage
+ // / parent state, nor escape via top-nav / popups / forms.
+ // Required so JS-driven charts (echarts / Plotly / vanilla
+ // SVG injection) render instead of showing a blank `<svg>`.
+ sandbox="allow-scripts"
className="h-full w-full bg-background"
title={state.filename}
/>
@@ -368,7 +371,11 @@ function PreviewContent({
attachmentId={state.attachmentId!}
onDownload={onDownload}
render={(text) => (
- <CodeBlock language={extensionToLanguage(state.filename)} body={text} />
+ <CodeBlockStatic
+ language={extensionToLanguage(state.filename)}
+ body={text}
+ className="px-6 py-4"
+ />
)}
/>
);
@@ -393,19 +400,7 @@ function TextBackedPreview({
render: (text: string) => ReactNode;
}) {
const { t } = useT("editor");
- const query = useQuery({
- queryKey: ["attachment-content", attachmentId] as const,
- queryFn: () => api.getAttachmentTextContent(attachmentId),
- // Errors are surfaced as typed fallbacks, not retried — 413 / 415 won't
- // become 200 on a retry, and a transient failure is easier to recover
- // from by closing and reopening the modal than waiting on background
- // retries that have no UI affordance.
- retry: false,
- // 413 / 415 bodies are tiny; keep the result around for the session so
- // the user can flip away and back without refetching.
- staleTime: 5 * 60_000,
- gcTime: 30 * 60_000,
- });
+ const query = useAttachmentHtmlText(attachmentId);
if (query.isLoading) {
return (
@@ -443,44 +438,6 @@ function TextBackedPreview({
return <>{render(query.data.text)}</>;
}
-// ---------------------------------------------------------------------------
-// Code block — lowlight, matches readonly-content's hljs CSS
-// ---------------------------------------------------------------------------
-
-const lowlight = createLowlight(common);
-
-function CodeBlock({ language, body }: { language: string | undefined; body: string }) {
- const html = useMemo(() => {
- const code = body.replace(/\n$/, "");
- try {
- const tree = language
- ? lowlight.highlight(language, code)
- : lowlight.highlightAuto(code);
- return toHtml(tree) as string;
- } catch {
- // Fallthrough to a plain escaped <pre> when lowlight rejects the
- // language tag. Avoids crashing the preview on an unknown extension.
- return escapeHtml(code);
- }
- }, [body, language]);
-
- return (
- <pre className="rich-text-editor m-0 overflow-auto px-6 py-4 text-sm">
- <code
- className={cn("hljs", language && `language-${language}`)}
- dangerouslySetInnerHTML={{ __html: html }}
- />
- </pre>
- );
-}
-
-function escapeHtml(s: string): string {
- return s
- .replace(/&/g, "&amp;")
- .replace(/</g, "&lt;")
- .replace(/>/g, "&gt;");
-}
-
// ---------------------------------------------------------------------------
// Fallback — used for 413 / 415 / unknown kinds
// ---------------------------------------------------------------------------
diff --git a/packages/views/editor/code-block-iframe.tsx b/packages/views/editor/code-block-iframe.tsx
new file mode 100644
index 0000000000..023bd6e210
--- /dev/null
+++ b/packages/views/editor/code-block-iframe.tsx
@@ -0,0 +1,58 @@
+"use client";
+
+/**
+ * Shared HTML preview iframe.
+ *
+ * Used by:
+ * - InlineHtmlIframe inside AttachmentCard (HTML attachments inline preview)
+ * - CodeBlockView for fenced ```html blocks (editable Tiptap NodeView)
+ * - HtmlBlockPreview for fenced ```html blocks (ReadonlyContent)
+ * - AttachmentPreviewModal's full-screen HTML kind
+ *
+ * Sandbox semantics:
+ * sandbox="allow-scripts" (NOT "allow-same-origin")
+ * → iframe runs in an opaque origin: scripts execute (chart JS works),
+ * but cookie / localStorage / parent access / top-nav / popups / forms
+ * remain blocked. This is the standard "preview untrusted HTML" model
+ * (HTML spec §iframe sandbox, MDN, Claude artifacts, v0.dev preview).
+ *
+ * The server-side `text/plain` + `nosniff` defense at
+ * /api/attachments/{id}/content remains untouched — we only feed iframe.srcDoc
+ * the text body we fetched, never point iframe.src at the proxy URL.
+ */
+
+import { cn } from "@multica/ui/lib/utils";
+
+interface CodeBlockIframeProps {
+ /** Document source for srcDoc. Empty string renders a blank frame. */
+ html: string;
+ /** Iframe title for accessibility. */
+ title: string;
+ className?: string;
+ /** Tailwind height token; defaults to h-[320px]. */
+ heightClassName?: string;
+}
+
+export function CodeBlockIframe({
+ html,
+ title,
+ className,
+ heightClassName = "h-[320px]",
+}: CodeBlockIframeProps) {
+ return (
+ <iframe
+ // srcDoc keeps the body in the parent's process but isolated to an
+ // opaque origin via sandbox. Critical that we never combine
+ // `allow-scripts` with `allow-same-origin` — that pairing defeats the
+ // sandbox per the HTML spec (notes on the sandbox attribute).
+ srcDoc={html}
+ sandbox="allow-scripts"
+ title={title}
+ className={cn(
+ "w-full rounded-md border border-border bg-background",
+ heightClassName,
+ className,
+ )}
+ />
+ );
+}
diff --git a/packages/views/editor/code-block-static.tsx b/packages/views/editor/code-block-static.tsx
new file mode 100644
index 0000000000..1c55bd8883
--- /dev/null
+++ b/packages/views/editor/code-block-static.tsx
@@ -0,0 +1,57 @@
+"use client";
+
+/**
+ * CodeBlockStatic — read-only lowlight-highlighted code block.
+ *
+ * Used by:
+ * - AttachmentPreviewModal's text-kind fallback (extracted from there).
+ * - HtmlBlockPreview's "source" toggle in ReadonlyContent.
+ *
+ * NOT used by Tiptap's editable code-block NodeView: that path must keep
+ * `<NodeViewContent as="code" />` so the user can continue typing into the
+ * code block. Replacing it with a static lowlight component would freeze
+ * the content and desync ProseMirror state from the DOM.
+ */
+
+import { useMemo } from "react";
+import { createLowlight, common } from "lowlight";
+// @ts-expect-error -- hast-util-to-html has no bundled type declarations
+import { toHtml } from "hast-util-to-html";
+import { cn } from "@multica/ui/lib/utils";
+
+const lowlight = createLowlight(common);
+
+interface CodeBlockStaticProps {
+ language: string | undefined;
+ body: string;
+ className?: string;
+}
+
+export function CodeBlockStatic({ language, body, className }: CodeBlockStaticProps) {
+ const html = useMemo(() => {
+ const code = body.replace(/\n$/, "");
+ try {
+ const tree = language
+ ? lowlight.highlight(language, code)
+ : lowlight.highlightAuto(code);
+ return toHtml(tree) as string;
+ } catch {
+ // Unknown language tag — fall back to escaped plain text so we don't
+ // crash on an esoteric extension.
+ return escapeHtml(code);
+ }
+ }, [body, language]);
+
+ return (
+ <pre className={cn("rich-text-editor m-0 overflow-auto text-sm", className)}>
+ <code
+ className={cn("hljs", language && `language-${language}`)}
+ dangerouslySetInnerHTML={{ __html: html }}
+ />
+ </pre>
+ );
+}
+
+function escapeHtml(s: string): string {
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
+}
diff --git a/packages/views/editor/extensions/code-block-view.test.tsx b/packages/views/editor/extensions/code-block-view.test.tsx
new file mode 100644
index 0000000000..7c61e210b7
--- /dev/null
+++ b/packages/views/editor/extensions/code-block-view.test.tsx
@@ -0,0 +1,98 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { act, fireEvent, render, screen } from "@testing-library/react";
+
+// Tiptap's NodeView primitives are hard to instantiate in jsdom without a
+// full editor. Stub them so the test can render <CodeBlockView /> as a plain
+// React component and inspect the resulting DOM shape.
+vi.mock("@tiptap/react", () => {
+ const NodeViewWrapper = ({ children, ...rest }: any) => (
+ <div data-testid="nvw" {...rest}>
+ {children}
+ </div>
+ );
+ // The real NodeViewContent renders an element managed by ProseMirror. For
+ // the test it's enough to surface a sentinel element so we can assert it
+ // remains mounted while CSS-hidden.
+ const NodeViewContent = ({ as = "div", ...rest }: any) => {
+ const Tag = as;
+ return <Tag data-testid="nvc" {...rest} />;
+ };
+ return { NodeViewWrapper, NodeViewContent };
+});
+
+vi.mock("../mermaid-diagram", () => ({
+ MermaidDiagram: () => null,
+}));
+
+vi.mock("../../i18n", () => ({
+ useT: () => ({
+ t: (sel: (s: Record<string, Record<string, string>>) => string) =>
+ sel({
+ code_block: {
+ copy_code: "Copy code",
+ show_preview: "Show preview",
+ show_source: "Show source",
+ },
+ }),
+ }),
+}));
+
+import { CodeBlockView } from "./code-block-view";
+
+function makeProps(language: string, text: string) {
+ return {
+ node: {
+ attrs: { language },
+ textContent: text,
+ },
+ } as unknown as Parameters<typeof CodeBlockView>[0];
+}
+
+describe("CodeBlockView — html language toggle", () => {
+ // Inner async timers in useDebouncedValue make the iframe srcDoc lag by
+ // ~200ms; use fake timers so the test stays deterministic.
+ beforeEach(() => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ });
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("defaults to preview view: renders an iframe with sandbox='allow-scripts' and keeps the <pre> mounted (hidden)", () => {
+ render(<CodeBlockView {...makeProps("html", "<p>hello</p>")} />);
+ act(() => {
+ vi.advanceTimersByTime(250);
+ });
+ const frame = document.querySelector("iframe");
+ expect(frame).toBeTruthy();
+ expect(frame?.getAttribute("sandbox")).toBe("allow-scripts");
+ // NodeViewContent (and its enclosing <pre>) MUST remain mounted —
+ // unmounting would break Tiptap's bindings and prevent editing.
+ const nvc = screen.getByTestId("nvc");
+ expect(nvc).toBeTruthy();
+ const pre = nvc.closest("pre");
+ expect(pre).toBeTruthy();
+ expect(pre?.className).toContain("sr-only");
+ });
+
+ it("toggles to source view: iframe is removed and the <pre> is no longer hidden", () => {
+ render(<CodeBlockView {...makeProps("html", "<p>hello</p>")} />);
+ act(() => {
+ vi.advanceTimersByTime(250);
+ });
+ expect(document.querySelector("iframe")).toBeTruthy();
+ const toggle = screen.getByTitle("Show source");
+ fireEvent.click(toggle);
+ expect(document.querySelector("iframe")).toBeNull();
+ const nvc = screen.getByTestId("nvc");
+ const pre = nvc.closest("pre")!;
+ expect(pre.className).not.toContain("sr-only");
+ });
+
+ it("does not show the toggle or an iframe for a non-html language", () => {
+ render(<CodeBlockView {...makeProps("typescript", "const x = 1;")} />);
+ expect(screen.queryByTitle("Show source")).toBeNull();
+ expect(screen.queryByTitle("Show preview")).toBeNull();
+ expect(document.querySelector("iframe")).toBeNull();
+ });
+});
diff --git a/packages/views/editor/extensions/code-block-view.tsx b/packages/views/editor/extensions/code-block-view.tsx
index a44b98dff1..188fc22d52 100644
--- a/packages/views/editor/extensions/code-block-view.tsx
+++ b/packages/views/editor/extensions/code-block-view.tsx
@@ -3,16 +3,22 @@
import { useEffect, useState } from "react";
import { NodeViewWrapper, NodeViewContent } from "@tiptap/react";
import type { NodeViewProps } from "@tiptap/react";
-import { Copy, Check } from "lucide-react";
+import { Code as CodeIcon, Copy, Check, Eye } from "lucide-react";
+import { cn } from "@multica/ui/lib/utils";
import { useT } from "../../i18n";
import { MermaidDiagram } from "../mermaid-diagram";
+import { CodeBlockIframe } from "../code-block-iframe";
-// Coalesces fast keystrokes before re-rendering the Mermaid preview.
+// Coalesces fast keystrokes before re-rendering live previews.
// `mermaid.initialize()` mutates a process-global config, so back-to-back
// renders during typing can race a concurrent ReadonlyContent render
// (e.g. a comment card) and clobber its theme variables. 200ms keeps the
// "live preview" feel while making concurrent inits unlikely in practice.
-const MERMAID_PREVIEW_DEBOUNCE_MS = 200;
+// HTML preview reuses the same debounce: re-keying iframe.srcDoc on every
+// keystroke causes the iframe to re-load and flicker.
+const PREVIEW_DEBOUNCE_MS = 200;
+
+const HTML_PREVIEW_HEIGHT = "h-[320px]";
function useDebouncedValue<T>(value: T, delayMs: number): T {
const [debounced, setDebounced] = useState(value);
@@ -26,12 +32,22 @@ function useDebouncedValue<T>(value: T, delayMs: number): T {
function CodeBlockView({ node }: NodeViewProps) {
const { t } = useT("editor");
const [copied, setCopied] = useState(false);
+ // HTML blocks default to "preview"; the user can flip to "source" to
+ // edit the markup directly. Note: the source `<pre>` MUST stay mounted
+ // (just hidden) so ProseMirror keeps its NodeView bindings — unmounting
+ // it would break editing.
+ const [view, setView] = useState<"preview" | "source">("preview");
const language = node.attrs.language || "";
const isMermaid = language === "mermaid";
+ const isHtml = language === "html";
const chart = node.textContent;
const debouncedChart = useDebouncedValue(
isMermaid ? chart : "",
- MERMAID_PREVIEW_DEBOUNCE_MS,
+ PREVIEW_DEBOUNCE_MS,
+ );
+ const debouncedHtml = useDebouncedValue(
+ isHtml ? chart : "",
+ PREVIEW_DEBOUNCE_MS,
);
const handleCopy = async () => {
@@ -42,6 +58,10 @@ function CodeBlockView({ node }: NodeViewProps) {
setTimeout(() => setCopied(false), 2000);
};
+ const showHtmlPreview = isHtml && view === "preview";
+ const toggleView = () =>
+ setView((v) => (v === "preview" ? "source" : "preview"));
+
return (
<NodeViewWrapper className="code-block-wrapper group/code relative my-2">
{isMermaid && debouncedChart.trim() && (
@@ -52,6 +72,18 @@ function CodeBlockView({ node }: NodeViewProps) {
<MermaidDiagram chart={debouncedChart} />
</div>
)}
+ {isHtml && showHtmlPreview && (
+ // CSS-hidden when toggled off so the `<pre>` below stays mounted —
+ // unmounting either side would either lose ProseMirror bindings
+ // (source) or thrash iframe.srcDoc (preview).
+ <div contentEditable={false} className="mb-1">
+ <CodeBlockIframe
+ html={debouncedHtml}
+ title="HTML preview"
+ heightClassName={HTML_PREVIEW_HEIGHT}
+ />
+ </div>
+ )}
<div
contentEditable={false}
className="code-block-header absolute top-0 right-0 z-10 flex items-center gap-1.5 px-2 py-1.5 opacity-0 transition-opacity group-hover/code:opacity-100"
@@ -61,6 +93,29 @@ function CodeBlockView({ node }: NodeViewProps) {
{language}
</span>
)}
+ {isHtml && (
+ <button
+ type="button"
+ onClick={toggleView}
+ className="flex h-6 w-6 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground transition-colors"
+ title={
+ view === "preview"
+ ? t(($) => $.code_block.show_source)
+ : t(($) => $.code_block.show_preview)
+ }
+ aria-label={
+ view === "preview"
+ ? t(($) => $.code_block.show_source)
+ : t(($) => $.code_block.show_preview)
+ }
+ >
+ {view === "preview" ? (
+ <CodeIcon className="h-3.5 w-3.5" />
+ ) : (
+ <Eye className="h-3.5 w-3.5" />
+ )}
+ </button>
+ )}
<button
type="button"
onClick={handleCopy}
@@ -74,7 +129,14 @@ function CodeBlockView({ node }: NodeViewProps) {
)}
</button>
</div>
- <pre spellCheck={false}>
+ {/* `<pre>` + NodeViewContent must remain mounted so the user can keep
+ editing the code block contents. When the HTML preview is showing
+ we just visually hide it — ProseMirror still tracks it. */}
+ <pre
+ spellCheck={false}
+ className={cn(showHtmlPreview && "sr-only")}
+ aria-hidden={showHtmlPreview ? "true" : undefined}
+ >
{/* @ts-expect-error -- NodeViewContent supports as="code" at runtime */}
<NodeViewContent as="code" />
</pre>
diff --git a/packages/views/editor/extensions/file-card.tsx b/packages/views/editor/extensions/file-card.tsx
index ba7f2f65bb..1256f32b01 100644
--- a/packages/views/editor/extensions/file-card.tsx
+++ b/packages/views/editor/extensions/file-card.tsx
@@ -17,51 +17,33 @@
import { Node, mergeAttributes } from "@tiptap/core";
import { ReactNodeViewRenderer, NodeViewWrapper } from "@tiptap/react";
import type { NodeViewProps } from "@tiptap/react";
-import { Eye, FileText, Loader2, Download } from "lucide-react";
import { FILE_CARD_URL_PATTERN } from "@multica/ui/markdown";
-import { useT } from "../../i18n";
import { useAttachmentDownloadResolver } from "../attachment-download-context";
import { useAttachmentPreview } from "../attachment-preview-modal";
-import { getPreviewKind } from "../utils/preview";
+import { AttachmentCard } from "../attachment-card";
const FILE_CARD_MARKDOWN_RE = new RegExp(
`^!file\\[([^\\]]*)\\]\\((${FILE_CARD_URL_PATTERN.source})\\)`,
);
-// ---------------------------------------------------------------------------
-// Helpers
-// ---------------------------------------------------------------------------
-
// ---------------------------------------------------------------------------
// React NodeView
// ---------------------------------------------------------------------------
function FileCardView({ node }: NodeViewProps) {
- const { t } = useT("editor");
const href = (node.attrs.href as string) || "";
const filename = (node.attrs.filename as string) || "";
const uploading = node.attrs.uploading as boolean;
const { openByUrl, resolveAttachment } = useAttachmentDownloadResolver();
const preview = useAttachmentPreview();
- const openFile = () => {
- openByUrl(href);
- };
-
- // Preview gate mirrors the Download gate (href is enough). We attempt
- // to resolve the full Attachment from the surrounding provider, but its
- // absence is no longer fatal — media kinds (pdf/video/audio) only need
- // the URL, so they remain previewable even when `resolveAttachment`
- // misses (e.g. the URL was copy-pasted across comments and isn't in the
- // current entity's attachments). Text kinds still require the id because
- // the preview proxy is ID-keyed.
+ // Preview gate widens to "anything that can be downloaded AND whose
+ // filename is a previewable type". Media kinds remain previewable when the
+ // attachment record isn't reachable (e.g. URL was copy-pasted across
+ // comments). Text kinds (markdown / html / text) need the id because the
+ // preview proxy is ID-keyed.
const attachment = href ? resolveAttachment(href) : undefined;
- const kind = filename
- ? getPreviewKind(attachment?.content_type ?? "", filename)
- : null;
- const isMediaKind = kind === "pdf" || kind === "video" || kind === "audio";
- const canPreview = !!href && kind !== null && (!!attachment || isMediaKind);
const openPreview = () => {
if (attachment) {
@@ -73,49 +55,16 @@ function FileCardView({ node }: NodeViewProps) {
return (
<NodeViewWrapper as="div" className="file-card-node" data-type="fileCard">
- <div
- className="my-1 flex items-center gap-2 rounded-md border border-border bg-muted/50 px-2.5 py-1 transition-colors hover:bg-muted"
- contentEditable={false}
- onMouseDown={(e) => e.stopPropagation()}
- >
- {uploading ? (
- <Loader2 className="size-4 shrink-0 animate-spin text-muted-foreground" />
- ) : (
- <FileText className="size-4 shrink-0 text-muted-foreground" />
- )}
- <div className="min-w-0 flex-1">
- <p className="truncate text-sm">{uploading ? t(($) => $.file_card.uploading, { filename }) : filename}</p>
- </div>
- {!uploading && canPreview && (
- <button
- type="button"
- className="shrink-0 rounded-md p-1 text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"
- title={t(($) => $.attachment.preview)}
- aria-label={t(($) => $.attachment.preview)}
- onMouseDown={(e) => {
- e.preventDefault();
- e.stopPropagation();
- openPreview();
- }}
- >
- <Eye className="size-3.5" />
- </button>
- )}
- {!uploading && href && (
- <button
- type="button"
- className="shrink-0 rounded-md p-1 text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"
- title={t(($) => $.image.download)}
- aria-label={t(($) => $.image.download)}
- onMouseDown={(e) => {
- e.preventDefault();
- e.stopPropagation();
- openFile();
- }}
- >
- <Download className="size-3.5" />
- </button>
- )}
+ <div contentEditable={false}>
+ <AttachmentCard
+ filename={filename}
+ contentType={attachment?.content_type ?? ""}
+ attachmentId={attachment?.id}
+ href={href}
+ uploading={uploading}
+ onPreview={openPreview}
+ onDownload={() => openByUrl(href)}
+ />
</div>
{preview.modal}
</NodeViewWrapper>
diff --git a/packages/views/editor/hooks/use-attachment-html-text.ts b/packages/views/editor/hooks/use-attachment-html-text.ts
new file mode 100644
index 0000000000..0a525650b3
--- /dev/null
+++ b/packages/views/editor/hooks/use-attachment-html-text.ts
@@ -0,0 +1,29 @@
+"use client";
+
+/**
+ * Shared React Query for fetching attachment text bodies via the
+ * `/api/attachments/{id}/content` proxy.
+ *
+ * Same retry / staleTime / gcTime policy as AttachmentPreviewModal's local
+ * TextBackedPreview, lifted out so the modal and the inline `AttachmentCard`
+ * (file-card NodeView / readonly file-card / standalone AttachmentList) hit
+ * the same cache key — opening the modal after the inline preview already
+ * loaded a body does not refetch.
+ */
+
+import { useQuery } from "@tanstack/react-query";
+import { api } from "@multica/core/api";
+
+export function useAttachmentHtmlText(attachmentId: string | null | undefined) {
+ return useQuery({
+ queryKey: ["attachment-content", attachmentId ?? ""] as const,
+ queryFn: () => api.getAttachmentTextContent(attachmentId as string),
+ enabled: !!attachmentId,
+ // 413 / 415 won't become 200 on retry; a transport error is easier to
+ // recover from by re-opening than waiting on background retries with
+ // no UI affordance.
+ retry: false,
+ staleTime: 5 * 60_000,
+ gcTime: 30 * 60_000,
+ });
+}
diff --git a/packages/views/editor/html-block-preview.tsx b/packages/views/editor/html-block-preview.tsx
new file mode 100644
index 0000000000..0801b43195
--- /dev/null
+++ b/packages/views/editor/html-block-preview.tsx
@@ -0,0 +1,108 @@
+"use client";
+
+/**
+ * HtmlBlockPreview — readonly rendering of fenced ```html code blocks.
+ *
+ * Default view is "preview" (iframe) per the V2 plan; user can flip to
+ * "source" to see the highlighted markup and Copy it.
+ *
+ * Mounted by ReadonlyContent's `code` renderer for `lang === "html"`. The
+ * `pre` renderer in ReadonlyContent recognizes this component by reference
+ * and unwraps it from the default `<pre>` envelope, matching the same
+ * two-layer trick already used for MermaidDiagram.
+ *
+ * NOT used in the editable Tiptap NodeView — that path must keep
+ * `<NodeViewContent as="code" />` so the user can continue typing.
+ */
+
+import { useState } from "react";
+import { Check, Code as CodeIcon, Copy, Eye } from "lucide-react";
+import { cn } from "@multica/ui/lib/utils";
+import { useT } from "../i18n";
+import { CodeBlockIframe } from "./code-block-iframe";
+import { CodeBlockStatic } from "./code-block-static";
+
+const CODE_BLOCK_IFRAME_HEIGHT = "h-[320px]";
+
+// Label shown in the code-block header. Not a translatable string — it's a
+// language identifier (matches the `lang === "html"` token below).
+const HTML_LANGUAGE_LABEL = "html";
+
+interface HtmlBlockPreviewProps {
+ html: string;
+ className?: string;
+}
+
+export function HtmlBlockPreview({ html, className }: HtmlBlockPreviewProps) {
+ const { t } = useT("editor");
+ const [view, setView] = useState<"preview" | "source">("preview");
+ const [copied, setCopied] = useState(false);
+
+ const handleCopy = async () => {
+ if (!html) return;
+ try {
+ await navigator.clipboard.writeText(html);
+ setCopied(true);
+ setTimeout(() => setCopied(false), 2000);
+ } catch {
+ // Clipboard failures are user-recoverable (click again, or copy
+ // manually from the source view) — no need for a toast here.
+ }
+ };
+
+ const toggleView = () =>
+ setView((v) => (v === "preview" ? "source" : "preview"));
+
+ return (
+ <div className={cn("code-block-wrapper group/code relative my-2", className)}>
+ <div
+ className="absolute top-0 right-0 z-10 flex items-center gap-1.5 px-2 py-1.5 opacity-0 transition-opacity group-hover/code:opacity-100"
+ >
+ <span className="text-xs text-muted-foreground select-none">{HTML_LANGUAGE_LABEL}</span>
+ <button
+ type="button"
+ onClick={toggleView}
+ className="flex h-6 w-6 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground transition-colors"
+ title={
+ view === "preview"
+ ? t(($) => $.code_block.show_source)
+ : t(($) => $.code_block.show_preview)
+ }
+ aria-label={
+ view === "preview"
+ ? t(($) => $.code_block.show_source)
+ : t(($) => $.code_block.show_preview)
+ }
+ >
+ {view === "preview" ? (
+ <CodeIcon className="h-3.5 w-3.5" />
+ ) : (
+ <Eye className="h-3.5 w-3.5" />
+ )}
+ </button>
+ <button
+ type="button"
+ onClick={handleCopy}
+ className="flex h-6 w-6 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground transition-colors"
+ title={t(($) => $.code_block.copy_code)}
+ aria-label={t(($) => $.code_block.copy_code)}
+ >
+ {copied ? (
+ <Check className="h-3.5 w-3.5" />
+ ) : (
+ <Copy className="h-3.5 w-3.5" />
+ )}
+ </button>
+ </div>
+ {view === "preview" ? (
+ <CodeBlockIframe
+ html={html}
+ title="HTML preview"
+ heightClassName={CODE_BLOCK_IFRAME_HEIGHT}
+ />
+ ) : (
+ <CodeBlockStatic language="xml" body={html} />
+ )}
+ </div>
+ );
+}
diff --git a/packages/views/editor/index.ts b/packages/views/editor/index.ts
index 6c5e4aa11e..725a13fe46 100644
--- a/packages/views/editor/index.ts
+++ b/packages/views/editor/index.ts
@@ -20,3 +20,5 @@ export {
isPreviewable,
} from "./attachment-preview-modal";
export type { AttachmentPreviewHandle } from "./attachment-preview-modal";
+export { AttachmentCard } from "./attachment-card";
+export type { AttachmentCardProps } from "./attachment-card";
diff --git a/packages/views/editor/readonly-content.test.tsx b/packages/views/editor/readonly-content.test.tsx
index 4ed94090e8..c87948b6ee 100644
--- a/packages/views/editor/readonly-content.test.tsx
+++ b/packages/views/editor/readonly-content.test.tsx
@@ -153,6 +153,23 @@ describe("ReadonlyContent Mermaid rendering", () => {
);
});
+ it("does not regress Mermaid unwrap after the HtmlBlockPreview branch was added", async () => {
+ // Both Mermaid and HtmlBlockPreview rely on react-markdown's `code`
+ // renderer returning a non-<code> React element, and on the `pre`
+ // renderer recognizing the element by reference and unwrapping it. If
+ // someone tightens the `pre` check to a single component, the other
+ // one quietly regresses into a `<pre>`-wrapped DOM. This test pins the
+ // contract.
+ const { container } = render(
+ <ReadonlyContent
+ content={["```mermaid", "graph LR", " A --> B", "```"].join("\n")}
+ />,
+ );
+ expect(container.querySelector(".mermaid-diagram")).not.toBeNull();
+ // No outer <pre> envelope.
+ expect(container.querySelector("pre")).toBeNull();
+ });
+
it("opens a fullscreen lightbox when the toolbar button is clicked", async () => {
const { container } = render(
<ReadonlyContent
@@ -186,3 +203,53 @@ describe("ReadonlyContent Mermaid rendering", () => {
});
});
});
+
+describe("ReadonlyContent HTML block rendering", () => {
+ // `language=html` fenced blocks should default to a preview iframe with
+ // sandbox="allow-scripts" (chart JS executes in an opaque origin) and
+ // must NOT be wrapped by react-markdown's default <pre>, which would
+ // clamp the iframe with monospace / overflow styles. The two-layer
+ // code+pre unwrap mirror's Mermaid's pattern.
+ it("renders an iframe with sandbox='allow-scripts' for ```html and skips the outer <pre>", () => {
+ const { container } = render(
+ <ReadonlyContent
+ content={["```html", '<h1 id="x">hi</h1>', "```"].join("\n")}
+ />,
+ );
+ const frame = container.querySelector<HTMLIFrameElement>("iframe");
+ expect(frame).not.toBeNull();
+ expect(frame?.getAttribute("sandbox")).toBe("allow-scripts");
+ expect(frame?.getAttribute("srcdoc")).toContain('<h1 id="x">hi</h1>');
+ expect(container.querySelector("pre")).toBeNull();
+ });
+
+ it("keeps the <pre><code> wrapper for adjacent languages like htmlbars / mermaidx", () => {
+ // Regression: the previous `className.includes("language-html")` check
+ // matched `language-htmlbars` too, so an htmlbars fence lost its outer
+ // <pre> envelope and rendered as bare lowlight-highlighted spans. The
+ // unwrap rule must match the exact class token, not a prefix.
+ const { container } = render(
+ <ReadonlyContent
+ content={[
+ "```htmlbars",
+ "<div>{{name}}</div>",
+ "```",
+ "",
+ "```mermaidx",
+ "not a real lang",
+ "```",
+ ].join("\n")}
+ />,
+ );
+ const pres = container.querySelectorAll("pre");
+ // Both fences keep their <pre> wrapper.
+ expect(pres.length).toBe(2);
+ // And the inner <code> still carries the original language class.
+ expect(
+ container.querySelector("pre code.language-htmlbars"),
+ ).not.toBeNull();
+ expect(
+ container.querySelector("pre code.language-mermaidx"),
+ ).not.toBeNull();
+ });
+});
diff --git a/packages/views/editor/readonly-content.tsx b/packages/views/editor/readonly-content.tsx
index e7a7868844..0820683735 100644
--- a/packages/views/editor/readonly-content.tsx
+++ b/packages/views/editor/readonly-content.tsx
@@ -30,7 +30,7 @@ import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
import { createLowlight, common } from "lowlight";
// @ts-expect-error -- hast-util-to-html has no bundled type declarations
import { toHtml } from "hast-util-to-html";
-import { Maximize2, Download, Eye, Link as LinkIcon, FileText } from "lucide-react";
+import { Maximize2, Download, Link as LinkIcon } from "lucide-react";
import { toast } from "sonner";
import { cn } from "@multica/ui/lib/utils";
import { useWorkspacePaths, useWorkspaceSlug } from "@multica/core/paths";
@@ -45,9 +45,10 @@ import { openLink, isMentionHref } from "./utils/link-handler";
import { isAllowedFileCardHref } from "@multica/ui/markdown";
import { preprocessMarkdown } from "./utils/preprocess";
import { MermaidDiagram } from "./mermaid-diagram";
+import { HtmlBlockPreview } from "./html-block-preview";
import { useDownloadAttachment } from "./use-download-attachment";
import { useAttachmentPreview, type PreviewSource } from "./attachment-preview-modal";
-import { getPreviewKind } from "./utils/preview";
+import { AttachmentCard } from "./attachment-card";
import "katex/dist/katex.min.css";
import "./content-editor.css";
@@ -57,6 +58,13 @@ import "./content-editor.css";
const lowlight = createLowlight(common);
+// Code fences that the `code` renderer returns as a non-<code> React element
+// (Mermaid diagram, HTML preview iframe). The `pre` renderer below unwraps
+// these so the default <pre><code> envelope doesn't clamp their styles.
+// Anchored to whole class tokens so `language-htmlbars` / `language-mermaidx`
+// don't accidentally match and lose their <pre> wrapper.
+const PRE_UNWRAP_RE = /(^|\s)language-(html|mermaid)(\s|$)/;
+
// ---------------------------------------------------------------------------
// Sanitization schema — extends GitHub defaults to allow file-card data attrs
// ---------------------------------------------------------------------------
@@ -235,10 +243,10 @@ function ReadonlyImage({
);
}
-// Inline file card — same download semantics as the standalone attachment
-// list: fresh-sign through `useDownloadAttachment` when the href matches a
-// known attachment, otherwise hand the raw URL to the platform's external
-// opener.
+// Inline file card — wraps the shared AttachmentCard with the same
+// download semantics as the standalone attachment list: fresh-sign through
+// `useDownloadAttachment` when the href matches a known attachment,
+// otherwise hand the raw URL to the platform's external opener.
function ReadonlyFileCard({
href,
filename,
@@ -252,16 +260,7 @@ function ReadonlyFileCard({
onDownload: (attachmentId: string) => void;
onPreview: (source: PreviewSource) => boolean;
}) {
- const { t } = useT("editor");
const attachment = href ? resolveAttachment(href) : undefined;
- // Mirror file-card.tsx (NodeView) — preview gate widens to "anything that
- // can be downloaded AND whose filename is a previewable type". Media kinds
- // fall through to URL-only when the attachment record isn't reachable.
- const kind = filename
- ? getPreviewKind(attachment?.content_type ?? "", filename)
- : null;
- const isMediaKind = kind === "pdf" || kind === "video" || kind === "audio";
- const canPreview = !!href && kind !== null && (!!attachment || isMediaKind);
const handleDownloadClick = () => {
if (attachment) {
onDownload(attachment.id);
@@ -277,34 +276,14 @@ function ReadonlyFileCard({
}
};
return (
- <div className="my-1 flex items-center gap-2 rounded-md border border-border bg-muted/50 px-2.5 py-1 transition-colors hover:bg-muted">
- <FileText className="size-4 shrink-0 text-muted-foreground" />
- <div className="min-w-0 flex-1">
- <p className="truncate text-sm">{filename}</p>
- </div>
- {canPreview && (
- <button
- type="button"
- className="shrink-0 rounded-md p-1 text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"
- title={t(($) => $.attachment.preview)}
- aria-label={t(($) => $.attachment.preview)}
- onClick={handlePreviewClick}
- >
- <Eye className="size-3.5" />
- </button>
- )}
- {href && (
- <button
- type="button"
- className="shrink-0 rounded-md p-1 text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"
- title={t(($) => $.image.download)}
- aria-label={t(($) => $.image.download)}
- onClick={handleDownloadClick}
- >
- <Download className="size-3.5" />
- </button>
- )}
- </div>
+ <AttachmentCard
+ filename={filename}
+ contentType={attachment?.content_type ?? ""}
+ attachmentId={attachment?.id}
+ href={href}
+ onPreview={handlePreviewClick}
+ onDownload={handleDownloadClick}
+ />
);
}
@@ -365,6 +344,13 @@ function buildComponents(
if (isBlock && lang === "mermaid") {
return <MermaidDiagram chart={String(children).replace(/\n$/, "")} />;
}
+ if (isBlock && lang === "html") {
+ // Like Mermaid, return the React element directly here and rely on
+ // the `pre` renderer below to unwrap it — react-markdown otherwise
+ // wraps `code` children in a `<pre>` whose monospace + overflow
+ // styles would clamp the preview iframe.
+ return <HtmlBlockPreview html={String(children).replace(/\n$/, "")} />;
+ }
if (!isBlock && !lang) {
// Inline code — CSS handles styling via .rich-text-editor code
@@ -393,10 +379,26 @@ function buildComponents(
}
},
- // Pre — pass through (CSS handles styling via .rich-text-editor pre)
+ // Pre — pass through (CSS handles styling via .rich-text-editor pre).
+ // Special-case Mermaid / HtmlBlockPreview returned from the `code`
+ // renderer above so the outer `<pre>` does not wrap them — this is the
+ // standard two-layer pattern used to escape react-markdown's default
+ // `<pre><code>` envelope.
pre: ({ children }) => {
- if (isValidElement(children) && children.type === MermaidDiagram) {
- return <>{children}</>;
+ // react-markdown calls `pre` BEFORE invoking the `code` renderer —
+ // `children` is the unrendered `<code>` element from the AST. So we
+ // identify "this block was meant to be unwrapped" by inspecting the
+ // child's className (`language-mermaid`, `language-html`), not by
+ // checking `children.type === MermaidDiagram`, which never matches.
+ //
+ // Match by exact class token: a substring `includes("language-html")`
+ // would also fire on neighboring languages like `language-htmlbars`
+ // and silently strip their <pre> wrapper.
+ if (isValidElement(children)) {
+ const childProps = children.props as { className?: string };
+ if (PRE_UNWRAP_RE.test(childProps.className ?? "")) {
+ return <>{children}</>;
+ }
}
return <pre>{children}</pre>;
},
diff --git a/packages/views/issues/components/comment-card.tsx b/packages/views/issues/components/comment-card.tsx
index 4940ec96eb..a2c1f03f87 100644
--- a/packages/views/issues/components/comment-card.tsx
+++ b/packages/views/issues/components/comment-card.tsx
@@ -1,7 +1,7 @@
"use client";
import { memo, useCallback, useRef, useState } from "react";
-import { CheckCircle2, ChevronRight, Copy, Download, Eye, FileText, MoreHorizontal, Pencil, RotateCcw, Trash2 } from "lucide-react";
+import { CheckCircle2, ChevronRight, Copy, MoreHorizontal, Pencil, RotateCcw, Trash2 } from "lucide-react";
import { toast } from "sonner";
import { Card } from "@multica/ui/components/ui/card";
import { Button } from "@multica/ui/components/ui/button";
@@ -30,7 +30,7 @@ import { QuickEmojiPicker } from "@multica/ui/components/common/quick-emoji-pick
import { cn } from "@multica/ui/lib/utils";
import { useActorName } from "@multica/core/workspace/hooks";
import { timeAgo } from "@multica/core/utils";
-import { ContentEditor, type ContentEditorRef, copyMarkdown, ReadonlyContent, useFileDropZone, FileDropOverlay, useDownloadAttachment, useAttachmentPreview, isPreviewable } from "../../editor";
+import { ContentEditor, type ContentEditorRef, copyMarkdown, ReadonlyContent, useFileDropZone, FileDropOverlay, useDownloadAttachment, useAttachmentPreview, AttachmentCard } from "../../editor";
import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";
import { useFileUpload } from "@multica/core/hooks/use-file-upload";
import { api } from "@multica/core/api";
@@ -122,7 +122,6 @@ function DeleteCommentDialog({
// ---------------------------------------------------------------------------
function AttachmentList({ attachments, content, className }: { attachments?: Attachment[]; content?: string; className?: string }) {
- const { t } = useT("editor");
const download = useDownloadAttachment();
const preview = useAttachmentPreview();
if (!attachments?.length) return null;
@@ -150,35 +149,15 @@ function AttachmentList({ attachments, content, className }: { attachments?: Att
return (
<div className={cn("flex flex-col gap-1", className)}>
{standalone.map((a) => (
- <div
+ <AttachmentCard
key={a.id}
- className="flex items-center gap-2 rounded-md border border-border bg-muted/50 px-2.5 py-1 transition-colors hover:bg-muted"
- >
- <FileText className="size-4 shrink-0 text-muted-foreground" />
- <div className="min-w-0 flex-1">
- <p className="truncate text-sm">{a.filename}</p>
- </div>
- {isPreviewable(a.content_type, a.filename) && (
- <button
- type="button"
- className="shrink-0 rounded-md p-1 text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"
- title={t(($) => $.attachment.preview)}
- aria-label={t(($) => $.attachment.preview)}
- onClick={() => preview.tryOpen({ kind: "full", attachment: a })}
- >
- <Eye className="size-3.5" />
- </button>
- )}
- <button
- type="button"
- className="shrink-0 rounded-md p-1 text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"
- title={t(($) => $.image.download)}
- aria-label={t(($) => $.image.download)}
- onClick={() => download(a.id)}
- >
- <Download className="size-3.5" />
- </button>
- </div>
+ filename={a.filename}
+ contentType={a.content_type}
+ attachmentId={a.id}
+ href={a.url}
+ onPreview={() => preview.tryOpen({ kind: "full", attachment: a })}
+ onDownload={() => download(a.id)}
+ />
))}
{preview.modal}
</div>
diff --git a/packages/views/locales/en/editor.json b/packages/views/locales/en/editor.json
index a076807e7e..430e343841 100644
--- a/packages/views/locales/en/editor.json
+++ b/packages/views/locales/en/editor.json
@@ -56,7 +56,9 @@
"no_results": "No results"
},
"code_block": {
- "copy_code": "Copy code"
+ "copy_code": "Copy code",
+ "show_preview": "Show preview",
+ "show_source": "Show source"
},
"file_card": {
"uploading": "Uploading {{filename}}"
diff --git a/packages/views/locales/zh-Hans/editor.json b/packages/views/locales/zh-Hans/editor.json
index 59d4ba25f0..0b3e117f59 100644
--- a/packages/views/locales/zh-Hans/editor.json
+++ b/packages/views/locales/zh-Hans/editor.json
@@ -56,7 +56,9 @@
"no_results": "无结果"
},
"code_block": {
- "copy_code": "复制代码"
+ "copy_code": "复制代码",
+ "show_preview": "显示预览",
+ "show_source": "显示源码"
},
"file_card": {
"uploading": "正在上传 {{filename}}"