| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268 |
- /* eslint-disable no-undef, no-control-regex */
- import fs from 'node:fs'
- import path from 'node:path'
- import { fileURLToPath } from 'node:url'
- const currentDir = path.dirname(fileURLToPath(import.meta.url))
- const escapeHtml = (str = '') =>
- String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
- const slugify = (text = '') => String(text).replace(/[^\w\u4e00-\u9fa5-]/g, '')
- // 行内解析:`code`、**bold**、[text](url),并透传 <span style> 标签
- const inline = (text = '') => {
- const codes = []
- const spans = []
- let out = String(text)
- out = out.replace(/`([^`]+)`/g, (_, c) => {
- codes.push(`<code>${escapeHtml(c)}</code>`)
- return `\u0000C${codes.length - 1}\u0000`
- })
- out = out.replace(/<\/?span[^>]*>/g, (m) => {
- spans.push(m)
- return `\u0000S${spans.length - 1}\u0000`
- })
- out = escapeHtml(out)
- out = out.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>')
- out = out.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
- out = out.replace(/\u0000C(\d+)\u0000/g, (_, i) => codes[+i])
- out = out.replace(/\u0000S(\d+)\u0000/g, (_, i) => spans[+i])
- return out
- }
- const splitRow = (line = '') =>
- line
- .trim()
- .replace(/^\|/, '')
- .replace(/\|$/, '')
- .split('|')
- .map((s) => s.trim())
- const isTableSep = (line = '') => /^\s*\|?[\s:|-]+\|?\s*$/.test(line) && line.includes('-')
- const markdownToHtml = (md = '') => {
- const lines = String(md).replace(/\r\n/g, '\n').split('\n')
- const n = lines.length
- let i = 0
- let html = ''
- let listType = null
- const closeList = () => {
- if (listType) {
- html += `</${listType}>\n`
- listType = null
- }
- }
- while (i < n) {
- const line = lines[i]
- // 代码块
- const fence = line.match(/^```(\w*)\s*$/)
- if (fence) {
- closeList()
- const lang = fence[1]
- i++
- const buf = []
- while (i < n && !/^```\s*$/.test(lines[i])) {
- buf.push(lines[i])
- i++
- }
- i++
- html += `<pre class="code-block" data-lang="${lang}"><code>${escapeHtml(buf.join('\n'))}</code></pre>\n`
- continue
- }
- // 空行
- if (/^\s*$/.test(line)) {
- closeList()
- i++
- continue
- }
- // 分隔线
- if (/^-{3,}\s*$/.test(line)) {
- closeList()
- html += '<hr/>\n'
- i++
- continue
- }
- // 标题
- const heading = line.match(/^(#{1,6})\s+(.*)$/)
- if (heading) {
- closeList()
- const level = heading[1].length
- const text = heading[2].trim()
- html += `<h${level} id="${slugify(text)}">${inline(text)}</h${level}>\n`
- i++
- continue
- }
- // 引用
- if (/^>\s?/.test(line)) {
- closeList()
- const buf = []
- while (i < n && /^>\s?/.test(lines[i])) {
- buf.push(lines[i].replace(/^>\s?/, ''))
- i++
- }
- html += `<blockquote>${markdownToHtml(buf.join('\n'))}</blockquote>\n`
- continue
- }
- // 表格
- if (/^\s*\|/.test(line) && i + 1 < n && isTableSep(lines[i + 1])) {
- closeList()
- const header = splitRow(line)
- i += 2
- const rows = []
- while (i < n && /^\s*\|/.test(lines[i])) {
- rows.push(splitRow(lines[i]))
- i++
- }
- html +=
- '<table><thead><tr>' +
- header.map((c) => `<th>${inline(c)}</th>`).join('') +
- '</tr></thead><tbody>' +
- rows
- .map((r) => '<tr>' + r.map((c) => `<td>${inline(c)}</td>`).join('') + '</tr>')
- .join('') +
- '</tbody></table>\n'
- continue
- }
- // 无序列表
- if (/^\s*[-*]\s+/.test(line)) {
- if (listType !== 'ul') {
- closeList()
- html += '<ul>\n'
- listType = 'ul'
- }
- html += `<li>${inline(line.replace(/^\s*[-*]\s+/, ''))}</li>\n`
- i++
- continue
- }
- // 有序列表
- if (/^\s*\d+\.\s+/.test(line)) {
- if (listType !== 'ol') {
- closeList()
- html += '<ol>\n'
- listType = 'ol'
- }
- html += `<li>${inline(line.replace(/^\s*\d+\.\s+/, ''))}</li>\n`
- i++
- continue
- }
- // 段落
- closeList()
- html += `<p>${inline(line.trim())}</p>\n`
- i++
- }
- closeList()
- return html
- }
- const pageStyle = `
- * { box-sizing: border-box; }
- body { margin: 0; background: #f5f6f8; color: #24292f; font-family: 'HarmonyOS Sans SC', 'PingFang SC', 'Microsoft YaHei', sans-serif; line-height: 1.7; }
- .doc-wrap { max-width: 1000px; margin: 0 auto; padding: 32px 40px 80px; background: #fff; min-height: 100vh; box-shadow: 0 0 12px rgba(0,0,0,.06); }
- h1, h2, h3, h4 { color: #1f2328; line-height: 1.3; }
- h1 { font-size: 28px; border-bottom: 2px solid #1677ff; padding-bottom: 12px; }
- h2 { font-size: 22px; border-bottom: 1px solid #e5e7eb; padding-bottom: 8px; margin-top: 36px; }
- h3 { font-size: 18px; margin-top: 28px; }
- a { color: #1677ff; text-decoration: none; }
- a:hover { text-decoration: underline; }
- code { background: #f0f2f5; color: #d4380d; padding: 2px 6px; border-radius: 4px; font-family: 'HarmonyOS Sans SC', 'PingFang SC', 'Microsoft YaHei', sans-serif; font-size: 13px; }
- .code-block { background: #1e1e1e; color: #d4d4d4; padding: 16px 18px; border-radius: 8px; overflow-x: auto; position: relative; }
- .code-block code { background: transparent; color: #d4d4d4; padding: 0; font-size: 13px; line-height: 1.6; white-space: pre; }
- .code-block[data-lang]::before { content: attr(data-lang); position: absolute; top: 0; right: 0; background: #1677ff; color: #fff; font-size: 11px; padding: 2px 10px; border-radius: 0 8px 0 8px; }
- table { border-collapse: collapse; width: 100%; margin: 16px 0; font-size: 14px; }
- th, td { border: 1px solid #e5e7eb; padding: 8px 12px; text-align: left; vertical-align: top; }
- th { background: #f6f8fa; font-weight: 500; }
- tr:nth-child(even) td { background: #fafbfc; }
- blockquote { margin: 16px 0; padding: 12px 16px; background: #f6f8fa; border-left: 4px solid #1677ff; color: #57606a; }
- blockquote p { margin: 0; }
- hr { border: none; border-top: 1px solid #e5e7eb; margin: 28px 0; }
- ul, ol { padding-left: 24px; }
- li { margin: 4px 0; }
- .doc-tip { max-width: 1000px; margin: 12px auto 0; padding: 0 40px; color: #8c8c8c; font-size: 12px; }
- `
- const renderPage = (title, body) => `<!DOCTYPE html>
- <html lang="zh-CN">
- <head>
- <meta charset="UTF-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <title>${escapeHtml(title)}</title>
- <style>${pageStyle}</style>
- </head>
- <body>
- <div class="doc-tip">sapit-ui 文档预览(由 Markdown 实时渲染)</div>
- <main class="doc-wrap">${body}</main>
- </body>
- </html>`
- /**
- * 文档预览插件
- * @param {object} options
- * @param {string} [options.route='/docs'] 访问路由
- * @param {string} [options.title] 页面标题
- * @param {string} [options.file] Markdown 文件路径(默认取插件同级的 ../docs/*.md)
- */
- export default function docsViewer(options = {}) {
- // 独立 HTML 预览路由(避免与 SPA 内的 /docs 静态页面冲突)
- const route = options.route || '/docs-preview'
- // 应用内静态页面路由(控制台提示用)
- const linkRoute = options.linkRoute || '/docs'
- const title = options.title || 'sapit-ui 基座说明与业务使用文档'
- const file = options.file
- ? path.resolve(process.cwd(), options.file)
- : path.resolve(currentDir, '../docs/sapit-ui-基座说明与业务使用.md')
- const getHtml = () => {
- let md
- try {
- md = fs.readFileSync(file, 'utf-8')
- } catch (e) {
- md = `# 文档未找到\n\n> 文件路径:${file}`
- }
- return renderPage(title, markdownToHtml(md))
- }
- const middleware = (req, res, next) => {
- const url = (req.url || '').split('?')[0]
- if (url !== route && url !== `${route}/`) return next()
- res.setHeader('Content-Type', 'text/html; charset=utf-8')
- res.end(getHtml())
- }
- const logUrl = (server) => {
- try {
- const urls = server.resolvedUrls
- const base =
- (urls && urls.local && urls.local[0]) || `http://localhost:${server.config.server.port}/`
- const root = base.replace(/\/+$/, '')
- console.log(`\n \x1b[32m➜\x1b[0m 文档(应用内): \x1b[36m${root}${linkRoute}\x1b[0m`)
- console.log(` \x1b[32m➜\x1b[0m 文档(独立预览): \x1b[36m${root}${route}\x1b[0m\n`)
- } catch (e) {
- // ignore
- }
- }
- return {
- name: 'sapit-docs-viewer',
- configureServer(server) {
- server.middlewares.use(middleware)
- if (server.httpServer) {
- if (server.httpServer.listening) logUrl(server)
- else server.httpServer.once('listening', () => logUrl(server))
- }
- },
- configurePreviewServer(server) {
- server.middlewares.use(middleware)
- }
- }
- }
|