SPB Git

Repository Public

markdown.js 4.3 KB 97 lines javascript

1/**2 * =============================================================================3 * SP BOUCHER | SOURCE FILE4 * =============================================================================5 * Project      : MacLustr LLM API6 * File         : web/assets/site/markdown.js7 * Author       : Simon-Pierre Boucher | https://spboucher.ai8 * Contact      : admin@spboucher.ai9 * Copyright    : (c) 2026 Simon-Pierre Boucher10 * License      : None specified (no license file in this repository)11 * =============================================================================12 * END OF SP BOUCHER SOURCE HEADER13 * =============================================================================14 */1516// Minimal, safe Markdown renderer for model output.17// It builds DOM nodes directly: model text only ever reaches the page through text nodes (never innerHTML),18// so HTML in a response is displayed as text. Supported: fenced code, inline code, bold, italic, links (http/https),19// headings, ordered and unordered lists, paragraphs with line breaks.20import { h } from "/assets/site/core.js";21import { snippet } from "/assets/site/codeblock.js";2223const INLINE = /(`[^`\n]+`)|(\*\*[^\n]+?\*\*)|(\*[^*\s][^*\n]*?\*)|(\b_[^_\s][^_\n]*?_\b)|(\[[^\]\n]+\]\([^\s)]+\))/g;24const HL = { js: "javascript", javascript: "javascript", ts: "typescript", typescript: "typescript", py: "python", python: "python",25  swift: "swift", sh: "bash", bash: "bash", shell: "bash", zsh: "bash", json: "json" };2627function inline(text, depth = 0) {28  const out = [];29  let last = 0;30  INLINE.lastIndex = 0;31  let m;32  const re = new RegExp(INLINE.source, "g");33  while ((m = re.exec(text)) !== null) {34    if (m.index > last) out.push(text.slice(last, m.index));35    const tok = m[0];36    if (m[1]) out.push(h("code", { class: "inline" }, tok.slice(1, -1)));37    else if (m[2]) out.push(h("strong", null, depth < 3 ? inline(tok.slice(2, -2), depth + 1) : tok.slice(2, -2)));38    else if (m[3] || m[4]) out.push(h("em", null, depth < 3 ? inline(tok.slice(1, -1), depth + 1) : tok.slice(1, -1)));39    else {40      const lm = /^\[([^\]]+)\]\(([^\s)]+)\)$/.exec(tok);41      let safe = null;42      try { const u = new URL(lm[2]); if (u.protocol === "http:" || u.protocol === "https:") safe = u.href; } catch { safe = null; }43      out.push(safe ? h("a", { href: safe, target: "_blank", rel: "noopener noreferrer" }, lm[1]) : tok);44    }45    last = m.index + tok.length;46  }47  if (last < text.length) out.push(text.slice(last));48  return out;49}5051function withBreaks(lines) {52  const out = [];53  lines.forEach((line, i) => { if (i) out.push(h("br")); out.push(...inline(line)); });54  return out;55}5657export function renderMarkdown(src) {58  const frag = document.createDocumentFragment();59  const lines = String(src).replace(/\r\n?/g, "\n").split("\n");60  let i = 0;61  while (i < lines.length) {62    const line = lines[i];63    const fence = /^\s*(```+|~~~+)\s*([\w+-]*)\s*$/.exec(line);64    if (fence) {65      const body = [];66      i++;67      while (i < lines.length && !lines[i].trimStart().startsWith(fence[1])) body.push(lines[i++]);68      i++; // closing fence (absent while a response is still streaming)69      const lang = fence[2].toLowerCase();70      frag.append(snippet(body.join("\n") || " ", HL[lang] || "text", lang || "code"));71      continue;72    }73    if (!line.trim()) { i++; continue; }74    const hd = /^(#{1,6})\s+(.*)$/.exec(line);75    if (hd) { frag.append(h(`h${Math.min(6, hd[1].length + 2)}`, null, inline(hd[2]))); i++; continue; }76    const ul = /^\s*[-*+]\s+(.*)$/, ol = /^\s*\d+[.)]\s+(.*)$/;77    if (ul.test(line) || ol.test(line)) {78      const re = ul.test(line) ? ul : ol;79      const list = h(re === ul ? "ul" : "ol");80      while (i < lines.length && re.test(lines[i])) {81        const item = [re.exec(lines[i])[1]];82        i++;83        while (i < lines.length && /^\s{2,}\S/.test(lines[i]) && !ul.test(lines[i]) && !ol.test(lines[i])) item.push(lines[i++].trim());84        list.append(h("li", null, withBreaks(item)));85      }86      frag.append(list);87      continue;88    }89    const para = [];90    while (i < lines.length && lines[i].trim() && !/^\s*(```+|~~~+)/.test(lines[i]) && !/^#{1,6}\s/.test(lines[i]) && !ul.test(lines[i]) && !ol.test(lines[i])) {91      para.push(lines[i++]);92    }93    frag.append(h("p", null, withBreaks(para)));94  }95  return frag;96}97
Files main
Menu

Theme