# Segmented control

Switches between two to five views or modes of the same content, and the change shows at once.

Status: Stable. Group: Inputs.

## When to use

- Changing the range of one view: Day, Week, Month in the calendar.
- Changing how the same list is shown: Board or List.

## When not to use

- Each option shows different content, such as Overview and Files. Use Tabs instead.
- The value is saved later with a form. Use Radio instead.
- It starts an action. Use Button instead.

## Scenarios

### Calendar range

Day, Week and Month sit above the calendar. The thumb glides to the new range while the grid redraws under it.

### Board or list

The project toolbar has a two-option control for Board and List; the choice is remembered per person.

## Do and avoid

- Do: Use one or two short words per option, all about the same length.
- Avoid: Put more than five options in one control; it stops reading as one choice.
- Do: Apply the change the moment an option is chosen.
- Avoid: Pair it with an Apply button.

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `label` | `string` |  | Names the control for assistive tech (aria-label on the radiogroup). |
| `options` | `SegmentedOption[]` |  | value, label and optional disabled for each segment. |
| `value` | `string` |  | Controlled value. |
| `defaultValue` | `string` |  | Starting value when uncontrolled. |
| `onValueChange` | `(value: string) => void` |  | Called with the chosen value. |
| `size` | `'sm' \| 'md'` | `'md'` | Segment height 28 or 32 px inside a 4 px track padding. |
| `disabled` | `boolean` | `false` | Disables every segment. |
| `fullWidth` | `boolean` | `false` | Stretches the track to its container and splits it evenly. |
| `invalid` | `boolean` | `false` | A 1 px error ring on the track and aria-invalid on the group. |
| `error` | `string` |  | The message under the track; implies invalid and is linked with aria-describedby. |
| `className` | `string` |  | Extra classes on the root. |
| `ref` | `Ref<HTMLDivElement>` |  | Reaches the root that holds the track and the message. React 19 passes ref as a plain prop. |

## Anatomy

1. Track (`data-part="track"`): Sunken full pill with 4 px padding.
2. Segment (`data-part="segment"`): Body 14/20, fg-muted, fg-strong when chosen; truncates instead of wrapping.
3. Thumb (`data-part="thumb"`): Surface pill with shadow 1 under the chosen segment. One element that moves.

## Motion

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

## Accessibility

| Keys | Action |
| --- | --- |
| Tab | Moves focus to the chosen segment. |
| Arrow keys | Choose the next or previous segment, skipping disabled ones. |
| Home and End | Choose the first or last segment. |

- role radiogroup with an aria-label; each segment is role radio with aria-checked.
- Roving tabindex: only the chosen segment is in the tab order.
- The choice is shown by the raised thumb as well as the darker label, never by colour alone.
- invalid or error sets aria-invalid; the error message is linked with aria-describedby.

## Code

### SegmentedControl.tsx

