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

66 lines · 2034 bytes

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