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

60a7fce7b2109cbc76b51e5e91b4105f6f4e3756
wotaku/docs/.vitepress/configs/markdown/index.ts

83 lines · 2236 bytes

 1import MdMTables from 'markdown-it-multimd-table'
 2// @ts-expect-error
 3import MdReg from 'markdown-it-regexp'
 4import type { MarkdownRenderer } from 'vitepress'
 5import { headersPlugin } from '../markdown/headers'
 6import { figure } from '@mdit/plugin-figure'
 7import { imgLazyload } from '@mdit/plugin-img-lazyload'
 8import { align } from '@mdit/plugin-align'
 9import { imgSize } from '@mdit/plugin-img-size'
10import { tabsMarkdownPlugin } from 'vitepress-plugin-tabs'
11import { emojiRender } from './emoji'
12import { getTooltip } from '../../utils/tooltips'
13import { attrs } from '@mdit/plugin-attrs'
14
15export function configureMarkdown(md: MarkdownRenderer) {
16  md.use(emojiRender)
17  md.use(imgLazyload)
18  md.use(align)
19  md.use(figure)
20  md.use(tabsMarkdownPlugin)
21  md.use(imgSize)
22  md.use(headersPlugin)
23  md.use(MdMTables, {
24    multiline: true,
25    rowspan: true,
26    headerless: true,
27    multibody: true,
28    aotolabel: true
29  })
30  md.use(attrs)
31  renderTooltip(md)
32  renderInlineTooltip(md)
33}
34
35function renderInlineTooltip(md: MarkdownRenderer) {
36  md.use(
37    MdReg(
38      /\^\[(.*?)\]\((.+?)\)/,
39      ([, cont, hint]: string[]) =>
40        '<VTooltip theme="hint">' +
41        span(md.renderInline(cont)) +
42        '<template v-slot:popper>' +
43        md.renderInline(hint) +
44        '</template></VTooltip>'
45    )
46  )
47}
48
49function renderTooltip(md: MarkdownRenderer) {
50  md.use(
51    MdReg(/==(.+?)==/, ([, cont]: string[]) => {
52      const item = getTooltip(cont)
53      if (!item) return `No tooltip found for ${cont}`
54
55      const icon = item.frontmatter.icon
56        ? `icon="${item.frontmatter.icon}"`
57        : ''
58
59      const title = item.frontmatter.title
60        ? `title="${item.frontmatter.title}"`
61        : item.id
62          ? `title="${item.id}"`
63          : '' /** Impossible */
64      const props = icon + title
65      const renderedContent = md.render(item.content)
66
67      return `<Tooltip ${props}>` + renderedContent + '</Tooltip>'
68    })
69  )
70}
71
72function span(
73  content: string,
74  attrs: Record<string, unknown> | undefined = undefined
75) {
76  let html = '<span'
77  if (attrs)
78    for (const [key, value] of Object.entries(attrs)) {
79      html += ` ${key}="${value}"`
80    }
81  html += `>${content}</span>`
82  return html
83}