# 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.

Status: Stable. Group: Navigation.

## 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.

## When not to use

- The choices are panels of one page. Use Tabs instead.
- The choices change how the same content is shown. Use Segmented control instead.
- There are more than five places. Use a menu or a drawer instead.

## Scenarios

### 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 avoid

- Do: Use a simple 22 px icon for each place and give every one a label; the label is the accessible name.
- Avoid: Rely on the icon alone for meaning.
- Do: Keep it to three to five places, in the same order on every screen.
- Avoid: Reorder or hide places by context.

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `label` | `string` |  | Required. Names the navigation landmark (aria-label): Main. |
| `items` | `PillNavItem[]` |  | id, label (the accessible name), icon (a ReactNode drawn with currentColor) and optional href for each place. |
| `value` | `string` |  | Controlled id of the current place. |
| `defaultValue` | `string` |  | Starting place when uncontrolled. Defaults to the first. |
| `onValueChange` | `(id: string) => void` |  | Called with the id when a place is chosen by click or arrow key. |
| `className` | `string` |  | Extra classes on the root, such as the fixed position. |

## Anatomy

1. Bar (`data-part="root"`): 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 (`data-part="item"`): 62 by 48 px pill, a button or a link, fg-muted and fg-strong when current.
3. Icon (`data-part="icon"`): 22 px, 1.5 px stroke in currentColor. Decorative; the label is read.
4. Thumb (`data-part="thumb"`): Surface pill with shadow 1 under the current place. One element that moves.

## Motion

| Interaction | Property | Duration | Easing | From the keyboard |
| --- | --- | --- | --- | --- |
| Choose with a pointer | thumb transform, retargeted mid-flight (shared with Tabs and Segmented control) | base | out | Arrow keys, Home and End move it at once. |
| Icon colour | color | quick | out | Same, colour only. |

## Accessibility

| Keys | Action |
| --- | --- |
| 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. |

- 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.

## Code

### PillNav.tsx

```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

```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
}
```

## HTML

The default example as plain HTML, for any stack. Needs nacre-theme.css.

```html
<nav aria-label="Main" data-part="root" class="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 ">
  <span aria-hidden="true" data-part="thumb" class="pointer-events-none absolute top-0 left-0 origin-top-left rounded-full bg-surface opacity-0 shadow-1"></span>
  <button type="button" aria-current="true" tabindex="0" data-state="on" data-id="home" data-part="item" data-press="" class="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 bg-surface text-fg-strong shadow-1 [[data-ready]&gt;&amp;]:bg-transparent [[data-ready]&gt;&amp;]:shadow-[0_0_#0000]">
    <span data-part="icon" aria-hidden="true" class="grid size-[22px] place-items-center [&amp;&gt;svg]:size-full">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
        <path d="M4 11l8-6 8 6v8a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1z"></path>
      </svg>
    </span>
    <span class="sr-only">Home</span>
  </button>
  <button type="button" tabindex="-1" data-state="off" data-id="calendar" data-part="item" data-press="" class="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 text-fg-muted hover:text-fg-strong">
    <span data-part="icon" aria-hidden="true" class="grid size-[22px] place-items-center [&amp;&gt;svg]:size-full">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
        <path d="M5 5h14a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1z"></path>
        <path d="M4 10h16M9 3v4M15 3v4"></path>
      </svg>
    </span>
    <span class="sr-only">Calendar</span>
  </button>
  <button type="button" tabindex="-1" data-state="off" data-id="library" data-part="item" data-press="" class="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 text-fg-muted hover:text-fg-strong">
    <span data-part="icon" aria-hidden="true" class="grid size-[22px] place-items-center [&amp;&gt;svg]:size-full">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
        <path d="M12 6c-2-1.5-5-2-8-1.5v13c3-.5 6 0 8 1.5 2-1.5 5-2 8-1.5v-13c-3-.5-6 0-8 1.5zM12 6v13"></path>
      </svg>
    </span>
    <span class="sr-only">Library</span>
  </button>
  <button type="button" tabindex="-1" data-state="off" data-id="chat" data-part="item" data-press="" class="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 text-fg-muted hover:text-fg-strong">
    <span data-part="icon" aria-hidden="true" class="grid size-[22px] place-items-center [&amp;&gt;svg]:size-full">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
        <path d="M5 5h14a1 1 0 0 1 1 1v9a1 1 0 0 1-1 1h-8l-5 4v-4H5a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1z"></path>
      </svg>
    </span>
    <span class="sr-only">Chat</span>
  </button>
</nav>
```

## Related

- [Segmented control](https://enxm.me/services/design-systems/nacre/components/segmented-control)
- [Tabs](https://enxm.me/services/design-systems/nacre/components/tabs)
