Components / NavigationStable

Pill nav

A floating translucent pill with three to five top-level places for a phone app. A white thumb glides to the place you are in.

View as Markdown

Playground

Code

PillNav.tsx
'use client'
import { useRef, useState, type KeyboardEvent, type ReactNode } from 'react'
import { useIndicator } from './Indicator'

// Nacre PillNav: the floating bar of three to five top-level places in a phone app. React plus Tailwind classes
// only; needs nacre-theme.css and Indicator.tsx (the gliding thumb it shares with Tabs and Segmented control). A
// translucent pill (the surface at 75 % with an 18 px blur; the solid surface without backdrop-filter), each place a
// 62 by 48 pill that is a link when it has an href and a button otherwise. Place it with fixed or absolute
// positioning at the bottom of the screen. Motion: one white thumb glides to the chosen place (base 240, out), by
// transform only and retargeted mid-flight; arrow keys, Home and End move it at once, as do reduced motion and
// [data-nacre-motion="off"].

export type PillNavItem = {
  id: string
  /** The accessible name; the icon is decorative. */
  label: string
  /** An icon that draws with currentColor, about 22 px. */
  icon: ReactNode
  /** Makes the place a link; the current one gets aria-current="page". */
  href?: string
}

export type PillNavProps = {
  /** Names the navigation landmark. */
  label: string
  items: PillNavItem[]
  value?: string
  defaultValue?: string
  onValueChange?: (id: string) => void
  className?: string
}

export function PillNav({ label, items, value, defaultValue, onValueChange, className = '' }: PillNavProps) {
  const [inner, setInner] = useState(defaultValue ?? items[0]?.id)
  const current = value ?? inner
  const list = useRef<HTMLElement>(null)
  const keyboard = useRef(false)
  const thumb = useIndicator(list, current, keyboard)
  const choose = (id: string) => {
    if (value === undefined) setInner(id)
    onValueChange?.(id)
  }
  // The tab stop is the current place, or the first one when nothing is chosen.
  const tabStop = items.some((i) => i.id === current) ? current : items[0]?.id
  const onKey = (e: KeyboardEvent<HTMLElement>) => {
    const n = items.length
    const at = items.findIndex((i) => i.id === current)
    const to =
      e.key === 'ArrowRight' ? items[at < 0 ? 0 : (at + 1) % n]
      : e.key === 'ArrowLeft' ? items[at < 0 ? n - 1 : (at - 1 + n) % n]
      : e.key === 'Home' ? items[0]
      : e.key === 'End' ? items[n - 1]
      : undefined
    if (!to) return
    e.preventDefault()
    choose(to.id)
    list.current?.querySelector<HTMLElement>(`[data-id="${CSS.escape(to.id)}"]`)?.focus()
  }
  return (
    <nav
      ref={list}
      aria-label={label}
      data-part="root"
      onKeyDown={(e) => { keyboard.current = true; onKey(e) }}
      onPointerDown={() => { keyboard.current = false }}
      className={`relative inline-flex gap-0.5 rounded-full bg-[color-mix(in_oklab,var(--nx-surface)_75%,transparent)] p-1.5 shadow-3 ring-1 ring-line-subtle backdrop-blur-[18px] supports-[not(backdrop-filter:blur(1px))]:bg-surface ${className}`}
    >
      <span ref={thumb} aria-hidden="true" data-part="thumb" className="pointer-events-none absolute top-0 left-0 origin-top-left rounded-full bg-surface opacity-0 shadow-1" />
      {items.map((it) => {
        const on = it.id === current
        const Tag = it.href ? 'a' : 'button'
        return (
          <Tag
            key={it.id}
            {...(it.href ? { href: it.href } : { type: 'button' as const })}
            aria-current={on ? (it.href ? 'page' : 'true') : undefined}
            tabIndex={it.id === tabStop ? 0 : -1}
            data-state={on ? 'on' : 'off'}
            data-id={it.id}
            data-part="item"
            data-press=""
            onClick={() => choose(it.id)}
            className={`relative grid h-12 w-[62px] cursor-pointer place-items-center rounded-full transition-colors duration-(--nx-dur-quick) ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus ${on ? 'bg-surface text-fg-strong shadow-1 [[data-ready]>&]:bg-transparent [[data-ready]>&]:shadow-[0_0_#0000]' : 'text-fg-muted hover:text-fg-strong'}`}
          >
            <span data-part="icon" aria-hidden="true" className="grid size-[22px] place-items-center [&>svg]:size-full">{it.icon}</span>
            <span className="sr-only">{it.label}</span>
          </Tag>
        )
      })}
    </nav>
  )
}
Indicator.tsx
'use client'
import { useLayoutEffect, useRef, type RefObject } from 'react'

