Repository Public
1/**2 * Standalone SVG export of the vector blocks (diagram, chart, matrix, svg, timeline).3 *4 * WORKER ONLY. This file imports react-dom/server and must never be imported by a Next.js page, layout or5 * component: it is used by the export worker process (src/worker) and by unit tests.6 *7 * "Standalone" means the file opens the same anywhere: every theme token is resolved to a concrete colour8 * (no CSS variable, no color-mix left), the font stack is embedded in a <style>, plus the @font-face rules the9 * caller passes in `fontCss`.10 */11import { createElement, type ReactElement } from "react";12import { renderToStaticMarkup } from "react-dom/server";13import type { Block, LeafBlock, Locale, Sheet } from "@/schema";14import { MatrixSvg } from "./blocks/MatrixSvg";15import { SvgTree, svgNaturalSize } from "./blocks/SvgTree";16import { TimelineSvg } from "./blocks/TimelineSvg";17import { ChartSvg } from "./chart/ChartSvg";18import { DiagramSvg } from "./diagram/DiagramSvg";19import { layoutDiagram } from "./diagram/layout";20import { inlineToPlain } from "./inline";21import { t } from "./i18n";22import { FONT_STACKS, mixHex, resolveTokens, THEME_PALETTES } from "./themes";2324export interface ExportSvgOptions { theme: Sheet["theme"]; locale: Locale; fontCss?: string }2526const escapeXml = (s: string): string => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);2728/** Negative side of diverging scales: same rule as sheet.css (--sh-contra). */29const contraTone = (accent: Sheet["theme"]["accent"]): "red" | "blue" => (accent === "red" || accent === "pink" || accent === "amber" ? "blue" : "red");3031/** Replaces var(--sh-*) and color-mix(in srgb, …) by concrete values. Exported for tests. */32export function resolveCss(markup: string, theme: Sheet["theme"]): string {33 const tokens = resolveTokens(theme.preset, theme.accent);34 tokens["--sh-contra"] = THEME_PALETTES[theme.preset].tones[contraTone(theme.accent)].strong;35 let out = markup.replace(/var\((--[a-z0-9-]+)(?:\s*,\s*([^()]*))?\)/g, (_, name: string, fallback?: string) => tokens[name] ?? fallback?.trim() ?? "currentColor");36 // Innermost first, until no mix is left.37 for (let i = 0; i < 6 && out.includes("color-mix("); i++) {38 out = out.replace(/color-mix\(in srgb,\s*(#[0-9a-fA-F]{3,6})\s+(\d+(?:\.\d+)?)%,\s*(#[0-9a-fA-F]{3,6})\)/g, (_, a: string, p: string, b: string) => mixHex(a, Number(p), b));39 }40 return out;41}4243/** Characters XML 1.0 forbids (they can come from pasted text). */44const stripInvalidXml = (s: string): string => s.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, "");4546export function renderBlockSvg(block: Block | LeafBlock, opts: ExportSvgOptions): string | null {47 const { locale } = opts;48 const caption = "caption" in block && block.caption ? inlineToPlain(block.caption) : undefined;49 const titleOf = (fallback: string) => block.alt ?? ("title" in block && block.title ? inlineToPlain(block.title) : undefined) ?? fallback;50 let element: ReactElement;51 switch (block.type) {52 case "diagram": element = createElement(DiagramSvg, { layout: layoutDiagram(block), idPrefix: block.id, title: titleOf(t(locale, "diagram")), desc: caption }); break;53 case "chart": element = createElement(ChartSvg, { chart: block, locale, width: 960, height: 540, idPrefix: block.id, label: titleOf(t(locale, "chart")), desc: caption }); break;54 case "matrix": element = createElement(MatrixSvg, { matrix: block, locale, label: titleOf(t(locale, "matrix")), desc: caption }); break;55 case "timeline": element = createElement(TimelineSvg, { timeline: block, locale, label: titleOf(t(locale, "timeline")) }); break;56 case "svg": { const size = svgNaturalSize(block.tree); element = createElement(SvgTree, { tree: block.tree, idPrefix: block.id, title: titleOf(t(locale, "illustration")), desc: caption, width: size.width, height: size.height }); break; }57 default: return null;58 }59 const markup = stripInvalidXml(resolveCss(renderToStaticMarkup(element), opts.theme));60 const open = /^<svg\b[^>]*>/.exec(markup);61 if (!open) return null;62 const palette = THEME_PALETTES[opts.theme.preset];63 const vb = /viewBox="([^"]+)"/.exec(open[0])?.[1].split(/\s+/).map(Number) ?? [0, 0, 0, 0];64 // <title> and <desc> stay the first children; the style and the background come right after them.65 let at = open[0].length;66 const head = /^(?:<title>[\s\S]*?<\/title>)?(?:<desc>[\s\S]*?<\/desc>)?/.exec(markup.slice(at));67 if (head) at += head[0].length;68 const fontCss = (opts.fontCss ?? "").replace(/<\/?style[^>]*>/gi, "").replace(/]]>/g, "");69 const style = `<style>${escapeXml(`${fontCss}\nsvg{color:${palette.ink}}text{font-family:${FONT_STACKS.body}}`)}</style>`;70 // An uploaded illustration keeps its own (transparent) background; generated figures get the surface colour.71 const background = block.type === "svg" ? "" : `<rect x="${vb[0]}" y="${vb[1]}" width="${vb[2]}" height="${vb[3]}" fill="${palette.surface}"/>`;72 const root = open[0].replace(/^<svg\b/, '<svg xmlns="http://www.w3.org/2000/svg"').replace(/\sclass="[^"]*"/, "");73 return `<?xml version="1.0" encoding="UTF-8"?>\n${root}${markup.slice(open[0].length, at)}${style}${background}${markup.slice(at)}`;74}75