From 697922c7826e1caf07bfd6431923c6afac57478e Mon Sep 17 00:00:00 2001 From: DIYgod Date: Wed, 5 Oct 2022 23:29:37 +0100 Subject: [PATCH] feat: headings smooth scroll --- src/components/site/PostHeading.tsx | 19 +++++++++++++++++++ src/components/site/PostLink.tsx | 20 ++++++++++++++++++++ src/markdown/index.ts | 8 ++++++++ 3 files changed, 47 insertions(+) create mode 100644 src/components/site/PostHeading.tsx create mode 100644 src/components/site/PostLink.tsx diff --git a/src/components/site/PostHeading.tsx b/src/components/site/PostHeading.tsx new file mode 100644 index 00000000..9d9c373f --- /dev/null +++ b/src/components/site/PostHeading.tsx @@ -0,0 +1,19 @@ +import { Element } from "react-scroll" + +export const getPostHeading = (tagName: "h2" | "h3" | "h4" | "h5" | "h6") => { + const PostHeading: React.FC< + { + children: React.ReactNode + } & React.HTMLAttributes + > = ({ children, ...props }) => { + const Tag = tagName as any + return ( + <> + + {children} + + ) + } + + return PostHeading +} diff --git a/src/components/site/PostLink.tsx b/src/components/site/PostLink.tsx new file mode 100644 index 00000000..5c4bb404 --- /dev/null +++ b/src/components/site/PostLink.tsx @@ -0,0 +1,20 @@ +import { Link } from "react-scroll" + +export const PostLink: React.FC = ({ children, ...props }) => { + console.log(props.href) + if (props.href?.startsWith("#")) { + return ( + + {children} + + ) + } else { + return {children} + } +} diff --git a/src/markdown/index.ts b/src/markdown/index.ts index 7cc3c3c8..ed35d940 100644 --- a/src/markdown/index.ts +++ b/src/markdown/index.ts @@ -26,6 +26,8 @@ import rehypeSlug from "rehype-slug" import rehypeAutolinkHeadings from "rehype-autolink-headings" import { toc } from "mdast-util-toc" import { PostToc } from "~/components/site/PostToc" +import { getPostHeading } from "~/components/site/PostHeading" +import { PostLink } from "~/components/site/PostLink" export type MarkdownEnv = { excerpt: string @@ -123,7 +125,13 @@ export const renderPageContent = ( createElement: createElement, components: { img: Image, + a: PostLink, toc: PostToc, + h2: getPostHeading("h2"), + h3: getPostHeading("h3"), + h4: getPostHeading("h4"), + h5: getPostHeading("h5"), + h6: getPostHeading("h6"), } as any, }) .processSync(content)