feat: enhanced in-page side navigation for docs with nested content and url navigation

This commit is contained in:
bitroy
2024-06-05 21:42:15 +05:30
parent 9618e7dae7
commit 821cbbdb07
5 changed files with 66 additions and 48 deletions

View File

@@ -44,7 +44,7 @@ const Anchor = ({ id, inView, children }: { id: string; inView: boolean; childre
);
};
export const Heading = <Level extends 2 | 3>({
export const Heading = <Level extends 2 | 3 | 4>({
children,
tag,
label,
@@ -59,11 +59,11 @@ export const Heading = <Level extends 2 | 3>({
anchor?: boolean;
}) => {
level = level ?? (2 as Level);
let Component = `h${level}` as "h2" | "h3";
let ref = useRef<HTMLHeadingElement>(null);
let registerHeading = useSectionStore((s) => s.registerHeading);
const Component: "h2" | "h3" | "h4" = `h${level}`;
const ref = useRef<HTMLHeadingElement>(null);
const registerHeading = useSectionStore((s) => s.registerHeading);
let inView = useInView(ref, {
const inView = useInView(ref, {
margin: `${remToPx(-3.5)}px 0px 0px 0px`,
amount: "all",
});
@@ -71,8 +71,12 @@ export const Heading = <Level extends 2 | 3>({
useEffect(() => {
if (level === 2) {
registerHeading({ id: props.id, ref, offsetRem: tag || label ? 8 : 6 });
} else if (level === 3) {
registerHeading({ id: props.id, ref, offsetRem: tag || label ? 7 : 5 });
} else if (level === 4) {
registerHeading({ id: props.id, ref, offsetRem: tag || label ? 6 : 4 });
}
});
}, [label, level, props.id, registerHeading, tag]);
return (
<>

View File

@@ -38,7 +38,7 @@ export const Layout = ({
</motion.header>
<div className="flex h-screen flex-col">
<div className="relative flex flex-1 flex-col px-4 pt-14 sm:px-6 lg:px-8">
<main className="flex-auto overflow-y-auto lg:w-[calc(100%-18rem)]">{children}</main>
<main className="flex-auto overflow-y-auto lg:w-[calc(100%-20rem)]">{children}</main>
<Footer />
</div>
<SideNavigation pathname={pathname} />

View File

@@ -1,3 +1,4 @@
import Link from "next/link";
import { useEffect, useState } from "react";
type Heading = {
@@ -12,7 +13,7 @@ const SideNavigation = ({ pathname }) => {
useEffect(() => {
const getHeadings = () => {
const headingElements = document.querySelectorAll("h1[id], h2[id], h3[id], h4[id], h5[id], h6[id]");
const headingElements = document.querySelectorAll("h2[id], h3[id], h4[id]");
const headings: Heading[] = Array.from(headingElements).map((heading) => ({
id: heading.id,
text: heading.textContent,
@@ -25,40 +26,44 @@ const SideNavigation = ({ pathname }) => {
getHeadings();
}, [pathname]);
const scrollToSection = (id: string) => {
const element = document.getElementById(id);
if (element) {
element.scrollIntoView({ behavior: "smooth" });
setActiveId(id);
}
};
const renderHeading = (items: Heading[], currentLevel: number) => (
<ul className="ml-1 mt-4">
{items.map((heading, index) => {
if (heading.level === currentLevel) {
let nextIndex = index + 1;
while (nextIndex < items.length && items[nextIndex].level > currentLevel) {
nextIndex++;
}
return (
<li
key={heading.text}
className={`mb-4 ml-4 text-slate-900 dark:text-white ml-${heading.level === 2 ? 0 : heading.level === 3 ? 4 : 6}`}>
<Link
href={`#${heading.id}`}
onClick={() => setActiveId(heading.id)}
className={`font-normal text-slate-900 dark:text-white ${
heading.id === activeId
? "rounded-r-md font-semibold text-blue-800 transition dark:text-amber-300"
: ""
}`}>
{heading.text}
</Link>
{nextIndex > index + 1 && renderHeading(items.slice(index + 1, nextIndex), currentLevel + 1)}
</li>
);
}
return null;
})}
</ul>
);
if (headings.length) {
return (
<aside className="fixed right-0 top-0 z-50 hidden h-full w-72 overflow-hidden overflow-y-auto pt-16 lg:mt-10 lg:block">
<aside className="fixed right-0 top-0 hidden h-[calc(100%-2.5rem)] w-80 overflow-hidden overflow-y-auto pt-16 lg:mt-10 lg:block">
<div className="border-l-2 border-gray-700">
<h3 className="ml-2 mt-1">On this page</h3>
<ul className="px-5 py-5">
{headings.map((heading) => (
<li
key={heading.id}
className={`mb-4 text-slate-900 dark:text-white ${
heading.id === activeId
? "rounded-r-md bg-slate-100 px-2 py-1 transition dark:bg-slate-800"
: ""
}`}>
<a
href={`#${heading.id}`}
onClick={(e) => {
e.preventDefault();
scrollToSection(heading.id);
}}
className="font-semibold text-slate-900 dark:text-white">
{heading.text}
</a>
</li>
))}
</ul>
{renderHeading(headings, 2)}
</div>
</aside>
);

View File

@@ -19,10 +19,19 @@ export const wrapper = ({ children }: { children: React.ReactNode }) => {
);
};
export const h2 = (props: Omit<React.ComponentPropsWithoutRef<typeof Heading>, "level">) => {
return <Heading level={2} {...props} />;
const createHeadingComponent = (level: 2 | 3 | 4) => {
const Component = (props: Omit<React.ComponentPropsWithoutRef<typeof Heading>, "level">) => {
return <Heading level={level} {...props} />;
};
Component.displayName = `H${level}`;
return Component;
};
export const h2 = createHeadingComponent(2);
export const h3 = createHeadingComponent(3);
export const h4 = createHeadingComponent(4);
const InfoIcon = (props: React.ComponentPropsWithoutRef<"svg">) => {
return (
<svg viewBox="0 0 16 16" aria-hidden="true" {...props}>

View File

@@ -46,9 +46,9 @@ const rehypeShiki = () => {
const rehypeSlugify = () => {
return (tree) => {
let slugify = slugifyWithCounter();
const slugify = slugifyWithCounter();
visit(tree, "element", (node) => {
if (node.tagName === "h2" && !node.properties.id) {
if (["h2", "h3", "h4"].includes(node.tagName) && !node.properties.id) {
node.properties.id = slugify(toString(node));
}
});
@@ -83,15 +83,15 @@ const rehypeAddMDXExports = (getExports) => {
};
const getSections = (node) => {
let sections = [];
const sections = [];
for (let child of node.children ?? []) {
if (child.type === "element" && child.tagName === "h2") {
for (const child of node.children ?? []) {
if (child.type === "element" && ["h2", "h3", "h4"].includes(child.tagName)) {
sections.push(`{
title: ${JSON.stringify(toString(child))},
id: ${JSON.stringify(child.properties.id)},
...${child.properties.annotation}
}`);
title: ${JSON.stringify(toString(child))},
id: ${JSON.stringify(child.properties.id)},
...${child.properties.annotation}
}`);
} else if (child.children) {
sections.push(...getSections(child));
}