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

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

59 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 =
22      idx +
23      tokens.slice(idx).findIndex((token) => token.type === 'heading_close')
24    if (idxClose <= idx) return result
25
26    const level = tokens[idx].tag.slice(1)
27    if (excluded.includes(env.frontmatter.title) || level !== '2') return result
28
29    // Find the token for the link.
30    //
31    // The token after `heading_open` contains the link as a child token.
32    const children = tokens[idx + 1].children || []
33    const linkOpenToken = children.findLast((c) => c.type === 'link_open')
34    if (!linkOpenToken) return result
35
36    const heading = tokens[idxClose - 1]
37
38    linkOpenToken.meta = linkOpenToken.meta || {}
39    linkOpenToken.meta.feedback = {
40      heading: heading.content
41    }
42
43    return result
44  }
45
46  let defaultRender = md.renderer.rules.link_open as any
47
48  md.renderer.rules.link_open = (tokens, idx, options, env, self) => {
49    const result = defaultRender(tokens, idx, options, env, self)
50
51    const meta = tokens[idx].meta
52    if (!meta || !meta.feedback) return result
53
54    const heading = meta.feedback.heading || ''
55    if (!heading) return result
56
57    return `<Feedback heading="${heading}" />${result}`
58  }
59}