// Nacre gliding indicator: the one moving selection that Segmented control and Tabs share. React only; copy it next
// to SegmentedControl.tsx or Tabs.tsx. Motion: base 240 out (a line stretches across on the way), by transform only,
// retargeted from where it is drawn.

type Box = { x: number; y: number; w: number; h: number }
const same = (a: Box, b: Box) => a.x === b.x && a.y === b.y && a.w === b.w && a.h === b.h

/** A duration token in ms, read from CSS so a slowed-down parent slows this too. */
export function tokenMs(el: Element, name: string, fallback: number): number {
  const v = getComputedStyle(el).getPropertyValue(name).trim()
  const n = parseFloat(v)
  if (!Number.isFinite(n)) return fallback
  return v.endsWith('ms') ? n : v.endsWith('s') ? n * 1000 : n
}

/** Reduced motion, or an ancestor that switched motion off, means no movement. */
export function motionOk(el: Element): boolean {
  return !window.matchMedia('(prefers-reduced-motion: reduce)').matches && !el.closest('[data-nacre-motion="off"]')
}

/**
 * One thumb under the child of `list` marked data-state="on". The thumb is laid out at the new item at once (width and
 * height set, never animated) and a FLIP transform carries it from where it is drawn now, so a change in mid-flight
 * continues from there instead of jumping or restarting. First placement, resizes, keyboard changes (keyboard.current)
 * and reduced motion are instant. `line` draws a 2 px bar on the item's bottom edge instead of a fill; it reaches over
 * both items before it lets go of the old one. The list gets data-ready once the thumb is placed; until then the
 * selected item draws its own selection.
 */
export function useIndicator(list: RefObject<HTMLElement | null>, active: string | undefined, keyboard: RefObject<boolean>, line = false) {
  const thumb = useRef<HTMLSpanElement>(null)
  const last = useRef<Box | null>(null)
  useLayoutEffect(() => {
    const c = list.current
    const t = thumb.current
    if (!c || !t) return
    const place = (animate: boolean) => {
      const item = c.querySelector<HTMLElement>(':scope > [data-state="on"]')
      if (!item || !item.offsetWidth) {
        c.removeAttribute('data-ready')
        t.style.opacity = '0'
        last.current = null
        return
      }
      const box: Box = line
        ? { x: item.offsetLeft, y: item.offsetTop + item.offsetHeight - 1, w: item.offsetWidth, h: 2 }
        : { x: item.offsetLeft, y: item.offsetTop, w: item.offsetWidth, h: item.offsetHeight }
      if (!animate && last.current && same(last.current, box)) return
      const running = t.getAnimations()
      let from = last.current
      if (running.length) {
        const cr = c.getBoundingClientRect()
        const tr = t.getBoundingClientRect()
        from = { x: tr.left - cr.left - c.clientLeft, y: tr.top - cr.top - c.clientTop, w: tr.width, h: tr.height }
        running.forEach((a) => a.cancel())
      }
      t.style.width = `${box.w}px`
      t.style.height = `${box.h}px`
      t.style.transform = `translate(${box.x}px, ${box.y}px)`
      t.style.opacity = '1'
      c.setAttribute('data-ready', '')
      last.current = box
      if (!animate || !from || same(from, box) || keyboard.current || !motionOk(c)) return
      const easing = getComputedStyle(c).getPropertyValue('--nx-ease-out').trim() || 'cubic-bezier(.23, 1, .32, 1)'
      const at = (b: Box) => `translate(${b.x}px, ${b.y}px) scale(${b.w / box.w}, ${b.h / box.h})`
      // The line stretches over both tabs on the way (leading edge first), then lets go of the old one.
      const reach = { x: Math.min(from.x, box.x), y: box.y, w: Math.max(from.x + from.w, box.x + box.w) - Math.min(from.x, box.x), h: box.h }
      const frames = line && from.y === box.y ? [{ transform: at(from) }, { transform: at(reach), offset: 0.4 }, { transform: at(box) }] : [{ transform: at(from) }, { transform: at(box) }]
      t.animate(frames, { duration: tokenMs(c, '--nx-dur-base', 240), easing })
    }
    let cancelled = false
    place(true)
    const ro = new ResizeObserver(() => place(false))
    ro.observe(c)
    document.fonts?.ready.then(() => { if (!cancelled) place(false) })
    return () => {
      cancelled = true
      ro.disconnect()
    }
  }, [list, active, keyboard, line])
  return thumb
}