```tsx
'use client'
import { useId, useRef, useState, type KeyboardEvent, type Ref } from 'react'
import { useIndicator } from './Indicator'

// Nacre Segmented control: switch between two to five views of the same content. React plus Tailwind classes only;
// needs nacre-theme.css and Indicator.tsx (the gliding thumb it shares with Tabs). One thumb glides to the selection
// (base 240, out), retargeted mid-flight; arrow keys, Home and End move it at once.
// invalid rings the track; error is the message under it and implies invalid. ref reaches the root.

export type SegmentedOption = { value: string; label: string; disabled?: boolean }
export type SegmentedSize = 'sm' | 'md'

export type SegmentedControlProps = {
  label: string
  options: SegmentedOption[]
  value?: string
  defaultValue?: string
  onValueChange?: (value: string) => void
  size?: SegmentedSize
  disabled?: boolean
  fullWidth?: boolean
  className?: string
  invalid?: boolean
  error?: string
  ref?: Ref<HTMLDivElement>
}

const heights: Record<SegmentedSize, string> = { sm: 'h-7 px-2.5 text-label', md: 'h-8 px-3.5 text-body' }

export function SegmentedControl({ label, options, value, defaultValue, onValueChange, size = 'md', disabled = false, fullWidth = false, invalid = false, error, className = '', ref }: SegmentedControlProps) {
  const [inner, setInner] = useState(defaultValue)
  const current = value ?? inner
  const list = useRef<HTMLDivElement>(null)
  const keyboard = useRef(false)
  const thumb = useIndicator(list, current, keyboard)
  const errorId = `${useId()}-error`
  const bad = invalid || Boolean(error)
  const enabled = disabled ? [] : options.filter((o) => !o.disabled)
  // The tab stop is the selected option, or the first enabled one when nothing is selected yet.
  const tabStop = options.some((o) => o.value === current) ? current : enabled[0]?.value
  const choose = (v: string) => {
    if (value === undefined) setInner(v)
    onValueChange?.(v)
  }
  const onKey = (e: KeyboardEvent<HTMLButtonElement>) => {
    const n = enabled.length
    if (!n) return
    const at = enabled.findIndex((o) => o.value === current)
    const next = e.key === 'ArrowRight' || e.key === 'ArrowDown'
    const prev = e.key === 'ArrowLeft' || e.key === 'ArrowUp'
    const to =
      next ? enabled[at < 0 ? 0 : (at + 1) % n]
      : prev ? enabled[at < 0 ? n - 1 : (at - 1 + n) % n]
      : e.key === 'Home' ? enabled[0]
      : e.key === 'End' ? enabled[n - 1]
      : undefined
    if (!to) return
    e.preventDefault()
    choose(to.value)
    list.current?.querySelector<HTMLElement>(`[data-value="${CSS.escape(to.value)}"]`)?.focus()
  }
  return (
    <div ref={ref} data-part="root" className={`max-w-full flex-col gap-1.5 ${fullWidth ? 'flex w-full' : 'inline-flex items-start'} ${className}`}>
      <div
        ref={list}
        role="radiogroup"
        aria-label={label}
        aria-disabled={disabled || undefined}
        aria-invalid={bad || undefined}
        aria-describedby={error ? errorId : undefined}
        data-part="track"
        onKeyDown={() => { keyboard.current = true }}
        onPointerDown={() => { keyboard.current = false }}
        className={`relative max-w-full gap-0.5 rounded-full bg-sunken p-1 ring-1 ${fullWidth ? 'flex w-full' : 'inline-flex'} ${bad ? 'ring-error' : 'ring-line-subtle'}`}
      >
        <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" />
        {options.map((o) => {
          const on = o.value === current
          return (
            <button
              key={o.value}
              type="button"
              role="radio"
              aria-checked={on}
              data-state={on ? 'on' : 'off'}
              data-value={o.value}
              data-part="segment"
              disabled={disabled || o.disabled}
              tabIndex={o.value === tabStop ? 0 : -1}
              onClick={() => choose(o.value)}
              onKeyDown={onKey}
              className={`relative min-w-0 ${fullWidth ? 'flex-1' : 'flex-auto'} cursor-pointer truncate rounded-full font-[600] transition-colors duration-(--nx-dur-quick) ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus disabled:cursor-not-allowed disabled:text-fg-disabled ${heights[size]} ${on ? 'bg-surface text-fg-strong shadow-1 [[data-ready]>&]:bg-transparent [[data-ready]>&]:shadow-[0_0_#0000]' : 'text-fg-muted enabled:hover:text-fg-strong'}`}
            >
              {o.label}
            </button>
          )
        })}
      </div>
      {error && <p data-part="error" id={errorId} className="text-caption text-error-strong transition-opacity duration-(--nx-dur-quick) ease-out starting:opacity-0">{error}</p>}
    </div>
  )
}
```

### 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
<div data-part="root" class="max-w-full flex-col gap-1.5 inline-flex items-start ">
  <div role="radiogroup" aria-label="Calendar range" data-part="track" class="relative max-w-full gap-0.5 rounded-full bg-sunken p-1 ring-1 inline-flex ring-line-subtle">
    <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" role="radio" aria-checked="false" data-state="off" data-value="day" data-part="segment" tabindex="-1" class="relative min-w-0 flex-auto cursor-pointer truncate rounded-full font-[600] transition-colors duration-(--nx-dur-quick) ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus disabled:cursor-not-allowed disabled:text-fg-disabled h-8 px-3.5 text-body text-fg-muted enabled:hover:text-fg-strong">Day</button>
    <button type="button" role="radio" aria-checked="true" data-state="on" data-value="week" data-part="segment" tabindex="0" class="relative min-w-0 flex-auto cursor-pointer truncate rounded-full font-[600] transition-colors duration-(--nx-dur-quick) ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus disabled:cursor-not-allowed disabled:text-fg-disabled h-8 px-3.5 text-body bg-surface text-fg-strong shadow-1 [[data-ready]&gt;&amp;]:bg-transparent [[data-ready]&gt;&amp;]:shadow-[0_0_#0000]">Week</button>
    <button type="button" role="radio" aria-checked="false" data-state="off" data-value="month" data-part="segment" tabindex="-1" class="relative min-w-0 flex-auto cursor-pointer truncate rounded-full font-[600] transition-colors duration-(--nx-dur-quick) ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus disabled:cursor-not-allowed disabled:text-fg-disabled h-8 px-3.5 text-body text-fg-muted enabled:hover:text-fg-strong">Month</button>
  </div>
</div>
```

## Related

- [Radio](https://enxm.me/services/design-systems/nacre/components/radio)
- [Tabs](https://enxm.me/services/design-systems/nacre/components/tabs)
