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