Skip to content

Commit

Permalink
scrollIntoView
Browse files Browse the repository at this point in the history
  • Loading branch information
abernier committed Aug 6, 2024
1 parent 0f3423f commit 81a29dd
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 11 deletions.
4 changes: 3 additions & 1 deletion apps/website/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
import Nav from "@/components/Nav";
import { getDemos } from "@/lib/helper";

const inter = Inter({ subsets: ["latin"] });
const demos = getDemos();

export const metadata: Metadata = {
title: "pmndrs examples",
Expand All @@ -30,7 +32,7 @@ export default function RootLayout({
/>

<main>{children}</main>
<Nav />
<Nav demos={demos} />
</body>
</html>
);
Expand Down
49 changes: 39 additions & 10 deletions apps/website/components/Nav.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,43 @@
"use client";

import Image from "next/image";
import Link from "next/link";
import {
ComponentProps,
createRef,
ElementRef,
useEffect,
useRef,
} from "react";
import { useParams } from "next/navigation";
import clsx from "clsx";

import { getDemos } from "@/lib/helper";
import { ComponentProps } from "react";

export const demos = getDemos();

export default function Nav({
current,
demos,
...props
}: ComponentProps<"nav"> & { current?: string }) {
}: { demos: ReturnType<typeof getDemos> } & ComponentProps<"nav">) {
const ulRef = useRef<ElementRef<"ul">>(null);
const lisRef = useRef(
Array.from({ length: demos.length }).map(() => createRef<HTMLLIElement>())
);

const { demoname } = useParams();

const firstRef = useRef(true);
useEffect(() => {
const i = demos.findIndex(({ name }) => name === demoname);
const li = lisRef.current[i]?.current;
if (li)
li.scrollIntoView({
inline: "center",
block: "center",
behavior: firstRef.current ? "instant" : "smooth",
});
firstRef.current = false;
}, [demoname, demos]);

return (
<>
<style
Expand Down Expand Up @@ -44,23 +72,24 @@ export default function Nav({
a {display:block; background:white;}
a.active {outline:1px solid black;}
a img {
object-fit:cover; aspect-ratio:16/9; width:auto; height:7rem;
}
}
`,
}}
/>

<nav {...props}>
<ul>
<ul ref={ulRef}>
{demos.map(({ name, thumb }, i) => {
return (
<li key={thumb}>
<li key={thumb} ref={lisRef.current[i]}>
<Link
href={`/demos/${name}`}
style={{
outline: `2px solid ${name === current ? "black" : "transparent"}`,
}}
className={clsx({ active: demoname === name })}
>
<Image src={thumb} width={16} height={9} alt="" />
</Link>
Expand Down

0 comments on commit 81a29dd

Please sign in to comment.