docs/.vitepress/configs/markdown/headers.ts

df7665701ac3fc34240e0d1b8b6dd2d4d8fb6b24
wotaku/docs/.vitepress/configs/markdown/headers.ts history · blame · raw

67 lines · 2223 bytes

 1/**
 2 *  Copyright (c) 2024 taskylizard
 3 *
 4 *  Licensed under the Apache License, Version 2.0 (the "License");
 5 *  you may not use this file except in compliance with the License.
 6 *  You may obtain a copy of the License at
 7 *
 8 *  http://www.apache.org/licenses/LICENSE-2.0
 9 *
10 *  Unless required by applicable law or agreed to in writing, software
11 *  distributed under the License is distributed on an "AS IS" BASIS,
12 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 *  See the License for the specific language governing permissions and
14 *  limitations under the License.
15 */
16import type { MarkdownRenderer } from 'vitepress'
17
18const excluded = ['Credits']
19
20export const headersPlugin = (md: MarkdownRenderer) => {
21  // Add the Feedback component in the heading, before the link.
22  //
23  // Adding it after the link is closed prevents vitepress from properly
24  // indexing the file's content.
25
26  md.renderer.rules.heading_open = (tokens, idx, options, env, self) => {
27    const result = self.renderToken(tokens, idx, options)
28
29    const idxClose =
30      idx +
31      tokens.slice(idx).findIndex((token) => token.type === 'heading_close')
32    if (idxClose <= idx) return result
33
34    const level = tokens[idx].tag.slice(1)
35    if (excluded.includes(env.frontmatter.title) || level !== '2') return result
36
37    // Find the token for the link.
38    //
39    // The token after `heading_open` contains the link as a child token.
40    const children = tokens[idx + 1].children || []
41    const linkOpenToken = children.findLast((c) => c.type === 'link_open')
42    if (!linkOpenToken) return result
43
44    const heading = tokens[idxClose - 1]
45
46    linkOpenToken.meta = linkOpenToken.meta || {}
47    linkOpenToken.meta.feedback = {
48      heading: heading.content
49    }
50
51    return result
52  }
53
54  let defaultRender = md.renderer.rules.link_open as any
55
56  md.renderer.rules.link_open = (tokens, idx, options, env, self) => {
57    const result = defaultRender(tokens, idx, options, env, self)
58
59    const meta = tokens[idx].meta
60    if (!meta || !meta.feedback) return result
61
62    const heading = meta.feedback.heading || ''
63    if (!heading) return result
64
65    return `<Feedback heading="${heading}" />${result}`
66  }
67}