This repository has been archived by the owner on Aug 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 150
/
mdx-components.tsx
104 lines (97 loc) · 2.38 KB
/
mdx-components.tsx
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import { CodeBlock, InlineCode } from "@/components/Document/Code";
import { DocLink } from "@/components/Document/DocLink";
import { Heading } from "@/components/Document/Heading";
import { UnorderedList, OrderedList } from "@/components/Document/List";
import { Paragraph } from "@/components/Document/Paragraph";
import { Separator } from "@/components/Document/Separator";
import { TBody, Table, Td, Th, Tr } from "@/components/Document/Table";
import type { MDXComponents } from "mdx/types";
import GithubSlugger from "github-slugger";
import type { BuiltinLanguage } from "shiki";
export function useMDXComponents(components: MDXComponents): MDXComponents {
const slugger = new GithubSlugger();
function nameToLink(name: React.ReactNode) {
if (typeof name !== "string") {
return undefined;
}
return slugger.slug(name);
}
function getHeading(
depth: number,
props: {
children?: React.ReactNode;
id?: string;
},
) {
return (
<Heading level={depth} id={props.id || nameToLink(props.children) || ""}>
{props.children}
</Heading>
);
}
return {
...components,
a(props) {
const { href, children } = props;
return <DocLink href={href || ""}>{children}</DocLink>;
},
h1(props) {
return getHeading(1, props);
},
h2(props) {
return getHeading(2, props);
},
h3(props) {
return getHeading(3, props);
},
h4(props) {
return getHeading(4, props);
},
h5(props) {
return getHeading(5, props);
},
h6(props) {
return getHeading(6, props);
},
code(props) {
const code = props.children;
const lang = props.className?.replace("language-", "");
if (!props.className) {
return <InlineCode code={typeof code === "string" ? code : ""} />;
}
return (
<CodeBlock
lang={lang as BuiltinLanguage}
code={typeof code === "string" ? code : ""}
/>
);
},
p(props) {
return <Paragraph>{props.children}</Paragraph>;
},
ul(props) {
return <UnorderedList>{props.children}</UnorderedList>;
},
ol(props) {
return <OrderedList>{props.children}</OrderedList>;
},
hr() {
return <Separator />;
},
table(props) {
return <Table>{props.children}</Table>;
},
th(props) {
return <Th>{props.children}</Th>;
},
td(props) {
return <Td>{props.children}</Td>;
},
tr(props) {
return <Tr>{props.children}</Tr>;
},
tbody(props) {
return <TBody>{props.children}</TBody>;
},
};
}