This commit is contained in:
parent
8e5b906663
commit
54e01c7666
4 changed files with 502 additions and 366 deletions
|
|
@ -26,7 +26,7 @@ A lightweight, customizable markdown renderer for web applications. MDRender con
|
|||
|
||||
```html
|
||||
<link rel="stylesheet" href="https://tyuxx.github.io/MDRender/css/markdown.css">
|
||||
<script src="https://tyuxx.github.io/MDRender/css/markdown.css"></script>
|
||||
<script src="https://tyuxx.github.io/MDRender/js/renderer.js"></script>
|
||||
```
|
||||
|
||||
### 2. Initialize the Renderer
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@
|
|||
<div class="header-controls">
|
||||
<select id="example-select">
|
||||
<option value="">Choose an example...</option>
|
||||
<option value="default">Feature Showcase</option>
|
||||
<option value="basic">Basic Markdown</option>
|
||||
<option value="advanced">Advanced Features</option>
|
||||
<option value="tables">Tables Example</option>
|
||||
|
|
|
|||
784
js/renderer.js
784
js/renderer.js
|
|
@ -1,375 +1,533 @@
|
|||
class MDRenderer {
|
||||
constructor() {
|
||||
this.rules = {
|
||||
heading: /^(#{1,6})\s+(.+)$/gm,
|
||||
paragraph: /^(?!#|>|\s*\d+\.|```|\s*-\s|\s*\*\s|\||\s*\[\s*[x\s]\s*\]|\^\[\d+\]|\s*={3,}|\s*-{3,})(.+)$/gm,
|
||||
bold: /\*\*(.+?)\*\*/g,
|
||||
italic: /\*(.+?)\*/g,
|
||||
strikethrough: /~~(.+?)~~/g,
|
||||
code: /`(.+?)`/g,
|
||||
codeblock: /```(\w*)\n([\s\S]*?)```/g,
|
||||
link: /\[(.+?)\]\((.+?)(?:\s+"(.+?)")?\)/g,
|
||||
image: /!\[(.+?)\]\((.+?)(?:\s+"(.+?)")?\)/g,
|
||||
list: /^(\s*)[*-]\s(.+)$/gm,
|
||||
orderedList: /^(\s*)\d+\.\s(.+)$/gm,
|
||||
blockquote: /^((?:\s*>+\s*)+)(.+)$/gm,
|
||||
horizontalRule: /^([-*_])\1{2,}$/gm,
|
||||
table: /^\|(.+)\|$/gm,
|
||||
tableDelimiter: /^\|(?:[-:]+[-| :]*)\|$/gm,
|
||||
taskList: /^(\s*)-\s+\[([ x])\]\s+(.+)$/gm,
|
||||
superscript: /\^(.+?)\^/g,
|
||||
subscript: /~(.+?)~/g,
|
||||
highlight: /==(.+?)==/g,
|
||||
footnoteRef: /\[\^(\d+)\]/g,
|
||||
footnote: /^\[\^(\d+)\]:\s(.+)$/gm,
|
||||
abbreviation: /\*\[(.+?)\]:\s(.+)$/gm,
|
||||
definition: /^:\s(.+?)\n\s{2,}(.+)$/gm,
|
||||
emoji: /:([\w+-]+):/g,
|
||||
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': 'ℹ️',
|
||||
// Add more emojis as needed
|
||||
'thumbsup': '👍',
|
||||
'thumbsdown': '👎',
|
||||
'rocket': '🚀',
|
||||
'star': '⭐',
|
||||
'fire': '🔥',
|
||||
'sunny': '☀️',
|
||||
'sun': '☀️',
|
||||
'moon': '🌙',
|
||||
'cloud': '☁️',
|
||||
'coffee': '☕',
|
||||
'pizza': '🍕',
|
||||
'cake': '🍰',
|
||||
'apple': '🍎',
|
||||
'tada': '🎉',
|
||||
'bug': '🐛',
|
||||
'zap': '⚡',
|
||||
};
|
||||
}
|
||||
|
||||
render(markdown) {
|
||||
let html = 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 = {};
|
||||
|
||||
// Reset collections
|
||||
this.footnotes.clear();
|
||||
this.abbreviations.clear();
|
||||
let html = this._render(String(markdown ?? ''));
|
||||
|
||||
// Pre-process footnotes and abbreviations
|
||||
html = this.collectFootnotes(html);
|
||||
html = this.collectAbbreviations(html);
|
||||
|
||||
// Convert code blocks first to prevent interference
|
||||
html = this.renderCodeBlocks(html);
|
||||
|
||||
// Process blockquotes first to handle nesting
|
||||
html = this.renderBlockquotes(html);
|
||||
|
||||
// Then process task lists
|
||||
html = this.renderTaskLists(html);
|
||||
|
||||
// Convert block elements
|
||||
html = this.renderHorizontalRules(html);
|
||||
html = this.renderHeadings(html);
|
||||
html = this.renderTables(html);
|
||||
html = this.renderLists(html);
|
||||
html = this.renderOrderedLists(html);
|
||||
html = this.renderDefinitions(html);
|
||||
html = this.renderParagraphs(html);
|
||||
|
||||
// Convert inline elements
|
||||
html = this.renderBold(html);
|
||||
html = this.renderItalic(html);
|
||||
html = this.renderStrikethrough(html);
|
||||
html = this.renderHighlight(html);
|
||||
html = this.renderSuperscript(html);
|
||||
html = this.renderSubscript(html);
|
||||
html = this.renderInlineCode(html);
|
||||
html = this.renderImages(html);
|
||||
html = this.renderLinks(html);
|
||||
html = this.renderFootnoteRefs(html);
|
||||
html = this.renderEmojis(html);
|
||||
|
||||
// Add footnotes section if any exist
|
||||
if (this.footnotes.size > 0) {
|
||||
html += this.renderFootnotesSection();
|
||||
}
|
||||
|
||||
// Wrap the content in a div with the mdrender class
|
||||
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>`;
|
||||
}
|
||||
|
||||
renderHeadings(text) {
|
||||
return text.replace(this.rules.heading, (match, level, content) => {
|
||||
const headingLevel = level.length;
|
||||
const id = content.toLowerCase().replace(/[^\w]+/g, '-');
|
||||
return `<h${headingLevel} id="${id}">${content}</h${headingLevel}>`;
|
||||
});
|
||||
_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);
|
||||
}
|
||||
|
||||
renderParagraphs(text) {
|
||||
return text.replace(this.rules.paragraph, (match, content) => {
|
||||
return `<p>${content}</p>`;
|
||||
});
|
||||
_stashHtml(html) {
|
||||
const token = `@@MDRENDER_${this._nonce}_${this._stash.length}@@`;
|
||||
this._stash.push(html);
|
||||
return token;
|
||||
}
|
||||
|
||||
renderBold(text) {
|
||||
return text.replace(this.rules.bold, '<strong>$1</strong>');
|
||||
_escapeHtml(s) {
|
||||
return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
}
|
||||
|
||||
renderItalic(text) {
|
||||
return text.replace(this.rules.italic, '<em>$1</em>');
|
||||
_escapeAttr(s) {
|
||||
return this._escapeHtml(s).replace(/"/g, '"');
|
||||
}
|
||||
|
||||
renderStrikethrough(text) {
|
||||
return text.replace(this.rules.strikethrough, '<del>$1</del>');
|
||||
_escapeRegExp(s) {
|
||||
return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
}
|
||||
|
||||
renderInlineCode(text) {
|
||||
return text.replace(this.rules.code, '<code>$1</code>');
|
||||
_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, (match, language, code) => {
|
||||
return `<pre><code class="language-${language}">${code.trim()}</code></pre>`;
|
||||
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>`);
|
||||
});
|
||||
}
|
||||
|
||||
renderLinks(text) {
|
||||
return text.replace(this.rules.link, (match, text, url, title) => {
|
||||
const titleAttr = title ? ` title="${title}"` : '';
|
||||
return `<a href="${url}"${titleAttr}>${text}</a>`;
|
||||
});
|
||||
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');
|
||||
}
|
||||
|
||||
renderImages(text) {
|
||||
return text.replace(this.rules.image, (match, alt, url, title) => {
|
||||
const titleAttr = title ? ` title="${title}"` : '';
|
||||
return `<img src="${url}" alt="${alt}"${titleAttr}>`;
|
||||
});
|
||||
}
|
||||
|
||||
renderLists(text) {
|
||||
const items = [];
|
||||
let lastIndentLevel = 0;
|
||||
let html = text.replace(this.rules.list, (match, indent, content) => {
|
||||
const indentLevel = indent.length;
|
||||
if (indentLevel > lastIndentLevel) {
|
||||
items.push('<ul>');
|
||||
} else if (indentLevel < lastIndentLevel) {
|
||||
items.push('</ul>');
|
||||
}
|
||||
lastIndentLevel = indentLevel;
|
||||
items.push(`<li>${content}</li>`);
|
||||
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 '';
|
||||
});
|
||||
|
||||
while (lastIndentLevel > 0) {
|
||||
items.push('</ul>');
|
||||
lastIndentLevel--;
|
||||
}
|
||||
|
||||
return html + items.join('');
|
||||
}
|
||||
|
||||
renderOrderedLists(text) {
|
||||
const items = [];
|
||||
let lastIndentLevel = 0;
|
||||
let html = text.replace(this.rules.orderedList, (match, indent, content) => {
|
||||
const indentLevel = indent.length;
|
||||
if (indentLevel > lastIndentLevel) {
|
||||
items.push('<ol>');
|
||||
} else if (indentLevel < lastIndentLevel) {
|
||||
items.push('</ol>');
|
||||
}
|
||||
lastIndentLevel = indentLevel;
|
||||
items.push(`<li>${content}</li>`);
|
||||
collectAbbreviations(text) {
|
||||
return text.replace(/^[ \t]{0,3}\*\[([^\]\n]+)\]:[ \t]*(.+?)[ \t]*$/gm, (m, abbr, def) => {
|
||||
this.abbreviations.set(abbr, def);
|
||||
return '';
|
||||
});
|
||||
|
||||
while (lastIndentLevel > 0) {
|
||||
items.push('</ol>');
|
||||
lastIndentLevel--;
|
||||
}
|
||||
|
||||
return html + items.join('');
|
||||
}
|
||||
|
||||
renderBlockquotes(text) {
|
||||
const lines = text.split('\n');
|
||||
const result = [];
|
||||
let inBlockquote = false;
|
||||
let currentContent = [];
|
||||
let currentLevel = 0;
|
||||
|
||||
function processBlockquote(content, level) {
|
||||
if (content.length === 0) return '';
|
||||
const innerContent = content.join('\n').trim();
|
||||
let html = innerContent;
|
||||
for (let i = 0; i < level; i++) {
|
||||
html = `<blockquote>${html}</blockquote>`;
|
||||
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++;
|
||||
}
|
||||
return html;
|
||||
}
|
||||
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
const match = line.match(/^(>+)?\s*(.*)$/);
|
||||
|
||||
if (match) {
|
||||
const [, quotes, content] = match;
|
||||
const level = quotes ? quotes.length : 0;
|
||||
|
||||
if (level > 0) {
|
||||
if (!inBlockquote) {
|
||||
inBlockquote = true;
|
||||
currentLevel = level;
|
||||
}
|
||||
|
||||
if (level !== currentLevel) {
|
||||
// Process previous blockquote
|
||||
result.push(processBlockquote(currentContent, currentLevel));
|
||||
currentContent = [];
|
||||
currentLevel = level;
|
||||
}
|
||||
|
||||
currentContent.push(content.trim());
|
||||
const inner = this._render(quoteLines.join('\n'));
|
||||
out.push(this._stashHtml(`<blockquote>\n${inner}\n</blockquote>`));
|
||||
} else {
|
||||
if (inBlockquote) {
|
||||
// End of blockquote
|
||||
result.push(processBlockquote(currentContent, currentLevel));
|
||||
currentContent = [];
|
||||
inBlockquote = false;
|
||||
}
|
||||
result.push(line);
|
||||
out.push(lines[i]);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Process any remaining blockquote
|
||||
if (inBlockquote && currentContent.length > 0) {
|
||||
result.push(processBlockquote(currentContent, currentLevel));
|
||||
}
|
||||
|
||||
return result.join('\n');
|
||||
}
|
||||
|
||||
renderTaskLists(text) {
|
||||
const processedLines = [];
|
||||
const lines = text.split('\n');
|
||||
let currentList = null;
|
||||
let currentIndent = 0;
|
||||
|
||||
for (let line of lines) {
|
||||
const taskMatch = line.match(/^(\s*)-\s+\[([ x])\]\s+(.+)$/);
|
||||
|
||||
if (taskMatch) {
|
||||
const [, indent, checked, content] = taskMatch;
|
||||
const indentLevel = indent.length;
|
||||
|
||||
const checkbox = `<input type="checkbox" class="task-list-item-checkbox" ${checked === 'x' ? 'checked' : ''} disabled>`;
|
||||
const listItem = `<li class="task-list-item">${checkbox}<span class="task-list-item-text">${content}</span></li>`;
|
||||
|
||||
if (currentList === null) {
|
||||
// Start a new list
|
||||
currentList = indentLevel;
|
||||
currentIndent = indentLevel;
|
||||
processedLines.push(`<ul class="task-list">${listItem}`);
|
||||
} else if (indentLevel > currentIndent) {
|
||||
// Nested list
|
||||
processedLines.push(`<ul class="task-list">${listItem}`);
|
||||
currentIndent = indentLevel;
|
||||
} else if (indentLevel < currentIndent) {
|
||||
// Close nested lists and start new item
|
||||
const closeLevels = Math.floor((currentIndent - indentLevel) / 2);
|
||||
processedLines.push('</ul>'.repeat(closeLevels));
|
||||
processedLines.push(listItem);
|
||||
currentIndent = indentLevel;
|
||||
} else {
|
||||
// Same level
|
||||
processedLines.push(listItem);
|
||||
}
|
||||
} else {
|
||||
if (currentList !== null) {
|
||||
// Close all open lists when encountering non-task-list content
|
||||
const closeLevels = Math.floor(currentIndent / 2) + 1;
|
||||
processedLines.push('</ul>'.repeat(closeLevels));
|
||||
currentList = null;
|
||||
currentIndent = 0;
|
||||
}
|
||||
processedLines.push(line);
|
||||
}
|
||||
}
|
||||
|
||||
// Close any remaining open lists
|
||||
if (currentList !== null) {
|
||||
const closeLevels = Math.floor(currentIndent / 2) + 1;
|
||||
processedLines.push('</ul>'.repeat(closeLevels));
|
||||
}
|
||||
|
||||
return processedLines.join('\n');
|
||||
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) {
|
||||
let html = 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 alignment = [];
|
||||
|
||||
// Split into lines
|
||||
const lines = html.split('\n');
|
||||
const newLines = [];
|
||||
|
||||
let currentAlign = [];
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
|
||||
if (this.rules.tableDelimiter.test(line)) {
|
||||
// Get alignment info
|
||||
alignment = line.split('|').slice(1, -1).map(cell => {
|
||||
cell = cell.trim();
|
||||
if (cell.startsWith(':') && cell.endsWith(':')) return 'center';
|
||||
if (cell.endsWith(':')) return 'right';
|
||||
return 'left';
|
||||
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;
|
||||
}
|
||||
|
||||
if (this.rules.table.test(line)) {
|
||||
const cells = line.split('|').slice(1, -1);
|
||||
const type = it.ordered ? 'ol' : 'ul';
|
||||
|
||||
if (!inTable) {
|
||||
inTable = true;
|
||||
newLines.push('<table>');
|
||||
newLines.push('<thead>');
|
||||
newLines.push('<tr>');
|
||||
cells.forEach((cell, index) => {
|
||||
const align = alignment[index] ? ` style="text-align: ${alignment[index]}"` : '';
|
||||
newLines.push(`<th${align}>${cell.trim()}</th>`);
|
||||
});
|
||||
newLines.push('</tr>');
|
||||
newLines.push('</thead>');
|
||||
newLines.push('<tbody>');
|
||||
// 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 {
|
||||
newLines.push('<tr>');
|
||||
cells.forEach((cell, index) => {
|
||||
const align = alignment[index] ? ` style="text-align: ${alignment[index]}"` : '';
|
||||
newLines.push(`<td${align}>${cell.trim()}</td>`);
|
||||
});
|
||||
newLines.push('</tr>');
|
||||
html += `<li>${item.content}${children}</li>`;
|
||||
}
|
||||
} else if (inTable) {
|
||||
inTable = false;
|
||||
newLines.push('</tbody>');
|
||||
newLines.push('</table>');
|
||||
newLines.push(line);
|
||||
}
|
||||
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 {
|
||||
newLines.push(line);
|
||||
break;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
const baseIndent = Math.min(...items.map(it => it.indent));
|
||||
out.push(this._renderListLevel(items, 0, baseIndent).html);
|
||||
}
|
||||
return out.join('\n');
|
||||
}
|
||||
|
||||
if (inTable) {
|
||||
newLines.push('</tbody>');
|
||||
newLines.push('</table>');
|
||||
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');
|
||||
}
|
||||
|
||||
return newLines.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) {
|
||||
|
|
@ -380,55 +538,7 @@ class MDRenderer {
|
|||
return text.replace(this.rules.subscript, '<sub>$1</sub>');
|
||||
}
|
||||
|
||||
renderHighlight(text) {
|
||||
return text.replace(this.rules.highlight, '<mark>$1</mark>');
|
||||
}
|
||||
|
||||
collectFootnotes(text) {
|
||||
return text.replace(this.rules.footnote, (match, ref, content) => {
|
||||
this.footnotes.set(ref, content);
|
||||
return '';
|
||||
});
|
||||
}
|
||||
|
||||
renderFootnoteRefs(text) {
|
||||
return text.replace(this.rules.footnoteRef, (match, ref) => {
|
||||
if (this.footnotes.has(ref)) {
|
||||
return `<sup class="footnote-ref"><a href="#fn${ref}" id="fnref${ref}">${ref}</a></sup>`;
|
||||
}
|
||||
return match;
|
||||
});
|
||||
}
|
||||
|
||||
renderFootnotesSection() {
|
||||
if (this.footnotes.size === 0) return '';
|
||||
|
||||
let html = '<section class="footnotes"><hr><ol>';
|
||||
for (const [ref, content] of this.footnotes) {
|
||||
html += `
|
||||
<li id="fn${ref}">
|
||||
${content}
|
||||
<a href="#fnref${ref}" class="footnote-backref">↩</a>
|
||||
</li>`;
|
||||
}
|
||||
html += '</ol></section>';
|
||||
return html;
|
||||
}
|
||||
|
||||
collectAbbreviations(text) {
|
||||
return text.replace(this.rules.abbreviation, (match, abbr, definition) => {
|
||||
this.abbreviations.set(abbr, definition);
|
||||
return '';
|
||||
});
|
||||
}
|
||||
|
||||
renderDefinitions(text) {
|
||||
return text.replace(this.rules.definition, '<dl><dt>$1</dt><dd>$2</dd></dl>');
|
||||
}
|
||||
|
||||
renderEmojis(text) {
|
||||
return text.replace(this.rules.emoji, (match, name) => {
|
||||
return this.emojis[name] || match;
|
||||
});
|
||||
return text.replace(this.rules.emoji, (m, name) => this.emojis[name.toLowerCase()] || m);
|
||||
}
|
||||
}
|
||||
51
js/script.js
51
js/script.js
|
|
@ -327,16 +327,16 @@ ___
|
|||
:coffee: :pizza: :cake: :apple:
|
||||
|
||||
## 12. Special Characters & Escaping
|
||||
\* Escaped asterisk
|
||||
\_ Escaped underscore
|
||||
\# Escaped hash
|
||||
\[ Escaped bracket
|
||||
\] Escaped bracket
|
||||
\` Escaped backtick
|
||||
\( Escaped parenthesis
|
||||
\) Escaped parenthesis
|
||||
\~ Escaped tilde
|
||||
\: Escaped colon
|
||||
\\* Escaped asterisk
|
||||
\\_ Escaped underscore
|
||||
\\# Escaped hash
|
||||
\\[ Escaped bracket
|
||||
\\] Escaped bracket
|
||||
\\\` Escaped backtick
|
||||
\\( Escaped parenthesis
|
||||
\\) Escaped parenthesis
|
||||
\\~ Escaped tilde
|
||||
\\: Escaped colon
|
||||
|
||||
## 13. HTML Support
|
||||
<div style="color: blue;">
|
||||
|
|
@ -387,14 +387,39 @@ That's all! This document showcases every feature supported by MDRender. Feel fr
|
|||
togglePreviewBtn.textContent = preview.style.display === 'none' ? 'Show Preview' : 'Hide Preview';
|
||||
});
|
||||
|
||||
function formatHtmlFallback(html) {
|
||||
const voidTags = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
|
||||
const tokens = html.split(/(<[^>]+>)/g).filter(t => t !== '');
|
||||
const out = [];
|
||||
let indent = 0;
|
||||
const pad = () => ' '.repeat(Math.max(indent, 0));
|
||||
for (const tok of tokens) {
|
||||
if (tok.startsWith('</')) {
|
||||
indent--;
|
||||
out.push(pad() + tok);
|
||||
} else if (tok.startsWith('<')) {
|
||||
const m = tok.match(/^<([a-zA-Z][a-zA-Z0-9]*)/);
|
||||
const tag = m ? m[1].toLowerCase() : '';
|
||||
out.push(pad() + tok);
|
||||
if (!tok.endsWith('/>') && !voidTags.has(tag)) indent++;
|
||||
} else {
|
||||
const text = tok.trim();
|
||||
if (text) out.push(pad() + text);
|
||||
}
|
||||
}
|
||||
return out.join('\n');
|
||||
}
|
||||
|
||||
formatHtmlBtn.addEventListener('click', () => {
|
||||
const formatted = html_beautify(htmlOutput.textContent, {
|
||||
const raw = htmlOutput.textContent;
|
||||
htmlOutput.textContent = typeof html_beautify === 'function'
|
||||
? html_beautify(raw, {
|
||||
indent_size: 2,
|
||||
wrap_line_length: 80,
|
||||
preserve_newlines: true,
|
||||
max_preserve_newlines: 2
|
||||
});
|
||||
htmlOutput.textContent = formatted;
|
||||
})
|
||||
: formatHtmlFallback(raw);
|
||||
});
|
||||
|
||||
exampleSelect.addEventListener('change', () => {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue