import type { HmmOptions } from "./types.ts"; import { mergeInlineNodes, Node } from "@dbushell/hyperless"; import { parseHTML, splitCode } from "./utils.ts"; import { parentTags, parseTags } from "./html.ts"; /** Render inline Markdown */ export const renderInline = ( text: string, options: HmmOptions, ): string => { for (const plugin of options.inlinePlugins.values()) { if (["anchor", "code"].includes(plugin.type)) { text = plugin.render(text, options); } else { text = splitCode(text, (part) => plugin.render(part, options)); } } return text; }; /** Apply inline render to text nodes */ export const renderTextNodes = ( node: Node, options: HmmOptions, ): void => { if (node.tag === "pre") return; if (node.tag === "code") return; if (node.type === "OPAQUE") return; if (node.type === "TEXT") { node.raw = renderInline(node.raw, options); return; } for (const child of node.children) { renderTextNodes(child, options); } }; /** Parse and render inline HTML and Markdown */ export const renderNode = ( text: string, options: HmmOptions, tag?: string, ): string => { const node = parseHTML(text, options, { rootTag: tag ?? "html" }); // Flag child nodes to ignore node.traverse((n) => { if ((parseTags.union(options.inlineTags)).has(n.tag)) return; node.type === "OPAQUE"; }); // Render inline markdown and then merge renderTextNodes(node, options); mergeInlineNodes(node, options.inlineTags); // Find text Nodes that need paragraphs const wrapNodes: Array = []; node.traverse((n) => { if (n.tag === "p") return false; if (n.type !== "TEXT") return; if (n.parent === null) return; if (parentTags.has(n.parent.tag)) { wrapNodes.push(n); } }); // Wrap text Nodes in paragraphs for (const oldText of wrapNodes) { // Collapse excess whitespace let raw = oldText.raw.trim(); raw = raw.replace(/\n{3,}/g, "\n\n"); // Iterate paragraphs for (const str of oldText.raw.split("\n\n")) { // Skip empty lines if (/^\s*$/.test(str)) continue; // Create new text Node const newText = parseHTML(str, options); // Do not wrap single elements if (newText.size === 1 && newText.at(0)?.tag === "img") { oldText.before(newText); continue; } // Handle line breaks newText.traverse((n) => { if (n.type !== "TEXT") return; if (n.previous === null) { n.raw = n.raw.replace(/^\s*\n/g, ""); } if (n.next === null) { n.raw = n.raw.replace(/\n\s*$/g, ""); } n.raw = n.raw.replaceAll("\n", "
"); }); // Wrap in paragraph Node const p = new Node(null, "ELEMENT", "

", "p"); p.append(newText); oldText.before(p); } // Remove original Node oldText.detach(); } return node.toString(); };