import { renderInline } from "../inline/render.js"; import type { BlockHandler } from "./handler.type.js"; /** Generate a URL-friendly heading ID from text. */ export function generateHeadingId(text: string): string { return text .toLowerCase() .replace(/[^\p{L}\p{N}\s-]/gu, "") .replace(/\s+/g, "-") .replace(/-+/g, "-") .replace(/^-|-$/g, ""); } export const headingHandler = { render(raw: string, attrs?: Record): string { const level = parseInt(attrs?.level ?? "1", 10); const tag = `h${Math.min(6, Math.max(1, level))}`; const id = generateHeadingId(raw); const idAttr = id === "" ? "" : ` id="${id}"`; return `<${tag}${idAttr}>${renderInline(raw)}`; }, serialize(raw: string, attrs?: Record): string { const level = parseInt(attrs?.level ?? "1", 10); return `${"#".repeat(Math.min(6, Math.max(1, level)))} ${raw}`; }, } satisfies BlockHandler;