Skip to content
This repository has been archived by the owner on Aug 5, 2024. It is now read-only.

Commit

Permalink
feat: nav appears on page scroll
Browse files Browse the repository at this point in the history
  • Loading branch information
gregfromstl committed Jul 29, 2024
1 parent 1634287 commit 701ad59
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
9 changes: 6 additions & 3 deletions src/components/others/TableOfContents.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import Link from "next/link";
import { cn } from "@/lib/utils";
import { useEffect, useRef, useState } from "react";
import { usePathname } from "next/navigation";
import { useScrollPosition } from "../../hooks/useScrollPosition";

/**
* Automatically query all the heading anchors inside the <main> and creates a table of contents
Expand All @@ -28,6 +29,7 @@ export function TableOfContentsSideBar(props: {
filterHeading?: (heading: HTMLHeadingElement) => boolean;
linkClassName?: string;
}) {
const scrollPosition = useScrollPosition();
const [nodes, setNodes] = useState<TableOfContentNode[]>([]);
const tocRef = useRef<HTMLDivElement>(null);
const pathname = usePathname();
Expand Down Expand Up @@ -106,12 +108,13 @@ export function TableOfContentsSideBar(props: {
observer.disconnect();
};
}, [pathname, filterHeading]);

return (
<nav
className={cn(
"hidden hrink-0 pt-6 xl:block text-sm",
"sticky top-sticky-top-height h-sidebar-height flex-col overflow-y-auto styled-scrollbar",
"sticky top-sticky-top-height h-sidebar-height flex-col overflow-y-auto styled-scrollbar transition-opacity duration-300",
scrollPosition > 100 ? 'opacity-100' : 'opacity-0 pointer-events-none'
)}
style={{
visibility: hideNav ? "hidden" : "visible",
Expand Down Expand Up @@ -171,7 +174,7 @@ function TOCLink(props: {
return (
<Link
className={cn(
"block overflow-hidden text-ellipsis font-medium text-f-300 transition-colors hover:text-f-100 data-[active='true']:text-accent-500",
"block overflow-hidden text-ellipsis font-medium text-f-300 transition-colors hover:text-f-100 data-[active='true']:text-accent-500 duration-300",
props.linkClassName,
)}
href={props.href}
Expand Down
19 changes: 19 additions & 0 deletions src/hooks/useScrollPosition.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { useEffect, useState } from "react";

export function useScrollPosition() {
const [scrollPosition, setScrollPosition] = useState(0);

useEffect(() => {
const handleScroll = () => {
setScrollPosition(window.scrollY);
};

window.addEventListener("scroll", handleScroll);

return () => {
window.removeEventListener("scroll", handleScroll);
};
}, []);

return scrollPosition;
}

0 comments on commit 701ad59

Please sign in to comment.