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