docs-viewer.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. /* eslint-disable no-undef, no-control-regex */
  2. import fs from 'node:fs'
  3. import path from 'node:path'
  4. import { fileURLToPath } from 'node:url'
  5. const currentDir = path.dirname(fileURLToPath(import.meta.url))
  6. const escapeHtml = (str = '') =>
  7. String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
  8. const slugify = (text = '') => String(text).replace(/[^\w\u4e00-\u9fa5-]/g, '')
  9. // 行内解析:`code`、**bold**、[text](url),并透传 <span style> 标签
  10. const inline = (text = '') => {
  11. const codes = []
  12. const spans = []
  13. let out = String(text)
  14. out = out.replace(/`([^`]+)`/g, (_, c) => {
  15. codes.push(`<code>${escapeHtml(c)}</code>`)
  16. return `\u0000C${codes.length - 1}\u0000`
  17. })
  18. out = out.replace(/<\/?span[^>]*>/g, (m) => {
  19. spans.push(m)
  20. return `\u0000S${spans.length - 1}\u0000`
  21. })
  22. out = escapeHtml(out)
  23. out = out.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>')
  24. out = out.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
  25. out = out.replace(/\u0000C(\d+)\u0000/g, (_, i) => codes[+i])
  26. out = out.replace(/\u0000S(\d+)\u0000/g, (_, i) => spans[+i])
  27. return out
  28. }
  29. const splitRow = (line = '') =>
  30. line.trim().replace(/^\|/, '').replace(/\|$/, '').split('|').map((s) => s.trim())
  31. const isTableSep = (line = '') => /^\s*\|?[\s:|-]+\|?\s*$/.test(line) && line.includes('-')
  32. const markdownToHtml = (md = '') => {
  33. const lines = String(md).replace(/\r\n/g, '\n').split('\n')
  34. const n = lines.length
  35. let i = 0
  36. let html = ''
  37. let listType = null
  38. const closeList = () => {
  39. if (listType) {
  40. html += `</${listType}>\n`
  41. listType = null
  42. }
  43. }
  44. while (i < n) {
  45. const line = lines[i]
  46. // 代码块
  47. const fence = line.match(/^```(\w*)\s*$/)
  48. if (fence) {
  49. closeList()
  50. const lang = fence[1]
  51. i++
  52. const buf = []
  53. while (i < n && !/^```\s*$/.test(lines[i])) {
  54. buf.push(lines[i])
  55. i++
  56. }
  57. i++
  58. html += `<pre class="code-block" data-lang="${lang}"><code>${escapeHtml(buf.join('\n'))}</code></pre>\n`
  59. continue
  60. }
  61. // 空行
  62. if (/^\s*$/.test(line)) {
  63. closeList()
  64. i++
  65. continue
  66. }
  67. // 分隔线
  68. if (/^-{3,}\s*$/.test(line)) {
  69. closeList()
  70. html += '<hr/>\n'
  71. i++
  72. continue
  73. }
  74. // 标题
  75. const heading = line.match(/^(#{1,6})\s+(.*)$/)
  76. if (heading) {
  77. closeList()
  78. const level = heading[1].length
  79. const text = heading[2].trim()
  80. html += `<h${level} id="${slugify(text)}">${inline(text)}</h${level}>\n`
  81. i++
  82. continue
  83. }
  84. // 引用
  85. if (/^>\s?/.test(line)) {
  86. closeList()
  87. const buf = []
  88. while (i < n && /^>\s?/.test(lines[i])) {
  89. buf.push(lines[i].replace(/^>\s?/, ''))
  90. i++
  91. }
  92. html += `<blockquote>${markdownToHtml(buf.join('\n'))}</blockquote>\n`
  93. continue
  94. }
  95. // 表格
  96. if (/^\s*\|/.test(line) && i + 1 < n && isTableSep(lines[i + 1])) {
  97. closeList()
  98. const header = splitRow(line)
  99. i += 2
  100. const rows = []
  101. while (i < n && /^\s*\|/.test(lines[i])) {
  102. rows.push(splitRow(lines[i]))
  103. i++
  104. }
  105. html +=
  106. '<table><thead><tr>' +
  107. header.map((c) => `<th>${inline(c)}</th>`).join('') +
  108. '</tr></thead><tbody>' +
  109. rows.map((r) => '<tr>' + r.map((c) => `<td>${inline(c)}</td>`).join('') + '</tr>').join('') +
  110. '</tbody></table>\n'
  111. continue
  112. }
  113. // 无序列表
  114. if (/^\s*[-*]\s+/.test(line)) {
  115. if (listType !== 'ul') {
  116. closeList()
  117. html += '<ul>\n'
  118. listType = 'ul'
  119. }
  120. html += `<li>${inline(line.replace(/^\s*[-*]\s+/, ''))}</li>\n`
  121. i++
  122. continue
  123. }
  124. // 有序列表
  125. if (/^\s*\d+\.\s+/.test(line)) {
  126. if (listType !== 'ol') {
  127. closeList()
  128. html += '<ol>\n'
  129. listType = 'ol'
  130. }
  131. html += `<li>${inline(line.replace(/^\s*\d+\.\s+/, ''))}</li>\n`
  132. i++
  133. continue
  134. }
  135. // 段落
  136. closeList()
  137. html += `<p>${inline(line.trim())}</p>\n`
  138. i++
  139. }
  140. closeList()
  141. return html
  142. }
  143. const pageStyle = `
  144. * { box-sizing: border-box; }
  145. body { margin: 0; background: #f5f6f8; color: #24292f; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", Arial, sans-serif; line-height: 1.7; }
  146. .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); }
  147. h1, h2, h3, h4 { color: #1f2328; line-height: 1.3; }
  148. h1 { font-size: 28px; border-bottom: 2px solid #1677ff; padding-bottom: 12px; }
  149. h2 { font-size: 22px; border-bottom: 1px solid #e5e7eb; padding-bottom: 8px; margin-top: 36px; }
  150. h3 { font-size: 18px; margin-top: 28px; }
  151. a { color: #1677ff; text-decoration: none; }
  152. a:hover { text-decoration: underline; }
  153. code { background: #f0f2f5; color: #d4380d; padding: 2px 6px; border-radius: 4px; font-family: Consolas, Monaco, "Courier New", monospace; font-size: 13px; }
  154. .code-block { background: #1e1e1e; color: #d4d4d4; padding: 16px 18px; border-radius: 8px; overflow-x: auto; position: relative; }
  155. .code-block code { background: transparent; color: #d4d4d4; padding: 0; font-size: 13px; line-height: 1.6; white-space: pre; }
  156. .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; }
  157. table { border-collapse: collapse; width: 100%; margin: 16px 0; font-size: 14px; }
  158. th, td { border: 1px solid #e5e7eb; padding: 8px 12px; text-align: left; vertical-align: top; }
  159. th { background: #f6f8fa; font-weight: 600; }
  160. tr:nth-child(even) td { background: #fafbfc; }
  161. blockquote { margin: 16px 0; padding: 12px 16px; background: #f6f8fa; border-left: 4px solid #1677ff; color: #57606a; }
  162. blockquote p { margin: 0; }
  163. hr { border: none; border-top: 1px solid #e5e7eb; margin: 28px 0; }
  164. ul, ol { padding-left: 24px; }
  165. li { margin: 4px 0; }
  166. .doc-tip { max-width: 1000px; margin: 12px auto 0; padding: 0 40px; color: #8c8c8c; font-size: 12px; }
  167. `
  168. const renderPage = (title, body) => `<!DOCTYPE html>
  169. <html lang="zh-CN">
  170. <head>
  171. <meta charset="UTF-8" />
  172. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  173. <title>${escapeHtml(title)}</title>
  174. <style>${pageStyle}</style>
  175. </head>
  176. <body>
  177. <div class="doc-tip">sapit-ui 文档预览(由 Markdown 实时渲染)</div>
  178. <main class="doc-wrap">${body}</main>
  179. </body>
  180. </html>`
  181. /**
  182. * 文档预览插件
  183. * @param {object} options
  184. * @param {string} [options.route='/docs'] 访问路由
  185. * @param {string} [options.title] 页面标题
  186. * @param {string} [options.file] Markdown 文件路径(默认取插件同级的 ../docs/*.md)
  187. */
  188. export default function docsViewer(options = {}) {
  189. // 独立 HTML 预览路由(避免与 SPA 内的 /docs 静态页面冲突)
  190. const route = options.route || '/docs-preview'
  191. // 应用内静态页面路由(控制台提示用)
  192. const linkRoute = options.linkRoute || '/docs'
  193. const title = options.title || 'sapit-ui 基座说明与业务使用文档'
  194. const file = options.file
  195. ? path.resolve(process.cwd(), options.file)
  196. : path.resolve(currentDir, '../docs/sapit-ui-基座说明与业务使用.md')
  197. const getHtml = () => {
  198. let md
  199. try {
  200. md = fs.readFileSync(file, 'utf-8')
  201. } catch (e) {
  202. md = `# 文档未找到\n\n> 文件路径:${file}`
  203. }
  204. return renderPage(title, markdownToHtml(md))
  205. }
  206. const middleware = (req, res, next) => {
  207. const url = (req.url || '').split('?')[0]
  208. if (url !== route && url !== `${route}/`) return next()
  209. res.setHeader('Content-Type', 'text/html; charset=utf-8')
  210. res.end(getHtml())
  211. }
  212. const logUrl = (server) => {
  213. try {
  214. const urls = server.resolvedUrls
  215. const base =
  216. (urls && urls.local && urls.local[0]) || `http://localhost:${server.config.server.port}/`
  217. const root = base.replace(/\/+$/, '')
  218. console.log(`\n \x1b[32m➜\x1b[0m 文档(应用内): \x1b[36m${root}${linkRoute}\x1b[0m`)
  219. console.log(` \x1b[32m➜\x1b[0m 文档(独立预览): \x1b[36m${root}${route}\x1b[0m\n`)
  220. } catch (e) {
  221. // ignore
  222. }
  223. }
  224. return {
  225. name: 'sapit-docs-viewer',
  226. configureServer(server) {
  227. server.middlewares.use(middleware)
  228. if (server.httpServer) {
  229. if (server.httpServer.listening) logUrl(server)
  230. else server.httpServer.once('listening', () => logUrl(server))
  231. }
  232. },
  233. configurePreviewServer(server) {
  234. server.middlewares.use(middleware)
  235. }
  236. }
  237. }