Nav Pill
zosasounds
"use client";
import { type CSSProperties, useLayoutEffect, useRef, useState } from "react";
/**
* Nav Pill: a row of links with one indicator that slides and stretches to
* whichever is current, instead of each link lighting up on its own. The nav
* on zosasounds.com uses the "line" look.
*
* const [tab, setTab] = useState("journey");
* <NavPill items={["journey", "ugc", "socials"]} value={tab} onChange={setTab} />
*
* The indicator is measured from the real link, so labels of any length and
* any font work, and it re-measures when the row changes size.
*/
export type NavPillProps = {
items: string[];
value: string;
onChange: (value: string) => void;
/** "line" sits under the label, "pill" sits behind it. */
look?: "line" | "pill";
color?: string;
label?: (item: string) => string;
className?: string;
style?: CSSProperties;
};
const EASE = "cubic-bezier(.16,1,.3,1)";
export function NavPill({
items,
value,
onChange,
look = "line",
color = "#0071e3",
label = (s) => s,
className,
style,
}: NavPillProps) {
const row = useRef<HTMLDivElement>(null);
const [box, setBox] = useState<{ left: number; width: number } | null>(null);
useLayoutEffect(() => {
const el = row.current;
if (!el) return;
const measure = () => {
const on = el.querySelector<HTMLElement>('[aria-current="page"]');
setBox(on ? { left: on.offsetLeft, width: on.offsetWidth } : null);
};
measure();
const ro = new ResizeObserver(measure);
ro.observe(el);
return () => ro.disconnect();
}, [value, items]);
const pill = look === "pill";
return (
<div
ref={row}
role="navigation"
className={className}
style={{ position: "relative", display: "inline-flex", gap: pill ? 4 : 24, ...style }}
>
<span
aria-hidden="true"
style={{
position: "absolute",
left: box?.left ?? 0,
width: box?.width ?? 0,
opacity: box ? 1 : 0,
pointerEvents: "none",
background: color,
transition: `left .5s ${EASE}, width .5s ${EASE}, opacity .3s`,
...(pill ? { top: 0, bottom: 0, borderRadius: 999 } : { bottom: -8, height: 2, borderRadius: 2 }),
}}
/>
{items.map((it) => {
const on = it === value;
return (
<a
key={it}
href={`#${it}`}
aria-current={on ? "page" : undefined}
onClick={(e) => {
e.preventDefault();
onChange(it);
}}
style={{
position: "relative",
padding: pill ? "6px 14px" : "2px 0",
color: pill && on ? "#fff" : "inherit",
opacity: on ? 1 : 0.6,
fontWeight: on ? 600 : 400,
textDecoration: "none",
transition: "opacity .2s, color .3s",
}}
>
{label(it)}
</a>
);
})}
</div>
);
}