File size: 779 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import { visit } from "unist-util-visit"

export function remarkCodeTitle() {
  return (tree: any, file: any) => {
    visit(tree, "code", (node, index, parent) => {
      const metaString = `${node.lang ?? ""} ${node.meta ?? ""}`.trim()

      if (!metaString) return
      const [title] = metaString.match(/(?<=title=("|'))(.*?)(?=("|'))/) ?? [""]

      if (!title && metaString.includes("title=")) {
        file.message("Invalid title", node, "remark-code-title")
        return
      }

      if (!title) return

      parent.children.splice(index, 1, {
        type: "paragraph",
        children: [node],
        data: {
          hName: "code-block",
          hProperties: {
            title,
            lang: node.lang,
          },
        },
      })
    })
  }
}