docs/.vitepress/plugins/urlSearchPlugin.ts
301 lines · 8219 bytes
1import { writeFileSync } from 'node:fs'
2import { join } from 'node:path'
3import { renderEmojiShortcodes } from '../configs/markdown/emoji'
4import {
5 getTabAnchor,
6 getTabHeadingAnchor,
7 parseTabLabel,
8 slugifyAnchor,
9 stripHeadingMarkup
10} from '../utils/tabAnchors'
11
12export interface PageLink {
13 href: string
14 linkText: string
15 pageId: string
16 anchor: string
17 titles: string[]
18 tabs?: string[]
19}
20
21export interface TabTarget {
22 pageId: string
23 anchor: string
24 tabs: string[]
25}
26
27interface PageSearchMetadata {
28 links: PageLink[]
29 tabTargets: TabTarget[]
30}
31
32function extractSearchMetadataFromMarkdown(
33 src: string,
34 pageId: string
35): PageSearchMetadata {
36 const links: PageLink[] = []
37 const seenLinks = new Set<string>()
38 const tabTargets = new Map<string, TabTarget>()
39 const headingStack: string[] = []
40 const slugCounts = new Map<string, number>()
41 const tabAnchorCounts = new Map<string, number>()
42 const containerStack: string[] = []
43 const tabPath: string[] = []
44 const tabResetStack: {
45 anchor: string
46 headings: string[]
47 }[] = []
48 const collapsibleStack: {
49 anchor: string
50 headings: string[]
51 }[] = []
52 let currentAnchor = ''
53
54 const body = src.startsWith('---')
55 ? src.replace(/^---[\s\S]*?---\n?/, '')
56 : src
57 const lines = body.split('\n')
58
59 const getAnchor = (text: string) => {
60 const slug = slugifyAnchor(text)
61 const count = slugCounts.get(slug) ?? 0
62 slugCounts.set(slug, count + 1)
63 return count === 0 ? slug : `${slug}-${count}`
64 }
65
66 const getCurrentTabPath = () => tabPath.filter(Boolean)
67
68 const recordTabTarget = (anchor: string) => {
69 const tabs = getCurrentTabPath()
70 if (!anchor || !tabs.length) return
71 tabTargets.set(anchor, { pageId, anchor, tabs })
72 }
73
74 const setHeading = (level: number, text: string, anchor?: string) => {
75 const title = stripHeadingMarkup(text)
76 if (!title) return
77
78 headingStack[level] = title
79 headingStack.length = level + 1
80 currentAnchor = anchor || getAnchor(title)
81 recordTabTarget(currentAnchor)
82 }
83
84 const getTitles = () => headingStack.filter(Boolean)
85
86 const restoreHeadingState = (state: {
87 anchor: string
88 headings: string[]
89 }) => {
90 currentAnchor = state.anchor
91 headingStack.length = 0
92 headingStack.push(...state.headings)
93 }
94
95 const getTabsDepth = () =>
96 containerStack.filter((name) => name === 'tabs').length
97
98 const pushLink = (href: string, linkText: string) => {
99 const tabs = getCurrentTabPath()
100 const key = [
101 href,
102 currentAnchor,
103 tabs.join('/')
104 ].join('\x00')
105 if (seenLinks.has(key)) return
106
107 seenLinks.add(key)
108 links.push({
109 href,
110 linkText,
111 pageId,
112 anchor: currentAnchor,
113 titles: getTitles(),
114 ...(tabs.length ? { tabs } : {})
115 })
116 }
117
118 for (let i = 0; i < lines.length; i++) {
119 const line = lines[i]
120
121 const containerOpenMatch = line.match(/^\s*:{3,}\s*([A-Za-z][\w-]*)\b/)
122 if (containerOpenMatch) {
123 const containerName = containerOpenMatch[1].toLowerCase()
124 containerStack.push(containerName)
125 if (containerName === 'tabs') {
126 tabResetStack.push({
127 anchor: currentAnchor,
128 headings: [...headingStack]
129 })
130 }
131 } else if (/^\s*:{3,}\s*$/.test(line)) {
132 const closed = containerStack.pop()
133 if (closed === 'tabs') {
134 tabPath.length = getTabsDepth()
135 const resetState = tabResetStack.pop()
136 if (resetState) restoreHeadingState(resetState)
137 }
138 }
139
140 const tabMatch = line.match(/^\s*==\s+(.+)$/)
141 if (tabMatch && containerStack.includes('tabs')) {
142 const rawTitle = tabMatch[1]
143 const parsed = parseTabLabel(rawTitle)
144 if (parsed.label) {
145 const depth = getTabsDepth()
146 const anchor = getTabAnchor(rawTitle, tabAnchorCounts)
147 const headingAnchor = getTabHeadingAnchor(anchor)
148 tabPath[depth - 1] = anchor
149 tabPath.length = depth
150
151 // The markdown renderer injects a hidden H3 for each tab label.
152 // Mirror that heading so search can deep-link to the selected tab.
153 setHeading(2, parsed.label, headingAnchor)
154 }
155 continue
156 }
157
158 const collapsibleMatch = line.match(
159 /^\s*<Collapsible\b(?=[^>]*\btitle=(['"])(.*?)\1)[^>]*>\s*$/i
160 )
161 if (collapsibleMatch) {
162 collapsibleStack.push({
163 anchor: currentAnchor,
164 headings: [...headingStack]
165 })
166
167 let nextLine = i + 1
168 while (nextLine < lines.length && lines[nextLine].trim() === '') {
169 nextLine++
170 }
171
172 // The markdown renderer injects searchable headings for collapsibles
173 // that don't already start with a heading. Mirror that anchor so URL
174 // search can deep-link into and auto-open those collapsibles.
175 if (!/^#{1,6}\s+/.test(lines[nextLine]?.trim() ?? '')) {
176 setHeading(
177 containerStack.includes('tabs') ? 3 : 2,
178 collapsibleMatch[2].trim()
179 )
180 }
181 continue
182 }
183
184 if (/^\s*<\/Collapsible>\s*$/i.test(line)) {
185 const previous = collapsibleStack.pop()
186 if (previous) restoreHeadingState(previous)
187 continue
188 }
189
190 const headingMatch = line.match(/^(#{1,6})\s+(.+)/)
191 if (headingMatch) {
192 const level = headingMatch[1].length - 1
193 setHeading(level, headingMatch[2].trim())
194 continue
195 }
196
197 const linkRE = /\[([^\]]*)\]\((https?:\/\/[^)]+)\)/g
198 let m: RegExpExecArray | null
199 while ((m = linkRE.exec(line)) !== null) {
200 pushLink(m[2].trim(), renderEmojiShortcodes(m[1].trim()))
201 }
202
203 const bareRE = /<(https?:\/\/[^>]+)>/g
204 while ((m = bareRE.exec(line)) !== null) {
205 const href = m[1].trim()
206 pushLink(href, href)
207 }
208 }
209
210 return { links, tabTargets: [...tabTargets.values()] }
211}
212
213const collectedByPage = new Map<string, PageSearchMetadata>()
214
215function getPageId(page: string) {
216 return '/' + page.replace(/\.md$/, '').replace(/\/index$/, '/')
217}
218
219function getDedupedLinks() {
220 const seen = new Set<string>()
221 const deduped: PageLink[] = []
222
223 for (const metadata of collectedByPage.values()) {
224 for (const link of metadata.links) {
225 const key = [
226 link.href,
227 link.pageId,
228 link.anchor,
229 link.tabs?.join('/') ?? ''
230 ].join('\x00')
231 if (seen.has(key)) continue
232 seen.add(key)
233 deduped.push(link)
234 }
235 }
236
237 return deduped
238}
239
240function getDedupedTabTargets() {
241 const seen = new Set<string>()
242 const deduped: TabTarget[] = []
243
244 for (const metadata of collectedByPage.values()) {
245 for (const target of metadata.tabTargets) {
246 const key = [
247 target.pageId,
248 target.anchor,
249 target.tabs.join('/')
250 ].join('\x00')
251 if (seen.has(key)) continue
252 seen.add(key)
253 deduped.push(target)
254 }
255 }
256
257 return deduped
258}
259
260export function collectPageLinks(src: string, page: string) {
261 const pageId = getPageId(page)
262 collectedByPage.set(pageId, extractSearchMetadataFromMarkdown(src, pageId))
263}
264
265export function writeUrlSearchIndex(outDir: string) {
266 const links = getDedupedLinks()
267 const linksPath = join(outDir, 'url-search-index.json')
268 writeFileSync(linksPath, JSON.stringify(links), 'utf-8')
269 console.log(`[url-search] wrote ${links.length} links -> ${linksPath}`)
270
271 const tabTargets = getDedupedTabTargets()
272 const tabTargetsPath = join(outDir, 'tab-search-index.json')
273 writeFileSync(tabTargetsPath, JSON.stringify(tabTargets), 'utf-8')
274 console.log(
275 `[url-search] wrote ${tabTargets.length} tab targets -> ${tabTargetsPath}`
276 )
277}
278
279export function urlSearchDevPlugin() {
280 return {
281 name: 'url-search-dev',
282 configureServer(server: any) {
283 server.middlewares.use(
284 '/url-search-index.json',
285 (_req: any, res: any) => {
286 const deduped = getDedupedLinks()
287 res.setHeader('Content-Type', 'application/json')
288 res.end(JSON.stringify(deduped))
289 }
290 )
291 server.middlewares.use(
292 '/tab-search-index.json',
293 (_req: any, res: any) => {
294 const deduped = getDedupedTabTargets()
295 res.setHeader('Content-Type', 'application/json')
296 res.end(JSON.stringify(deduped))
297 }
298 )
299 }
300 }
301}