Navbars & Headersv0.3.0
Morphing Dropdown Nav
One dropdown panel that reshapes and slides between menus.
Installation
CLI
npx shadcn@latest add https://hantui-theta.vercel.app/r/morph-dropdown-nav.jsonManual
Install the dependencies
npm install clsx lucide-react motion tailwind-mergeAdd the shared helpers
Components use
cn()fromlib/utils.tsand the motion tokens below. See Installation if you have not set them up yet.lib/nav/mobile-menu.tsx"use client"; import { useEffect, useId, useState } from "react"; import { AnimatePresence, motion, useReducedMotion } from "motion/react"; import { ChevronDown } from "lucide-react"; import { cn } from "@/lib/utils"; import type { NavAction, NavItem } from "@/lib/nav/types"; export interface MobileMenuProps { items: NavItem[]; actions?: NavAction[]; /** Colors for light or dark navbars. @default "light" */ tone?: "light" | "dark"; /** Classes for the toggle button. */ className?: string; /** Classes for the panel, to place it under narrow navbars. */ panelClassName?: string; } /** * The compact menu every navbar falls back to on narrow widths: a hamburger that morphs into an X, * and a panel with expandable groups and the actions. Escape closes it and returns focus. */ export function MobileMenu({ items, actions = [], tone = "light", className, panelClassName }: MobileMenuProps) { const id = useId(); const reduceMotion = useReducedMotion(); const [open, setOpen] = useState(false); const [group, setGroup] = useState<string | null>(null); const dark = tone === "dark"; useEffect(() => { if (!open) return; const onKey = (e: KeyboardEvent) => { if (e.key !== "Escape") return; setOpen(false); document.getElementById(`${id}-toggle`)?.focus(); }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); }, [open, id]); const line = cn("absolute left-1/2 h-[1.5px] w-4 -translate-x-1/2 rounded-full transition-transform duration-300 motion-reduce:transition-none", dark ? "bg-white" : "bg-[#0b0b0c]"); return ( <> <button id={`${id}-toggle`} type="button" aria-expanded={open} aria-controls={`${id}-panel`} aria-label={open ? "Close menu" : "Open menu"} onClick={() => setOpen((o) => !o)} className={cn("relative grid size-9 shrink-0 cursor-pointer place-items-center rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring", dark ? "hover:bg-white/10" : "hover:bg-black/5", className)} > <span aria-hidden="true" className={cn(line, open ? "top-1/2 rotate-45" : "top-[13px]")} /> <span aria-hidden="true" className={cn(line, open ? "top-1/2 -rotate-45" : "top-[21px]")} /> </button> <AnimatePresence> {open ? ( <motion.div id={`${id}-panel`} initial={reduceMotion ? { opacity: 0 } : { opacity: 0, y: -8, scale: 0.98 }} animate={{ opacity: 1, y: 0, scale: 1 }} exit={{ opacity: 0, transition: { duration: 0.12 } }} transition={{ duration: 0.22, ease: [0.22, 1, 0.36, 1] }} className={cn("absolute inset-x-2 top-full z-50 mt-2 origin-top rounded-2xl border p-2 shadow-xl", dark ? "border-white/10 bg-[#111113] text-white" : "border-black/[0.06] bg-white text-[#0b0b0c]", panelClassName)} > <ul> {items.map((item) => item.items?.length ? ( <li key={item.label}> <button type="button" aria-expanded={group === item.label} onClick={() => setGroup((g) => (g === item.label ? null : item.label))} className={cn("flex h-11 w-full cursor-pointer items-center justify-between rounded-xl px-3 text-[15px] font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring", dark ? "hover:bg-white/5" : "hover:bg-black/[0.03]")} > {item.label} <ChevronDown className={cn("size-4 opacity-60 transition-transform", group === item.label && "rotate-180")} aria-hidden="true" /> </button> <div className={cn("grid transition-[grid-template-rows] duration-300 motion-reduce:transition-none", group === item.label ? "grid-rows-[1fr]" : "grid-rows-[0fr]")}> <ul className="min-h-0 overflow-hidden" inert={group !== item.label}> {item.items.map((link) => ( <li key={link.label}> <a href={link.href} className={cn("flex items-center gap-2.5 rounded-lg py-2 pr-3 pl-6 text-[14px] outline-none focus-visible:ring-2 focus-visible:ring-ring", dark ? "text-white/75 hover:text-white" : "text-[#52525b] hover:text-[#0b0b0c]")}> {link.icon ? <span aria-hidden="true" className="opacity-70 [&_svg]:size-4">{link.icon}</span> : null} {link.label} </a> </li> ))} </ul> </div> </li> ) : ( <li key={item.label}> <a href={item.href ?? "#"} className={cn("flex h-11 items-center rounded-xl px-3 text-[15px] font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring", dark ? "hover:bg-white/5" : "hover:bg-black/[0.03]")}> {item.label} </a> </li> ), )} </ul> {actions.length ? ( <div className={cn("mt-2 grid gap-2 border-t pt-3", dark ? "border-white/10" : "border-black/[0.06]")}> {actions.map((a, i) => ( <a key={a.label} href={a.href} className={cn( "flex h-11 items-center justify-center rounded-xl text-[14px] font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring", i === actions.length - 1 ? (dark ? "bg-white text-[#0b0b0c]" : "bg-[#0b0b0c] text-white") : dark ? "border border-white/15" : "border border-black/10", )} > {a.label} </a> ))} </div> ) : null} </motion.div> ) : null} </AnimatePresence> </> ); }lib/nav/types.tsimport type { ReactNode } from "react"; /** A link in a menu or panel. */ export interface NavLink { label: string; href: string; /** A short line under the label in rich menus. */ description?: string; /** An icon shown beside the label in rich menus. */ icon?: ReactNode; } /** A top-level navbar entry: a plain link, or a trigger with links under it. */ export interface NavItem { label: string; /** Destination when the item is a plain link. */ href?: string; /** Links shown in the item's menu; makes the item a menu trigger. */ items?: NavLink[]; } /** A call-to-action button. */ export interface NavAction { label: string; href: string; }lib/nav/use-menu.ts"use client"; import { useEffect, useRef, useState, type RefObject } from "react"; /** * Open/close state for a navbar's menus: one menu open at a time, opened by click or by hover with a * short intent delay, closed by Escape (focus returns to its trigger), an outside click, or the * pointer leaving the navbar. */ export function useMenu(root: RefObject<HTMLElement | null>) { const [open, setOpen] = useState<string | null>(null); const timer = useRef(0); const triggers = useRef(new Map<string, HTMLElement>()); useEffect(() => { if (!open) return; const onKey = (e: KeyboardEvent) => { if (e.key !== "Escape") return; triggers.current.get(open)?.focus(); setOpen(null); }; const onDown = (e: PointerEvent) => { if (root.current && !root.current.contains(e.target as Node)) setOpen(null); }; window.addEventListener("keydown", onKey); window.addEventListener("pointerdown", onDown); return () => { window.removeEventListener("keydown", onKey); window.removeEventListener("pointerdown", onDown); }; }, [open, root]); useEffect(() => () => window.clearTimeout(timer.current), []); const hoverOpen = (id: string) => { window.clearTimeout(timer.current); timer.current = window.setTimeout(() => setOpen(id), open ? 0 : 90); }; const hoverClose = () => { window.clearTimeout(timer.current); timer.current = window.setTimeout(() => setOpen(null), 160); }; const cancelClose = () => window.clearTimeout(timer.current); /** Props for a menu trigger button. */ const triggerProps = (id: string, panelId: string) => ({ ref: (el: HTMLElement | null) => { if (el) triggers.current.set(id, el); else triggers.current.delete(id); }, "aria-expanded": open === id, "aria-controls": panelId, onClick: () => setOpen((o) => (o === id ? null : id)), onPointerEnter: (e: React.PointerEvent) => e.pointerType === "mouse" && hoverOpen(id), onPointerLeave: (e: React.PointerEvent) => e.pointerType === "mouse" && hoverClose(), }); /** Props for a menu panel, so moving onto it keeps it open. */ const panelProps = { onPointerEnter: cancelClose, onPointerLeave: (e: React.PointerEvent) => e.pointerType === "mouse" && hoverClose(), }; return { open, setOpen, triggerProps, panelProps, close: () => setOpen(null) }; }Copy the source
components/ui/morph-dropdown-nav/morph-dropdown-nav.tsx"use client"; import { useEffect, useId, useRef, useState, type ReactNode } from "react"; import { AnimatePresence, motion, useReducedMotion } from "motion/react"; import { ChevronDown } from "lucide-react"; import { cn } from "@/lib/utils"; import { MobileMenu } from "@/lib/nav/mobile-menu"; import type { NavAction, NavItem } from "@/lib/nav/types"; import { useMenu } from "@/lib/nav/use-menu"; export interface MorphDropdownNavProps { /** Logo and name. */ brand: ReactNode; /** Top-level entries; entries with `items` share the morphing panel. */ items: NavItem[]; /** Actions on the right; the last one is the filled button. */ actions?: NavAction[]; /** Accessible name for the navigation. @default "Main" */ label?: string; /** Classes for the header. */ className?: string; } const EASE = [0.22, 1, 0.36, 1] as const; /** Menus with four or more links lay out in two columns. */ const widthOf = (item: NavItem) => ((item.items?.length ?? 0) >= 4 ? 520 : 300); /** * A dark bar whose menus share one panel: moving between triggers, the panel glides across and * resizes to fit while the old content slides out in the direction you moved and the new one in. */ export function MorphDropdownNav({ brand, items, actions = [], label = "Main", className }: MorphDropdownNavProps) { const id = useId(); const reduceMotion = useReducedMotion(); const root = useRef<HTMLElement>(null); const navRef = useRef<HTMLElement>(null); const measure = useRef<HTMLDivElement>(null); const menu = useMenu(root); const [anchor, setAnchor] = useState({ center: 0, bound: 0 }); const [height, setHeight] = useState(0); const [shown, setShown] = useState<{ key: string | null; dir: number }>({ key: null, dir: 0 }); const index = (key: string | null) => items.findIndex((i) => i.label === key); if (menu.open !== shown.key) { setShown({ key: menu.open, dir: menu.open && shown.key ? Math.sign(index(menu.open) - index(shown.key)) : 0 }); } const active = items.find((i) => i.label === menu.open && i.items?.length); const width = active ? widthOf(active) : 300; const left = Math.max(0, Math.min(anchor.bound - width, anchor.center - width / 2)); useEffect(() => { const el = measure.current; if (!el || !active) return; const ro = new ResizeObserver(() => setHeight(el.offsetHeight)); ro.observe(el); return () => ro.disconnect(); }, [active]); /** Remember where the trigger sits so the panel can center under it. */ const aim = (e: { currentTarget: HTMLElement }) => { const nav = navRef.current?.getBoundingClientRect(); const r = e.currentTarget.getBoundingClientRect(); if (nav) setAnchor({ center: r.left - nav.left + r.width / 2, bound: nav.width }); }; const slide = { enter: (dir: number) => (reduceMotion ? { opacity: 0 } : { opacity: 0, x: dir * 48 }), center: { opacity: 1, x: 0 }, exit: (dir: number) => (reduceMotion ? { opacity: 0 } : { opacity: 0, x: dir * -48 }), }; const spring = reduceMotion ? { duration: 0 } : { type: "spring" as const, stiffness: 420, damping: 38 }; const primary = actions.at(-1); return ( <header ref={root} className={cn("@container sticky top-0 z-40 border-b border-white/[0.08] bg-[#09090b]/90 text-white backdrop-blur-xl", className)}> <nav ref={navRef} aria-label={label} className="relative mx-auto flex h-16 max-w-6xl items-center gap-2 px-4"> <div className="mr-6">{brand}</div> <ul className="hidden items-center gap-0.5 @2xl:flex"> {items.map((item) => { if (!item.items?.length) { return ( <li key={item.label}> <a href={item.href ?? "#"} className="flex h-9 relative after:absolute after:inset-x-0 after:-inset-y-0.5 whitespace-nowrap items-center rounded-full px-3.5 text-[14px] text-white/70 outline-none transition-colors hover:text-white focus-visible:ring-2 focus-visible:ring-white/50"> {item.label} </a> </li> ); } const open = menu.open === item.label; return ( <li key={item.label} onPointerEnter={aim} onFocus={aim}> <button type="button" {...menu.triggerProps(item.label, `${id}-panel`)} className={cn("flex h-9 relative after:absolute after:inset-x-0 after:-inset-y-0.5 whitespace-nowrap cursor-pointer items-center gap-1 rounded-full px-3.5 text-[14px] outline-none transition-colors focus-visible:ring-2 focus-visible:ring-white/50", open ? "bg-white/10 text-white" : "text-white/70 hover:text-white")} > {item.label} <ChevronDown className={cn("size-3.5 opacity-60 transition-transform duration-200", open && "rotate-180")} aria-hidden="true" /> </button> </li> ); })} </ul> <div className="ml-auto hidden items-center gap-1 @2xl:flex"> {actions.slice(0, -1).map((a) => ( <a key={a.label} href={a.href} className="flex h-9 relative after:absolute after:inset-x-0 after:-inset-y-0.5 whitespace-nowrap items-center rounded-full px-3.5 text-[14px] text-white/70 outline-none hover:text-white focus-visible:ring-2 focus-visible:ring-white/50"> {a.label} </a> ))} {primary ? ( <a href={primary.href} className="flex h-9 relative after:absolute after:inset-x-0 after:-inset-y-0.5 whitespace-nowrap items-center rounded-full bg-white px-4 text-[14px] font-medium text-[#09090b] outline-none transition-colors hover:bg-white/85 focus-visible:ring-2 focus-visible:ring-white/50 focus-visible:ring-offset-2 focus-visible:ring-offset-[#09090b]"> {primary.label} </a> ) : null} </div> <div className="ml-auto @2xl:hidden"> <MobileMenu items={items} actions={actions} tone="dark" /> </div> <AnimatePresence> {active ? ( <motion.div key="panel" id={`${id}-panel`} {...menu.panelProps} initial={reduceMotion ? { opacity: 0, x: left, width } : { opacity: 0, y: 8, scale: 0.98, x: left, width }} animate={{ opacity: 1, y: 0, scale: 1, x: left, width, height: height || "auto" }} exit={{ opacity: 0, y: reduceMotion ? 0 : 6, transition: { duration: 0.14 } }} transition={{ ...spring, opacity: { duration: 0.18, ease: EASE } }} className="absolute top-[calc(100%-4px)] left-0 z-50 hidden origin-top overflow-hidden rounded-2xl border border-white/10 bg-[#141416] shadow-[0_30px_60px_-20px_rgb(0_0_0/0.7)] @2xl:block" > <div ref={measure} className="relative"> <AnimatePresence mode="popLayout" initial={false} custom={shown.dir}> <motion.div key={active.label} custom={shown.dir} variants={slide} initial="enter" animate="center" exit="exit" transition={{ duration: 0.26, ease: EASE }} style={{ width: widthOf(active) }} className="p-2" > <ul className={cn("grid gap-0.5", active.items!.length >= 4 && "grid-cols-2")}> {active.items!.map((l) => ( <li key={l.label}> <a href={l.href} onClick={menu.close} className="group flex items-start gap-3 rounded-xl p-3 outline-none hover:bg-white/[0.05] focus-visible:bg-white/[0.07]"> {l.icon ? ( <span aria-hidden="true" className="grid size-8 shrink-0 place-items-center rounded-lg border border-white/10 bg-white/[0.04] text-white/70 transition-colors group-hover:text-white [&_svg]:size-4"> {l.icon} </span> ) : null} <span> <span className="block text-[14px] font-medium text-white">{l.label}</span> {l.description ? <span className="mt-0.5 block text-[12.5px] leading-snug text-white/50">{l.description}</span> : null} </span> </a> </li> ))} </ul> </motion.div> </AnimatePresence> </div> </motion.div> ) : null} </AnimatePresence> </nav> </header> ); }
Usage
import { MorphDropdownNav } from "@/components/ui/morph-dropdown-nav/morph-dropdown-nav";
<MorphDropdownNav brand={<Logo />} items={items} actions={actions} />API reference
| Prop | Type | Default | Description |
|---|---|---|---|
brand* | ReactNode | – | Logo and name. |
items* | NavItem[] | – | Top-level entries; entries with `items` share the morphing panel. |
actions | NavAction[] | – | Actions on the right; the last one is the filled button. |
label | string | "Main" | Accessible name for the navigation. |
className | string | – | Classes for the header. |
- The panel measures its content and springs to the new size and position as you move between menus; content slides in the direction you moved.
- Menus with four or more links use two columns.
Accessibility
- Every trigger controls the same panel (`aria-controls`) and reports its own `aria-expanded`.
- Escape closes the panel and returns focus to the trigger; keyboard focus moves the panel too.
- Under reduced motion the panel and its content swap without sliding.