Skip to content

[Feature] Render `svg fences as inline SVG #421

Closed

Description

@xfz2021

Render ```svg fences as inline SVG

Summary

ompweb renders ```mermaid fences as diagrams but shows every other fenced language as a plain code block. ```svg therefore stays source text with line numbers and a copy button, even though omp/omp CLI sessions emit exactly those fences expecting them to display inline.

Environment

  • @kahme247/ompweb 0.6.0 (also checked 0.5.2)
  • Node 24 / Next 16.3.4
  • Chrome on Windows 11 (relay and plain tabs behave the same)

Steps to reproduce

  1. Start ompweb.

  2. Send an omp session a message that produces this reply:

    ```svg
    <svg viewBox="0 0 420 90" font-family="system-ui, sans-serif">
      <text x="0" y="18" font-size="13" fill="var(--muted)">svg block renders inline</text>
      <rect x="0" y="30" width="400" height="46" rx="6" fill="none" stroke="var(--border)"/>
    </svg>
    ```
  3. Open the session in ompweb.

Actual: the block renders as .markdown-code-block — line numbers, an svg language chip, only a Copy action.
Expected: the same inline rendering the TUI gives, i.e. a picture.

A ```mermaid fence in the same conversation at least offers a "Preview Mermaid diagram" action, which confirms the fence is parsed correctly and the language chip is svg, not something else.

Root cause

components are not shipped in the npm package, so this is read from the built chunk .next/static/chunks/app/page-<hash>.js. The markdown code renderer dispatches on the fence language and special-cases only mermaid:

let s = className?.replace("language-", "").toLowerCase() ?? "", o = String(children);
return className?.includes("language-") || o.includes("\n")
  ? "mermaid" === s
    ? <MermaidBlock code={...} isStreaming={...} defaultPreview={...} />
    : <CodeBlock code={...} lang={s} isStreaming={...} />
  : <code ...>{children}</code>;

svg has no branch, so it can never reach the renderer no matter how the fence is written.

Second issue: theme variables do not exist in the web UI

omp's SVG conventions use var(--fg), var(--muted), var(--surface) and var(--c1)…var(--c6). The ompweb theme defines --text, --text-muted, --bg-panel, --accent and --status-* — but none of the former. Inline-rendering an omp-style <svg> therefore resolves those fills to the initial value and the drawing goes black on a black background, i.e. invisible.

Proposed change

Add an svg branch next to the mermaid one:

"svg" === s
  ? <SvgBlock code={o.replace(/\n$/, "")} isStreaming={isStreaming} />
  : <CodeBlock ... />

with SvgBlock doing the following (reference implementation attached below):

  1. Parse with DOMParser.parseFromString(code, "image/svg+xml").

  2. If there is a parsererror or the root element is not svg, fall back to <CodeBlock lang="svg">. This also covers streaming, where the fence is still half-written.

  3. Strip script, foreignObject, on* attributes, and javascript: / data:text/html values in href / xlink:href.

  4. Add max-width:100%;height:auto and default fill="currentColor", so drawings without an explicit fill stay visible in dark themes.

  5. Render inside a wrapper div whose style defines the missing variables as aliases:

    {
      "--fg": "var(--text)",
      "--muted": "var(--text-muted)",
      "--surface": "var(--bg-panel)",
      "--c1": "var(--accent)",
      "--c2": "var(--status-success)",
      "--c3": "var(--status-warning)",
      "--c4": "var(--status-error)",
      "--c5": "var(--status-modified)",
      "--c6": "var(--status-renamed)",
    }

    --c1…--c6 is a deliberate approximation; if you prefer real series colours, define them in the theme and drop those five entries.

Two design questions worth your call:

  • Whether the alias map belongs in the theme (--fg: var(--text) at :root) rather than in this component. A theme-level alias would also fix ```mermaid themes and any future HTML generated from omp output.
  • Whether <style> inside an inline SVG should be stripped like script. Inline SVG CSS applies to the whole document. I left it in place for fidelity (AI-generated diagrams often rely on class= + <style>), but it is a real surface.

Verification I ran against a locally patched 0.6.0

Check Result
Valid fence .markdown-svg-block > svg, width 100%, aspect preserved via viewBox
Theme variables --muted resolves to rgb(201,201,209), --border to the theme border
<script> / onload / foreignObject / javascript: href removed; no globals set
Malformed / unclosed SVG falls back to the code block
mermaid, json, powershell fences unchanged
mermaid preview action still works

Note on caching (unrelated but worth knowing)

