docs-viewer.js 8.5 KB

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