docs/.vitepress/configs/markdown/index.ts
274 lines · 8032 bytes
1/**
2 * All Rights Reserved
3 *
4 * Copyright (c) 2025 taskylizard
5 *
6 * All rights reserved. This code and its associated files may not be copied, modified, distributed, sublicensed, or used in any form, in whole or in part, without prior written permission from the copyright holder.
7 */
8import MdMTables from 'markdown-it-multimd-table'
9// @ts-expect-error
10import { align } from '@mdit/plugin-align'
11import { attrs } from '@mdit/plugin-attrs'
12import { figure } from '@mdit/plugin-figure'
13import { imgLazyload } from '@mdit/plugin-img-lazyload'
14import { imgSize } from '@mdit/plugin-img-size'
15import MdReg from 'markdown-it-regexp'
16import type { MarkdownRenderer } from 'vitepress'
17import {
18 getCollapsibleHeadingAnchor,
19 getTabAnchor,
20 getTabHeadingAnchor,
21 getUniqueAnchor,
22 parseTabLabel
23} from '../../utils/tabAnchors'
24import { getTooltip } from '../../utils/tooltips'
25import { headersPlugin } from '../markdown/headers'
26import { emojiRender } from './emoji'
27import { extRepoPlugin } from './extRepoPlugin'
28import { nestedContainersPlugin } from './nestedContainers'
29import { scrapeTablePlugin } from './scrapeTablePlugin'
30import markdownSteps from './steps'
31import { tabsMarkdownPlugin } from './tabs'
32
33export function configureMarkdown(md: MarkdownRenderer) {
34 md.use(emojiRender)
35 md.use(imgLazyload)
36 md.use(align)
37 md.use(figure)
38 md.use(tabsMarkdownPlugin)
39 md.use(nestedContainersPlugin)
40 md.use(imgSize)
41 md.use(headersPlugin)
42 md.use(MdMTables, {
43 multiline: true,
44 rowspan: true,
45 headerless: true,
46 multibody: true,
47 aotolabel: true
48 })
49 md.use(attrs)
50 renderTooltip(md)
51 renderInlineTooltip(md)
52 md.use(markdownSteps)
53 md.use(scrapeTablePlugin)
54 md.use(extRepoPlugin)
55 renderHighlight(md)
56}
57
58function renderInlineTooltip(md: MarkdownRenderer) {
59 md.use(
60 MdReg(
61 /\^\[(.*?)\]\((.+?)\)/,
62 ([, cont, hint]: string[]) =>
63 '<VTooltip theme="hint">' +
64 span(md.renderInline(cont)) +
65 '<template v-slot:popper>' +
66 md.renderInline(hint) +
67 '</template></VTooltip>'
68 )
69 )
70}
71
72function renderTooltip(md: MarkdownRenderer) {
73 md.use(
74 MdReg(/==(.+?)==/, ([, cont]: string[]) => {
75 const item = getTooltip(cont)
76 if (!item) return `No tooltip found for ${cont}`
77
78 const icon = item.frontmatter.icon
79 ? `icon="${item.frontmatter.icon}"`
80 : ''
81
82 const title = item.frontmatter.title
83 ? `title="${item.frontmatter.title}"`
84 : item.id
85 ? `title="${item.id}"`
86 : '' /** Impossible */
87 const props = icon + title
88 const renderedContent = md.render(item.content)
89
90 return `<Tooltip ${props}>` + renderedContent + '</Tooltip>'
91 })
92 )
93}
94
95function span(
96 content: string,
97 attrs: Record<string, unknown> | undefined = undefined
98) {
99 let html = '<span'
100 if (attrs) {
101 for (const [key, value] of Object.entries(attrs)) {
102 html += ` ${key}="${value}"`
103 }
104 }
105 html += `>${content}</span>`
106 return html
107}
108
109function renderHighlight(md: MarkdownRenderer) {
110 const original = md.render.bind(md)
111 md.render = (src, env) => {
112 const withSearchHeadings = injectSearchHeadings(src)
113
114 // Replace [||text||](url) — linked pill
115 let replaced = withSearchHeadings.replace(
116 /\[([!x]?)\|\|(.+?)\|\|\]\((.+?)\)/g,
117 (_, prefix, cont, url) => {
118 const variant = prefix === '!'
119 ? 'warning'
120 : prefix === 'x'
121 ? 'danger'
122 : 'default'
123 const inner = md.renderInline(cont, env)
124 return `<a href="${url}" target="_blank" rel="noopener noreferrer"><hl variant="${variant}" linked="true">${inner}</hl></a>`
125 }
126 )
127 // Replace standalone ||text||
128 replaced = replaced.replace(/([!x]?)\|\|(.+?)\|\|/g, (_, prefix, cont) => {
129 const variant = prefix === '!'
130 ? 'warning'
131 : prefix === 'x'
132 ? 'danger'
133 : 'default'
134 return `<hl variant="${variant}">${md.renderInline(cont, env)}</hl>`
135 })
136 return original(replaced, env)
137 }
138}
139
140interface SearchHeading {
141 level: number
142 title: string
143}
144
145function getHeadingTitle(value: string) {
146 return value.replace(/\s+\{[^}]*\}\s*$/, '').trim()
147}
148
149function injectSearchHeadings(src: string) {
150 const lines = src.split('\n')
151 const containerStack: string[] = []
152 const headingStack: (SearchHeading | undefined)[] = []
153 const tabResetStack: (SearchHeading | undefined)[] = []
154 const tabAnchorCounts = new Map<string, number>()
155 const collapsibleAnchorCounts = new Map<string, number>()
156 const getCurrentHeading = () => {
157 for (let i = headingStack.length - 1; i >= 0; i--) {
158 if (headingStack[i]) return headingStack[i]
159 }
160 }
161 const isHeadingLine = (line: string | undefined) =>
162 /^#{1,6}\s+/.test(line?.trim() ?? '')
163
164 for (let i = 0; i < lines.length; i++) {
165 const headingMatch = lines[i].match(/^(#{1,6})\s+(.+)/)
166 if (headingMatch && !containerStack.includes('tabs')) {
167 const level = headingMatch[1].length
168 const title = getHeadingTitle(headingMatch[2])
169 if (title) {
170 headingStack[level - 1] = { level, title }
171 headingStack.length = level
172 }
173 }
174
175 const containerOpenMatch = lines[i].match(
176 /^\s*:{3,}\s*([A-Za-z][\w-]*)\b/
177 )
178 if (containerOpenMatch) {
179 const containerName = containerOpenMatch[1].toLowerCase()
180 containerStack.push(containerName)
181 if (containerName === 'tabs') tabResetStack.push(getCurrentHeading())
182 } else if (/^\s*:{3,}\s*$/.test(lines[i])) {
183 const closed = containerStack.pop()
184 if (closed === 'tabs') {
185 const resetHeading = tabResetStack.pop()
186 let nextLine = i + 1
187 while (nextLine < lines.length && lines[nextLine].trim() === '') {
188 nextLine++
189 }
190
191 if (
192 resetHeading && nextLine < lines.length &&
193 !isHeadingLine(lines[nextLine])
194 ) {
195 const indent = lines[i].match(/^(\s*):{3,}\s*$/)?.[1] ?? ''
196 lines.splice(
197 i + 1,
198 0,
199 '',
200 `${indent}${
201 '#'.repeat(resetHeading.level)
202 } ${resetHeading.title} {.tab-search-heading .ignore-header}`,
203 ''
204 )
205 i += 3
206 }
207 }
208 continue
209 }
210
211 const tabMatch = lines[i].match(/^(\s*)==\s+(.+)$/)
212 if (tabMatch && containerStack.includes('tabs')) {
213 const [, indent, title] = tabMatch
214 const parsed = parseTabLabel(title)
215 const headingTitle = parsed.label
216 if (!headingTitle) continue
217 const anchor = getTabAnchor(title, tabAnchorCounts)
218 const headingAnchor = getTabHeadingAnchor(anchor)
219
220 lines.splice(
221 i + 1,
222 0,
223 '',
224 `${indent}### ${headingTitle} {#${headingAnchor} .tab-search-heading .ignore-header}`,
225 ''
226 )
227 i += 3
228 continue
229 }
230
231 const match = lines[i].match(
232 /^(\s*)<Collapsible\b(?=[^>]*\btitle=(['"])(.*?)\2)[^>]*>\s*$/i
233 )
234 if (!match) continue
235
236 const [, indent, , rawTitle] = match
237 const parsedTitle = parseTabLabel(rawTitle)
238 const headingTitle = parsedTitle.label
239 if (!headingTitle) continue
240
241 const collapsibleAnchor = parsedTitle.anchor ||
242 getUniqueAnchor(headingTitle, collapsibleAnchorCounts)
243
244 lines[i] = lines[i].replace(
245 /(<Collapsible\b[^>]*?\btitle=)(['"]).*?\2/i,
246 (_full, pre: string, quote: string) =>
247 `${pre}${quote}${headingTitle}${quote} anchor=${quote}${collapsibleAnchor}${quote}`
248 )
249
250 let nextLine = i + 1
251 while (nextLine < lines.length && lines[nextLine].trim() === '') {
252 nextLine++
253 }
254
255 if (/^#{1,6}\s+/.test(lines[nextLine]?.trim() ?? '')) continue
256
257 const headingLevel = containerStack.includes('tabs') ? 4 : 3
258
259 lines.splice(
260 i + 1,
261 0,
262 '',
263 `${indent}${
264 '#'.repeat(headingLevel)
265 } ${headingTitle} {#${
266 getCollapsibleHeadingAnchor(collapsibleAnchor)
267 } .collapsible-search-heading}`,
268 ''
269 )
270 i += 3
271 }
272
273 return lines.join('\n')
274}