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