docs/.vitepress/configs/markdown/themeRepoPlugin.ts
96 lines · 2670 bytes
5 symbols in this file
1import type MarkdownIt from 'markdown-it'
2import type { ThemeRepoEntry } from '../../../ext/themeRepos/types'
3
4const MARKER = ':'
5const MIN_MARKERS = 3
6const NAME = 'themerepo'
7
8function parseEntries(bodyLines: string[]): ThemeRepoEntry[] {
9 const entries: ThemeRepoEntry[] = []
10 let current: ThemeRepoEntry | null = null
11
12 for (const rawLine of bodyLines) {
13 const line = rawLine.trim()
14 if (!line) continue
15
16 const headingMatch = line.match(/^==\s+(.+)$/)
17 if (headingMatch) {
18 if (current) entries.push(current)
19 current = { name: headingMatch[1].trim() }
20 continue
21 }
22
23 const fieldMatch = line.match(/^-\s*([a-zA-Z]+)\s*:\s*(.+)$/)
24 if (fieldMatch && current) {
25 const key = fieldMatch[1].toLowerCase()
26 const value = fieldMatch[2].trim()
27 if (key === 'url' || key === 'src' || key === 'raw') {
28 current[key] = value
29 }
30 }
31 }
32 if (current) entries.push(current)
33
34 return entries
35}
36
37export function themeRepoPlugin(md: MarkdownIt): void {
38 md.block.ruler.before(
39 'fence',
40 'theme_repo',
41 (state, startLine, endLine, silent) => {
42 let pos = state.bMarks[startLine] + state.tShift[startLine]
43 const max = state.eMarks[startLine]
44
45 let markerCount = 0
46 while (pos < max && state.src[pos] === MARKER) {
47 pos++
48 markerCount++
49 }
50 if (markerCount < MIN_MARKERS) return false
51
52 const params = state.src.slice(pos, max).trim()
53 if (params.split(/\s+/)[0].toLowerCase() !== NAME) return false
54
55 if (silent) return true
56
57 let nextLine = startLine + 1
58 let found = false
59 while (nextLine < endLine) {
60 let p = state.bMarks[nextLine] + state.tShift[nextLine]
61 const m = state.eMarks[nextLine]
62 if (p < m && state.sCount[nextLine] < state.blkIndent) break
63
64 let cnt = 0
65 while (p < m && state.src[p] === MARKER) {
66 p++
67 cnt++
68 }
69 if (cnt >= markerCount && state.src.slice(p, m).trim() === '') {
70 found = true
71 break
72 }
73 nextLine++
74 }
75
76 const body = state.getLines(
77 startLine + 1,
78 nextLine,
79 state.blkIndent,
80 false
81 )
82 const entries = parseEntries(body.split('\n'))
83 const attrs = entries.length
84 ? ` :themes='${JSON.stringify(entries).replace(/'/g, ''')}'`
85 : ''
86
87 const token = state.push('html_block', '', 0)
88 token.map = [startLine, nextLine]
89 token.content = `<ThemeRepos${attrs} />\n`
90
91 state.line = found ? nextLine + 1 : nextLine
92 return true
93 },
94 { alt: ['paragraph', 'reference', 'blockquote', 'list'] }
95 )
96}