docs/.vitepress/plugins/urlSearchPlugin.ts
230 lines · 6418 bytes
1import { writeFileSync } from 'node:fs'
2import { join } from 'node:path'
3import { renderEmojiShortcodes } from '../configs/markdown/emoji'
4
5export interface PageLink {
6 href: string
7 linkText: string
8 pageId: string
9 anchor: string
10 titles: string[]
11}
12
13function extractLinksFromMarkdown(src: string, pageId: string): PageLink[] {
14 const results: PageLink[] = []
15 const seen = new Set<string>()
16 const headingStack: string[] = []
17 const slugCounts = new Map<string, number>()
18 const containerStack: string[] = []
19 const tabStack: {
20 title: string
21 headings: string[]
22 }[] = []
23 const collapsibleStack: {
24 anchor: string
25 headings: string[]
26 }[] = []
27 let currentAnchor = ''
28
29 // Strip frontmatter
30 const body = src.startsWith('---')
31 ? src.replace(/^---[\s\S]*?---\n?/, '')
32 : src
33 const lines = body.split('\n')
34
35 const slugify = (value: string) =>
36 value
37 .replace(/\{[^}]*\}\s*$/, '')
38 .replace(/<[^>]*>/g, '')
39 .replace(/`([^`]+)`/g, '$1')
40 .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
41 .replace(/[*_~]/g, '')
42 .trim()
43 .toLowerCase()
44 .replace(/[^\w\s-]/g, '')
45 .replace(/\s+/g, '-')
46 .replace(/-+/g, '-')
47 .replace(/^-|-$/g, '')
48
49 const getAnchor = (text: string) => {
50 const slug = slugify(text)
51 const count = slugCounts.get(slug) ?? 0
52 slugCounts.set(slug, count + 1)
53 return count === 0 ? slug : `${slug}-${count}`
54 }
55
56 const setHeading = (level: number, text: string) => {
57 headingStack[level] = text
58 headingStack.length = level + 1
59 currentAnchor = getAnchor(text)
60 }
61
62 const getActiveTab = () =>
63 tabStack.length ? tabStack[tabStack.length - 1] : undefined
64
65 const getTitles = () => {
66 const tab = getActiveTab()
67 if (!tab) return headingStack.filter(Boolean)
68
69 const baseHeadings = tab.headings.filter(Boolean)
70 const nestedHeadings = headingStack
71 .slice(tab.headings.length)
72 .filter(Boolean)
73 return [...baseHeadings, tab.title, ...nestedHeadings]
74 }
75
76 for (let i = 0; i < lines.length; i++) {
77 const line = lines[i]
78
79 const containerOpenMatch = line.match(/^\s*:{3,}\s*([A-Za-z][\w-]*)\b/)
80 if (containerOpenMatch) {
81 containerStack.push(containerOpenMatch[1].toLowerCase())
82 } else if (/^\s*:{3,}\s*$/.test(line)) {
83 const closed = containerStack.pop()
84 if (closed === 'tabs') tabStack.pop()
85 }
86
87 const tabMatch = line.match(/^\s*==\s+(.+)$/)
88 if (tabMatch && containerStack.includes('tabs')) {
89 const title = tabMatch[1].trim()
90 if (title) {
91 const tab = getActiveTab()
92 if (tab) {
93 tab.title = title
94 tab.headings = [...headingStack]
95 } else {
96 tabStack.push({ title, headings: [...headingStack] })
97 }
98 }
99 continue
100 }
101
102 const collapsibleMatch = line.match(
103 /^\s*<Collapsible\b(?=[^>]*\btitle=(['"])(.*?)\1)[^>]*>\s*$/i
104 )
105 if (collapsibleMatch) {
106 collapsibleStack.push({
107 anchor: currentAnchor,
108 headings: [...headingStack]
109 })
110
111 let nextLine = i + 1
112 while (nextLine < lines.length && lines[nextLine].trim() === '') {
113 nextLine++
114 }
115
116 // The markdown renderer injects a searchable H3 for collapsibles that
117 // don't already start with a heading. Mirror that anchor so URL search
118 // can deep-link into and auto-open those collapsibles.
119 if (!/^#{1,6}\s+/.test(lines[nextLine]?.trim() ?? '')) {
120 setHeading(2, collapsibleMatch[2].trim())
121 }
122 continue
123 }
124
125 if (/^\s*<\/Collapsible>\s*$/i.test(line)) {
126 const previous = collapsibleStack.pop()
127 if (previous) {
128 currentAnchor = previous.anchor
129 headingStack.length = 0
130 headingStack.push(...previous.headings)
131 }
132 continue
133 }
134
135 // Heading: ## Title or === Title (setext-style ignored, ATX only)
136 const headingMatch = line.match(/^(#{1,6})\s+(.+)/)
137 if (headingMatch) {
138 const level = headingMatch[1].length - 1
139 const text = headingMatch[2].trim()
140 setHeading(level, text)
141 continue
142 }
143
144 // Markdown links: [text](https://...)
145 const linkRE = /\[([^\]]*)\]\((https?:\/\/[^)]+)\)/g
146 let m: RegExpExecArray | null
147 while ((m = linkRE.exec(line)) !== null) {
148 const linkText = renderEmojiShortcodes(m[1].trim())
149 const href = m[2].trim()
150 const key = href + '\x00' + currentAnchor
151 if (seen.has(key)) continue
152 seen.add(key)
153 results.push({
154 href,
155 linkText,
156 pageId,
157 anchor: currentAnchor,
158 titles: getTitles()
159 })
160 }
161
162 // Bare angle-bracket URLs: <https://...>
163 const bareRE = /<(https?:\/\/[^>]+)>/g
164 while ((m = bareRE.exec(line)) !== null) {
165 const href = m[1].trim()
166 const key = href + '\x00' + currentAnchor
167 if (seen.has(key)) continue
168 seen.add(key)
169 results.push({
170 href,
171 linkText: href,
172 pageId,
173 anchor: currentAnchor,
174 titles: getTitles()
175 })
176 }
177 }
178
179 return results
180}
181
182const collectedByPage = new Map<string, PageLink[]>()
183
184function getPageId(page: string) {
185 return '/' + page.replace(/\.md$/, '').replace(/\/index$/, '/')
186}
187
188function getDedupedLinks() {
189 const seen = new Set<string>()
190 const deduped: PageLink[] = []
191
192 for (const links of collectedByPage.values()) {
193 for (const link of links) {
194 const key = link.href + '\x00' + link.pageId + '\x00' + link.anchor
195 if (seen.has(key)) continue
196 seen.add(key)
197 deduped.push(link)
198 }
199 }
200
201 return deduped
202}
203
204export function collectPageLinks(src: string, page: string) {
205 const pageId = getPageId(page)
206 collectedByPage.set(pageId, extractLinksFromMarkdown(src, pageId))
207}
208
209export function writeUrlSearchIndex(outDir: string) {
210 const deduped = getDedupedLinks()
211 const outPath = join(outDir, 'url-search-index.json')
212 writeFileSync(outPath, JSON.stringify(deduped), 'utf-8')
213 console.log(`[url-search] wrote ${deduped.length} links → ${outPath}`)
214}
215
216export function urlSearchDevPlugin() {
217 return {
218 name: 'url-search-dev',
219 configureServer(server: any) {
220 server.middlewares.use(
221 '/url-search-index.json',
222 (_req: any, res: any) => {
223 const deduped = getDedupedLinks()
224 res.setHeader('Content-Type', 'application/json')
225 res.end(JSON.stringify(deduped))
226 }
227 )
228 }
229 }
230}