From 54e01c7666c3db901689f95de9cca0ea3473ee7b Mon Sep 17 00:00:00 2001 From: tyuXX Date: Sun, 8 Nov 2026 00:48:45 +0300 Subject: [PATCH] Update --- README.md | 2 +- index.html | 1 + js/renderer.js | 806 ++++++++++++++++++++++++++++--------------------- js/script.js | 59 ++-- 4 files changed, 502 insertions(+), 366 deletions(-) diff --git a/README.md b/README.md index ff50bbe..f299b39 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ A lightweight, customizable markdown renderer for web applications. MDRender con ```html - + ``` ### 2. Initialize the Renderer diff --git a/index.html b/index.html index a50e028..600428a 100644 --- a/index.html +++ b/index.html @@ -18,6 +18,7 @@
`; - const listItem = `
  • ${checkbox}${content}
  • `; - - if (currentList === null) { - // Start a new list - currentList = indentLevel; - currentIndent = indentLevel; - processedLines.push(`'.repeat(closeLevels)); - currentList = null; - currentIndent = 0; - } - processedLines.push(line); + out.push(lines[i]); + i++; } } - - // Close any remaining open lists - if (currentList !== null) { - const closeLevels = Math.floor(currentIndent / 2) + 1; - processedLines.push(''.repeat(closeLevels)); - } - - return processedLines.join('\n'); + return out.join('\n'); } renderHorizontalRules(text) { return text.replace(this.rules.horizontalRule, '
    '); } + 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 `${content}`; + }); + } + + _isTableDelimiter(line) { + return this.rules.tableDelimiter.test(line); + } + + _isTableRow(line) { + return this.rules.tableRow.test(line); + } + + _splitTableRow(line) { + return line.split(/(? 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('', '', ''); + this._splitTableRow(line).forEach((cell, idx) => { + out.push(`${cell}`); }); + out.push('', '', ''); + } else if (inTable && this._isTableRow(line)) { + out.push(''); + this._splitTableRow(line).forEach((cell, idx) => { + out.push(`${cell}`); + }); + out.push(''); + } else { + if (inTable) { + inTable = false; + out.push('', '
    '); + } + out.push(line); + } + } + if (inTable) out.push('', ''); + 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); - - if (!inTable) { - inTable = true; - newLines.push(''); - newLines.push(''); - newLines.push(''); - cells.forEach((cell, index) => { - const align = alignment[index] ? ` style="text-align: ${alignment[index]}"` : ''; - newLines.push(`${cell.trim()}`); - }); - newLines.push(''); - newLines.push(''); - newLines.push(''); - } else { - newLines.push(''); - cells.forEach((cell, index) => { - const align = alignment[index] ? ` style="text-align: ${alignment[index]}"` : ''; - newLines.push(`${cell.trim()}`); - }); - newLines.push(''); + + 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; } - } else if (inTable) { - inTable = false; - newLines.push(''); - newLines.push('
    '); - newLines.push(line); + } + 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 += `
  • ${task[2]}${children}
  • `; + } else { + html += `
  • ${item.content}${children}
  • `; + } + } + html += ``; + } + 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(`
    ${term}
    ${defs.map(d => `
    ${d}
    `).join('')}
    `); + i = j - 1; } else { - newLines.push(line); + out.push(lines[i]); } } - - if (inTable) { - newLines.push(''); - newLines.push(''); + return out.join('\n'); + } + + renderParagraphs(text) { + return text + .replace(this.rules.paragraph, '

    $1

    ') + .replace(/<\/p>\n

    /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(`${this._escapeHtml(code)}`)); + html = this.renderImages(html); + html = this.renderLinks(html); + html = html.replace(this.rules.boldItalic, '$1'); + html = html.replace(this.rules.boldItalicU, '$1'); + html = html.replace(this.rules.bold, '$1'); + html = html.replace(this.rules.boldU, '$1'); + html = html.replace(this.rules.italic, '$1'); + html = html.replace(this.rules.italicU, '$1'); + html = html.replace(this.rules.strikethrough, '$1'); + html = html.replace(this.rules.highlight, '$1'); + 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 `${text}`; + } + + 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 `${this._escapeAttr(alt)}`; + }); + 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 `${text}`; + }); + } + + renderImages(text) { + return text.replace(this.rules.image, (m, alt, url, title) => { + const titleAttr = title ? ` title="${this._escapeAttr(title)}"` : ''; + return `${this._escapeAttr(alt)}`; + }); + } + + renderFootnoteRefs(text) { + return text.replace(this.rules.footnoteRef, (m, ref) => { + if (this.footnotes.has(ref)) { + const fid = this._fnId(ref); + return `${this._escapeHtml(ref)}`; + } + return m; + }); + } + + renderFootnotesSection() { + let html = '


      '; + for (const [ref, content] of this.footnotes) { + const fid = this._fnId(ref); + html += `
    1. ${this._render(content)}↩
    2. `; } - - return newLines.join('\n'); + return html + '
    '; + } + + renderAbbreviations(text) { + for (const [abbr, def] of this.abbreviations) { + const re = new RegExp(`(?${abbr}`); + } + return text; } renderSuperscript(text) { @@ -380,55 +538,7 @@ class MDRenderer { return text.replace(this.rules.subscript, '$1'); } - renderHighlight(text) { - return text.replace(this.rules.highlight, '$1'); - } - - 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 `${ref}`; - } - return match; - }); - } - - renderFootnotesSection() { - if (this.footnotes.size === 0) return ''; - - let html = '

      '; - for (const [ref, content] of this.footnotes) { - html += ` -
    1. - ${content} - ↩ -
    2. `; - } - html += '
    '; - 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, '
    $1
    $2
    '); - } - 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); } -} \ No newline at end of file +} diff --git a/js/script.js b/js/script.js index 4650c94..287dccb 100644 --- a/js/script.js +++ b/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
    @@ -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('') && !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, { - indent_size: 2, - wrap_line_length: 80, - preserve_newlines: true, - max_preserve_newlines: 2 - }); - htmlOutput.textContent = formatted; + 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 + }) + : formatHtmlFallback(raw); }); exampleSelect.addEventListener('change', () => {