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

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

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