|
1 | 1 | import { toString } from "hast-util-to-string"; |
2 | 2 | import { visit } from "unist-util-visit"; |
3 | 3 | import GithubSlugger from "github-slugger"; |
| 4 | +import type { Root } from "hast"; |
| 5 | +import type { MdxTextExpression } from "mdast-util-mdx-expression"; |
4 | 6 |
|
5 | 7 | const slugs = new GithubSlugger(); |
6 | 8 |
|
7 | 9 | // # foo {/*bar*/} = <a id="bar">foo</a> |
8 | 10 | export default function () { |
9 | | - return function (tree: any) { |
| 11 | + return function (tree: Root) { |
10 | 12 | slugs.reset(); |
11 | 13 |
|
12 | | - visit(tree, "element", function (element: any) { |
| 14 | + visit(tree, "element", function (element) { |
13 | 15 | if (/^h[1-6]$/.test(element.tagName)) { |
14 | 16 | const last = element.children.at(-1); |
15 | 17 |
|
16 | | - if ( |
17 | | - last.type === "mdxTextExpression" && |
18 | | - last.value.startsWith("/*") && |
19 | | - last.value.endsWith("*/") |
20 | | - ) { |
21 | | - const id = last.value.slice(2, -2).trim(); |
22 | | - element.properties.id = slugs.slug(id); |
| 18 | + // @ts-expect-error this is added by mdast-util-mdx-expression |
| 19 | + if (last.type === "mdxTextExpression") { |
| 20 | + const lastElement = last as MdxTextExpression; |
| 21 | + if ( |
| 22 | + lastElement.value.startsWith("/*") && |
| 23 | + lastElement.value.endsWith("*/") |
| 24 | + ) { |
| 25 | + const id = lastElement.value.slice(2, -2).trim(); |
| 26 | + element.properties.id = slugs.slug(id); |
23 | 27 |
|
24 | | - const text = element.children.at(-2); |
25 | | - text.value = text.value.trimEnd(); |
26 | | - element.children.with(-2, text); |
27 | | - } else { |
28 | | - if (!element.properties.id) { |
29 | | - element.properties.id = slugs.slug(toString(element)); |
| 28 | + const text = element.children.at(-2) as MdxTextExpression; |
| 29 | + text.value = text.value.trimEnd(); |
| 30 | + element.children.with(-2, text); |
| 31 | + } else { |
| 32 | + if (!element.properties.id) { |
| 33 | + element.properties.id = slugs.slug(toString(element)); |
| 34 | + } |
30 | 35 | } |
31 | 36 | } |
32 | 37 | } |
|
0 commit comments