-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmdx-components.tsx
More file actions
65 lines (60 loc) · 1.79 KB
/
Copy pathmdx-components.tsx
File metadata and controls
65 lines (60 loc) · 1.79 KB
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
import type { MDXComponents } from "mdx/types";
import CodeBlock from "@/components/CodeBlock";
import InteractiveGrid from "@/components/docs/InteractiveGrid";
import InteractiveButtonGroup from "@/components/docs/InteractiveButtonGroup";
import SnapCard from "@/components/docs/SnapCard";
import ConfettiDemo from "@/components/docs/ConfettiDemo";
function slugify(text: string): string {
return text
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/(^-|-$)/g, "");
}
function extractText(children: React.ReactNode): string {
if (typeof children === "string") return children;
if (Array.isArray(children)) return children.map(extractText).join("");
if (
children &&
typeof children === "object" &&
"props" in children
) {
const props = (children as { props?: Record<string, unknown> }).props;
if (props?.children) {
return extractText(props.children as React.ReactNode);
}
}
return "";
}
function Heading({
level,
children,
...props
}: {
level: 1 | 2 | 3 | 4;
children?: React.ReactNode;
} & React.HTMLAttributes<HTMLHeadingElement>) {
const Tag = `h${level}` as "h1" | "h2" | "h3" | "h4";
const text = extractText(children);
const id = slugify(text);
return (
<Tag id={id} {...props}>
<a href={`#${id}`} className="heading-anchor">
{children}
</a>
</Tag>
);
}
export function useMDXComponents(components: MDXComponents): MDXComponents {
return {
...components,
h1: (props) => <Heading level={1} {...props} />,
h2: (props) => <Heading level={2} {...props} />,
h3: (props) => <Heading level={3} {...props} />,
h4: (props) => <Heading level={4} {...props} />,
pre: (props) => <CodeBlock {...props} />,
InteractiveGrid,
InteractiveButtonGroup,
SnapCard,
ConfettiDemo,
};
}