docs/.vitepress/configs/markdown/tabs.ts
216 lines · 6239 bytes
1import type { MarkdownRenderer } from 'vitepress'
2import { getUniqueAnchor, parseTabLabel } from '../../utils/tabAnchors'
3
4function containerPlugin(md: MarkdownRenderer, name: string, options: any) {
5 function validateDefault(params: string) {
6 return params.trim().split(' ', 2)[0] === name
7 }
8
9 function renderDefault(
10 tokens: any[],
11 idx: number,
12 opts: any,
13 env: any,
14 slf: any
15 ) {
16 if (tokens[idx].nesting === 1) tokens[idx].attrJoin('class', name)
17 return slf.renderToken(tokens, idx, opts, env, slf)
18 }
19
20 const minMarkers = 3
21 const markerStr = options.marker || ':'
22 const markerChar = markerStr.charCodeAt(0)
23 const markerLen = markerStr.length
24 const validate = options.validate || validateDefault
25 const render = options.render || renderDefault
26
27 function container(
28 state: any,
29 startLine: number,
30 endLine: number,
31 silent: boolean
32 ) {
33 let pos
34 let autoClosed = false
35 let start = state.bMarks[startLine] + state.tShift[startLine]
36 let max = state.eMarks[startLine]
37
38 if (markerChar !== state.src.charCodeAt(start)) return false
39
40 for (pos = start + 1; pos <= max; pos++) {
41 if (markerStr[(pos - start) % markerLen] !== state.src[pos]) break
42 }
43
44 const markerCount = Math.floor((pos - start) / markerLen)
45 if (markerCount < minMarkers) return false
46
47 pos -= (pos - start) % markerLen
48 const markup = state.src.slice(start, pos)
49 const params = state.src.slice(pos, max)
50
51 if (!validate(params, markup)) return false
52 if (silent) return true
53
54 let nextLine = startLine
55 for (;;) {
56 nextLine++
57 if (nextLine >= endLine) break
58
59 start = state.bMarks[nextLine] + state.tShift[nextLine]
60 max = state.eMarks[nextLine]
61
62 if (start < max && state.sCount[nextLine] < state.blkIndent) break
63 if (markerChar !== state.src.charCodeAt(start)) continue
64 if (state.sCount[nextLine] - state.blkIndent >= 4) continue
65
66 for (pos = start + 1; pos <= max; pos++) {
67 if (markerStr[(pos - start) % markerLen] !== state.src[pos]) break
68 }
69 if (Math.floor((pos - start) / markerLen) < markerCount) continue
70
71 pos -= (pos - start) % markerLen
72 pos = state.skipSpaces(pos)
73 if (pos < max) continue
74
75 autoClosed = true
76 break
77 }
78
79 const oldParent = state.parentType
80 const oldLineMax = state.lineMax
81
82 state.parentType = 'container'
83 state.lineMax = nextLine
84
85 const tokenOpen = state.push(`container_${name}_open`, 'div', 1)
86 tokenOpen.markup = markup
87 tokenOpen.block = true
88 tokenOpen.info = params
89 tokenOpen.map = [startLine, nextLine]
90
91 state.md.block.tokenize(state, startLine + 1, nextLine)
92
93 const tokenClose = state.push(`container_${name}_close`, 'div', -1)
94 tokenClose.markup = state.src.slice(start, pos)
95 tokenClose.block = true
96
97 state.parentType = oldParent
98 state.lineMax = oldLineMax
99 state.line = nextLine + (autoClosed ? 1 : 0)
100
101 return true
102 }
103
104 md.block.ruler.before('fence', `container_${name}`, container, {
105 alt: ['paragraph', 'reference', 'blockquote', 'list']
106 })
107 md.renderer.rules[`container_${name}_open`] = render
108 md.renderer.rules[`container_${name}_close`] = render
109}
110
111const tabMarkerCode = '='.charCodeAt(0)
112const minTabMarkerLen = 2
113
114const ruleBlockTab = (
115 state: any,
116 startLine: number,
117 endLine: number,
118 silent: boolean
119) => {
120 let pos = state.bMarks[startLine] + state.tShift[startLine]
121 const max = state.eMarks[startLine]
122
123 if (state.parentType !== 'container') return false
124 if (pos + minTabMarkerLen > max) return false
125
126 const marker = state.src.charCodeAt(pos)
127 if (marker !== tabMarkerCode) return false
128
129 const mem = pos
130 pos = state.skipChars(pos + 1, marker)
131 const tabMarkerLen = pos - mem
132 if (tabMarkerLen < minTabMarkerLen - 1) return false
133 if (silent) return true
134
135 let nextLine = startLine
136 let endStart = mem
137 let endPos = pos
138
139 for (;;) {
140 nextLine++
141 if (nextLine >= endLine) break
142
143 endStart = state.bMarks[nextLine] + state.tShift[nextLine]
144 const lineMax = state.eMarks[nextLine]
145
146 if (endStart < lineMax && state.sCount[nextLine] < state.blkIndent) break
147 if (state.src.charCodeAt(endStart) !== tabMarkerCode) continue
148
149 const p = state.skipChars(endStart + 1, marker)
150 if (p - endStart !== tabMarkerLen) continue
151
152 endPos = p
153 break
154 }
155
156 const oldParent = state.parentType
157 const oldLineMax = state.lineMax
158
159 state.parentType = 'tab'
160 state.lineMax = nextLine
161
162 const startToken = state.push('tab_open', 'div', 1)
163 startToken.markup = state.src.slice(mem, pos)
164 startToken.block = true
165 startToken.info = state.src.slice(pos, max).trimStart()
166 startToken.map = [startLine, nextLine - 1]
167
168 state.md.block.tokenize(state, startLine + 1, nextLine)
169
170 const endToken = state.push('tab_close', 'div', -1)
171 endToken.markup = state.src.slice(endStart, endPos)
172 endToken.block = true
173
174 state.parentType = oldParent
175 state.lineMax = oldLineMax
176 state.line = nextLine
177
178 return true
179}
180
181function parseTabsParams(input: string) {
182 return { shareStateKey: input.match(/key:(\S+)/)?.[1] }
183}
184
185function getTabAnchorCounts(env: any) {
186 env.__tabAnchorCounts ??= new Map<string, number>()
187 return env.__tabAnchorCounts as Map<string, number>
188}
189
190export function tabsMarkdownPlugin(md: MarkdownRenderer) {
191 containerPlugin(md, 'tabs', {
192 render(tokens: any[], index: number) {
193 const token = tokens[index]
194 if (token.nesting !== 1) return '</PluginTabs>\n'
195
196 const params = parseTabsParams(token.info)
197 const sharedState = params.shareStateKey
198 ? ` sharedStateKey="${md.utils.escapeHtml(params.shareStateKey)}"`
199 : ''
200 return `<PluginTabs${sharedState}>\n`
201 }
202 })
203
204 md.block.ruler.after('container_tabs', 'tab', ruleBlockTab)
205
206 md.renderer.rules.tab_open = (tokens, index, _options, env) => {
207 const parsed = parseTabLabel(tokens[index].info)
208 const anchor = parsed.anchor ||
209 getUniqueAnchor(parsed.label, getTabAnchorCounts(env))
210
211 return `<PluginTabsTab label="${
212 md.utils.escapeHtml(parsed.label)
213 }" anchor="${md.utils.escapeHtml(anchor)}">\n`
214 }
215 md.renderer.rules.tab_close = () => '</PluginTabsTab>\n'
216}