docs/.vitepress/configs/markdown/scrapeTablePlugin.ts

33a4e4c6fa7d78deb08b14d2b151ff82c28e461a
wotaku/docs/.vitepress/configs/markdown/scrapeTablePlugin.ts history · blame · raw

168 lines · 4754 bytes

  1import type MarkdownIt from 'markdown-it'
  2
  3// Types
  4
  5interface ParsedEntry {
  6  source: string
  7  metadata: string[]
  8}
  9
 10interface ParsedSite {
 11  name: string
 12  entries: ParsedEntry[]
 13}
 14
 15interface ParsedBlock {
 16  cornerLabel: string | null
 17  sites: ParsedSite[]
 18}
 19
 20// Parser
 21
 22function parseCornerLabel(info: string): string | null {
 23  const match = info.match(/\{([^}]*)\}/)
 24  return match ? match[1].trim() || null : null
 25}
 26
 27function parseEntry(raw: string): ParsedEntry | null {
 28  const trimmed = raw.trim()
 29  if (!trimmed.startsWith('(') || !trimmed.endsWith(')')) return null
 30  const inner = trimmed.slice(1, -1)
 31  const parts = inner.split(',').map(s => s.trim()).filter(Boolean)
 32  if (parts.length === 0) return null
 33  const [source, ...metadata] = parts
 34  return { source, metadata }
 35}
 36
 37function parseSiteRow(line: string): ParsedSite | null {
 38  const match = line.match(/^-\s+(.+)$/)
 39  if (!match) return null
 40  const rest = match[1]
 41  const colonIdx = rest.indexOf(':')
 42  if (colonIdx === -1) return null
 43  const siteName = rest.slice(0, colonIdx).trim()
 44  if (!siteName) return null
 45  const entryStr = rest.slice(colonIdx + 1).replace(/;\s*$/, '').trim()
 46
 47  const rawEntries = entryStr
 48    .split(/\)\s*,\s*(?=\()/)
 49    .map(s => s.trim())
 50    .filter(Boolean)
 51    .map((s, i, arr) => (i < arr.length - 1 && !s.endsWith(')') ? s + ')' : s))
 52
 53  const entries: ParsedEntry[] = []
 54  for (const raw of rawEntries) {
 55    const entry = parseEntry(raw)
 56    if (entry) entries.push(entry)
 57  }
 58  return { name: siteName, entries }
 59}
 60
 61function parseBlock(info: string, body: string): ParsedBlock {
 62  const cornerLabel = parseCornerLabel(info)
 63  const sites: ParsedSite[] = []
 64  for (const line of body.split('\n')) {
 65    const site = parseSiteRow(line.trim())
 66    if (site) sites.push(site)
 67  }
 68  return { cornerLabel, sites }
 69}
 70
 71// Code generator
 72
 73function escStr(s: string): string {
 74  return s.replace(/\\/g, '\\\\').replace(/'/g, "\\'")
 75}
 76
 77function generateComponent(block: ParsedBlock): string {
 78  const sitesJson = JSON.stringify(
 79    block.sites.map(site => {
 80      const scrapes: Record<string, string | { name: string; metadata: string[] }> = {}
 81      for (const entry of site.entries) {
 82        const [playerName, ...tags] = entry.metadata
 83        if (!playerName) {
 84          scrapes[entry.source] = ""
 85        } else if (tags.length === 0) {
 86          scrapes[entry.source] = playerName
 87        } else {
 88          scrapes[entry.source] = { name: playerName, metadata: tags }
 89        }
 90      }
 91      return { name: site.name, scrapes }
 92    }),
 93    null,
 94    0,
 95  )
 96
 97  const cornerProp = block.cornerLabel
 98    ? ` corner-label="${escStr(block.cornerLabel)}"`
 99    : ''
100
101  return `<ScrapeTable${cornerProp} :sites='${sitesJson.replace(/'/g, "\\'")}' />\n`
102}
103
104// Plugin
105
106export function scrapeTablePlugin(md: MarkdownIt): void {
107
108  const MARKER = ':'
109  const MIN_MARKERS = 3
110  const NAME = 'scrapetable'
111
112  md.block.ruler.before(
113    'fence',
114    'scrape_table',
115    (state, startLine, endLine, silent) => {
116      let pos = state.bMarks[startLine] + state.tShift[startLine]
117      let max = state.eMarks[startLine]
118
119      // Count opening colons
120      let markerCount = 0
121      while (pos < max && state.src[pos] === MARKER) {
122        pos++
123        markerCount++
124      }
125      if (markerCount < MIN_MARKERS) return false
126
127      // Must be followed by optional space then "scrapetable"
128      const markup = state.src.slice(state.bMarks[startLine] + state.tShift[startLine], pos)
129      const params = state.src.slice(pos, max).trim()
130      if (!params.toLowerCase().startsWith(NAME)) return false
131
132      if (silent) return true
133
134      // Find closing fence (same or more colons)
135      let nextLine = startLine + 1
136      let found = false
137      while (nextLine < endLine) {
138        let p = state.bMarks[nextLine] + state.tShift[nextLine]
139        const m = state.eMarks[nextLine]
140        if (p < m && state.sCount[nextLine] < state.blkIndent) break
141
142        let cnt = 0
143        while (p < m && state.src[p] === MARKER) { p++; cnt++ }
144        if (cnt >= markerCount && state.src.slice(p, m).trim() === '') {
145          found = true
146          break
147        }
148        nextLine++
149      }
150
151      // Collect body lines
152      const bodyLines: string[] = []
153      for (let i = startLine + 1; i < nextLine; i++) {
154        bodyLines.push(state.src.slice(state.bMarks[i], state.eMarks[i]))
155      }
156      const body = bodyLines.join('\n')
157      const block = parseBlock(params, body)
158
159      const token = state.push('html_block', '', 0)
160      token.map = [startLine, nextLine]
161      token.content = generateComponent(block)
162
163      state.line = found ? nextLine + 1 : nextLine
164      return true
165    },
166    { alt: ['paragraph', 'reference', 'blockquote', 'list'] }
167  )
168}