From 99ab34b2ac4df4b16fb4dfa0a77cd5698b1dd965 Mon Sep 17 00:00:00 2001 From: Rainnny7 Date: Sun, 6 Oct 2024 20:21:08 -0400 Subject: [PATCH] fix heading mdx components always being h1, and not having an id Took 19 minutes --- src/components/mdx.tsx | 38 +++++++++++++++++++++++++++----------- 1 file changed, 27 insertions(+), 11 deletions(-) diff --git a/src/components/mdx.tsx b/src/components/mdx.tsx index adedede..d8771aa 100644 --- a/src/components/mdx.tsx +++ b/src/components/mdx.tsx @@ -8,32 +8,32 @@ import remarkGfm from "remark-gfm"; */ const components = { h1: ({ children }: { children: ReactNode }): ReactElement => ( - + {children} ), h2: ({ children }: { children: ReactNode }): ReactElement => ( - + {children} ), h3: ({ children }: { children: ReactNode }): ReactElement => ( - + {children} ), h4: ({ children }: { children: ReactNode }): ReactElement => ( - + {children} ), h5: ({ children }: { children: ReactNode }): ReactElement => ( - + {children} ), h6: ({ children }: { children: ReactNode }): ReactElement => ( - + {children} ), @@ -89,15 +89,31 @@ export const CustomMDX = (props: any): ReactElement => ( * @return the heading jsx */ const Heading = ({ + as: Component, className, size, children, }: { + as: "h1" | "h2" | "h3" | "h4" | "h5" | "h6"; className: string; size: number; children: ReactNode; -}): ReactElement => ( -

= 2 && "pt-7", className)}> - {children} -

-); +}): ReactElement => { + const id: string | undefined = + typeof children === "string" ? slugify(children) : undefined; + return ( + = 2 && "pt-7", className)} + > + {children} + + ); +}; + +const slugify = (text: string): string => + text + .toLowerCase() + .replace(/[^\w\s-]/g, "") + .replace(/[\s_-]+/g, "-") + .trim();