packServer/backend/app/lib/markdown.js
2026-11-21 16:14:42 +08:00

185 lines
5.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

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

'use strict';
/**
* 极简 Markdown → HTML(文档站专用)
*
* 只支持写文档够用的子集:标题 / 段落 / 列表 / 引用 / 代码块 / 行内代码 / 粗体 / 斜体 / 删除线 / 链接 / 图片 / 分割线。
* **先转义再拼 HTML**:文档站是公开页面,后台输入的内容一律当纯文本处理,避免把 `<script>` 原样吐出去。
*
* `render()` 同时返回文章内目录(`toc`),供页面右侧的「本页目录」使用。
*/
const ESCAPE_MAP = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
'\'': '&#39;',
};
function escapeHtml(value) {
return String(value === undefined || value === null ? '' : value)
.replace(/[&<>"']/g, ch => ESCAPE_MAP[ch]);
}
/** 只要 http(s) / mailto / 站内绝对路径 / 锚点 / 相对路径,拒绝 javascript: 之类的协议 */
function safeHref(href) {
const raw = String(href || '').trim();
if (!raw) return '';
if (/^(https?:\/\/|mailto:)/i.test(raw)) return raw;
if (/^[/#]/.test(raw)) return raw;
// 相对路径里不能出现协议(`//evil.com` 或 `javascript:`)
if (/^[a-z][a-z0-9+.-]*:/i.test(raw)) return '';
if (raw.startsWith('//')) return '';
return raw;
}
/** 行内样式:先处理代码片段、图片与链接,再处理强调(避免把链接文字里的 * 吃掉) */
function inline(text) {
const codeSpans = [];
let out = escapeHtml(text).replace(/`([^`]+)`/g, (match, code) => {
codeSpans.push(`<code>${code}</code>`);
return `\u0000${codeSpans.length - 1}\u0000`;
});
// 图片:必须写在链接之前,否则 `![alt](src)` 会先被链接规则吃成 `!<a>…</a>`
// 此时整段已被 escapeHtml 过,URL 里的 & 是 &amp;,还原后再统一按属性转义,避免 &amp;amp;
out = out.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g, (match, alt, src) => {
const target = safeHref(src.replace(/&amp;/g, '&'));
if (!target) return alt;
return `<img src="${escapeHtml(target)}" alt="${alt}" loading="lazy">`;
});
out = out.replace(/\[([^\]]*)\]\(([^)\s]+)\)/g, (match, label, href) => {
const target = safeHref(href.replace(/&amp;/g, '&'));
if (!target) return label;
const external = /^https?:\/\//i.test(target);
return `<a href="${escapeHtml(target)}"${external ? ' target="_blank" rel="noopener"' : ''}>${label}</a>`;
});
out = out
.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
.replace(/~~([^~]+)~~/g, '<del>$1</del>')
.replace(/(^|[^*])\*([^*\n]+)\*/g, '$1<em>$2</em>');
return out.replace(/\u0000(\d+)\u0000/g, (match, index) => codeSpans[Number(index)] || '');
}
/**
* @param {string} markdown 原文
* @returns {{ html: string, toc: Array<{ id: string, text: string, level: number }> }}
*/
function render(markdown) {
const lines = String(markdown || '').replace(/\r\n?/g, '\n').split('\n');
const blocks = [];
const toc = [];
let headingIndex = 0;
let paragraph = [];
const flushParagraph = () => {
if (!paragraph.length) return;
const text = paragraph.join('\n').trim();
paragraph = [];
if (!text) return;
blocks.push(`<p>${inline(text).replace(/\n/g, '<br>')}</p>`);
};
let i = 0;
while (i < lines.length) {
const line = lines[i];
// 代码块:```lang ... ```
const fence = /^```\s*([\w+-]*)\s*$/.exec(line);
if (fence) {
flushParagraph();
const lang = fence[1];
const code = [];
i += 1;
while (i < lines.length && !/^```\s*$/.test(lines[i])) {
code.push(lines[i]);
i += 1;
}
i += 1; // 吃掉结尾的 ```
const cls = lang ? ` class="language-${escapeHtml(lang)}"` : '';
blocks.push(`<pre><code${cls}>${escapeHtml(code.join('\n'))}</code></pre>`);
continue;
}
if (!line.trim()) {
flushParagraph();
i += 1;
continue;
}
// 标题
const heading = /^(#{1,6})\s+(.*)$/.exec(line);
if (heading) {
flushParagraph();
const level = heading[1].length;
const text = heading[2].trim();
headingIndex += 1;
const id = `sec-${headingIndex}`;
toc.push({ id, text: text.replace(/[*`~]/g, ''), level });
blocks.push(`<h${level} id="${id}">${inline(text)}</h${level}>`);
i += 1;
continue;
}
// 分割线
if (/^\s*(---+|\*\*\*+|___+)\s*$/.test(line)) {
flushParagraph();
blocks.push('<hr>');
i += 1;
continue;
}
// 引用(整段连续 > 行)
if (/^\s*>\s?/.test(line)) {
flushParagraph();
const quote = [];
while (i < lines.length && /^\s*>\s?/.test(lines[i])) {
quote.push(lines[i].replace(/^\s*>\s?/, ''));
i += 1;
}
blocks.push(`<blockquote>${render(quote.join('\n')).html}</blockquote>`);
continue;
}
// 列表(有序 / 无序;只支持一层)
if (/^\s*(?:[-*+]|\d+\.)\s+/.test(line)) {
flushParagraph();
const ordered = /^\s*\d+\.\s+/.test(line);
const items = [];
while (i < lines.length) {
const item = /^\s*(?:[-*+]|\d+\.)\s+(.*)$/.exec(lines[i]);
if (!item) break;
items.push(item[1]);
i += 1;
}
const tag = ordered ? 'ol' : 'ul';
blocks.push(`<${tag}>${items.map(text => `<li>${inline(text)}</li>`).join('')}</${tag}>`);
continue;
}
paragraph.push(line);
i += 1;
}
flushParagraph();
return { html: blocks.join('\n'), toc };
}
/** 纯文本摘要:去掉 Markdown 记号,给列表 / meta description 用 */
function plainText(markdown, maxLength = 120) {
const text = String(markdown || '')
.replace(/```[\s\S]*?```/g, ' ')
.replace(/!\[[^\]]*\]\([^)]*\)/g, ' ')
.replace(/[#>*`~\-]/g, ' ')
.replace(/\s+/g, ' ')
.trim();
if (text.length <= maxLength) return text;
return `${text.slice(0, maxLength)}…`;
}
module.exports = { render, plainText, escapeHtml };