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

311 lines · 9450 bytes

10 symbols in this file
  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 { getMirror } from '../../utils/mirrors'
 18import {
 19  getCollapsibleHeadingAnchor,
 20  getTabAnchor,
 21  getTabHeadingAnchor,
 22  getUniqueAnchor,
 23  parseTabLabel
 24} from '../../utils/tabAnchors'
 25import { getTooltip } from '../../utils/tooltips'
 26import { headersPlugin } from '../markdown/headers'
 27import { emojiRender } from './emoji'
 28import { extRepoPlugin } from './extRepoPlugin'
 29import { nestedContainersPlugin } from './nestedContainers'
 30import { scrapeTablePlugin } from './scrapeTablePlugin'
 31import markdownSteps from './steps'
 32import { tableMorePlugin } from './tableMore'
 33import { tabsMarkdownPlugin } from './tabs'
 34import { themeRepoPlugin } from './themeRepoPlugin'
 35
 36export function configureMarkdown(md: MarkdownRenderer) {
 37  md.use(emojiRender)
 38  md.use(imgLazyload)
 39  md.use(align)
 40  md.use(figure)
 41  md.use(tabsMarkdownPlugin)
 42  md.use(nestedContainersPlugin)
 43  md.use(imgSize)
 44  md.use(headersPlugin)
 45  md.use(MdMTables, {
 46    multiline: true,
 47    rowspan: true,
 48    headerless: true,
 49    multibody: true,
 50    aotolabel: true
 51  })
 52  md.use(attrs)
 53  renderMirrorTooltip(md)
 54  renderLibrarySize(md)
 55  renderTooltip(md)
 56  renderInlineTooltip(md)
 57  md.use(markdownSteps)
 58  md.use(tableMorePlugin)
 59  md.use(scrapeTablePlugin)
 60  md.use(extRepoPlugin)
 61  md.use(themeRepoPlugin)
 62  renderHighlight(md)
 63}
 64
 65function renderLibrarySize(md: MarkdownRenderer) {
 66  md.use(
 67    MdReg(/==l:(.+?)==/, ([, name]: string[]) => {
 68      const site = name.trim().replace(/"/g, '"')
 69      return `<LibrarySize name="${site}" />`
 70    })
 71  )
 72}
 73
 74function renderInlineTooltip(md: MarkdownRenderer) {
 75  md.use(
 76    MdReg(
 77      /\^\[(.*?)\]\((.+?)\)/,
 78      ([, cont, hint]: string[]) =>
 79        '<VTooltip theme="hint">' +
 80        span(md.renderInline(cont)) +
 81        '<template v-slot:popper>' +
 82        md.renderInline(hint) +
 83        '</template></VTooltip>'
 84    )
 85  )
 86}
 87
 88function renderMirrorTooltip(md: MarkdownRenderer) {
 89  md.use(
 90    MdReg(/==m:(.+?)==/, ([, cont]: string[]) => {
 91      const id = cont.trim()
 92
 93      if (/^https?:\/\/\S+$/i.test(id)) {
 94        const safeUrl = id.replace(/"/g, '&quot;')
 95        return `<a href="${safeUrl}" target="_blank" rel="noopener noreferrer"><span class="icon-tip" data-tip="Mirrors" tabindex="-1"><span class="i-material-symbols-directions-alt"></span></span></a>`
 96      }
 97
 98      const item = getMirror(id)
 99      if (!item) return `No mirror found for ${id}`
100
101      const title = (item.title || item.id).replace(/"/g, '&quot;')
102      const src = (item.src || '').replace(/"/g, '&quot;')
103      const note = (item.note || '').replace(/"/g, '&quot;')
104      const mirrorsAttr = JSON.stringify(item.mirrors).replace(/'/g, '&#39;')
105
106      return `<MirrorTooltip id="${id}" title="${title}" src="${src}" note="${note}" note-type="${item.noteType}" mirrors='${mirrorsAttr}' />`
107    })
108  )
109}
110
111function renderTooltip(md: MarkdownRenderer) {
112  md.use(
113    MdReg(/==(.+?)==/, ([, cont]: string[]) => {
114      const item = getTooltip(cont)
115      if (!item) return `No tooltip found for ${cont}`
116
117      const icon = item.frontmatter.icon
118        ? `icon="${item.frontmatter.icon}"`
119        : ''
120
121      const title = item.frontmatter.title
122        ? `title="${item.frontmatter.title}"`
123        : item.id
124        ? `title="${item.id}"`
125        : '' /** Impossible */
126      const props = icon + title
127      const renderedContent = md.render(item.content)
128
129      return `<Tooltip ${props}>` + renderedContent + '</Tooltip>'
130    })
131  )
132}
133
134function span(
135  content: string,
136  attrs: Record<string, unknown> | undefined = undefined
137) {
138  let html = '<span'
139  if (attrs) {
140    for (const [key, value] of Object.entries(attrs)) {
141      html += ` ${key}="${value}"`
142    }
143  }
144  html += `>${content}</span>`
145  return html
146}
147
148function renderHighlight(md: MarkdownRenderer) {
149  const original = md.render.bind(md)
150  md.render = (src, env) => {
151    const withSearchHeadings = injectSearchHeadings(src)
152
153    // Replace [||text||](url) — linked pill
154    let replaced = withSearchHeadings.replace(
155      /\[([!x]?)\|\|(.+?)\|\|\]\((.+?)\)/g,
156      (_, prefix, cont, url) => {
157        const variant = prefix === '!'
158          ? 'warning'
159          : prefix === 'x'
160          ? 'danger'
161          : 'default'
162        const inner = md.renderInline(cont, env)
163        return `<a href="${url}" target="_blank" rel="noopener noreferrer"><hl variant="${variant}" linked="true">${inner}</hl></a>`
164      }
165    )
166    // Replace standalone ||text||
167    replaced = replaced.replace(/([!x]?)\|\|(.+?)\|\|/g, (_, prefix, cont) => {
168      const variant = prefix === '!'
169        ? 'warning'
170        : prefix === 'x'
171        ? 'danger'
172        : 'default'
173      return `<hl variant="${variant}">${md.renderInline(cont, env)}</hl>`
174    })
175    return original(replaced, env)
176  }
177}
178
179interface SearchHeading {
180  level: number
181  title: string
182}
183
184function getHeadingTitle(value: string) {
185  return value.replace(/\s+\{[^}]*\}\s*$/, '').trim()
186}
187
188function injectSearchHeadings(src: string) {
189  const lines = src.split('\n')
190  const containerStack: string[] = []
191  const headingStack: (SearchHeading | undefined)[] = []
192  const tabResetStack: (SearchHeading | undefined)[] = []
193  const tabAnchorCounts = new Map<string, number>()
194  const collapsibleAnchorCounts = new Map<string, number>()
195  const getCurrentHeading = () => {
196    for (let i = headingStack.length - 1; i >= 0; i--) {
197      if (headingStack[i]) return headingStack[i]
198    }
199  }
200  const isHeadingLine = (line: string | undefined) =>
201    /^#{1,6}\s+/.test(line?.trim() ?? '')
202
203  for (let i = 0; i < lines.length; i++) {
204    const headingMatch = lines[i].match(/^(#{1,6})\s+(.+)/)
205    if (headingMatch && !containerStack.includes('tabs')) {
206      const level = headingMatch[1].length
207      const title = getHeadingTitle(headingMatch[2])
208      if (title) {
209        headingStack[level - 1] = { level, title }
210        headingStack.length = level
211      }
212    }
213
214    const containerOpenMatch = lines[i].match(
215      /^\s*:{3,}\s*([A-Za-z][\w-]*)\b/
216    )
217    if (containerOpenMatch) {
218      const containerName = containerOpenMatch[1].toLowerCase()
219      containerStack.push(containerName)
220      if (containerName === 'tabs') tabResetStack.push(getCurrentHeading())
221    } else if (/^\s*:{3,}\s*$/.test(lines[i])) {
222      const closed = containerStack.pop()
223      if (closed === 'tabs') {
224        const resetHeading = tabResetStack.pop()
225        let nextLine = i + 1
226        while (nextLine < lines.length && lines[nextLine].trim() === '') {
227          nextLine++
228        }
229
230        if (
231          resetHeading && nextLine < lines.length &&
232          !isHeadingLine(lines[nextLine])
233        ) {
234          const indent = lines[i].match(/^(\s*):{3,}\s*$/)?.[1] ?? ''
235          lines.splice(
236            i + 1,
237            0,
238            '',
239            `${indent}${
240              '#'.repeat(resetHeading.level)
241            } ${resetHeading.title} {.tab-search-heading .ignore-header}`,
242            ''
243          )
244          i += 3
245        }
246      }
247      continue
248    }
249
250    const tabMatch = lines[i].match(/^(\s*)==\s+(.+)$/)
251    if (tabMatch && containerStack.includes('tabs')) {
252      const [, indent, title] = tabMatch
253      const parsed = parseTabLabel(title)
254      const headingTitle = parsed.label
255      if (!headingTitle) continue
256      const anchor = getTabAnchor(title, tabAnchorCounts)
257      const headingAnchor = getTabHeadingAnchor(anchor)
258
259      lines.splice(
260        i + 1,
261        0,
262        '',
263        `${indent}### ${headingTitle} {#${headingAnchor} .tab-search-heading .ignore-header}`,
264        ''
265      )
266      i += 3
267      continue
268    }
269
270    const match = lines[i].match(
271      /^(\s*)<Collapsible\b(?=[^>]*\btitle=(['"])(.*?)\2)[^>]*>\s*$/i
272    )
273    if (!match) continue
274
275    const [, indent, , rawTitle] = match
276    const parsedTitle = parseTabLabel(rawTitle)
277    const headingTitle = parsedTitle.label
278    if (!headingTitle) continue
279
280    const collapsibleAnchor = parsedTitle.anchor ||
281      getUniqueAnchor(headingTitle, collapsibleAnchorCounts)
282
283    lines[i] = lines[i].replace(
284      /(<Collapsible\b[^>]*?\btitle=)(['"]).*?\2/i,
285      (_full, pre: string, quote: string) =>
286        `${pre}${quote}${headingTitle}${quote} anchor=${quote}${collapsibleAnchor}${quote}`
287    )
288
289    let nextLine = i + 1
290    while (nextLine < lines.length && lines[nextLine].trim() === '') {
291      nextLine++
292    }
293
294    if (/^#{1,6}\s+/.test(lines[nextLine]?.trim() ?? '')) continue
295
296    const headingLevel = containerStack.includes('tabs') ? 4 : 3
297
298    lines.splice(
299      i + 1,
300      0,
301      '',
302      `${indent}${'#'.repeat(headingLevel)} ${headingTitle} {#${
303        getCollapsibleHeadingAnchor(collapsibleAnchor)
304      } .collapsible-search-heading}`,
305      ''
306    )
307    i += 3
308  }
309
310  return lines.join('\n')
311}