MDRender/js/renderer.js
tyuXX 54e01c7666
Some checks failed
Deploy static content to Pages / deploy (push) Has been cancelled
Update
2026-11-08 00:48:45 +03:00

544 lines
20 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

class MDRenderer {
constructor() {
this.rules = {
heading: /^[ \t]{0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/gm,
paragraph: /^(?!<|@@MDRENDER_|[ \t]{0,3}(?:#{1,6}[ \t]|[-*+][ \t]|\d{1,9}[.)][ \t])|[ \t]*(?:[-*_][ \t]*){3,}[ \t]*$|[ \t]*={3,}[ \t]*$)(.*\S.*)$/gm,
boldItalic: /\*\*\*([^*]+?)\*\*\*/g,
boldItalicU: /___([^_]+?)___/g,
bold: /\*\*([^*]+?)\*\*/g,
boldU: /__([^_]+?)__/g,
italic: /\*([^*\n]+?)\*/g,
italicU: /(?<!\w)_([^_\n]+?)_(?!\w)/g,
strikethrough: /~~([^~\n]+?)~~/g,
highlight: /==([^=\n]+?)==/g,
superscript: /\^([^\n^]+?)\^/g,
subscript: /~([^~\n]+?)~/g,
inlineCode: /`([^`\n]+)`/g,
link: /\[([^\]\n]+)\]\((.+?)(?:\s+"([^"]*)")?\)/g,
image: /!\[([^\]\n]+)\]\((.+?)(?:\s+"([^"]*)")?\)/g,
codeblock: /^[ \t]*```([^\n`]*)\n([\s\S]*?)^[ \t]*```[ \t]*$/gm,
horizontalRule: /^[ \t]{0,3}([-*_])(?:[ \t]*\1){2,}[ \t]*$/gm,
tableRow: /^\|.*\|[ \t]*$/,
tableDelimiter: /^\|(?:[ \t]*:?-+:?[ \t]*\|)+$/,
unorderedItem: /^([ \t]*)[-*+][ \t]+(.*)$/,
orderedItem: /^([ \t]*)(\d{1,9})\.[ \t]+(.*)$/,
footnoteRef: /\[\^([^\]\n]+)\]/g,
escapes: /\\([!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~])/g,
refLink: /\[([^\]\n]+)\]\[([^\]\n]*)\]/g,
refShortcut: /\[([^\]\n]+)\](?![\(\[])/g,
refImage: /!\[([^\]\n]+)\]\[([^\]\n]*)\]/g,
emoji: /:([a-zA-Z0-9_+-]+):/g,
};
this.footnotes = new Map();
this.abbreviations = new Map();
this.references = new Map();
this._stash = [];
this._nonce = '';
this._headingIds = {};
this.emojis = {
'smile': '😊',
'laugh': '😄',
'joy': '😂',
'wink': '😉',
'heart': '❤️',
'heart_eyes': '😍',
'thinking': '🤔',
'clap': '👏',
'wave': '👋',
'eyes': '👀',
'check': '✅',
'x': '❌',
'warning': '⚠️',
'info': 'ℹ️',
'thumbsup': '👍',
'thumbsdown': '👎',
'rocket': '🚀',
'star': '⭐',
'fire': '🔥',
'sunny': '☀️',
'sun': '☀️',
'moon': '🌙',
'cloud': '☁️',
'coffee': '☕',
'pizza': '🍕',
'cake': '🍰',
'apple': '🍎',
'tada': '🎉',
'bug': '🐛',
'zap': '⚡',
};
}
render(markdown) {
this.footnotes = new Map();
this.abbreviations = new Map();
this.references = new Map();
this._stash = [];
this._nonce = Math.random().toString(36).slice(2, 10);
this._headingIds = {};
let html = this._render(String(markdown ?? ''));
if (this.footnotes.size > 0) {
html += this.renderFootnotesSection();
}
const tokenRe = new RegExp(`@@MDRENDER_${this._nonce}_(\\d+)@@`, 'g');
const resolve = (s) => s.replace(tokenRe, (m, i) => {
const v = this._stash[+i];
return v === undefined ? m : resolve(v);
});
html = resolve(html);
return `<div class="mdrender">${html}</div>`;
}
_render(markdown) {
let html = markdown.replace(/\r\n?/g, '\n');
// Protect raw HTML blocks that must not be touched by inline rules
html = html.replace(/<script\b[\s\S]*?<\/script\s*>/gi, m => this._stashHtml(m));
html = html.replace(/<style\b[\s\S]*?<\/style\s*>/gi, m => this._stashHtml(m));
html = html.replace(/<!--[\s\S]*?-->/g, m => this._stashHtml(m));
// Code blocks first so their content is never parsed as markdown
html = this.renderCodeBlocks(html);
// Extract footnote/reference/abbreviation definitions before block parsing
html = this.collectFootnotes(html);
html = this.collectReferences(html);
html = this.collectAbbreviations(html);
// Block-level elements
html = this.renderBlockquotes(html);
html = this.renderHorizontalRules(html);
html = this.renderHeadings(html);
html = this.renderTables(html);
html = this.renderLists(html);
html = this.renderDefinitions(html);
html = this.renderParagraphs(html);
// Inline elements
return this.renderInline(html);
}
_stashHtml(html) {
const token = `@@MDRENDER_${this._nonce}_${this._stash.length}@@`;
this._stash.push(html);
return token;
}
_escapeHtml(s) {
return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
_escapeAttr(s) {
return this._escapeHtml(s).replace(/"/g, '&quot;');
}
_escapeRegExp(s) {
return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
_indentWidth(indent) {
return indent.replace(/\t/g, ' ').length;
}
_fnId(ref) {
return ref.replace(/[^\w-]+/g, '-').replace(/^-+|-+$/g, '') || 'fn';
}
// ---------- Block-level rendering ----------
renderCodeBlocks(text) {
return text.replace(this.rules.codeblock, (m, lang, code) => {
lang = (lang || '').trim();
const cls = lang ? ` class="language-${this._escapeAttr(lang)}"` : '';
return this._stashHtml(`<pre><code${cls}>${this._escapeHtml(code.trim())}</code></pre>`);
});
}
collectFootnotes(text) {
const lines = text.split('\n');
const out = [];
for (let i = 0; i < lines.length; i++) {
const m = lines[i].match(/^\[\^([^\]\n]+)\]:[ \t]*(.*)$/);
if (!m) {
out.push(lines[i]);
continue;
}
let defLines = [m[2]];
let j = i + 1;
while (j < lines.length) {
if (/^[ \t]+\S/.test(lines[j])) {
defLines.push(lines[j].trim());
j++;
} else if (/^[ \t]*$/.test(lines[j]) && j + 1 < lines.length && /^[ \t]+\S/.test(lines[j + 1])) {
defLines.push('');
j++;
} else {
break;
}
}
this.footnotes.set(m[1], defLines.join('\n').trim());
i = j - 1;
}
return out.join('\n');
}
collectReferences(text) {
return text.replace(/^[ \t]{0,3}\[([^\]\n]+)\]:[ \t]*(\S+)(?:[ \t]+["']([^"']*)["'])?[ \t]*$/gm,
(m, label, url, title) => {
this.references.set(label.toLowerCase(), { url, title });
return '';
});
}
collectAbbreviations(text) {
return text.replace(/^[ \t]{0,3}\*\[([^\]\n]+)\]:[ \t]*(.+?)[ \t]*$/gm, (m, abbr, def) => {
this.abbreviations.set(abbr, def);
return '';
});
}
renderBlockquotes(text) {
const lines = text.split('\n');
const out = [];
let i = 0;
while (i < lines.length) {
if (/^[ \t]{0,3}>/.test(lines[i])) {
const quoteLines = [];
while (i < lines.length && /^[ \t]{0,3}>/.test(lines[i])) {
quoteLines.push(lines[i].replace(/^[ \t]{0,3}>[ \t]?/, ''));
i++;
}
const inner = this._render(quoteLines.join('\n'));
out.push(this._stashHtml(`<blockquote>\n${inner}\n</blockquote>`));
} else {
out.push(lines[i]);
i++;
}
}
return out.join('\n');
}
renderHorizontalRules(text) {
return text.replace(this.rules.horizontalRule, '<hr>');
}
renderHeadings(text) {
return text.replace(this.rules.heading, (m, level, content) => {
const n = level.length;
let id = content.toLowerCase()
.replace(/[^\w\s-]+/g, '')
.trim()
.replace(/[\s]+/g, '-')
.replace(/-+/g, '-')
.replace(/^-+|-+$/g, '');
if (!id) id = 'section';
const count = this._headingIds[id] = (this._headingIds[id] || 0) + 1;
if (count > 1) id = `${id}-${count}`;
return `<h${n} id="${id}">${content}</h${n}>`;
});
}
_isTableDelimiter(line) {
return this.rules.tableDelimiter.test(line);
}
_isTableRow(line) {
return this.rules.tableRow.test(line);
}
_splitTableRow(line) {
return line.split(/(?<!\\)\|/).slice(1, -1).map(c => c.trim().replace(/\\\|/g, '|'));
}
_parseAlignment(delimLine) {
return this._splitTableRow(delimLine).map(cell => {
const left = cell.startsWith(':');
const right = cell.endsWith(':');
if (left && right) return 'center';
if (right) return 'right';
if (left) return 'left';
return '';
});
}
_alignAttr(alignments, index) {
const a = alignments && alignments[index];
return a ? ` style="text-align: ${a}"` : '';
}
renderTables(text) {
const lines = text.split('\n');
// First pass: find header rows (a table row directly followed by a delimiter)
const alignments = new Map();
for (let i = 0; i < lines.length - 1; i++) {
if (this._isTableRow(lines[i]) && this._isTableDelimiter(lines[i + 1])) {
alignments.set(i, this._parseAlignment(lines[i + 1]));
}
}
if (alignments.size === 0) return text;
const out = [];
let inTable = false;
let currentAlign = [];
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (this._isTableDelimiter(line)) continue;
if (alignments.has(i)) {
inTable = true;
currentAlign = alignments.get(i);
out.push('<table>', '<thead>', '<tr>');
this._splitTableRow(line).forEach((cell, idx) => {
out.push(`<th${this._alignAttr(currentAlign, idx)}>${cell}</th>`);
});
out.push('</tr>', '</thead>', '<tbody>');
} else if (inTable && this._isTableRow(line)) {
out.push('<tr>');
this._splitTableRow(line).forEach((cell, idx) => {
out.push(`<td${this._alignAttr(currentAlign, idx)}>${cell}</td>`);
});
out.push('</tr>');
} else {
if (inTable) {
inTable = false;
out.push('</tbody>', '</table>');
}
out.push(line);
}
}
if (inTable) out.push('</tbody>', '</table>');
return out.join('\n');
}
_isTaskItem(content) {
return /^\[[ xX]\][ \t]/.test(content);
}
_renderListLevel(items, start, indent) {
let html = '';
let i = start;
while (i < items.length) {
const it = items[i];
if (it.indent < indent) break;
if (it.indent > indent) {
const r = this._renderListLevel(items, i, it.indent);
html += r.html;
i = r.next;
continue;
}
const type = it.ordered ? 'ol' : 'ul';
// Scan direct members of this list run (for task-list detection)
let memberCount = 0;
let allTask = type === 'ul';
for (let j = i; j < items.length; j++) {
const jt = items[j];
if (jt.indent < indent) break;
if (jt.indent === indent && (jt.ordered ? 'ol' : 'ul') !== type) break;
if (jt.indent === indent) {
memberCount++;
if (!this._isTaskItem(jt.content)) allTask = false;
}
}
if (memberCount === 0) { i++; continue; }
let attrs = '';
if (type === 'ol' && it.num !== 1) attrs += ` start="${it.num}"`;
if (type === 'ul' && allTask) attrs += ' class="task-list"';
html += `<${type}${attrs}>`;
while (i < items.length && items[i].indent === indent &&
(items[i].ordered ? 'ol' : 'ul') === type) {
const item = items[i];
i++;
let children = '';
if (i < items.length && items[i].indent > indent) {
const r = this._renderListLevel(items, i, items[i].indent);
children = r.html;
i = r.next;
}
const task = item.content.match(/^\[([ xX])\][ \t]+(.*)$/);
if (task) {
const chk = task[1].toLowerCase() === 'x' ? ' checked' : '';
html += `<li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox"${chk} disabled><span class="task-list-item-text">${task[2]}</span>${children}</li>`;
} else {
html += `<li>${item.content}${children}</li>`;
}
}
html += `</${type}>`;
}
return { html, next: i };
}
renderLists(text) {
const lines = text.split('\n');
const out = [];
let i = 0;
while (i < lines.length) {
const um = lines[i].match(this.rules.unorderedItem);
const om = um ? null : lines[i].match(this.rules.orderedItem);
if (!um && !om) {
out.push(lines[i]);
i++;
continue;
}
const items = [];
while (i < lines.length) {
const um2 = lines[i].match(this.rules.unorderedItem);
const om2 = um2 ? null : lines[i].match(this.rules.orderedItem);
if (um2) {
items.push({ indent: this._indentWidth(um2[1]), ordered: false, num: 0, content: um2[2] });
} else if (om2) {
items.push({ indent: this._indentWidth(om2[1]), ordered: true, num: parseInt(om2[2], 10), content: om2[3] });
} else {
break;
}
i++;
}
const baseIndent = Math.min(...items.map(it => it.indent));
out.push(this._renderListLevel(items, 0, baseIndent).html);
}
return out.join('\n');
}
renderDefinitions(text) {
const defRe = /^[ \t]{0,3}:[ \t]+(.*)$/;
const isTerm = (s) => {
const t = s.trim();
if (!t) return false;
if (/^[ \t]{0,3}(?:#{1,6}[ \t]|[-*+][ \t]|\d{1,9}[.)][ \t]|\||>|<|@@MDRENDER_)/.test(s)) return false;
if (/^[ \t]*(?:[-*_][ \t]*){3,}[ \t]*$/.test(s)) return false;
if (defRe.test(s)) return false;
return true;
};
const lines = text.split('\n');
const out = [];
for (let i = 0; i < lines.length; i++) {
if (i + 1 < lines.length && isTerm(lines[i]) && defRe.test(lines[i + 1])) {
const term = lines[i];
const defs = [];
let j = i + 1;
while (j < lines.length) {
const dm = lines[j].match(defRe);
if (!dm) break;
defs.push(dm[1]);
j++;
}
out.push(`<dl><dt>${term}</dt>${defs.map(d => `<dd>${d}</dd>`).join('')}</dl>`);
i = j - 1;
} else {
out.push(lines[i]);
}
}
return out.join('\n');
}
renderParagraphs(text) {
return text
.replace(this.rules.paragraph, '<p>$1</p>')
.replace(/<\/p>\n<p>/g, ' ');
}
// ---------- Inline rendering ----------
renderInline(text) {
let html = text;
html = html.replace(this.rules.escapes, (m, c) => this._stashHtml(this._escapeHtml(c)));
html = html.replace(this.rules.inlineCode, (m, code) =>
this._stashHtml(`<code>${this._escapeHtml(code)}</code>`));
html = this.renderImages(html);
html = this.renderLinks(html);
html = html.replace(this.rules.boldItalic, '<strong><em>$1</em></strong>');
html = html.replace(this.rules.boldItalicU, '<strong><em>$1</em></strong>');
html = html.replace(this.rules.bold, '<strong>$1</strong>');
html = html.replace(this.rules.boldU, '<strong>$1</strong>');
html = html.replace(this.rules.italic, '<em>$1</em>');
html = html.replace(this.rules.italicU, '<em>$1</em>');
html = html.replace(this.rules.strikethrough, '<del>$1</del>');
html = html.replace(this.rules.highlight, '<mark>$1</mark>');
html = this.renderFootnoteRefs(html);
html = this.renderSuperscript(html);
html = this.renderSubscript(html);
html = this.renderAbbreviations(html);
return this.renderEmojis(html);
}
_refLinkHtml(text, ref) {
const title = ref.title ? ` title="${this._escapeAttr(ref.title)}"` : '';
return `<a href="${this._escapeAttr(ref.url)}"${title}>${text}</a>`;
}
renderLinks(text) {
text = text.replace(this.rules.refImage, (m, alt, label) => {
const ref = this.references.get((label || alt).toLowerCase());
if (!ref) return m;
const title = ref.title ? ` title="${this._escapeAttr(ref.title)}"` : '';
return `<img src="${this._escapeAttr(ref.url)}" alt="${this._escapeAttr(alt)}"${title}>`;
});
text = text.replace(this.rules.refLink, (m, t, l) => {
const ref = this.references.get((l || t).toLowerCase());
return ref ? this._refLinkHtml(t, ref) : m;
});
text = text.replace(this.rules.refShortcut, (m, t) => {
if (t.startsWith('^')) return m; // leave footnote refs alone
const ref = this.references.get(t.toLowerCase());
return ref ? this._refLinkHtml(t, ref) : m;
});
return text.replace(this.rules.link, (m, text, url, title) => {
const titleAttr = title ? ` title="${this._escapeAttr(title)}"` : '';
return `<a href="${this._escapeAttr(url)}"${titleAttr}>${text}</a>`;
});
}
renderImages(text) {
return text.replace(this.rules.image, (m, alt, url, title) => {
const titleAttr = title ? ` title="${this._escapeAttr(title)}"` : '';
return `<img src="${this._escapeAttr(url)}" alt="${this._escapeAttr(alt)}"${titleAttr}>`;
});
}
renderFootnoteRefs(text) {
return text.replace(this.rules.footnoteRef, (m, ref) => {
if (this.footnotes.has(ref)) {
const fid = this._fnId(ref);
return `<sup class="footnote-ref"><a href="#fn-${fid}" id="fnref-${fid}">${this._escapeHtml(ref)}</a></sup>`;
}
return m;
});
}
renderFootnotesSection() {
let html = '<section class="footnotes"><hr><ol>';
for (const [ref, content] of this.footnotes) {
const fid = this._fnId(ref);
html += `<li id="fn-${fid}">${this._render(content)}<a href="#fnref-${fid}" class="footnote-backref">↩</a></li>`;
}
return html + '</ol></section>';
}
renderAbbreviations(text) {
for (const [abbr, def] of this.abbreviations) {
const re = new RegExp(`(?<![\\w"'])${this._escapeRegExp(abbr)}(?![\\w"'])`);
text = text.replace(re, `<abbr title="${this._escapeAttr(def)}">${abbr}</abbr>`);
}
return text;
}
renderSuperscript(text) {
return text.replace(this.rules.superscript, '<sup>$1</sup>');
}
renderSubscript(text) {
return text.replace(this.rules.subscript, '<sub>$1</sub>');
}
renderEmojis(text) {
return text.replace(this.rules.emoji, (m, name) => this.emojis[name.toLowerCase()] || m);
}
}