docs/.vitepress/plugins/urlSearchPlugin.ts

9c6588973e856dbc27ebb283f0d963c792faa8df
wotaku/docs/.vitepress/plugins/urlSearchPlugin.ts history · blame · raw

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