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

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

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form