import MarkdownIt from "markdown-it"; import { useBaseMarkdownPlugins } from "./markdown/base-plugins.ts"; import { highlightPlugin } from "./markdown/highlight-plugin.ts"; import type { KatexPluginEnv } from "./markdown/katex-plugin.ts"; import { sanitizeMarkdownHtml } from "./markdown/sanitize.ts"; import { parseWikilinkTarget, type WikilinkEnv, type WikilinkTarget, } from "./markdown/wikilink-plugin.ts"; import { type VizPluginEnv, vizPlugin } from "./viz/plugin.ts"; interface RenderResult { html: string; hasViz: boolean; hasMath: boolean; } interface MarkdownEnv extends VizPluginEnv, WikilinkEnv, KatexPluginEnv { [key: string | symbol]: unknown; } const md = new MarkdownIt({ html: false, linkify: true }); useBaseMarkdownPlugins(md); md.use(highlightPlugin); md.use(vizPlugin); export function renderMarkdown( source: string, wikiSlug?: string, ownerHandle?: string, ): RenderResult { const env: MarkdownEnv = { ...(wikiSlug ? { wikiSlug } : {}), ...(ownerHandle ? { ownerHandle } : {}), }; const html = sanitizeMarkdownHtml(md.render(source, env)); return { html, hasViz: env.hasViz === true, hasMath: env.hasMath === true }; } // Dedup key ignores the #heading suffix — backlinks are per-note, not per-heading. export function extractWikilinks( content: string, currentWikiSlug?: string, ): WikilinkTarget[] { const seen = new Set(); const links: WikilinkTarget[] = []; let pos = 0; while (pos < content.length) { if (content[pos] === "[" && content[pos + 1] === "[") { const closeIdx = content.indexOf("]]", pos + 2); if (closeIdx === -1) break; const target = parseWikilinkTarget( content.slice(pos + 2, closeIdx), currentWikiSlug, ); if (target && (target.noteSlug || target.wikiSlug)) { const noteSlug = target.noteSlug || "home"; const key = `${target.wikiSlug ?? ""}:${noteSlug}`; if (!seen.has(key)) { seen.add(key); links.push({ ...target, noteSlug }); } } pos = closeIdx + 2; } else { pos++; } } return links; }