Nav
A navigation list of links with icon slots and a sliding active pill, horizontal or vertical, or a quiet plain variant for a table of contents.
Installation
npx shadcn@latest add https://ui.mattdowney.com/r/nav.jsonUsage
import { Nav, NavList, NavSection, NavLabel, NavItem } from "@/components/ui/nav"
import { resolveActiveHref } from "@/components/ui/nav-active"Examples
Default
Horizontal, the top nav pattern. Pass href and handle the click yourself, or swap in a router link with render.
Sizes
size steps items along the control scale: sm (h-7, 12px), default (h-8, 13px), lg (h-10, 14px). One prop on Nav sizes every item, label, and count chip, in both orientations.
With Count
Pass a count to add a counter chip, the same one a TabsTrigger carries: solid accent on the active item, a neutral tint on the rest. size on Nav scales it with the items. Cap large counts at "99+" so a growing number cannot widen the item.
In a header
Nav shares the kit's control heights, so a header lines up when every control in the row is set to the same size: sm is 28px, default 32px, lg 40px, matching Button tier for tier.
Vertical
orientation="vertical" groups items into NavSections with a NavLabel heading, the sidebar pattern.
Vertical with Count
A count sits at the trailing edge of a vertical item, not against the label, so a column of numbers reads as a column. That needs a width on the Nav: items size to their own content, and there is no shared trailing edge to push a count to until you give them one.
Mobile
A composition, not a separate component: a Button opens a Drawer containing the vertical Nav.
Vertical, long labels
truncate on NavItem cuts a long label with an ellipsis inside a fixed-width sidebar instead of running past the active pill. Give it a plain-text label.
Vertical, two lines
description adds a quieter second line to a vertical item, for a list beside an editor. Both lines cut short with an ellipsis, a count stays on the first line, and rows without a description sit in the same list.
Plain
A table of contents beside a pill sidebar: quiet text links on a hairline track, the current one marked in accent, nothing that slides or fills. Use it one size below the sidebar. Vertical only. Pass aria-current="location" for links to spots on the same page, and indent a deeper level with className.
API Reference
| Prop | Type | Default | Description |
|---|---|---|---|
| orientationNav | "horizontal" | "vertical" | "horizontal" | Lays out the list as a row (top nav) or a column (sidebar) and sizes items to match. |
| variantNav | "pill" | "plain" | "pill" | pill slides a filled indicator to the active item. plain is a quiet text list on a hairline track, the active item in accent text with its stretch of the track in accent, for a table of contents beside a pill sidebar. Vertical only: a horizontal Nav keeps the pill. |
| sizeNav | "sm" | "default" | "lg" | "default" | Steps items and labels along the control scale, from sm (h-7, 12px type) up to lg (h-10, 14px type). |
| iconNavItem | React.ReactNode | None | Leading icon rendered before the item's label, e.g. <Star />. |
| countNavItem | React.ReactNode | None | Counter chip after the label, matching the TabsTrigger chip tier for tier. Inline in a horizontal nav, pushed to the trailing edge in a vertical one. Add an aria-label where a bare number needs context (aria-label="Inbox, 12 unread"). Arrives and leaves like Button's count. |
| activeNavItem | boolean | None | Marks the item as the current page. Sets aria-current="page" and drives the sliding pill. |
| aria-currentNavItem | "page" | "location" | ... | "page" | What the active item is to the reader, set only while it is active. Pass location for a link to a spot on the same page, as a table of contents does. |
| renderNavItem | React.ReactElement | None | Swaps the default <a> for another element, e.g. render={<Link href="/dashboard" />} to compose with a router. |
| truncateNavItem | boolean | false | Cuts a long label short with an ellipsis instead of running past the row. Pass a plain-text label; the label of a vertical item may shrink either way, so a long one no longer pushes past the pill. |
| descriptionNavItem | React.ReactNode | None | A second line under the label of a vertical item: timing, a status, a short preview. Plain text, one type step smaller and quieter. Both lines cut short with an ellipsis, so the label must be plain text too; a count stays on the first line. A horizontal item ignores it. |
| orientationNav"horizontal" | "vertical" = "horizontal"Lays out the list as a row (top nav) or a column (sidebar) and sizes items to match. |
variantNav"pill" | "plain" = "pill"pill slides a filled indicator to the active item. plain is a quiet text list on a hairline track, the active item in accent text with its stretch of the track in accent, for a table of contents beside a pill sidebar. Vertical only: a horizontal Nav keeps the pill. |
sizeNav"sm" | "default" | "lg" = "default"Steps items and labels along the control scale, from sm (h-7, 12px type) up to lg (h-10, 14px type). |
iconNavItemReact.ReactNodeLeading icon rendered before the item's label, e.g. <Star />. |
countNavItemReact.ReactNodeCounter chip after the label, matching the TabsTrigger chip tier for tier. Inline in a horizontal nav, pushed to the trailing edge in a vertical one. Add an aria-label where a bare number needs context (aria-label="Inbox, 12 unread"). Arrives and leaves like Button's count. |
activeNavItembooleanMarks the item as the current page. Sets aria-current="page" and drives the sliding pill. |
aria-currentNavItem"page" | "location" | ... = "page"What the active item is to the reader, set only while it is active. Pass location for a link to a spot on the same page, as a table of contents does. |
renderNavItemReact.ReactElementSwaps the default <a> for another element, e.g. render={<Link href="/dashboard" />} to compose with a router. |
| truncateNavItemboolean = falseCuts a long label short with an ellipsis instead of running past the row. Pass a plain-text label; the label of a vertical item may shrink either way, so a long one no longer pushes past the pill. |
| descriptionNavItemReact.ReactNodeA second line under the label of a vertical item: timing, a status, a short preview. Plain text, one type step smaller and quieter. Both lines cut short with an ellipsis, so the label must be plain text too; a count stays on the first line. A horizontal item ignores it. |
"use client"
import * as React from "react"
import {
createContext,
useContext,
useState,
useRef,
useEffect,
useLayoutEffect,
} from "react"
import { useRender } from "@base-ui/react/use-render"
import { motion, useReducedMotion } from "motion/react"
import { cn } from "@/registry/lib/utils"
import { CountArrival } from "@/registry/lib/count-arrival"
/* ─────────────────────────────────────────────────────────
* NAV
*
* A navigation list of real links, horizontal (top nav) or
* vertical (sidebar). This is link navigation, not content
* switching: Nav renders anchors that go somewhere, Tabs
* renders triggers that switch a panel in place. Reach for
* Tabs when the "active" thing is a view you're rendering;
* reach for Nav when it's a page you'd navigate to directly.
*
* The active item gets the kit's quiet-selected treatment as
* a single sliding pill, the same pattern as tabs.tsx: one
* persistent `motion.span` moved to the active item's box,
* never a per-item `layoutId`. See tabs.tsx's header comment
* for why a per-item shared element balloons across a long
* slide. Nav's pill differs from tabs' in one way: items can
* sit inside nested `li`/`ul`/section wrappers (vertical nav
* with grouped sections), so its box is measured with
* `getBoundingClientRect` deltas against the `Nav` root
* instead of `offsetLeft` against the immediate list.
*
* EXACTLY ONE item may carry `active`. The pill is a single
* element and takes the first `[data-active]` it finds, while
* every active item paints its own accent label colour, so a second
* one splits the selection in two: the pill sits on the first
* and the colour sits on both. Deriving `active` from a path
* PREFIX is how this happens, because section prefixes nest
* ("/docs" contains "/docs/components") and a page in the
* inner section matches both.
*
* Do not hand-roll that check. `resolveActiveHref` ships beside
* this file in `nav-active.ts` for exactly this: it returns the
* ONE href that wins, so comparing each item against it can
* only be true once.
*
* const activeHref = resolveActiveHref(pathname, hrefs)
* <NavItem active={item.href === activeHref} />
*
* It is a separate, directive-free module so a Server Component
* can call it; see the header comment there. `Nav` itself never
* reads the router.
*
* `pillReady` (context) is false until the pill's first
* successful measurement. While false, the active item paints
* its own static tint (see `NavItem`) so SSR and the first
* paint before layout effects run still show the selected
* item; the instant the pill lands in the same box, the static
* tint switches off and the pill takes over. The swap is
* invisible because both read the same tokens.
*
* `variant="plain"` is the quiet vertical list for a table of
* contents read beside a pill sidebar while the page moves under
* it: text only, regular weight, muted, the current item marked
* by accent text and its stretch of a hairline track down the
* list's start edge. No pill or fill is rendered, nothing slides,
* and the weight never changes. A rail that
* animates or competes with the main nav reads as noise; use it
* one Nav size below the sidebar. Its `NavLabel` takes a quiet
* sentence-case style on its own. It is vertical only: a
* horizontal nav asked for it warns in development and keeps the
* pill. Indent a deeper level with `className` on its `NavItem`
* (`ps-3`); there is no level prop.
* ───────────────────────────────────────────────────────── */
// Paired with the item's own `transition-[color] duration-small ease-small`: the pill and
// the label are ONE selection, so they share a duration and land together.
// A 200ms spring under a 150ms color change made the destination read as
// selected while the pill was still two rows away. `bounce: 0` because a nav
// is chrome you click all day, and one bouncy control in a crisp kit reads as
// a mistake. Change one of these two values and you must change the other.
const PILL = {
spring: { type: "spring" as const, visualDuration: 0.15, bounce: 0 },
}
// useLayoutEffect warns during SSR; fall back to useEffect there.
const useIsomorphicLayoutEffect =
typeof window !== "undefined" ? useLayoutEffect : useEffect
type NavOrientation = "horizontal" | "vertical"
type NavSize = "sm" | "default" | "lg"
type NavVariant = "pill" | "plain"
// Sizes ride the kit's control scale (Button's tiers): type steps
// 12px / 13px / 14px, icons one step behind, horizontal items on the
// h-7 / h-8 / h-10 heights. Vertical items size from padding instead of a
// fixed height; the pointer-coarse guard keeps touch rows tall at any size.
const ROOT_SIZE: Record<NavSize, string> = {
sm: "text-1xs",
default: "text-xs",
lg: "text-sm",
}
// Only `sm` gets a pointer-coarse height bump on the horizontal row: at h-7 it
// is the one rung under the 32px floor, so it grows to 32. `default` (32) and
// `lg` (40) already clear it, and bumping them would reflow a dense nav for
// nothing. Same reasoning as button-variants.ts's short rungs. Vertical rows
// have no fixed height, so every size grows its padding on coarse instead.
//
// Side padding steps 8 / 12 / 12 rather than 8 / 10 / 12: 10px is off the 4px
// grid, and `default` is a 32px control carrying 13px type, the same object a
// 32px Button is, so it takes the same 12px inset. These values must stay equal
// to the tabs.tsx trigger of the same size: a tab and a nav item are one object.
// `label` is the icon-to-label gap INSIDE the label span, and it repeats the
// link's own gap: icon+label wrap together so the count can be their sibling
// (see NavItem), and the wrap must not change how the row reads. It is
// Button's icon gap at the same height (4 / 6 / 6): a nav item and a button
// are one object, and a looser gap reads as an icon apart from its word.
// `described` is the vertical padding of a row that carries a second line: one
// step more than a plain row, so two lines are not pressed against the pill's
// edge; the coarse-pointer floor is unchanged. `indent` is the second line's
// start inset when the row has an icon: icon box plus the label gap
// (12+4, 14+6, 16+6), so the meta sits under the label text, not under the icon.
// `iconStart` is a horizontal item's start padding when it leads with an icon:
// 2px less than the label side, the same trim Button gives its icon side, since
// a glyph carries side bearing a drawn icon lacks. Vertical rows keep the full
// inset so every icon in the column stays aligned under the group label.
const ITEM_SIZE: Record<
NavSize,
{
shared: string
horizontal: string
iconStart: string
vertical: string
described: string
indent: string
label: "gap-1" | "gap-1.5"
}
> = {
sm: {
shared: "gap-1 [&_svg:not([class*='size-'])]:size-3",
horizontal: "h-7 px-2 pointer-coarse:min-h-8",
iconStart: "ps-1.5",
vertical: "px-2 py-1 pointer-coarse:py-2.5",
described: "px-2 py-1.5 pointer-coarse:py-2.5",
indent: "ps-4",
label: "gap-1",
},
default: {
shared: "gap-1.5 [&_svg:not([class*='size-'])]:size-3.5",
horizontal: "h-8 px-3",
iconStart: "ps-2.5",
vertical: "px-3 py-1 pointer-coarse:py-2.5",
described: "px-3 py-1.5 pointer-coarse:py-2.5",
indent: "ps-5",
label: "gap-1.5",
},
lg: {
shared: "gap-1.5 [&_svg:not([class*='size-'])]:size-4",
horizontal: "h-10 px-3",
iconStart: "ps-2.5",
vertical: "px-3 py-1.5 pointer-coarse:py-2.5",
described: "px-3 py-2 pointer-coarse:py-2.5",
indent: "ps-5.5",
label: "gap-1.5",
},
}
// Identical to tabs.tsx's COUNT_SIZE, and it must stay identical: a nav item
// and a tab of the same size are one object, so their count chips are too.
// Change one file, change the other.
const COUNT_SIZE: Record<NavSize, string> = {
sm: "h-4 min-w-4 px-1 text-2xs [&_svg]:!size-2.5",
default: "h-4 min-w-4 px-1 text-2xs [&_svg]:!size-2.5",
lg: "h-5 min-w-5 px-1.5 text-1xs [&_svg]:!size-3",
}
// The second line is meta: one type step under the item's own (13px -> 12px,
// and so on down the ramp), regular weight where the label is medium.
const DESCRIPTION_SIZE: Record<NavSize, string> = {
sm: "text-2xs",
default: "text-1xs",
lg: "text-xs",
}
// Radius follows the item's HEIGHT, not its size name, and reads from the
// action ramp Button uses: each `rounded-action-*` rung is 3/8 of its own
// height, so every row reads as one shape at three scales. A single fixed
// corner cannot do that, since roundness is seen as a fraction of the box.
// Vertical rows size from padding rather than a fixed height, so they land a
// step shorter than their horizontal twin at the same size name and take the
// rung below it. The sliding indicator reads from this same map: it is the
// fill sitting behind the item, so a mismatched corner shows as a crescent at
// each end. A two-line row keeps its size's rung and does not climb to the next
// one: the corner is held per size so rows with and without a description sit in
// one list as one shape, and the pill reads the same map so it still matches.
const ITEM_RADIUS: Record<NavSize, Record<NavOrientation, string>> = {
// 28px horizontal / ~24px vertical
sm: { horizontal: "rounded-action-sm", vertical: "rounded-action-xs" },
// 32px horizontal / ~28px vertical
default: { horizontal: "rounded-action", vertical: "rounded-action-sm" },
// 40px horizontal / ~33px vertical
lg: { horizontal: "rounded-action-lg", vertical: "rounded-action" },
}
// Label padding tracks the item padding so the label stays flush with the
// item text. The micro-cap steps TWO type tiers behind the items: capitals
// fill the whole letter height and the label is semibold and tracked, so one
// tier behind read louder than the links under it. `sm` stops at the ramp's
// floor, 11px.
const LABEL_SIZE: Record<NavSize, string> = {
sm: "px-2 text-2xs",
default: "px-3 text-2xs",
lg: "px-3 text-1xs",
}
// The plain variant's item padding. No start inset: with no fill to sit in, the
// text starts on the list's own edge, under its label, and a deeper level
// indents from there in whole steps. The vertical padding is the plain vertical
// row's, so rows stay tight and keep the touch floor.
const PLAIN_SIZE: Record<NavSize, string> = {
sm: "ps-2.5 pe-2 py-1 pointer-coarse:py-2.5",
default: "ps-3 pe-3 py-1 pointer-coarse:py-2.5",
lg: "ps-3 pe-3 py-1.5 pointer-coarse:py-2.5",
}
const NavContext = createContext<{
orientation: NavOrientation
size: NavSize
variant: NavVariant
pillReady: boolean
}>({ orientation: "horizontal", size: "default", variant: "pill", pillReady: false })
// How far the overflow fade reaches in from an edge (px), the same as Tabs and
// ScrollFade, so every sideways strip fades alike.
const FADE = 24
// @use-when a row or column of navigation items with a current-page state: the
// sidebar of an app shell (dashboard, settings), or a row of section links.
// Not AppShell, which is the whole page frame a sidebar Nav sits inside. A
// vertical item takes a `description` second line: a list of emails or documents beside an editor.
// `variant="plain"` is the table of contents: an "on this page" list of links to
// spots on the page, the current one in accent text instead of a sliding pill.
function Nav({
orientation = "horizontal",
size = "default",
variant: variantProp = "pill",
className,
style,
children,
...props
}: React.ComponentProps<"nav"> & {
orientation?: NavOrientation
size?: NavSize
/** `pill` (default): a sliding filled indicator. `plain`: text only, the current item in accent, for a table of contents. Vertical only. */
variant?: NavVariant
}) {
// A quiet text list is a column idea; a horizontal row keeps the pill.
const variant: NavVariant = orientation === "vertical" ? variantProp : "pill"
if (
process.env.NODE_ENV !== "production" &&
variantProp === "plain" &&
orientation === "horizontal"
) {
console.warn('Nav: variant="plain" is vertical only; this horizontal Nav keeps the pill.')
}
const navRef = useRef<HTMLElement>(null)
const [pill, setPill] = useState<{
x: number
y: number
width: number
height: number
/** Set when the box moved because a trigger resized (a count's slot
* opening or closing, a font landing), not because the pick changed. */
follow?: boolean
} | null>(null)
const [pillReady, setPillReady] = useState(false)
const shouldReduceMotion = useReducedMotion()
useIsomorphicLayoutEffect(() => {
const root = navRef.current
if (!root) return
// The plain variant renders no indicator, so there is nothing to measure.
if (variant === "plain") {
setPill(null)
return
}
const measure = (follow = false) => {
const active = root.querySelector<HTMLElement>(
'[data-slot="nav-item-link"][data-active]'
)
if (!active) {
setPill(null)
return
}
// Items can live inside li/ul/section wrappers, so an offsetLeft walk
// against the list isn't enough: measure both boxes in viewport space
// and take the delta against the nav root, the pill's own anchor. The
// root can scroll (horizontal overflow), and the pill lives in its
// CONTENT space, so fold the scroll offset back in; the position then
// stays correct at any scroll without re-measuring.
const rootRect = root.getBoundingClientRect()
const activeRect = active.getBoundingClientRect()
setPill({
x: activeRect.left - rootRect.left + root.scrollLeft,
y: activeRect.top - rootRect.top + root.scrollTop,
width: activeRect.width,
height: activeRect.height,
follow,
})
setPillReady(true)
}
measure()
// A nav that scrolls sideways (more links than its container is wide)
// brings the current item into view, centred, so the reader can see which
// page they are on. Once per change of items, never on resize, so it does
// not fight a reader who has scrolled the row themselves. Only the nav
// scrolls, never the page.
const current = root.querySelector<HTMLElement>(
'[data-slot="nav-item-link"][data-active]'
)
if (orientation === "horizontal" && current && root.scrollWidth > root.clientWidth) {
const rootRect = root.getBoundingClientRect()
const currentRect = current.getBoundingClientRect()
if (currentRect.left < rootRect.left || currentRect.right > rootRect.right) {
root.scrollLeft +=
currentRect.left - rootRect.left - (rootRect.width - currentRect.width) / 2
}
}
// Items resize on font load, container resize, and count changes. A
// resize is followed frame by frame with no spring: a count's slot tweens
// the item's width, and a spring retargeted every frame would trail the
// item's edge. Only a change of page slides. The observer reports once on
// connect, which `measure()` above already covered, so that first report
// is skipped or it would cancel the slide a new page just started.
let connected = false
const observer = new ResizeObserver(() => {
if (connected) measure(true)
connected = true
})
observer.observe(root)
root
.querySelectorAll('[data-slot="nav-item-link"]')
.forEach((el) => observer.observe(el))
return () => observer.disconnect()
}, [children, orientation, variant])
// Overflow fades for a horizontal nav that scrolls, the same as TabsList:
// each edge fades only while there is more past it, ramping in with scroll
// distance, so a nav that fits shows none. A MASK, not a painted gradient,
// so it matches whatever surface the nav sits on (a FloatingBar, a header).
// Written straight to the DOM so scrolling never re-renders.
useIsomorphicLayoutEffect(() => {
const root = navRef.current
if (!root || orientation !== "horizontal") return
const update = () => {
const scroll = Math.abs(root.scrollLeft)
const overflow = root.scrollWidth - root.clientWidth
root.style.setProperty("--nav-fade-start", `${Math.max(Math.min(scroll, FADE), 0)}px`)
root.style.setProperty("--nav-fade-end", `${Math.max(Math.min(overflow - scroll, FADE), 0)}px`)
}
update()
root.addEventListener("scroll", update, { passive: true })
const observer = new ResizeObserver(update)
observer.observe(root)
root
.querySelectorAll('[data-slot="nav-item-link"]')
.forEach((el) => observer.observe(el))
return () => {
root.removeEventListener("scroll", update)
observer.disconnect()
}
}, [children, orientation])
const mask =
orientation === "horizontal"
? "linear-gradient(to right, transparent 0, #000 var(--nav-fade-start, 0px), #000 calc(100% - var(--nav-fade-end, 0px)), transparent 100%)"
: undefined
return (
<NavContext.Provider value={{ orientation, size, variant, pillReady }}>
<nav
ref={navRef}
data-slot="nav"
data-orientation={orientation}
data-variant={variant}
style={mask ? { maskImage: mask, WebkitMaskImage: mask, ...style } : style}
className={cn(
"relative",
ROOT_SIZE[size],
// A horizontal nav wider than its container scrolls instead of
// clipping items, same treatment as TabsList.
orientation === "horizontal" &&
"max-w-full overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",
className
)}
{...props}
>
{/* Rendered before the items so they paint over it. */}
{pill && (
<motion.span
aria-hidden
data-slot="nav-indicator"
className={cn(
// ui-md-allow-physical-direction: the indicator is placed by a translate from the item's measured offset, which is physical
"pointer-events-none absolute top-0 left-0 bg-accent-100 dark:bg-accent-800",
// Must stay equal to the item's own radius (ITEM_RADIUS).
// Change one, change the other.
ITEM_RADIUS[size][orientation]
)}
// initial={false}: adopt the first measurement instead of
// animating in from x:0/y:0/width:0/height:0 on mount.
initial={false}
animate={{ x: pill.x, y: pill.y, width: pill.width, height: pill.height }}
transition={shouldReduceMotion || pill.follow ? { duration: 0 } : PILL.spring}
/>
)}
{children}
</nav>
</NavContext.Provider>
)
}
function NavList({ className, ...props }: React.ComponentProps<"ul">) {
const { orientation, variant } = useContext(NavContext)
return (
<ul
data-slot="nav-list"
className={cn(
orientation === "horizontal"
? "flex items-center gap-1"
: variant === "plain"
? // A hairline track down the start edge; the current item paints
// its own stretch of it in the accent (NavItem).
"flex flex-col border-s border-border"
: "flex flex-col gap-0.5",
className
)}
{...props}
/>
)
}
function NavSection({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="nav-section"
className={cn("mb-(--spacing-rhythm-peer) last:mb-0", className)}
{...props}
/>
)
}
function NavLabel({ className, ...props }: React.ComponentProps<"div">) {
const { size, variant } = useContext(NavContext)
return (
<div
data-slot="nav-label"
className={cn(
"mb-(--spacing-rhythm-label) text-foreground",
variant === "plain"
? // A quiet heading for a quiet list: sentence case at the items'
// own size, one weight up from them, on the list's start edge.
"font-medium"
: cn("font-semibold tracking-wide uppercase", LABEL_SIZE[size]),
className
)}
{...props}
/>
)
}
// Polymorphic link. Renders an <a> by default; pass `render={<Link />}`
// (or any element) to compose with a router. Never uses `asChild`.
function NavItem({
icon,
count,
description,
active,
truncate = false,
"aria-current": ariaCurrent,
className,
render,
children,
...props
}: useRender.ComponentProps<"a"> & {
icon?: React.ReactNode
count?: React.ReactNode
/** A second line under the label, for a vertical item: timing, a status, a short preview. Plain text. Both lines cut short with an ellipsis. A horizontal item ignores it. */
description?: React.ReactNode
active?: boolean
/** Cut a long label short with an ellipsis instead of running past the row. Pass a plain-text label. */
truncate?: boolean
}) {
const { orientation, size, variant, pillReady } = useContext(NavContext)
const plain = variant === "plain"
// Two lines are a vertical idea: a horizontal item is a fixed-height control
// in a row, so it stays one line and ignores `description`.
const described = orientation === "vertical" && description != null
const label = (
<span
className={cn(
"inline-flex items-center",
// A vertical row is a fixed-width column, so its label must
// be allowed to shrink or a long one runs past the pill.
orientation === "vertical" && "min-w-0",
ITEM_SIZE[size].label
)}
>
{icon}
{truncate || described ? <span className="truncate">{children}</span> : children}
</span>
)
const countChip = (
<CountArrival
count={count}
// The link's own gap and the label row's are the same step (ITEM_SIZE),
// so one value cancels either while the slot is closed. A vertical row
// pushes the chip to its far edge, so it holds still there.
gap={ITEM_SIZE[size].label}
pinned={orientation === "vertical" ? "end" : "start"}
data-slot="nav-item-count"
className={cn(
// The chip recipe is tabs.tsx's, verbatim: active gets a
// solid accent FILL, not an accent number (accent-on-accent
// fails contrast), and the fill tracks the LABEL's accent
// step per mode so the count is never the dimmer of the
// two. tabular-nums so a live count doesn't jitter.
// `transition-colors` (background included) is safe HERE:
// the chip paints above the pill inside the positioned
// link, so its fill can cross-fade without muddying the
// indicator. 150ms keeps it paired with the label.
"inline-flex items-center justify-center gap-1 rounded-full font-medium tabular-nums transition-colors duration-small ease-small [&_svg]:shrink-0",
COUNT_SIZE[size],
active
? "bg-accent text-accent-foreground dark:bg-accent-400 dark:text-accent-950"
: "bg-neutral-500/10 dark:bg-neutral-500/15 text-muted-foreground"
)}
/>
)
return (
<li data-slot="nav-item">
{useRender({
render: render ?? <a />,
props: {
"data-slot": "nav-item-link",
"data-active": active ? true : undefined,
// `page` unless the caller names another kind: a table of contents
// passes `aria-current="location"`. Only ever set on the active item.
"aria-current": active ? (ariaCurrent ?? "page") : undefined,
className: plain
? cn(
// The plain variant: text, and its stretch of the list's track.
// Regular weight in every state, so it reads quieter than a
// pill sidebar beside it. Only colours change: the text and
// the 1px edge laid over the track (`-ms-px`), accent on the
// current item. No radius, fill or press, and nothing slides,
// so nothing moves while the page scrolls under it.
"relative -ms-px flex w-full min-w-0 items-center justify-between border-s border-transparent font-normal outline-none transition-[color,border-color] duration-small ease-small motion-reduce:transition-none focus-visible:rounded-xs focus-visible:ring-[3px] focus-visible:ring-ring-focus [&_svg]:shrink-0",
ITEM_SIZE[size].shared,
PLAIN_SIZE[size],
active ? "border-accent text-accent" : "text-muted-foreground hover:text-foreground",
className
)
: cn(
// `transition-[color]`, NOT `transition-colors`: background-color
// must NOT transition here. The indicator renders before the items
// so they paint over it, which means a hover fill that fades out
// sits ON TOP of the arriving pill and muddies it. Clearing the
// fill instantly also matches the frequency principle: a nav item
// is a 100+/day hover, and those should not animate. `transform`
// is in the list so the 0.98 press eases back like a Button's;
// reduced motion keeps the colour change and drops the press.
"relative flex items-center font-medium whitespace-nowrap outline-none transition-[color,transform] duration-small ease-small motion-reduce:transition-[color] rotate-[0.0001deg] active:scale-[0.98] focus-visible:ring-ring-focus focus-visible:ring-[3px] [&_svg]:shrink-0",
ITEM_RADIUS[size][orientation],
ITEM_SIZE[size].shared,
// `justify-between` rather than `justify-start`, same move as the
// vertical tabs trigger: the count is a SIBLING of the label span,
// so between pushes it to the trailing edge, which is how a column
// of counts is read (every mail sidebar does this). With no count
// there is only one child, and between puts a lone child at the
// start, so an item without one is unaffected and nothing reflows.
orientation === "horizontal"
? cn(ITEM_SIZE[size].horizontal, icon != null && ITEM_SIZE[size].iconStart)
: cn(
"w-full min-w-0 justify-between",
ITEM_SIZE[size][described ? "described" : "vertical"]
),
active
? cn("text-accent-700 dark:text-accent-200", !pillReady && "bg-accent-100 dark:bg-accent-800")
: "text-muted-foreground hover:text-foreground hover:bg-neutral-500/10",
className
),
children: described ? (
// One column: the label row (with the count) over the meta line.
// The count belongs to line 1 and is centred on it, because it
// labels the item and not the meta under it; sitting it in the
// label row, not at the link's own edge, is what keeps it there.
<span className="flex min-w-0 flex-1 flex-col">
<span className={cn("flex items-center justify-between", ITEM_SIZE[size].label)}>
{label}
{countChip}
</span>
<span
data-slot="nav-item-description"
className={cn(
"truncate font-normal transition-[color] duration-small ease-small",
DESCRIPTION_SIZE[size],
icon != null && ITEM_SIZE[size].indent,
// subtle-foreground reads on the light pill (about 4.2:1
// on accent-100) but not on the dark one (about 2.6:1 on
// accent-800), so an active row takes the muted tone in both
// modes (about 5:1 on the dark pill). Re-measure if either moves.
active ? "text-muted-foreground" : "text-subtle-foreground"
)}
>
{description}
</span>
</span>
) : (
<>
{label}
{countChip}
</>
),
...props,
},
})}
</li>
)
}
export { Nav, NavList, NavSection, NavLabel, NavItem }type ActiveHrefResolver = (pathname: string, hrefs: string[]) => string | null
// THE ALIAS ABOVE IS LOAD-BEARING. Do not fold it into the signature below.
//
// The shadcn CLI reprints every file it installs, and everything above the
// file's FIRST STATEMENT is dropped on the way: plain comments and JSDoc
// alike, the whole run of it. This module used to open with the warning below
// and the resolver's own JSDoc, and a consumer received neither, on every
// pull. One real statement in front of them is what makes them survive, and it
// may as well be a useful one: this is the resolver's shape, for a consumer
// threading it through props or a config object. `verify:registry` fails the
// build if a comment ever leads this file again.
//
// NO "use client" HERE, ON PURPOSE.
//
// `nav.tsx` is a client module (Motion, layout effects, context), and under
// React Server Components EVERY export of a client module becomes a client
// reference: renderable, passable as a prop, never CALLED on the server. This
// resolver is meant to be called while rendering, and an App Router page is a
// Server Component by default, so declaring it inside `nav.tsx` would hard-fail
// the production build the moment a server page used it:
//
// Attempted to call resolveActiveHref() from the server but
// resolveActiveHref is on the client.
//
// Re-exporting it from `nav.tsx` would NOT fix that, because the re-export is
// itself a client reference. It lives here, with no directive, so both graphs
// can import it. Same reason `button-variants.ts` and `site-header-classes.ts`
// exist. There is deliberately no back-compat re-export from `nav.tsx`: this
// export is new, so nothing imports it from there yet, and adding one would
// only hand callers the broken path.
//
// This is a pure function. `Nav` does not read the router itself and must not
// start: the kit is router-agnostic, and `SiteHeader` is explicit that the
// shell never learns what page it is on. The consumer resolves the route and
// hands `active` down.
/**
* Resolves the one nav href that should be marked active for a pathname.
*
* "/" only matches an exact "/". Every other href matches on a path-segment
* boundary (the pathname equals the href, or starts with `${href}/`), so
* "/shop" does not also match "/shopping". When more than one href matches
* (nested sections, e.g. "/shop" and "/shop/vip"), the longest one wins.
* Returns null when nothing matches.
*
* `Nav` requires that EXACTLY ONE item carry `active`. Its pill is a single
* sliding element that takes the first `[data-active]` it finds, while every
* active item paints its own accent colour, so two matches put the pill on one
* item and the colour on two. This returns at most one, always.
*
* Usage: resolve once, then compare each item against the result.
*
* const activeHref = resolveActiveHref(pathname, items.map((i) => i.href))
* items.map((i) => <NavItem active={i.href === activeHref} ... />)
*
* Hrefs need not be the link targets. When a section's link points at a page
* inside it, pass the section prefixes and compare against those instead.
*/
function resolveActiveHref(
pathname: string,
hrefs: string[]
): string | null {
let best: string | null = null
for (const href of hrefs) {
const matches =
href === "/"
? // 1. "/" is EXACT-ONLY. Prefix-matching root makes it active on
// every page in the site.
pathname === "/"
: // 2. SEGMENT-BOUNDARY matching, never a bare startsWith(href):
// "/shop" must not match "/shopping". This also means an external
// href ("https://...") can never match, with no branch for it.
pathname === href || pathname.startsWith(`${href}/`)
// 3. LONGEST WINS, so nested sections resolve to the innermost one and
// the answer is a single value rather than a set.
if (matches && (best === null || href.length > best.length)) {
best = href
}
}
return best
}
export { resolveActiveHref }
export type { ActiveHrefResolver }