import type MarkdownIt from "markdown-it"; import { escapeHtml } from "../html.ts"; import { type VizType, validate } from "./schemas.ts"; const VIZ_PREFIX = "viz-"; const SUPPORTED_TYPES: ReadonlySet = new Set(["graph", "sunburst"]); export interface VizPluginEnv { hasViz?: boolean; } export function vizPlugin(md: MarkdownIt): void { const defaultFence = md.renderer.rules.fence ?? ((tokens, idx, options, _env, self) => self.renderToken(tokens, idx, options)); md.renderer.rules.fence = (tokens, idx, options, env, self) => { const token = tokens[idx]; if (!token) return defaultFence(tokens, idx, options, env, self); const info = token.info.trim(); if (!info.startsWith(VIZ_PREFIX)) { return defaultFence(tokens, idx, options, env, self); } const vizType = info.slice(VIZ_PREFIX.length) as VizType; if (!SUPPORTED_TYPES.has(vizType)) { return `
Unknown visualization type: ${escapeHtml(vizType)}
\n`; } const raw = token.content.trimEnd(); const result = validate(vizType, raw); if (!result.ok) { return `
Invalid viz data: ${escapeHtml(result.error ?? "unknown error")}
\n`; } const encoded = btoa(raw); (env as VizPluginEnv).hasViz = true; return `
\n`; }; }