Repository Public
1import { createElement, type CSSProperties, type ReactNode } from "react";2import { SVG_TAGS, type SvgNode } from "@/schema";3import { safeStyle, safeSvgAttr } from "../sanitize-svg";45const TAGS: ReadonlySet<string> = new Set(SVG_TAGS);6const camel = (name: string): string => name.replace(/-([a-z])/g, (_, c: string) => c.toUpperCase());78export interface SvgTreeProps {9 tree: SvgNode;10 /** Prefix added to every id and local reference, so two drawings on a page cannot collide. */11 idPrefix: string;12 /** Accessible name / description. */13 title?: string; desc?: string;14 /** Fixed pixel size (export). */15 width?: number; height?: number; className?: string;16}1718/** Natural size of a drawing, from its viewBox (or width/height). */19export function svgNaturalSize(tree: SvgNode): { width: number; height: number; viewBox: string } {20 const vb = (tree.attrs.viewBox ?? "").trim().split(/[\s,]+/).map(Number);21 if (vb.length === 4 && vb.every(Number.isFinite) && vb[2] > 0 && vb[3] > 0) return { width: vb[2], height: vb[3], viewBox: vb.join(" ") };22 const w = parseFloat(tree.attrs.width ?? ""), h = parseFloat(tree.attrs.height ?? "");23 if (w > 0 && h > 0) return { width: w, height: h, viewBox: `0 0 ${w} ${h}` };24 return { width: 300, height: 150, viewBox: "0 0 300 150" };25}2627/**28 * Draws a sanitised SVG tree with React elements — never as markup. The whitelist is checked again here:29 * unknown tags are skipped, event handlers, external references, unsafe styles and javascript: values are dropped.30 */31export function SvgTree({ tree, idPrefix, title, desc, width, height, className }: SvgTreeProps) {32 const localRef = (v: string): string => v.replace(/url\(#([^)]+)\)/g, (_, id: string) => `url(#${idPrefix}-${id})`);33 const draw = (node: SvgNode, key: number, depth: number): ReactNode => {34 if (!TAGS.has(node.tag) || depth > 32) return null;35 const props: Record<string, string | CSSProperties> = {};36 for (const [name, value] of Object.entries(node.attrs)) {37 if (typeof value !== "string" || !safeSvgAttr(name, value)) continue;38 if (depth > 0 && (name === "role" || name === "aria-label" || name === "aria-hidden")) continue;39 if (name === "style") {40 const style: Record<string, string> = {};41 for (const [p, v] of safeStyle(value)) style[camel(p)] = v;42 if (Object.keys(style).length) props.style = style as CSSProperties;43 } else if (name === "id") props.id = `${idPrefix}-${value}`;44 else if (name === "href" || name === "xlink:href") props.href = `#${idPrefix}-${value.trim().slice(1)}`;45 else if (name.startsWith("aria-")) props[name] = value;46 else props[camel(name)] = localRef(value);47 }48 const children = node.children.map((c, i) => (typeof c === "string" ? c : draw(c, i, depth + 1)));49 return createElement(node.tag, { key, ...props }, ...children);50 };51 if (tree.tag !== "svg") return null;52 const size = svgNaturalSize(tree);53 const rootPaint: Record<string, string> = {};54 for (const name of ["fill", "stroke", "stroke-width", "stroke-linecap", "stroke-linejoin", "font-family", "font-size", "color"]) {55 const v = tree.attrs[name];56 if (typeof v === "string" && safeSvgAttr(name, v)) rootPaint[camel(name)] = localRef(v);57 }58 const inner = tree.children.filter((c): c is SvgNode => typeof c !== "string" && !(c.tag === "title" || c.tag === "desc"));59 return (60 <svg className={className ?? "sh-svg-art"} viewBox={size.viewBox} width={width ?? size.width} height={height ?? size.height} role="img" aria-label={title} preserveAspectRatio="xMidYMid meet" {...rootPaint}>61 {title ? <title>{title}</title> : null}62 {desc ? <desc>{desc}</desc> : null}63 {inner.map((c, i) => draw(c, i, 1))}64 </svg>65 );66}67