Usage

When to use

  • The main navigation of a phone app, floating above the content at the bottom of the screen.
  • Switching between top-level places such as Home, Calendar, Library and Chat, one tap away from anywhere.

Choose something else when

In the Nacre workspace

App home

Four places float over the bottom of the Home screen. Choosing Calendar slides the white thumb across and the screen changes behind the glass.

Link places

Each place has an href. The current one carries aria-current="page", and onValueChange lets the app update its state as the route changes.

Do and don't

  • DoUse a simple 22 px icon for each place and give every one a label; the label is the accessible name.

    Don'tRely on the icon alone for meaning.

  • DoKeep it to three to five places, in the same order on every screen.

    Don'tReorder or hide places by context.

Anatomy

  1. Bar. Full pill, the surface at 75 % over an 18 px blur (the solid surface when blur is not available), 6 px padding, a 1 px line-subtle ring and shadow 3.
  2. Place. 62 by 48 px pill, a button or a link, fg-muted and fg-strong when current.
  3. Icon. 22 px, 1.5 px stroke in currentColor. Decorative; the label is read.
  4. Thumb. Surface pill with shadow 1 under the current place. One element that moves.

API

labelType stringDefault -Required. Names the navigation landmark (aria-label): Main.
itemsType PillNavItem[]Default -id, label (the accessible name), icon (a ReactNode drawn with currentColor) and optional href for each place.
valueType stringDefault -Controlled id of the current place.
defaultValueType stringDefault -Starting place when uncontrolled. Defaults to the first.
onValueChangeType (id: string) => voidDefault -Called with the id when a place is chosen by click or arrow key.
classNameType stringDefault -Extra classes on the root, such as the fixed position.

Motion

Choose with a pointerProperty thumb transform, retargeted mid-flight (shared with Tabs and Segmented control)Duration base 240Easing outKeyboard Arrow keys, Home and End move it at once.
Icon colourProperty colorDuration quick 160Easing outKeyboard Same, colour only.

Accessibility

Keyboard

Tab
Moves focus to the current place (one tab stop).
Arrow keys
Choose and focus the next or previous place, wrapping at the ends.
Home and End
Choose and focus the first or last place.
Enter, Space
Activates a button place. Enter follows a link place.

ARIA and semantics

  • A nav landmark named by label. Links are native links, buttons are native buttons.
  • The current place has aria-current="page" when it is a link and aria-current="true" when it is a button.
  • Each place is named by a hidden label; the icon is aria-hidden.
  • Roving tabindex: only the current place is in the tab order.

Contrast

Current icon on the thumbfg-strong on surfaceLight 19.01:1Dark 16.29:1Needs 4.5:1
Other icons on the barfg-muted on surfaceLight 5.57:1Dark 6.68:1Needs 4.5:1
Focus ringfocus on pageLight 3.74:1Dark 13.14:1Needs 3:1