154 lines
5.2 KiB
JavaScript
154 lines
5.2 KiB
JavaScript
/**
|
|
* a2host - Lightweight Markdown Parser (ES Module)
|
|
* Renderizador de Markdown a HTML semántico y seguro, optimizado para especificaciones técnicas (IEEE, OpenAPI, Tablas).
|
|
*/
|
|
|
|
export function renderMarkdown(markdownText) {
|
|
if (!markdownText) return '';
|
|
|
|
// Escapar HTML no deseado primero
|
|
let text = markdownText
|
|
.replace(/&/g, '&')
|
|
.replace(/</g, '<')
|
|
.replace(/>/g, '>');
|
|
|
|
// Restaurar saltos de línea consistentes
|
|
text = text.replace(/\r\n/g, '\n');
|
|
|
|
// Procesar bloques de código con triple backtick ```lang ... ```
|
|
text = text.replace(/```([a-zA-Z0-9_-]*)\n([\s\S]*?)```/g, (match, lang, code) => {
|
|
const language = lang || 'text';
|
|
const cleanCode = code.trim();
|
|
const encoded = encodeURIComponent(cleanCode);
|
|
return `<div class="code-block-wrapper">
|
|
<div class="code-block-header">
|
|
<span class="code-lang-tag">${escapeText(language)}</span>
|
|
<button type="button" class="btn-copy-code" data-code="${encoded}" title="Copiar código">
|
|
<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2"><rect x="5" y="5" width="8" height="8" rx="1.5"/><path d="M3 11V3a1.5 1.5 0 0 1 1.5-1.5H11"/></svg>
|
|
<span>Copiar</span>
|
|
</button>
|
|
</div>
|
|
<pre class="code-pre"><code class="language-${language}">${cleanCode}</code></pre>
|
|
</div>`;
|
|
});
|
|
|
|
// Procesar Tablas Markdown (| Col 1 | Col 2 | ...)
|
|
text = text.replace(/((?:^|\n)\|[^\n]+\|\n\|(?:\s*[:-]+[-| :]*\s*)\|\n(?:\|[^\n]+\|\n?)+)/g, (match) => {
|
|
const lines = match.trim().split('\n');
|
|
if (lines.length < 2) return match;
|
|
|
|
const parseRow = (line) => {
|
|
return line
|
|
.replace(/^\|/, '')
|
|
.replace(/\|$/, '')
|
|
.split('|')
|
|
.map(cell => cell.trim());
|
|
};
|
|
|
|
const headerCells = parseRow(lines[0]);
|
|
// líneas de delimitadores como |:---|:---:|---:|
|
|
const alignLine = parseRow(lines[1]);
|
|
const aligns = alignLine.map(a => {
|
|
const start = a.startsWith(':');
|
|
const end = a.endsWith(':');
|
|
if (start && end) return 'center';
|
|
if (end) return 'right';
|
|
return 'left';
|
|
});
|
|
|
|
const bodyLines = lines.slice(2);
|
|
|
|
let html = `<div class="table-responsive"><table class="docs-table"><thead><tr>`;
|
|
headerCells.forEach((th, idx) => {
|
|
const align = aligns[idx] || 'left';
|
|
html += `<th style="text-align: ${align}">${formatInline(th)}</th>`;
|
|
});
|
|
html += `</tr></thead><tbody>`;
|
|
|
|
bodyLines.forEach(row => {
|
|
if (!row.trim()) return;
|
|
const cells = parseRow(row);
|
|
html += `<tr>`;
|
|
cells.forEach((td, idx) => {
|
|
const align = aligns[idx] || 'left';
|
|
html += `<td style="text-align: ${align}">${formatInline(td)}</td>`;
|
|
});
|
|
html += `</tr>`;
|
|
});
|
|
|
|
html += `</tbody></table></div>`;
|
|
return html;
|
|
});
|
|
|
|
// Procesar Encabezados (# H1 a ###### H6)
|
|
text = text.replace(/^(#{1,6})\s+(.+)$/gm, (match, hashes, content) => {
|
|
const level = hashes.length;
|
|
const cleanContent = formatInline(content.trim());
|
|
const id = content
|
|
.toLowerCase()
|
|
.replace(/[^\w\s-]/g, '')
|
|
.replace(/\s+/g, '-');
|
|
return `<h${level} id="${id}" class="docs-heading docs-h${level}">${cleanContent}</h${level}>`;
|
|
});
|
|
|
|
// Blockquotes (> Cita)
|
|
text = text.replace(/^(?:>|>)\s*(.+)$/gm, (match, content) => {
|
|
return `<blockquote class="docs-blockquote">${formatInline(content.trim())}</blockquote>`;
|
|
});
|
|
|
|
// Reglas horizontales (--- o ***)
|
|
text = text.replace(/^(?:---|\*\*\*|___)\s*$/gm, '<hr class="docs-divider" />');
|
|
|
|
// Listas ordenadas e inordenadas
|
|
// Convertir listas no ordenadas (- o *)
|
|
text = text.replace(/^(?:[-*+])\s+(.+)$/gm, '<li class="docs-li-bullet">$1</li>');
|
|
text = text.replace(/((?:<li class="docs-li-bullet">.*<\/li>\s*)+)/g, '<ul class="docs-ul">$1</ul>');
|
|
|
|
// Convertir listas ordenadas (1. 2. 3.)
|
|
text = text.replace(/^(\d+)\.\s+(.+)$/gm, '<li class="docs-li-num">$2</li>');
|
|
text = text.replace(/((?:<li class="docs-li-num">.*<\/li>\s*)+)/g, '<ol class="docs-ol">$1</ol>');
|
|
|
|
// Párrafos regulares (líneas que no están ya envueltas en tags de bloque)
|
|
const paragraphs = text.split(/\n{2,}/);
|
|
text = paragraphs.map(p => {
|
|
p = p.trim();
|
|
if (!p) return '';
|
|
if (
|
|
p.startsWith('<h') ||
|
|
p.startsWith('<div') ||
|
|
p.startsWith('<table') ||
|
|
p.startsWith('<blockquote') ||
|
|
p.startsWith('<ul') ||
|
|
p.startsWith('<ol') ||
|
|
p.startsWith('<hr')
|
|
) {
|
|
return p;
|
|
}
|
|
return `<p class="docs-paragraph">${formatInline(p)}</p>`;
|
|
}).join('\n\n');
|
|
|
|
return text;
|
|
}
|
|
|
|
/**
|
|
* Formateo en línea (Inline formatting): negrita, cursiva, links, inline code, badges
|
|
*/
|
|
function formatInline(str) {
|
|
if (!str) return '';
|
|
|
|
return str
|
|
// Código en línea `code`
|
|
.replace(/`([^`]+)`/g, '<code class="docs-inline-code">$1</code>')
|
|
// Negrita **text**
|
|
.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
|
|
// Cursiva *text*
|
|
.replace(/\*([^*]+)\*/g, '<em>$1</em>')
|
|
// Enlaces [label](url)
|
|
.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" class="docs-link" target="_blank" rel="noopener noreferrer">$1</a>');
|
|
}
|
|
|
|
function escapeText(str) {
|
|
if (!str) return '';
|
|
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
}
|