packServer/backend/app/lib/markdown.js
liufumingren 78cee0fe1a feat(doc): 首页登录分流 + 文档站(简易 CMS / 静态 HTML / sitemap)
- 首页:`/` 未登录原地显示登录页(不再跳 /login),已登录直接进 `/dashboard`;
  看板路由由 `/` 迁到 `/dashboard`,侧边栏「首页」与无权限回跳同步;
  桌面端「工具 → 打开配置页」的 `/?token=` 免登录仍然可用
- 文档站:`/doc/**` 由后端整站生成静态 HTML(顶部分类 tab 全局切换、左侧栏目 → 内容页、
  右侧本页目录);`/sitemap.txt` 新链接追加到末尾,下架 / 删除的会被清理
- 平台管理 · 文档管理(`/admin/doc`):分类 / 栏目 / 内容页(Markdown)简易 CMS,
  内容页有编辑表单与列表,保存后自动重生成目录与静态页面
- 登录页右下角、顶栏(登录后)、看板右上角新增进入文档站的链接
- 部署:nginx 模板为 `/doc`、`/doc/`、`/sitemap.txt` 增加反代(否则会落到 SPA 回退);
  Vite dev server 增加同名代理;`middleware/frontend.js` 排除这些路径
- 登录页插画改为内联 SVG(沿用工作区已有的未提交改动)
- 测试:新增 Markdown 渲染单测;后端 218 个用例通过,前端 typecheck / build 通过

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-07 20:33:46 +08:00

176 lines
5.2 KiB
JavaScript
Raw Permalink 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`;
});
out = out.replace(/\[([^\]]*)\]\(([^)\s]+)\)/g, (match, label, href) => {
const target = safeHref(href);
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(/\s+/g, ' ')
.trim();
if (text.length <= maxLength) return text;
return `${text.slice(0, maxLength)}…`;
}
module.exports = { render, plainText, escapeHtml };