Something went wrong. Try again.
🌿 Collaborative wiki on ATProto forked from juprodh.me/lichen.wiki
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263import 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<string> = new Set(["graph", "sunburst"]);
export interface VizPluginEnv { hasViz?: boolean;}
function vizError(message: string): string { return `<div class="viz-error">${escapeHtml(message)}</div>\n`;}
function renderVizBlock(info: string, content: string, env: unknown): string { const vizType = info.slice(VIZ_PREFIX.length) as VizType; if (!SUPPORTED_TYPES.has(vizType)) { return `<div class="viz-error">Unknown visualization type: <code>${escapeHtml(vizType)}</code></div>\n`; }
const raw = content.trimEnd(); const result = validate(vizType, raw);
if (!result.ok) { return vizError(`Invalid viz data: ${result.error ?? "unknown error"}`); }
// Buffer, not btoa: btoa throws on any code point above U+00FF, and the // hydrator decodes these bytes back as UTF-8. const encoded = Buffer.from(raw, "utf8").toString("base64"); (env as VizPluginEnv).hasViz = true;
return `<div class="viz-container" data-viz-type="${vizType}" data-viz="${encoded}"></div>\n`;}
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); }
try { return renderVizBlock(info, token.content, env); } catch (err) { // A throw here escapes renderMarkdown and 500s the note on every // request, so one bad block must never take the page down. return vizError( `Viz render failed: ${err instanceof Error ? err.message : String(err)}`, ); } };}