docs/.vitepress/plugins/urlSearchPlugin.ts

29fae34075541b9056536846db51ac39afbc3e91
wotaku/docs/.vitepress/plugins/urlSearchPlugin.ts history · blame · raw

188 lines · 5207 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 collapsibleStack: {
 19    anchor: string
 20    headings: string[]
 21  }[] = []
 22  let currentAnchor = ''
 23
 24  // Strip frontmatter
 25  const body = src.startsWith('---')
 26    ? src.replace(/^---[\s\S]*?---\n?/, '')
 27    : src
 28  const lines = body.split('\n')
 29
 30  const slugify = (value: string) =>
 31    value
 32      .replace(/\{[^}]*\}\s*$/, '')
 33      .replace(/<[^>]*>/g, '')
 34      .replace(/`([^`]+)`/g, '$1')
 35      .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
 36      .replace(/[*_~]/g, '')
 37      .trim()
 38      .toLowerCase()
 39      .replace(/[^\w\s-]/g, '')
 40      .replace(/\s+/g, '-')
 41      .replace(/-+/g, '-')
 42      .replace(/^-|-$/g, '')
 43
 44  const getAnchor = (text: string) => {
 45    const slug = slugify(text)
 46    const count = slugCounts.get(slug) ?? 0
 47    slugCounts.set(slug, count + 1)
 48    return count === 0 ? slug : `${slug}-${count}`
 49  }
 50
 51  const setHeading = (level: number, text: string) => {
 52    headingStack[level] = text
 53    headingStack.length = level + 1
 54    currentAnchor = getAnchor(text)
 55  }
 56
 57  for (let i = 0; i < lines.length; i++) {
 58    const line = lines[i]
 59
 60    const collapsibleMatch = line.match(
 61      /^\s*<Collapsible\b(?=[^>]*\btitle=(['"])(.*?)\1)[^>]*>\s*$/i
 62    )
 63    if (collapsibleMatch) {
 64      collapsibleStack.push({
 65        anchor: currentAnchor,
 66        headings: [...headingStack]
 67      })
 68
 69      let nextLine = i + 1
 70      while (nextLine < lines.length && lines[nextLine].trim() === '') {
 71        nextLine++
 72      }
 73
 74      // The markdown renderer injects a searchable H3 for collapsibles that
 75      // don't already start with a heading. Mirror that anchor so URL search
 76      // can deep-link into and auto-open those collapsibles.
 77      if (!/^#{1,6}\s+/.test(lines[nextLine]?.trim() ?? '')) {
 78        setHeading(2, collapsibleMatch[2].trim())
 79      }
 80      continue
 81    }
 82
 83    if (/^\s*<\/Collapsible>\s*$/i.test(line)) {
 84      const previous = collapsibleStack.pop()
 85      if (previous) {
 86        currentAnchor = previous.anchor
 87        headingStack.length = 0
 88        headingStack.push(...previous.headings)
 89      }
 90      continue
 91    }
 92
 93    // Heading: ## Title or === Title (setext-style ignored, ATX only)
 94    const headingMatch = line.match(/^(#{1,6})\s+(.+)/)
 95    if (headingMatch) {
 96      const level = headingMatch[1].length - 1
 97      const text = headingMatch[2].trim()
 98      setHeading(level, text)
 99      continue
100    }
101
102    // Markdown links: [text](https://...)
103    const linkRE = /\[([^\]]*)\]\((https?:\/\/[^)]+)\)/g
104    let m: RegExpExecArray | null
105    while ((m = linkRE.exec(line)) !== null) {
106      const linkText = renderEmojiShortcodes(m[1].trim())
107      const href = m[2].trim()
108      const key = href + '\x00' + currentAnchor
109      if (seen.has(key)) continue
110      seen.add(key)
111      results.push({
112        href,
113        linkText,
114        pageId,
115        anchor: currentAnchor,
116        titles: headingStack.filter(Boolean)
117      })
118    }
119
120    // Bare angle-bracket URLs: <https://...>
121    const bareRE = /<(https?:\/\/[^>]+)>/g
122    while ((m = bareRE.exec(line)) !== null) {
123      const href = m[1].trim()
124      const key = href + '\x00' + currentAnchor
125      if (seen.has(key)) continue
126      seen.add(key)
127      results.push({
128        href,
129        linkText: href,
130        pageId,
131        anchor: currentAnchor,
132        titles: headingStack.filter(Boolean)
133      })
134    }
135  }
136
137  return results
138}
139
140const collectedByPage = new Map<string, PageLink[]>()
141
142function getPageId(page: string) {
143  return '/' + page.replace(/\.md$/, '').replace(/\/index$/, '/')
144}
145
146function getDedupedLinks() {
147  const seen = new Set<string>()
148  const deduped: PageLink[] = []
149
150  for (const links of collectedByPage.values()) {
151    for (const link of links) {
152      const key = link.href + '\x00' + link.pageId + '\x00' + link.anchor
153      if (seen.has(key)) continue
154      seen.add(key)
155      deduped.push(link)
156    }
157  }
158
159  return deduped
160}
161
162export function collectPageLinks(src: string, page: string) {
163  const pageId = getPageId(page)
164  collectedByPage.set(pageId, extractLinksFromMarkdown(src, pageId))
165}
166
167export function writeUrlSearchIndex(outDir: string) {
168  const deduped = getDedupedLinks()
169  const outPath = join(outDir, 'url-search-index.json')
170  writeFileSync(outPath, JSON.stringify(deduped), 'utf-8')
171  console.log(`[url-search] wrote ${deduped.length} links → ${outPath}`)
172}
173
174export function urlSearchDevPlugin() {
175  return {
176    name: 'url-search-dev',
177    configureServer(server: any) {
178      server.middlewares.use(
179        '/url-search-index.json',
180        (_req: any, res: any) => {
181          const deduped = getDedupedLinks()
182          res.setHeader('Content-Type', 'application/json')
183          res.end(JSON.stringify(deduped))
184        }
185      )
186    }
187  }
188}