/*
* Copyright (C) 2026 Mateusz Gruszczyński @linuxiarz.pl
* Source-Available Code / Dual-Licensed.
*
* Free for non-commercial and evaluation use under terms of BSL/GPLv3.
* Commercial or production use requires a valid paid license.
* See LICENSE file in repository root for details.
*/
import { EMOJI_SHORTCODES } from "@rustpad/emoji-data";
function escapeHtml(value) {
return String(value).replace(/[&<>"']/g, c => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));
}
function safeUrl(value) {
const raw = String(value || "").trim();
if (!raw || raw.startsWith("//")) return "#";
if (raw.startsWith("#")) return escapeHtml(raw);
try {
const url = new URL(raw, location.origin);
if (url.protocol === "mailto:") return escapeHtml(url.href);
if (url.protocol !== "http:" && url.protocol !== "https:") return "#";
return escapeHtml(url.href);
} catch {
return "#";
}
}
const emoji = EMOJI_SHORTCODES;
function inline(value) {
const tokens = [];
const stash = html => {
const token = `\u0000T${tokens.length}\u0000`;
tokens.push(html);
return token;
};
let html = escapeHtml(value);
html = html.replace(/`([^`]+)`/g, (_, code) => stash(`${code}`));
html = html.replace(/!\[([^\]]*)\]\(([^\s)]+)(?:\s+["']([^"']*)["'])?\)/g, (_, alt, url, title) => {
const titleAttr = title ? ` title="${escapeHtml(title)}"` : "";
return stash(``);
});
html = html.replace(/\[([^\]]+)\]\(([^\s)]+)(?:\s+["']([^"']*)["'])?\)/g, (_, label, url, title) => {
const titleAttr = title ? ` title="${escapeHtml(title)}"` : "";
return stash(`${label}`);
});
html = html.replace(/\[\^([^\]\s]+)\]/g, (_, id) => stash(`?`));
html = html
.replace(/\*\*([^*]+)\*\*/g, "$1")
.replace(/~~([^~]+)~~/g, "
$1")
.replace(/==([^=]+)==/g, "$1")
.replace(/\*([^*]+)\*/g, "$1")
.replace(/(?$1")
.replace(/\^([^^\n]+)\^/g, "$1")
.replace(/:([a-z0-9_+-]+):/gi, (match, name) => emoji[name] || match);
html = html.replace(/(^|[\s(])((?:https?:\/\/|mailto:)[^\s<]+)/gi, (match, prefix, url) => {
const clean = url.replace(/[.,!?;:]+$/, "");
const suffix = url.slice(clean.length);
return `${prefix}${stash(`${clean}`)}${suffix}`;
});
return html.replace(/\u0000T(\d+)\u0000/g, (_, index) => tokens[Number(index)] || "");
}
const languageAliases = {
js: "javascript", javascript: "javascript", jsx: "javascript",
ts: "typescript", typescript: "typescript", tsx: "typescript",
py: "python", python: "python",
rb: "ruby", ruby: "ruby",
rs: "rust", rust: "rust",
php: "php",
sh: "bash", shell: "bash", bash: "bash", zsh: "bash",
c: "c", h: "c",
cpp: "cpp", "c++": "cpp", cxx: "cpp", hpp: "cpp",
cs: "csharp", "c#": "csharp", csharp: "csharp",
java: "java", kotlin: "kotlin", kt: "kotlin",
go: "go", golang: "go",
swift: "swift", dart: "dart", scala: "scala",
html: "html", htm: "html", xml: "xml", svg: "xml",
css: "css", scss: "scss", sass: "scss", less: "less",
json: "json", jsonc: "json", yaml: "yaml", yml: "yaml", toml: "ini", ini: "ini",
sql: "sql", graphql: "graphql", gql: "graphql",
md: "markdown", markdown: "markdown",
dockerfile: "dockerfile", docker: "dockerfile",
makefile: "makefile", make: "makefile",
powershell: "powershell", ps1: "powershell",
lua: "lua", perl: "perl", pl: "perl", r: "r", matlab: "matlab",
nginx: "nginx", apache: "apache", diff: "diff", patch: "diff",
text: "plaintext", txt: "plaintext", plaintext: "plaintext", none: "plaintext",
mermaid: "mermaid"
};
function normalizeLanguage(value) {
const language = String(value || "").trim().toLowerCase();
if (!language) return "";
return languageAliases[language] || language.replace(/[^a-z0-9_-]/g, "");
}
const attrs = (line, editable = false, prefix = "", suffix = "", lineOffset = 0) => ` class="preview-source-line${editable ? " preview-editable" : ""}" data-source-line="${line + lineOffset + 1}"${editable ? ` data-source-prefix="${escapeHtml(prefix)}" data-source-suffix="${escapeHtml(suffix)}"` : ""}`;
const isPlainText = line => !/[`*_~^=\[\]<>|:#]/.test(line) && !/^\s*(?:[-+*>]|\d+\.)\s/.test(line);
function listLine(line) {
const match = line.match(/^(\s*)([-*+]|(\d+)\.)\s+(?:\[([ xX])\]\s+)?(.+)$/);
if (!match) return null;
const indent = match[1].replace(/\t/g, " ").length;
return {
indent,
whitespace: match[1],
type: match[3] ? "ol" : "ul",
number: match[3] ? Number(match[3]) : null,
checked: match[4] == null ? null : match[4].toLowerCase() === "x",
text: match[5],
marker: match[3] ? `${match[3]}. ` : `${match[2]} `
};
}
function renderList(lines, start, lineOffset = 0, baseIndent = null, forcedType = null, depth = 0) {
const first = listLine(lines[start]);
if (!first) return null;
const indent = baseIndent == null ? first.indent : baseIndent;
const type = forcedType || first.type;
let index = start;
let body = "";
let hasTask = false;
while (index < lines.length) {
const item = listLine(lines[index]);
if (!item || item.indent < indent || item.indent !== indent || item.type !== type) break;
const sourceLine = index + lineOffset + 1;
const prefix = `${item.whitespace}${item.marker}${item.checked == null ? "" : `[${item.checked ? "x" : " "}] `}`;
const valueAttr = "";
const taskClass = item.checked == null ? "" : " task-list-item";
hasTask ||= item.checked != null;
const gutterOffset = `${(depth + 1) * 1.75}em`;
body += `
${numbered}`;
} else {
const languageClass = lang ? ` class="language-${escapeHtml(lang)}"` : "";
html += `${body}`;
}
code = []; language = ""; codeLineStart = null; fence = "";
};
for (let index = 0; index < lines.length; index++) {
const line = lines[index];
const fenceMatch = line.match(/^\s*(```+|~~~+)\s*([^\s]*)\s*$/);
if (fenceMatch) {
closeList();
if (inCode && fenceMatch[1][0] === fence[0] && fenceMatch[1].length >= fence.length) closeCode();
else if (!inCode) {
fence = fenceMatch[1];
const info = fenceMatch[2] || "";
// Generic syntax for every fenced code block:
// ```rust=, ```python=101, ```= or ```=101.
const numbered = info.match(/^(.*?)=(\d*)$/);
language = numbered ? numbered[1] : info;
codeLineStart = numbered ? Number(numbered[2] || 1) : null;
codeStart = index;
}
inCode = !inCode;
continue;
}
if (inCode) { code.push(line); continue; }
const delimiter = index + 1 < lines.length ? tableDelimiter(lines[index + 1]) : null;
if (line.includes("|") && delimiter) {
closeList();
const headers = splitTableRow(line);
html += `| ${inline(cell)} | `); html += `
|---|
| ${inline(cells[i] || "")} | `); html += `
", "", lineOffset)}>${inline(line.slice(2))}`; else if (line.trim()) html += `
${inline(line)}
`; else html += `