docs/.vitepress/configs/markdown/index.ts

9c6588973e856dbc27ebb283f0d963c792faa8df
wotaku/docs/.vitepress/configs/markdown/index.ts history · blame · raw

272 lines · 7960 bytes

  1/**
  2 *  All Rights Reserved
  3 *
  4 *  Copyright (c) 2025 taskylizard
  5 *
  6 *  All rights reserved. This code and its associated files may not be copied, modified, distributed, sublicensed, or used in any form, in whole or in part, without prior written permission from the copyright holder.
  7 */
  8import MdMTables from 'markdown-it-multimd-table'
  9// @ts-expect-error
 10import { align } from '@mdit/plugin-align'
 11import { attrs } from '@mdit/plugin-attrs'
 12import { figure } from '@mdit/plugin-figure'
 13import { imgLazyload } from '@mdit/plugin-img-lazyload'
 14import { imgSize } from '@mdit/plugin-img-size'
 15import MdReg from 'markdown-it-regexp'
 16import type { MarkdownRenderer } from 'vitepress'
 17import {
 18  getCollapsibleHeadingAnchor,
 19  getTabAnchor,
 20  getTabHeadingAnchor,
 21  getUniqueAnchor,
 22  parseTabLabel
 23} from '../../utils/tabAnchors'
 24import { getTooltip } from '../../utils/tooltips'
 25import { headersPlugin } from '../markdown/headers'
 26import { emojiRender } from './emoji'
 27import { nestedContainersPlugin } from './nestedContainers'
 28import { scrapeTablePlugin } from './scrapeTablePlugin'
 29import markdownSteps from './steps'
 30import { tabsMarkdownPlugin } from './tabs'
 31
 32export function configureMarkdown(md: MarkdownRenderer) {
 33  md.use(emojiRender)
 34  md.use(imgLazyload)
 35  md.use(align)
 36  md.use(figure)
 37  md.use(tabsMarkdownPlugin)
 38  md.use(nestedContainersPlugin)
 39  md.use(imgSize)
 40  md.use(headersPlugin)
 41  md.use(MdMTables, {
 42    multiline: true,
 43    rowspan: true,
 44    headerless: true,
 45    multibody: true,
 46    aotolabel: true
 47  })
 48  md.use(attrs)
 49  renderTooltip(md)
 50  renderInlineTooltip(md)
 51  md.use(markdownSteps)
 52  md.use(scrapeTablePlugin)
 53  renderHighlight(md)
 54}
 55
 56function renderInlineTooltip(md: MarkdownRenderer) {
 57  md.use(
 58    MdReg(
 59      /\^\[(.*?)\]\((.+?)\)/,
 60      ([, cont, hint]: string[]) =>
 61        '<VTooltip theme="hint">' +
 62        span(md.renderInline(cont)) +
 63        '<template v-slot:popper>' +
 64        md.renderInline(hint) +
 65        '</template></VTooltip>'
 66    )
 67  )
 68}
 69
 70function renderTooltip(md: MarkdownRenderer) {
 71  md.use(
 72    MdReg(/==(.+?)==/, ([, cont]: string[]) => {
 73      const item = getTooltip(cont)
 74      if (!item) return `No tooltip found for ${cont}`
 75
 76      const icon = item.frontmatter.icon
 77        ? `icon="${item.frontmatter.icon}"`
 78        : ''
 79
 80      const title = item.frontmatter.title
 81        ? `title="${item.frontmatter.title}"`
 82        : item.id
 83        ? `title="${item.id}"`
 84        : '' /** Impossible */
 85      const props = icon + title
 86      const renderedContent = md.render(item.content)
 87
 88      return `<Tooltip ${props}>` + renderedContent + '</Tooltip>'
 89    })
 90  )
 91}
 92
 93function span(
 94  content: string,
 95  attrs: Record<string, unknown> | undefined = undefined
 96) {
 97  let html = '<span'
 98  if (attrs) {
 99    for (const [key, value] of Object.entries(attrs)) {
100      html += ` ${key}="${value}"`
101    }
102  }
103  html += `>${content}</span>`
104  return html
105}
106
107function renderHighlight(md: MarkdownRenderer) {
108  const original = md.render.bind(md)
109  md.render = (src, env) => {
110    const withSearchHeadings = injectSearchHeadings(src)
111
112    // Replace [||text||](url) — linked pill
113    let replaced = withSearchHeadings.replace(
114      /\[([!x]?)\|\|(.+?)\|\|\]\((.+?)\)/g,
115      (_, prefix, cont, url) => {
116        const variant = prefix === '!'
117          ? 'warning'
118          : prefix === 'x'
119          ? 'danger'
120          : 'default'
121        const inner = md.renderInline(cont, env)
122        return `<a href="${url}" target="_blank" rel="noopener noreferrer"><hl variant="${variant}" linked="true">${inner}</hl></a>`
123      }
124    )
125    // Replace standalone ||text||
126    replaced = replaced.replace(/([!x]?)\|\|(.+?)\|\|/g, (_, prefix, cont) => {
127      const variant = prefix === '!'
128        ? 'warning'
129        : prefix === 'x'
130        ? 'danger'
131        : 'default'
132      return `<hl variant="${variant}">${md.renderInline(cont, env)}</hl>`
133    })
134    return original(replaced, env)
135  }
136}
137
138interface SearchHeading {
139  level: number
140  title: string
141}
142
143function getHeadingTitle(value: string) {
144  return value.replace(/\s+\{[^}]*\}\s*$/, '').trim()
145}
146
147function injectSearchHeadings(src: string) {
148  const lines = src.split('\n')
149  const containerStack: string[] = []
150  const headingStack: (SearchHeading | undefined)[] = []
151  const tabResetStack: (SearchHeading | undefined)[] = []
152  const tabAnchorCounts = new Map<string, number>()
153  const collapsibleAnchorCounts = new Map<string, number>()
154  const getCurrentHeading = () => {
155    for (let i = headingStack.length - 1; i >= 0; i--) {
156      if (headingStack[i]) return headingStack[i]
157    }
158  }
159  const isHeadingLine = (line: string | undefined) =>
160    /^#{1,6}\s+/.test(line?.trim() ?? '')
161
162  for (let i = 0; i < lines.length; i++) {
163    const headingMatch = lines[i].match(/^(#{1,6})\s+(.+)/)
164    if (headingMatch && !containerStack.includes('tabs')) {
165      const level = headingMatch[1].length
166      const title = getHeadingTitle(headingMatch[2])
167      if (title) {
168        headingStack[level - 1] = { level, title }
169        headingStack.length = level
170      }
171    }
172
173    const containerOpenMatch = lines[i].match(
174      /^\s*:{3,}\s*([A-Za-z][\w-]*)\b/
175    )
176    if (containerOpenMatch) {
177      const containerName = containerOpenMatch[1].toLowerCase()
178      containerStack.push(containerName)
179      if (containerName === 'tabs') tabResetStack.push(getCurrentHeading())
180    } else if (/^\s*:{3,}\s*$/.test(lines[i])) {
181      const closed = containerStack.pop()
182      if (closed === 'tabs') {
183        const resetHeading = tabResetStack.pop()
184        let nextLine = i + 1
185        while (nextLine < lines.length && lines[nextLine].trim() === '') {
186          nextLine++
187        }
188
189        if (
190          resetHeading && nextLine < lines.length &&
191          !isHeadingLine(lines[nextLine])
192        ) {
193          const indent = lines[i].match(/^(\s*):{3,}\s*$/)?.[1] ?? ''
194          lines.splice(
195            i + 1,
196            0,
197            '',
198            `${indent}${
199              '#'.repeat(resetHeading.level)
200            } ${resetHeading.title} {.tab-search-heading .ignore-header}`,
201            ''
202          )
203          i += 3
204        }
205      }
206      continue
207    }
208
209    const tabMatch = lines[i].match(/^(\s*)==\s+(.+)$/)
210    if (tabMatch && containerStack.includes('tabs')) {
211      const [, indent, title] = tabMatch
212      const parsed = parseTabLabel(title)
213      const headingTitle = parsed.label
214      if (!headingTitle) continue
215      const anchor = getTabAnchor(title, tabAnchorCounts)
216      const headingAnchor = getTabHeadingAnchor(anchor)
217
218      lines.splice(
219        i + 1,
220        0,
221        '',
222        `${indent}### ${headingTitle} {#${headingAnchor} .tab-search-heading .ignore-header}`,
223        ''
224      )
225      i += 3
226      continue
227    }
228
229    const match = lines[i].match(
230      /^(\s*)<Collapsible\b(?=[^>]*\btitle=(['"])(.*?)\2)[^>]*>\s*$/i
231    )
232    if (!match) continue
233
234    const [, indent, , rawTitle] = match
235    const parsedTitle = parseTabLabel(rawTitle)
236    const headingTitle = parsedTitle.label
237    if (!headingTitle) continue
238
239    const collapsibleAnchor = parsedTitle.anchor ||
240      getUniqueAnchor(headingTitle, collapsibleAnchorCounts)
241
242    lines[i] = lines[i].replace(
243      /(<Collapsible\b[^>]*?\btitle=)(['"]).*?\2/i,
244      (_full, pre: string, quote: string) =>
245        `${pre}${quote}${headingTitle}${quote} anchor=${quote}${collapsibleAnchor}${quote}`
246    )
247
248    let nextLine = i + 1
249    while (nextLine < lines.length && lines[nextLine].trim() === '') {
250      nextLine++
251    }
252
253    if (/^#{1,6}\s+/.test(lines[nextLine]?.trim() ?? '')) continue
254
255    const headingLevel = containerStack.includes('tabs') ? 4 : 3
256
257    lines.splice(
258      i + 1,
259      0,
260      '',
261      `${indent}${
262        '#'.repeat(headingLevel)
263      } ${headingTitle} {#${
264        getCollapsibleHeadingAnchor(collapsibleAnchor)
265      } .collapsible-search-heading}`,
266      ''
267    )
268    i += 3
269  }
270
271  return lines.join('\n')
272}