|
1
|
import React from "react" |
|
2
|
import { MDXComponents } from "@/components/MDXComponents" |
|
3
|
import { MarkdownContent } from "@/components/MarkdownContent" |
|
4
|
|
|
5
|
type MdxComponentProps = React.HTMLAttributes<HTMLElement> & { |
|
6
|
href?: string |
|
7
|
} |
|
8
|
|
|
9
|
/** |
|
10
|
* The same components MDX pages use, so rendered references match their |
|
11
|
* styling (headings, inline code, links, lists, ...). |
|
12
|
*/ |
|
13
|
export const Mdx = MDXComponents as Record< |
|
14
|
string, |
|
15
|
React.ComponentType<MdxComponentProps> |
|
16
|
> |
|
17
|
|
|
18
|
/** |
|
19
|
* Block elements that must not render inside a heading. `p` is included so its |
|
20
|
* children unwrap inline (with `unwrapDisallowed`), and the list/blockquote/etc. |
|
21
|
* elements guard against any block markdown that slips through the escaping in |
|
22
|
* {@link escapeLeadingBlockMarker}. |
|
23
|
*/ |
|
24
|
const DISALLOWED_HEADING_ELEMENTS = [ |
|
25
|
"p", |
|
26
|
"ol", |
|
27
|
"ul", |
|
28
|
"li", |
|
29
|
"h1", |
|
30
|
"h2", |
|
31
|
"h3", |
|
32
|
"h4", |
|
33
|
"h5", |
|
34
|
"h6", |
|
35
|
"blockquote", |
|
36
|
"pre", |
|
37
|
"hr", |
|
38
|
"table", |
|
39
|
"thead", |
|
40
|
"tbody", |
|
41
|
"tr", |
|
42
|
"td", |
|
43
|
"th", |
|
44
|
"img", |
|
45
|
] |
|
46
|
|
|
47
|
/** |
|
48
|
* Escapes a leading markdown block marker so heading text isn't parsed as a |
|
49
|
* block — e.g. "1. Create ..." must stay literal text, not an ordered list. |
|
50
|
*/ |
|
51
|
function escapeLeadingBlockMarker(text: string): string { |
|
52
|
return text |
|
53
|
.replace(/^(\s*)(\d+)([.)])(\s)/, "$1$2\\$3$4") |
|
54
|
.replace(/^(\s*)([-*+>#])(\s)/, "$1\\$2$3") |
|
55
|
} |
|
56
|
|
|
57
|
/** |
|
58
|
* Renders a heading (h1–h4) with the shared MDX heading components. Heading |
|
59
|
* content is phrasing content in the MDX theme, so string text is rendered as |
|
60
|
* *inline* markdown (inline code, links) via {@link MarkdownContent} with block |
|
61
|
* elements disallowed and unwrapped. |
|
62
|
*/ |
|
63
|
export const DocHeading = ({ |
|
64
|
level, |
|
65
|
id, |
|
66
|
className, |
|
67
|
children, |
|
68
|
}: { |
|
69
|
level: number |
|
70
|
id?: string |
|
71
|
className?: string |
|
72
|
children: React.ReactNode |
|
73
|
}) => { |
|
74
|
const Heading = Mdx[`h${Math.min(Math.max(level, 1), 4)}`] |
|
75
|
const content = |
|
76
|
typeof children === "string" ? ( |
|
77
|
<MarkdownContent |
|
78
|
disallowedElements={DISALLOWED_HEADING_ELEMENTS} |
|
79
|
unwrapDisallowed |
|
80
|
> |
|
81
|
{escapeLeadingBlockMarker(children)} |
|
82
|
</MarkdownContent> |
|
83
|
) : ( |
|
84
|
children |
|
85
|
) |
|
86
|
return ( |
|
87
|
<Heading id={id} className={className}> |
|
88
|
{content} |
|
89
|
</Heading> |
|
90
|
) |
|
91
|
} |