Site header
444 lines · 1 file · MIT
A header that is part of the page at the top, then shrinks into a frosted pill, with a panel menu and a phone menu.
import {
useEffect,
useRef,
useState,
useSyncExternalStore,
type MouseEvent,
type ReactNode,
type RefObject,
} from "react";
import { ChevronDown, Moon, Sun } from "./icons";
import { cn } from "./cn";
export interface SiteHeaderLink {
href: string;
label: string;
/** A few words on why you would go there, shown in the panel and the phone menu. */
hint?: string;
current?: boolean;
}
export interface SiteHeaderProps {
/** The brand, linked to `logoHref`. */
logo: ReactNode;
logoHref?: string;
/** An optional disclosure ("Product") whose panel holds a grid of links. */
menu?: { label: string; links: SiteHeaderLink[] };
/** The plain links beside it. */
links: SiteHeaderLink[];
/** The right side on wider screens: search, sign in, the main action. */
actions?: ReactNode;
/** The big buttons at the foot of the phone menu. */
phoneActions?: ReactNode;
/** Show the light and dark switch (right side from lg up, and in the phone menu). */
themeSwitch?: boolean;
/** Past this many pixels of scroll the header leaves the page and floats. */
floatAfter?: number;
/** Called for every link followed from the header; call `preventDefault` to route it yourself. */
onNavigate?: (href: string, event: MouseEvent<HTMLAnchorElement>) => void;
className?: string;
}
function subscribeScroll(onChange: () => void) {
addEventListener("scroll", onChange, { passive: true });
return () => removeEventListener("scroll", onChange);
}
const flag = (on: boolean) => (on ? "" : undefined);
/** Light and dark side by side, the chosen one raised. Writes `data-theme`
* on the root and the `theme` key in localStorage. */
export function ThemeSwitch({ className }: { className?: string }) {
const set = (mode: "light" | "dark") => {
const root = document.documentElement;
root.setAttribute("data-theme-switching", "");
root.dataset.theme = mode;
try {
localStorage.setItem("theme", mode);
} catch {
// Private mode: the choice lasts until the page closes.
}
requestAnimationFrame(() =>
requestAnimationFrame(() => root.removeAttribute("data-theme-switching")),
);
};
const button =
"grid cursor-pointer place-items-center rounded-full p-1.5 text-muted [@media(hover:hover)]:hover:text-text [:root:not([data-theme=dark])_&[data-mode=light]]:bg-surface-2 [:root:not([data-theme=dark])_&[data-mode=light]]:text-text [:root[data-theme=dark]_&[data-mode=dark]]:bg-surface-2 [:root[data-theme=dark]_&[data-mode=dark]]:text-text";
return (
<div
role="group"
aria-label="Theme"
className={cn("flex w-fit rounded-full border border-border p-0.5", className)}
>
<button
type="button"
aria-label="Light theme"
data-mode="light"
className={button}
onClick={() => set("light")}
>
<Sun size={14} />
</button>
<button
type="button"
aria-label="Dark theme"
data-mode="dark"
className={button}
onClick={() => set("dark")}
>
<Moon size={14} />
</button>
</div>
);
}
/** Close on Escape (focus back on the button), and on a click or focus that
* lands outside `root`. */
function useDismiss(
open: boolean,
root: RefObject<HTMLElement | null>,
close: () => void,
button: RefObject<HTMLButtonElement | null>,
) {
useEffect(() => {
if (!open) return;
const outside = (event: Event) => {
if (event.target instanceof Node && !root.current?.contains(event.target)) close();
};
const escape = (event: KeyboardEvent) => {
if (event.key !== "Escape") return;
close();
button.current?.focus();
};
document.addEventListener("pointerdown", outside);
document.addEventListener("focusin", outside);
document.addEventListener("keydown", escape);
return () => {
document.removeEventListener("pointerdown", outside);
document.removeEventListener("focusin", outside);
document.removeEventListener("keydown", escape);
};
}, [open, root, close, button]);
}
/** While the phone menu is open the page under it holds still. */
function useScrollLock(locked: boolean) {
useEffect(() => {
if (!locked) return;
const root = document.documentElement;
const before = root.style.overflow;
root.style.overflow = "hidden";
return () => {
root.style.overflow = before;
};
}, [locked]);
}
const NAV_ITEM =
"cursor-pointer rounded-sm whitespace-nowrap text-muted transition-colors duration-150 hover:text-text focus-visible:text-text aria-[current=page]:text-text";
/** A disclosure, not a menu: the panel holds ordinary links, so Tab walks
* through them. Opens on click, or on hover where a pointer can hover;
* closes on Escape, on a click or focus outside, and once a link is followed. */
function PanelMenu({
label,
links,
onNavigate,
}: {
label: string;
links: SiteHeaderLink[];
onNavigate?: SiteHeaderProps["onNavigate"];
}) {
const [open, setOpen] = useState(false);
const root = useRef<HTMLDivElement>(null);
const button = useRef<HTMLButtonElement>(null);
const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
const hoveredAt = useRef(0);
const close = () => {
clearTimeout(timer.current);
setOpen(false);
};
useDismiss(open, root, close, button);
useEffect(() => () => clearTimeout(timer.current), []);
const canHover = () => matchMedia("(hover: hover)").matches;
const enter = () => {
if (!canHover()) return;
clearTimeout(timer.current);
hoveredAt.current = performance.now();
setOpen(true);
};
const leave = () => {
if (!canHover()) return;
hoveredAt.current = 0;
timer.current = setTimeout(() => setOpen(false), 120);
};
const toggle = () => {
// A click just after hover opened the panel means "open", not "close".
if (performance.now() - hoveredAt.current < 600) return;
setOpen((was) => !was);
};
return (
<div ref={root} onPointerEnter={enter} onPointerLeave={leave}>
<button
ref={button}
type="button"
aria-expanded={open}
aria-controls="site-header-panel"
aria-current={links.some((l) => l.current) ? "page" : undefined}
onClick={toggle}
className={cn(NAV_ITEM, "inline-flex items-center gap-1")}
>
{label}
<ChevronDown
size={14}
className={cn("transition-transform motion-reduce:transition-none", open && "rotate-180")}
/>
</button>
{/* Rendered closed rather than not at all, so its links are in the
HTML. `inert` keeps it out of the tab order. The top padding is
part of the panel, so the pointer crosses no gap on the way down. */}
<div
id="site-header-panel"
inert={!open}
data-open={flag(open)}
className="invisible absolute top-full left-1/2 w-md origin-top -translate-x-1/2 -translate-y-1 scale-[0.97] pt-2 opacity-0 blur-[4px] transition-[opacity,translate,scale,filter,visibility] duration-150 ease-in data-open:visible data-open:translate-y-0 data-open:scale-100 data-open:opacity-100 data-open:blur-none data-open:duration-200 data-open:ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:translate-y-0 motion-reduce:scale-100 motion-reduce:blur-none"
>
<ul className="grid grid-cols-2 gap-1 rounded-2xl border border-border bg-surface p-2 shadow-[0_16px_40px_-18px_rgb(30_20_50/0.35)]">
{links.map((link) => (
<li key={link.href}>
<a
href={link.href}
aria-current={link.current ? "page" : undefined}
onClick={(e) => {
onNavigate?.(link.href, e);
close();
}}
className="block rounded-xl px-3 py-2.5 transition-colors hover:bg-surface-2 focus-visible:bg-surface-2"
>
<span className="block text-sm font-bold text-text">{link.label}</span>
{link.hint && <span className="block text-sm text-muted">{link.hint}</span>}
</a>
</li>
))}
</ul>
</div>
</div>
);
}
/** The two bars, crossing into an X while the menu is open. */
function MenuButton({
open,
onToggle,
buttonRef,
}: {
open: boolean;
onToggle: () => void;
buttonRef: RefObject<HTMLButtonElement | null>;
}) {
const bar =
"absolute left-1/2 h-[1.5px] w-4 -translate-x-1/2 rounded-full bg-text transition-transform duration-200 motion-reduce:transition-none";
return (
<button
ref={buttonRef}
type="button"
aria-expanded={open}
aria-controls="site-header-phone-menu"
aria-label={open ? "Close menu" : "Open menu"}
onClick={onToggle}
className="relative grid size-9 shrink-0 cursor-pointer rounded-full bg-surface-2 md:hidden"
>
<span className={cn(bar, "top-[13px]", open && "translate-y-[4px] rotate-45")} />
<span className={cn(bar, "top-[21px]", open && "-translate-y-[4px] -rotate-45")} />
</button>
);
}
const ROW =
"relative flex cursor-pointer items-baseline justify-between gap-4 rounded-xl px-2.5 py-2 transition-colors hover:bg-surface-2 focus-visible:bg-surface-2 aria-[current=page]:before:absolute aria-[current=page]:before:top-1/2 aria-[current=page]:before:-left-1 aria-[current=page]:before:size-1.5 aria-[current=page]:before:-translate-y-1/2 aria-[current=page]:before:rounded-full aria-[current=page]:before:bg-accent";
/** The pill grows down into a card that holds every page and the main actions. */
function PhoneMenu({
open,
links,
actions,
themeSwitch,
onNavigate,
onClose,
}: {
open: boolean;
links: SiteHeaderLink[];
actions?: ReactNode;
themeSwitch: boolean;
onNavigate?: SiteHeaderProps["onNavigate"];
onClose: () => void;
}) {
useScrollLock(open);
return (
// Rows from 0fr to 1fr: the card grows to its content's height without
// anyone measuring it. `invisible` once closed keeps the links out of
// the tab order and the accessibility tree.
<div
id="site-header-phone-menu"
data-open={flag(open)}
className="invisible grid grid-rows-[0fr] transition-[grid-template-rows,visibility] duration-300 ease-out data-open:visible data-open:grid-rows-[1fr] motion-reduce:transition-none md:hidden"
>
<div className="min-h-0 overflow-hidden">
<nav aria-label="Menu" className="px-1.5 pt-5 pb-1">
<ul className="flex flex-col">
{links.map((link) => (
<li key={link.href}>
<a
href={link.href}
aria-current={link.current ? "page" : undefined}
onClick={(e) => {
onNavigate?.(link.href, e);
onClose();
}}
className={ROW}
>
<span className="text-xl font-bold tracking-tight">{link.label}</span>
{link.hint && <span className="truncate text-sm text-muted">{link.hint}</span>}
</a>
</li>
))}
</ul>
</nav>
{actions && <div className="grid grid-cols-2 gap-2 px-1.5 pt-3">{actions}</div>}
{themeSwitch && (
<div className="flex items-center justify-between px-3 pt-3 pb-2 text-sm text-muted">
Theme
<ThemeSwitch />
</div>
)}
</div>
</div>
);
}
/**
* A marketing header. At the top of the page it is part of the page: no
* fill, no edge. Once the page moves it shrinks into a frosted pill a little
* below the top edge, everything easing together over 700ms. On a phone the
* pill opens into a card with every page in it, over a blurred page.
*/
export function SiteHeader({
logo,
logoHref = "/",
menu,
links,
actions,
phoneActions,
themeSwitch = true,
floatAfter = 8,
onNavigate,
className,
}: SiteHeaderProps) {
const [menuOpen, setMenuOpen] = useState(false);
const pill = useRef<HTMLDivElement>(null);
const menuButton = useRef<HTMLButtonElement>(null);
const closeMenu = () => setMenuOpen(false);
useDismiss(menuOpen, pill, closeMenu, menuButton);
const scrolled = useSyncExternalStore(
subscribeScroll,
() => window.scrollY > floatAfter,
() => false,
);
// A reload partway down the page restores the scroll, so the header is
// already floating when it first runs: take that state at once rather
// than animate into it. Transitions switch on from the next frame.
const [settled, setSettled] = useState(false);
useEffect(() => {
const id = requestAnimationFrame(() => requestAnimationFrame(() => setSettled(true)));
return () => cancelAnimationFrame(id);
}, []);
return (
<header
data-floating={flag(scrolled || menuOpen)}
// flow-root: the pill's top margin stays inside the header rather
// than collapsing through it and moving the whole header down.
className={cn("group/header sticky top-0 z-40 flow-root h-16 px-3 sm:px-6", className)}
>
{/* The page behind the open phone menu, blurred. A sibling of the
pill: its backdrop filter would make "fixed" mean fixed to it. */}
<div
aria-hidden="true"
data-open={flag(menuOpen)}
className="pointer-events-none fixed inset-0 bg-bg/60 opacity-0 backdrop-blur-md transition-opacity duration-300 data-open:pointer-events-auto data-open:opacity-100 motion-reduce:transition-none md:hidden"
/>
<div
ref={pill}
data-open={flag(menuOpen)}
className={cn(
"relative mx-auto max-w-5xl rounded-[1.75rem] border border-transparent px-1 py-3 sm:px-4",
settled
? "transition-[max-width,margin,padding,background-color,border-color,box-shadow] duration-700 ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:transition-none"
: "transition-none",
"group-data-floating/header:mt-1.5 group-data-floating/header:max-w-[calc(100%-1.5rem)] group-data-floating/header:px-2 group-data-floating/header:py-1.5 sm:group-data-floating/header:px-2.5 md:group-data-floating/header:max-w-3xl",
"group-data-floating/header:border-border/60 group-data-floating/header:bg-surface/70 group-data-floating/header:backdrop-blur-xl group-data-floating/header:backdrop-saturate-150",
"group-data-floating/header:shadow-[inset_0_1px_0_rgb(255_255_255/0.35),inset_0_-1px_0_rgb(255_255_255/0.12),0_1px_1px_rgb(0_0_0/0.06),0_8px_24px_rgb(0_0_0/0.1)]",
// The open phone menu keeps the full width: its rows need it.
"data-open:bg-surface data-open:pb-2 group-data-floating/header:data-open:max-w-full",
)}
>
<div className="flex items-center justify-between gap-3">
<div className="flex items-center gap-7 self-stretch">
<a
href={logoHref}
onClick={(e) => {
onNavigate?.(logoHref, e);
closeMenu();
}}
className="flex shrink-0 items-center rounded-full text-lg leading-none"
>
{logo}
</a>
{/* relative: the panel hangs from the nav's foot. */}
<nav
aria-label="Main"
className="relative hidden items-center gap-6 self-stretch text-sm md:flex"
>
{menu && <PanelMenu label={menu.label} links={menu.links} onNavigate={onNavigate} />}
{links.map((link) => (
<a
key={link.href}
href={link.href}
onClick={(e) => onNavigate?.(link.href, e)}
aria-current={link.current ? "page" : undefined}
className={NAV_ITEM}
>
{link.label}
</a>
))}
</nav>
</div>
<div className="flex items-center gap-1.5">
{/* The open phone menu carries its own actions, so these step
aside rather than say them twice. */}
<div className="flex items-center gap-1 text-sm in-data-open:max-md:hidden">
{themeSwitch && <ThemeSwitch className="mr-1 hidden lg:flex" />}
{actions}
</div>
<MenuButton
open={menuOpen}
onToggle={() => setMenuOpen((was) => !was)}
buttonRef={menuButton}
/>
</div>
</div>
<PhoneMenu
open={menuOpen}
links={[...links, ...(menu?.links ?? [])]}
actions={phoneActions}
themeSwitch={themeSwitch}
onNavigate={onNavigate}
onClose={closeMenu}
/>
</div>
</header>
);
}
Install
One command. The files land in your repo, with everything they import.
$ bunx shadcn@latest add @blocco/site-header- Category
- Navigation
- Files
- site-header.tsx