Nick Meslovich / Products / Gravitas

web/markdown.js

8.9 KB · raw

// Safe, dependency-free Markdown -> HTML renderer for Gravitas.
// All raw text is HTML-escaped before inline formatting is applied.
// Links are restricted to http:, https:, mailto:, file:, and safe relative paths.
(function (global) {
  "use strict";

  function escapeHtml(str) {
    return String(str == null ? "" : str)
      .replace(/&/g, "&")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/"/g, "&quot;")
      .replace(/'/g, "&#39;");
  }

  function safeUrl(raw) {
    const trimmed = String(raw || "").trim();
    if (!trimmed) return null;
    if (/^(https?:|mailto:|file:)/i.test(trimmed)) return trimmed;
    if (trimmed.startsWith("/") && !trimmed.startsWith("//")) return trimmed;
    if (trimmed.startsWith("#")) return trimmed;
    return null;
  }

  function unescapeEntities(s) {
    return String(s || "")
      .replace(/&amp;/g, "&")
      .replace(/&lt;/g, "<")
      .replace(/&gt;/g, ">")
      .replace(/&quot;/g, '"')
      .replace(/&#39;/g, "'");
  }

  function renderInline(src) {
    if (!src) return "";
    const tokens = [];
    const stash = (html) => {
      const idx = tokens.length;
      tokens.push(html);
      return "\u0000TOK" + idx + "\u0000";
    };

    // 1. Stash inline code spans first so nothing inside backticks is transformed
    let work = String(src).replace(/`([^`\n]+)`/g, (_, code) => {
      return stash("<code>" + escapeHtml(code) + "</code>");
    });

    // 2. Escape all remaining raw HTML
    let out = escapeHtml(work);

    // 3. Stash inline images ![alt](url)
    out = out.replace(/!\[([^\]]*)\]\(([^)\s]+)(?:\s+&quot;([^&]*)&quot;)?\)/g, (_, alt, href, title) => {
      const safe = safeUrl(unescapeEntities(href));
      if (!safe) return alt;
      const titleAttr = title ? ' title="' + title + '"' : "";
      return stash('<img class="md-inline-img" src="' + escapeHtml(safe) + '" alt="' + alt + '"' + titleAttr + ' loading="lazy">');
    });

    // 4. Stash markdown links [label](url) so bare-URL autolinking never nests <a> inside <a>
    out = out.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+&quot;([^&]*)&quot;)?\)/g, (_, label, href, title) => {
      const safe = safeUrl(unescapeEntities(href));
      if (!safe) return label;
      const titleAttr = title ? ' title="' + title + '"' : "";
      const formattedLabel = label
        .replace(/\*\*([^*\n]+)\*\*/g, "<strong>$1</strong>")
        .replace(/(^|[^*])\*([^*\n]+)\*(?!\*)/g, "$1<em>$2</em>");
      return stash('<a href="' + escapeHtml(safe) + '"' + titleAttr + ' target="_blank" rel="noopener noreferrer">' + formattedLabel + "</a>");
    });

    // 5. Bare URL autolinking
    out = out.replace(/(^|[\s(])(https?:\/\/[^\s<)]+)/g, (m, lead, url) => {
      const trailing = url.match(/[.,;:!?]+$/);
      const clean = trailing ? url.slice(0, -trailing[0].length) : url;
      const tail = trailing ? trailing[0] : "";
      const safe = safeUrl(unescapeEntities(clean));
      if (!safe) return m;
      return lead + stash('<a href="' + escapeHtml(safe) + '" target="_blank" rel="noopener noreferrer">' + clean + "</a>") + tail;
    });

    // 6. Emphasis & strikethrough
    out = out.replace(/\*\*\*([^*\n]+)\*\*\*/g, "<strong><em>$1</em></strong>");
    out = out.replace(/\*\*([^*\n]+)\*\*/g, "<strong>$1</strong>");
    out = out.replace(/__([^_\n]+)__/g, "<strong>$1</strong>");
    out = out.replace(/(^|[^*])\*([^*\n]+)\*(?!\*)/g, "$1<em>$2</em>");
    out = out.replace(/(^|[^_])_([^_\n]+)_(?!_)/g, "$1<em>$2</em>");
    out = out.replace(/~~([^~\n]+)~~/g, "<del>$1</del>");

    // 7. Restore stashed tokens (iterate twice in case a link contained an inline code token)
    for (let pass = 0; pass < 2; pass++) {
      out = out.replace(/\u0000TOK(\d+)\u0000/g, (_, idx) => tokens[Number(idx)] || "");
    }
    return out;
  }

  function splitTableRow(line) {
    let s = line.trim();
    if (s.startsWith("|")) s = s.slice(1);
    if (s.endsWith("|")) s = s.slice(0, -1);
    return s.split("|").map((c) => c.trim());
  }

  function isTableDivider(line) {
    if (!line || !line.includes("|")) return false;
    const cells = splitTableRow(line);
    if (cells.length === 0) return false;
    return cells.every((c) => /^:?-{3,}:?$/.test(c));
  }

  function renderListItemBody(raw) {
    const taskMatch = raw.match(/^\[([ xX])\]\s+(.*)$/);
    if (taskMatch) {
      const checked = taskMatch[1].toLowerCase() === "x";
      return (
        '<span class="md-task">' +
          '<input type="checkbox" disabled' + (checked ? " checked" : "") + ' aria-hidden="true">' +
          "<span>" + renderInline(taskMatch[2]) + "</span>" +
        "</span>"
      );
    }
    return renderInline(raw);
  }

  function renderMarkdown(src) {
    if (!src) return "";
    const normalized = String(src).replace(/\r\n?/g, "\n");
    const lines = normalized.split("\n");
    const out = [];
    let i = 0;

    while (i < lines.length) {
      const line = lines[i];

      const fence = line.match(/^\s*(`{3,}|~{3,})\s*([^\s`~]*)\s*$/);
      if (fence) {
        const marker = fence[1];
        const lang = fence[2] || "";
        const codeLines = [];
        i++;
        while (i < lines.length && !new RegExp("^\\s*" + marker[0] + "{" + marker.length + ",}\\s*$").test(lines[i])) {
          codeLines.push(lines[i]);
          i++;
        }
        if (i < lines.length) i++;
        const codeText = codeLines.join("\n");
        const langLabel = lang ? escapeHtml(lang) : "code";
        out.push(
          '<div class="code-block">' +
            '<div class="code-header">' +
              '<span class="code-lang">' + langLabel + "</span>" +
              '<button type="button" class="code-copy" data-copy="code" aria-label="Copy code">Copy</button>' +
            "</div>" +
            '<pre><code class="lang-' + langLabel + '">' + escapeHtml(codeText) + "</code></pre>" +
          "</div>"
        );
        continue;
      }

      if (/^\s*$/.test(line)) {
        i++;
        continue;
      }

      if (/^\s*(?:-\s*){3,}$|^\s*(?:\*\s*){3,}$|^\s*(?:_\s*){3,}$/.test(line)) {
        out.push("<hr>");
        i++;
        continue;
      }

      const heading = line.match(/^\s*(#{1,6})\s+(.+?)\s*#*$/);
      if (heading) {
        const level = heading[1].length;
        out.push("<h" + level + ">" + renderInline(heading[2]) + "</h" + level + ">");
        i++;
        continue;
      }

      if (/^\s*>\s?/.test(line)) {
        const quoteLines = [];
        while (i < lines.length && /^\s*>\s?/.test(lines[i])) {
          quoteLines.push(lines[i].replace(/^\s*>\s?/, ""));
          i++;
        }
        out.push("<blockquote>" + renderMarkdown(quoteLines.join("\n")) + "</blockquote>");
        continue;
      }

      if (line.includes("|") && i + 1 < lines.length && isTableDivider(lines[i + 1])) {
        const headers = splitTableRow(line);
        i += 2;
        const rows = [];
        while (i < lines.length && lines[i].includes("|") && !/^\s*$/.test(lines[i])) {
          rows.push(splitTableRow(lines[i]));
          i++;
        }
        let html = '<div class="table-wrap"><table><thead><tr>';
        for (const h of headers) html += "<th>" + renderInline(h) + "</th>";
        html += "</tr></thead><tbody>";
        for (const r of rows) {
          html += "<tr>";
          for (let c = 0; c < headers.length; c++) {
            html += "<td>" + renderInline(r[c] || "") + "</td>";
          }
          html += "</tr>";
        }
        html += "</tbody></table></div>";
        out.push(html);
        continue;
      }

      const ulMatch = line.match(/^(\s*)([-*+])\s+(.*)$/);
      const olMatch = line.match(/^(\s*)(\d+)\.\s+(.*)$/);
      if (ulMatch || olMatch) {
        const ordered = Boolean(olMatch);
        const tag = ordered ? "ol" : "ul";
        const baseIndent = (olMatch ? olMatch[1] : ulMatch[1]).length;
        const items = [];
        while (i < lines.length) {
          const m = ordered
            ? lines[i].match(/^(\s*)(\d+)\.\s+(.*)$/)
            : lines[i].match(/^(\s*)([-*+])\s+(.*)$/);
          if (!m) break;
          const indent = m[1].length;
          const cls = indent > baseIndent + 1 ? ' class="md-nested"' : "";
          items.push("<li" + cls + ">" + renderListItemBody(m[3]) + "</li>");
          i++;
        }
        out.push("<" + tag + ">" + items.join("") + "</" + tag + ">");
        continue;
      }

      const para = [line];
      i++;
      while (
        i < lines.length &&
        !/^\s*$/.test(lines[i]) &&
        !/^\s*(#{1,6})\s+/.test(lines[i]) &&
        !/^\s*(`{3,}|~{3,})/.test(lines[i]) &&
        !/^\s*>\s?/.test(lines[i]) &&
        !/^(\s*)([-*+]|\d+\.)\s+/.test(lines[i]) &&
        !/^\s*(?:-\s*){3,}$|^\s*(?:\*\s*){3,}$|^\s*(?:_\s*){3,}$/.test(lines[i])
      ) {
        para.push(lines[i]);
        i++;
      }
      out.push("<p>" + para.map(renderInline).join("<br>") + "</p>");
    }

    return out.join("\n");
  }

  global.GravitasMarkdown = {
    escapeHtml: escapeHtml,
    renderInline: renderInline,
    render: renderMarkdown
  };
})(typeof window !== "undefined" ? window : globalThis);