/ _next/static/** is served with cache-control: public, max-age=31536000, immutable. Any in-place edit of a built chunk stays invisible after a restart because the file name does not change; only a hard reload or a renamed chunk takes effect. Not a bug, but it makes local patches look broken.

Activity

  1. added
    enhancement
    on Nov 6, 2026
  2. xfz2021 commented on Nov 6, 2026

    @xfz2021
    Author
    // Reference implementation of the ` ```svg ` fence branch.
    // This is the readable form of what apply.mjs injects into the minified client
    // chunk; use it to apply the patch by hand (or to open an upstream PR).
    //
    // Insertion point — the markdown `code` component renderer:
    //
    //   return className?.includes("language-") || text.includes("\n")
    //     ? lang === "mermaid"
    //       ? <MermaidBlock ... />
    //       : <CodeBlock code={text} lang={lang} isStreaming={...} />
    //     : <code ...>{children}</code>;
    //
    // becomes
    //
    //   return className?.includes("language-") || text.includes("\n")
    //     ? lang === "mermaid"
    //       ? <MermaidBlock ... />
    //       : lang === "svg"
    //         ? <SvgBlock code={text.replace(/\n$/, "")} isStreaming={...} />
    //         : <CodeBlock code={text} lang={lang} isStreaming={...} />
    //     : <code ...>{children}</code>;
    
    import { useMemo } from "react";
    
    // omp/ompweb theme variable aliases. The TUI-facing svg conventions use
    // --fg / --muted / --surface / --c1..--c6, which do not exist in the web theme;
    // without aliases those fills resolve to nothing and the drawing turns black on
    // a dark background. `--c1..--c6` map to status colours as an approximation.
    const ALIASES = {
      "--fg": "var(--text)",
      "--muted": "var(--text-muted)",
      "--surface": "var(--bg-panel)",
      "--c1": "var(--accent)",
      "--c2": "var(--status-success)",
      "--c3": "var(--status-warning)",
      "--c4": "var(--status-error)",
      "--c5": "var(--status-modified)",
      "--c6": "var(--status-renamed)",
    };
    
    const UNSAFE_TAGS = ["script", "foreignObject"];
    const UNSAFE_HREF = /^\s*(javascript|data:text\/html)/i;
    
    function sanitize(root) {
      for (const tag of UNSAFE_TAGS) for (const el of root.querySelectorAll(tag)) el.remove();
      for (const el of root.querySelectorAll("*")) {
        for (const attr of [...el.attributes]) {
          if (/^on/i.test(attr.name)) {
            el.removeAttribute(attr.name);
            continue;
          }
          if (/^(href|xlink:href)$/i.test(attr.name) && UNSAFE_HREF.test(attr.value)) {
            el.removeAttribute(attr.name);
          }
        }
      }
    }
    
    export function SvgBlock({ code, isStreaming }) {
      const markup = useMemo(() => {
        let doc;
        try {
          doc = new DOMParser().parseFromString(code, "image/svg+xml");
        } catch {
          return null;
        }
        if (doc.querySelector("parsererror")) return null;
        const root = doc.documentElement;
        if (!root || root.nodeName.toLowerCase() !== "svg") return null;
        sanitize(root);
        const style = root.getAttribute("style");
        root.setAttribute("style", `${style ? `${style};` : ""}max-width:100%;height:auto`);
        if (!root.hasAttribute("fill")) root.setAttribute("fill", "currentColor");
        if (!root.hasAttribute("xmlns")) root.setAttribute("xmlns", "http://www.w3.org/2000/svg");
        return new XMLSerializer().serializeToString(root);
      }, [code]);
    
      // Streaming generates half-written markup; fall back to the code block until
      // the fence closes.
      if (!markup) {
        return <CodeBlock code={code} lang="svg" isStreaming={isStreaming} />;
      }
      return (
        <div
          className="markdown-svg-block"
          style={{
            ...ALIASES,
            color: "var(--text)",
            display: "flex",
            justifyContent: "center",
            overflow: "auto",
            padding: "4px 0",
          }}
          dangerouslySetInnerHTML={{ __html: markup }}
        />
      );
    }
  3. anhnt256 commented on Nov 11, 2026

    @anhnt256
    Contributor

    I'll fix this — adding an svg branch next to mermaid in the markdown code renderer, with a new SvgBlock that parses the fence with DOMParser, sanitizes it (script/foreignObject/style, on* attributes, javascript: / data:text/html hrefs) and renders it inline with the omp theme-variable aliases the web theme lacks. Malformed or still-streaming markup falls back to the code block. Opening a PR with the component, the renderer branch, and tests for the sanitizer and the dispatch.

  4. added a commit that references this issue on Nov 22, 2026
    e6ce004
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions