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
|
```html
|
||||||
<link rel="stylesheet" href="https://tyuxx.github.io/MDRender/css/markdown.css">
|
<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
|
### 2. Initialize the Renderer
|
||||||
|
|
|
||||||
|
|
@ -18,6 +18,7 @@
|
||||||
<div class="header-controls">
|
<div class="header-controls">
|
||||||
<select id="example-select">
|
<select id="example-select">
|
||||||
<option value="">Choose an example...</option>
|
<option value="">Choose an example...</option>
|
||||||
|
<option value="default">Feature Showcase</option>
|
||||||
<option value="basic">Basic Markdown</option>
|
<option value="basic">Basic Markdown</option>
|
||||||
<option value="advanced">Advanced Features</option>
|
<option value="advanced">Advanced Features</option>
|
||||||
<option value="tables">Tables Example</option>
|
<option value="tables">Tables Example</option>
|
||||||
|
|
|
||||||
784
js/renderer.js
784
js/renderer.js
|
|
@ -1,375 +1,533 @@
|
||||||
class MDRenderer {
|
class MDRenderer {
|
||||||
constructor() {
|
constructor() {
|
||||||
this.rules = {
|
this.rules = {
|
||||||
heading: /^(#{1,6})\s+(.+)$/gm,
|
heading: /^[ \t]{0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/gm,
|
||||||
paragraph: /^(?!#|>|\s*\d+\.|```|\s*-\s|\s*\*\s|\||\s*\[\s*[x\s]\s*\]|\^\[\d+\]|\s*={3,}|\s*-{3,})(.+)$/gm,
|
paragraph: /^(?!<|@@MDRENDER_|[ \t]{0,3}(?:#{1,6}[ \t]|[-*+][ \t]|\d{1,9}[.)][ \t])|[ \t]*(?:[-*_][ \t]*){3,}[ \t]*$|[ \t]*={3,}[ \t]*$)(.*\S.*)$/gm,
|
||||||
bold: /\*\*(.+?)\*\*/g,
|
boldItalic: /\*\*\*([^*]+?)\*\*\*/g,
|
||||||
italic: /\*(.+?)\*/g,
|
boldItalicU: /___([^_]+?)___/g,
|
||||||
strikethrough: /~~(.+?)~~/g,
|
bold: /\*\*([^*]+?)\*\*/g,
|
||||||
code: /`(.+?)`/g,
|
boldU: /__([^_]+?)__/g,
|
||||||
codeblock: /```(\w*)\n([\s\S]*?)```/g,
|
italic: /\*([^*\n]+?)\*/g,
|
||||||
link: /\[(.+?)\]\((.+?)(?:\s+"(.+?)")?\)/g,
|
italicU: /(?<!\w)_([^_\n]+?)_(?!\w)/g,
|
||||||
image: /!\[(.+?)\]\((.+?)(?:\s+"(.+?)")?\)/g,
|
strikethrough: /~~([^~\n]+?)~~/g,
|
||||||
list: /^(\s*)[*-]\s(.+)$/gm,
|
highlight: /==([^=\n]+?)==/g,
|
||||||
orderedList: /^(\s*)\d+\.\s(.+)$/gm,
|
superscript: /\^([^\n^]+?)\^/g,
|
||||||
blockquote: /^((?:\s*>+\s*)+)(.+)$/gm,
|
subscript: /~([^~\n]+?)~/g,
|
||||||
horizontalRule: /^([-*_])\1{2,}$/gm,
|
inlineCode: /`([^`\n]+)`/g,
|
||||||
table: /^\|(.+)\|$/gm,
|
link: /\[([^\]\n]+)\]\((.+?)(?:\s+"([^"]*)")?\)/g,
|
||||||
tableDelimiter: /^\|(?:[-:]+[-| :]*)\|$/gm,
|
image: /!\[([^\]\n]+)\]\((.+?)(?:\s+"([^"]*)")?\)/g,
|
||||||
taskList: /^(\s*)-\s+\[([ x])\]\s+(.+)$/gm,
|
codeblock: /^[ \t]*```([^\n`]*)\n([\s\S]*?)^[ \t]*```[ \t]*$/gm,
|
||||||
superscript: /\^(.+?)\^/g,
|
horizontalRule: /^[ \t]{0,3}([-*_])(?:[ \t]*\1){2,}[ \t]*$/gm,
|
||||||
subscript: /~(.+?)~/g,
|
tableRow: /^\|.*\|[ \t]*$/,
|
||||||
highlight: /==(.+?)==/g,
|
tableDelimiter: /^\|(?:[ \t]*:?-+:?[ \t]*\|)+$/,
|
||||||
footnoteRef: /\[\^(\d+)\]/g,
|
unorderedItem: /^([ \t]*)[-*+][ \t]+(.*)$/,
|
||||||
footnote: /^\[\^(\d+)\]:\s(.+)$/gm,
|
orderedItem: /^([ \t]*)(\d{1,9})\.[ \t]+(.*)$/,
|
||||||
abbreviation: /\*\[(.+?)\]:\s(.+)$/gm,
|
footnoteRef: /\[\^([^\]\n]+)\]/g,
|
||||||
definition: /^:\s(.+?)\n\s{2,}(.+)$/gm,
|
escapes: /\\([!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~])/g,
|
||||||
emoji: /:([\w+-]+):/g,
|
refLink: /\[([^\]\n]+)\]\[([^\]\n]*)\]/g,
|
||||||
|
refShortcut: /\[([^\]\n]+)\](?![\(\[])/g,
|
||||||
|
refImage: /!\[([^\]\n]+)\]\[([^\]\n]*)\]/g,
|
||||||
|
emoji: /:([a-zA-Z0-9_+-]+):/g,
|
||||||
};
|
};
|
||||||
|
|
||||||
this.footnotes = new Map();
|
this.footnotes = new Map();
|
||||||
this.abbreviations = new Map();
|
this.abbreviations = new Map();
|
||||||
|
this.references = new Map();
|
||||||
|
this._stash = [];
|
||||||
|
this._nonce = '';
|
||||||
|
this._headingIds = {};
|
||||||
this.emojis = {
|
this.emojis = {
|
||||||
'smile': '😊',
|
'smile': '😊',
|
||||||
'laugh': '😄',
|
'laugh': '😄',
|
||||||
|
'joy': '😂',
|
||||||
'wink': '😉',
|
'wink': '😉',
|
||||||
'heart': '❤️',
|
'heart': '❤️',
|
||||||
|
'heart_eyes': '😍',
|
||||||
|
'thinking': '🤔',
|
||||||
|
'clap': '👏',
|
||||||
|
'wave': '👋',
|
||||||
|
'eyes': '👀',
|
||||||
'check': '✅',
|
'check': '✅',
|
||||||
'x': '❌',
|
'x': '❌',
|
||||||
'warning': '⚠️',
|
'warning': '⚠️',
|
||||||
'info': 'ℹ️',
|
'info': 'ℹ️',
|
||||||
// Add more emojis as needed
|
'thumbsup': '👍',
|
||||||
|
'thumbsdown': '👎',
|
||||||
|
'rocket': '🚀',
|
||||||
|
'star': '⭐',
|
||||||
|
'fire': '🔥',
|
||||||
|
'sunny': '☀️',
|
||||||
|
'sun': '☀️',
|
||||||
|
'moon': '🌙',
|
||||||
|
'cloud': '☁️',
|
||||||
|
'coffee': '☕',
|
||||||
|
'pizza': '🍕',
|
||||||
|
'cake': '🍰',
|
||||||
|
'apple': '🍎',
|
||||||
|
'tada': '🎉',
|
||||||
|
'bug': '🐛',
|
||||||
|
'zap': '⚡',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
render(markdown) {
|
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
|
let html = this._render(String(markdown ?? ''));
|
||||||
this.footnotes.clear();
|
|
||||||
this.abbreviations.clear();
|
|
||||||
|
|
||||||
// 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) {
|
if (this.footnotes.size > 0) {
|
||||||
html += this.renderFootnotesSection();
|
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>`;
|
return `<div class="mdrender">${html}</div>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
renderHeadings(text) {
|
_render(markdown) {
|
||||||
return text.replace(this.rules.heading, (match, level, content) => {
|
let html = markdown.replace(/\r\n?/g, '\n');
|
||||||
const headingLevel = level.length;
|
|
||||||
const id = content.toLowerCase().replace(/[^\w]+/g, '-');
|
// Protect raw HTML blocks that must not be touched by inline rules
|
||||||
return `<h${headingLevel} id="${id}">${content}</h${headingLevel}>`;
|
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) {
|
_stashHtml(html) {
|
||||||
return text.replace(this.rules.paragraph, (match, content) => {
|
const token = `@@MDRENDER_${this._nonce}_${this._stash.length}@@`;
|
||||||
return `<p>${content}</p>`;
|
this._stash.push(html);
|
||||||
});
|
return token;
|
||||||
}
|
}
|
||||||
|
|
||||||
renderBold(text) {
|
_escapeHtml(s) {
|
||||||
return text.replace(this.rules.bold, '<strong>$1</strong>');
|
return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||||
}
|
}
|
||||||
|
|
||||||
renderItalic(text) {
|
_escapeAttr(s) {
|
||||||
return text.replace(this.rules.italic, '<em>$1</em>');
|
return this._escapeHtml(s).replace(/"/g, '"');
|
||||||
}
|
}
|
||||||
|
|
||||||
renderStrikethrough(text) {
|
_escapeRegExp(s) {
|
||||||
return text.replace(this.rules.strikethrough, '<del>$1</del>');
|
return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||||
}
|
}
|
||||||
|
|
||||||
renderInlineCode(text) {
|
_indentWidth(indent) {
|
||||||
return text.replace(this.rules.code, '<code>$1</code>');
|
return indent.replace(/\t/g, ' ').length;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
_fnId(ref) {
|
||||||
|
return ref.replace(/[^\w-]+/g, '-').replace(/^-+|-+$/g, '') || 'fn';
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Block-level rendering ----------
|
||||||
|
|
||||||
renderCodeBlocks(text) {
|
renderCodeBlocks(text) {
|
||||||
return text.replace(this.rules.codeblock, (match, language, code) => {
|
return text.replace(this.rules.codeblock, (m, lang, code) => {
|
||||||
return `<pre><code class="language-${language}">${code.trim()}</code></pre>`;
|
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) {
|
collectFootnotes(text) {
|
||||||
return text.replace(this.rules.link, (match, text, url, title) => {
|
const lines = text.split('\n');
|
||||||
const titleAttr = title ? ` title="${title}"` : '';
|
const out = [];
|
||||||
return `<a href="${url}"${titleAttr}>${text}</a>`;
|
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) {
|
collectReferences(text) {
|
||||||
return text.replace(this.rules.image, (match, alt, url, title) => {
|
return text.replace(/^[ \t]{0,3}\[([^\]\n]+)\]:[ \t]*(\S+)(?:[ \t]+["']([^"']*)["'])?[ \t]*$/gm,
|
||||||
const titleAttr = title ? ` title="${title}"` : '';
|
(m, label, url, title) => {
|
||||||
return `<img src="${url}" alt="${alt}"${titleAttr}>`;
|
this.references.set(label.toLowerCase(), { url, title });
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
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>`);
|
|
||||||
return '';
|
return '';
|
||||||
});
|
});
|
||||||
|
|
||||||
while (lastIndentLevel > 0) {
|
|
||||||
items.push('</ul>');
|
|
||||||
lastIndentLevel--;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return html + items.join('');
|
collectAbbreviations(text) {
|
||||||
}
|
return text.replace(/^[ \t]{0,3}\*\[([^\]\n]+)\]:[ \t]*(.+?)[ \t]*$/gm, (m, abbr, def) => {
|
||||||
|
this.abbreviations.set(abbr, def);
|
||||||
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>`);
|
|
||||||
return '';
|
return '';
|
||||||
});
|
});
|
||||||
|
|
||||||
while (lastIndentLevel > 0) {
|
|
||||||
items.push('</ol>');
|
|
||||||
lastIndentLevel--;
|
|
||||||
}
|
|
||||||
|
|
||||||
return html + items.join('');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
renderBlockquotes(text) {
|
renderBlockquotes(text) {
|
||||||
const lines = text.split('\n');
|
const lines = text.split('\n');
|
||||||
const result = [];
|
const out = [];
|
||||||
let inBlockquote = false;
|
let i = 0;
|
||||||
let currentContent = [];
|
while (i < lines.length) {
|
||||||
let currentLevel = 0;
|
if (/^[ \t]{0,3}>/.test(lines[i])) {
|
||||||
|
const quoteLines = [];
|
||||||
function processBlockquote(content, level) {
|
while (i < lines.length && /^[ \t]{0,3}>/.test(lines[i])) {
|
||||||
if (content.length === 0) return '';
|
quoteLines.push(lines[i].replace(/^[ \t]{0,3}>[ \t]?/, ''));
|
||||||
const innerContent = content.join('\n').trim();
|
i++;
|
||||||
let html = innerContent;
|
|
||||||
for (let i = 0; i < level; i++) {
|
|
||||||
html = `<blockquote>${html}</blockquote>`;
|
|
||||||
}
|
}
|
||||||
return html;
|
const inner = this._render(quoteLines.join('\n'));
|
||||||
}
|
out.push(this._stashHtml(`<blockquote>\n${inner}\n</blockquote>`));
|
||||||
|
|
||||||
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());
|
|
||||||
} else {
|
} else {
|
||||||
if (inBlockquote) {
|
out.push(lines[i]);
|
||||||
// End of blockquote
|
i++;
|
||||||
result.push(processBlockquote(currentContent, currentLevel));
|
|
||||||
currentContent = [];
|
|
||||||
inBlockquote = false;
|
|
||||||
}
|
|
||||||
result.push(line);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
return out.join('\n');
|
||||||
|
|
||||||
// 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');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
renderHorizontalRules(text) {
|
renderHorizontalRules(text) {
|
||||||
return text.replace(this.rules.horizontalRule, '<hr>');
|
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) {
|
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 inTable = false;
|
||||||
let alignment = [];
|
let currentAlign = [];
|
||||||
|
|
||||||
// Split into lines
|
|
||||||
const lines = html.split('\n');
|
|
||||||
const newLines = [];
|
|
||||||
|
|
||||||
for (let i = 0; i < lines.length; i++) {
|
for (let i = 0; i < lines.length; i++) {
|
||||||
const line = lines[i];
|
const line = lines[i];
|
||||||
|
if (this._isTableDelimiter(line)) continue;
|
||||||
if (this.rules.tableDelimiter.test(line)) {
|
if (alignments.has(i)) {
|
||||||
// Get alignment info
|
inTable = true;
|
||||||
alignment = line.split('|').slice(1, -1).map(cell => {
|
currentAlign = alignments.get(i);
|
||||||
cell = cell.trim();
|
out.push('<table>', '<thead>', '<tr>');
|
||||||
if (cell.startsWith(':') && cell.endsWith(':')) return 'center';
|
this._splitTableRow(line).forEach((cell, idx) => {
|
||||||
if (cell.endsWith(':')) return 'right';
|
out.push(`<th${this._alignAttr(currentAlign, idx)}>${cell}</th>`);
|
||||||
return 'left';
|
|
||||||
});
|
});
|
||||||
|
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;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.rules.table.test(line)) {
|
const type = it.ordered ? 'ol' : 'ul';
|
||||||
const cells = line.split('|').slice(1, -1);
|
|
||||||
|
|
||||||
if (!inTable) {
|
// Scan direct members of this list run (for task-list detection)
|
||||||
inTable = true;
|
let memberCount = 0;
|
||||||
newLines.push('<table>');
|
let allTask = type === 'ul';
|
||||||
newLines.push('<thead>');
|
for (let j = i; j < items.length; j++) {
|
||||||
newLines.push('<tr>');
|
const jt = items[j];
|
||||||
cells.forEach((cell, index) => {
|
if (jt.indent < indent) break;
|
||||||
const align = alignment[index] ? ` style="text-align: ${alignment[index]}"` : '';
|
if (jt.indent === indent && (jt.ordered ? 'ol' : 'ul') !== type) break;
|
||||||
newLines.push(`<th${align}>${cell.trim()}</th>`);
|
if (jt.indent === indent) {
|
||||||
});
|
memberCount++;
|
||||||
newLines.push('</tr>');
|
if (!this._isTaskItem(jt.content)) allTask = false;
|
||||||
newLines.push('</thead>');
|
}
|
||||||
newLines.push('<tbody>');
|
}
|
||||||
|
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 {
|
} else {
|
||||||
newLines.push('<tr>');
|
html += `<li>${item.content}${children}</li>`;
|
||||||
cells.forEach((cell, index) => {
|
|
||||||
const align = alignment[index] ? ` style="text-align: ${alignment[index]}"` : '';
|
|
||||||
newLines.push(`<td${align}>${cell.trim()}</td>`);
|
|
||||||
});
|
|
||||||
newLines.push('</tr>');
|
|
||||||
}
|
}
|
||||||
} else if (inTable) {
|
}
|
||||||
inTable = false;
|
html += `</${type}>`;
|
||||||
newLines.push('</tbody>');
|
}
|
||||||
newLines.push('</table>');
|
return { html, next: i };
|
||||||
newLines.push(line);
|
}
|
||||||
|
|
||||||
|
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 {
|
} 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) {
|
renderDefinitions(text) {
|
||||||
newLines.push('</tbody>');
|
const defRe = /^[ \t]{0,3}:[ \t]+(.*)$/;
|
||||||
newLines.push('</table>');
|
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) {
|
renderSuperscript(text) {
|
||||||
|
|
@ -380,55 +538,7 @@ class MDRenderer {
|
||||||
return text.replace(this.rules.subscript, '<sub>$1</sub>');
|
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) {
|
renderEmojis(text) {
|
||||||
return text.replace(this.rules.emoji, (match, name) => {
|
return text.replace(this.rules.emoji, (m, name) => this.emojis[name.toLowerCase()] || m);
|
||||||
return this.emojis[name] || match;
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
51
js/script.js
51
js/script.js
|
|
@ -327,16 +327,16 @@ ___
|
||||||
:coffee: :pizza: :cake: :apple:
|
:coffee: :pizza: :cake: :apple:
|
||||||
|
|
||||||
## 12. Special Characters & Escaping
|
## 12. Special Characters & Escaping
|
||||||
\* Escaped asterisk
|
\\* Escaped asterisk
|
||||||
\_ Escaped underscore
|
\\_ Escaped underscore
|
||||||
\# Escaped hash
|
\\# Escaped hash
|
||||||
\[ Escaped bracket
|
\\[ Escaped bracket
|
||||||
\] Escaped bracket
|
\\] Escaped bracket
|
||||||
\` Escaped backtick
|
\\\` Escaped backtick
|
||||||
\( Escaped parenthesis
|
\\( Escaped parenthesis
|
||||||
\) Escaped parenthesis
|
\\) Escaped parenthesis
|
||||||
\~ Escaped tilde
|
\\~ Escaped tilde
|
||||||
\: Escaped colon
|
\\: Escaped colon
|
||||||
|
|
||||||
## 13. HTML Support
|
## 13. HTML Support
|
||||||
<div style="color: blue;">
|
<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';
|
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', () => {
|
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,
|
indent_size: 2,
|
||||||
wrap_line_length: 80,
|
wrap_line_length: 80,
|
||||||
preserve_newlines: true,
|
preserve_newlines: true,
|
||||||
max_preserve_newlines: 2
|
max_preserve_newlines: 2
|
||||||
});
|
})
|
||||||
htmlOutput.textContent = formatted;
|
: formatHtmlFallback(raw);
|
||||||
});
|
});
|
||||||
|
|
||||||
exampleSelect.addEventListener('change', () => {
|
exampleSelect.addEventListener('change', () => {
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue