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

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

93 lines · 2588 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 { tabsMarkdownPlugin } from 'vitepress-plugin-tabs'
18import { getTooltip } from '../../utils/tooltips'
19import { headersPlugin } from '../markdown/headers'
20import { emojiRender } from './emoji'
21import markdownSteps from './steps'
22
23export function configureMarkdown(md: MarkdownRenderer) {
24  md.use(emojiRender)
25  md.use(imgLazyload)
26  md.use(align)
27  md.use(figure)
28  md.use(tabsMarkdownPlugin)
29  md.use(imgSize)
30  md.use(headersPlugin)
31  md.use(MdMTables, {
32    multiline: true,
33    rowspan: true,
34    headerless: true,
35    multibody: true,
36    aotolabel: true
37  })
38  md.use(attrs)
39  renderTooltip(md)
40  renderInlineTooltip(md)
41  md.use(markdownSteps)
42}
43
44function renderInlineTooltip(md: MarkdownRenderer) {
45  md.use(
46    MdReg(
47      /\^\[(.*?)\]\((.+?)\)/,
48      ([, cont, hint]: string[]) =>
49        '<VTooltip theme="hint">' +
50        span(md.renderInline(cont)) +
51        '<template v-slot:popper>' +
52        md.renderInline(hint) +
53        '</template></VTooltip>'
54    )
55  )
56}
57
58function renderTooltip(md: MarkdownRenderer) {
59  md.use(
60    MdReg(/==(.+?)==/, ([, cont]: string[]) => {
61      const item = getTooltip(cont)
62      if (!item) return `No tooltip found for ${cont}`
63
64      const icon = item.frontmatter.icon
65        ? `icon="${item.frontmatter.icon}"`
66        : ''
67
68      const title = item.frontmatter.title
69        ? `title="${item.frontmatter.title}"`
70        : item.id
71        ? `title="${item.id}"`
72        : '' /** Impossible */
73      const props = icon + title
74      const renderedContent = md.render(item.content)
75
76      return `<Tooltip ${props}>` + renderedContent + '</Tooltip>'
77    })
78  )
79}
80
81function span(
82  content: string,
83  attrs: Record<string, unknown> | undefined = undefined
84) {
85  let html = '<span'
86  if (attrs) {
87    for (const [key, value] of Object.entries(attrs)) {
88      html += ` ${key}="${value}"`
89    }
90  }
91  html += `>${content}</span>`
92  return html
93}