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

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

58 lines · 1901 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 type { MarkdownRenderer } from 'vitepress'
 9
10const excluded = ['Credits']
11
12export const headersPlugin = (md: MarkdownRenderer) => {
13  // Add the Feedback component in the heading, before the link.
14  //
15  // Adding it after the link is closed prevents vitepress from properly
16  // indexing the file's content.
17
18  md.renderer.rules.heading_open = (tokens, idx, options, env, self) => {
19    const result = self.renderToken(tokens, idx, options)
20
21    const idxClose = idx +
22      tokens.slice(idx).findIndex((token) => token.type === 'heading_close')
23    if (idxClose <= idx) return result
24
25    const level = tokens[idx].tag.slice(1)
26    if (excluded.includes(env.frontmatter.title) || level !== '2') return result
27
28    // Find the token for the link.
29    //
30    // The token after `heading_open` contains the link as a child token.
31    const children = tokens[idx + 1].children || []
32    const linkOpenToken = children.findLast((c) => c.type === 'link_open')
33    if (!linkOpenToken) return result
34
35    const heading = tokens[idxClose - 1]
36
37    linkOpenToken.meta = linkOpenToken.meta || {}
38    linkOpenToken.meta.feedback = {
39      heading: heading.content
40    }
41
42    return result
43  }
44
45  let defaultRender = md.renderer.rules.link_open as any
46
47  md.renderer.rules.link_open = (tokens, idx, options, env, self) => {
48    const result = defaultRender(tokens, idx, options, env, self)
49
50    const meta = tokens[idx].meta
51    if (!meta || !meta.feedback) return result
52
53    const heading = meta.feedback.heading || ''
54    if (!heading) return result
55
56    return `<Feedback heading="${heading}" />${result}`
57  }
58}