# Tabs

Splits related content into panels so the reader sees one at a time without leaving the page.

Status: Stable. Group: Navigation.

## When to use

- Sections of one object: a project with Overview, Tasks and Files.
- Settings grouped by topic, when each group is long enough to deserve its own panel.
- Code in several forms, such as React and HTML, as on this page.

## When not to use

- It changes how the same data is shown (day, week, month). Use Segmented control instead.
- The panels are steps that must be done in order. Use a step indicator instead.
- Each panel is a separate destination with its own URL. Use links in the navigation instead.

## Scenarios

### Project page

Overview, Tasks and Files sit under the project title, in the pill track or, on a page with its own rule, the line variant. The tab names never change, so people learn where things are.

### Message filters

In the inbox side panel, the default pill variant switches between All, Mentions and Unread in a narrow column.

## Do and avoid

- Do: Keep labels to one or two words and the count of tabs low, up to six.
- Avoid: Let tabs wrap onto three lines or scroll sideways.
- Do: Keep the panel content related, so moving between tabs feels like one object.
- Avoid: Hide a required form step behind a tab people may never open.

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `label` | `string` |  | Names the tab list for assistive tech (aria-label). |
| `items` | `TabItem[]` |  | value, label, content and optional disabled for each tab. |
| `value` | `string` |  | Controlled selected value. |
| `defaultValue` | `string` | `first enabled item` | Starting tab when uncontrolled. |
| `onValueChange` | `(value: string) => void` |  | Called with the new value on click or arrow key. |
| `variant` | `'pill' \| 'line'` | `'pill'` | Pill is the default: the same sunken track and white thumb as Segmented control. Line is a rule under page sections. |
| `size` | `'sm' \| 'md'` | `'md'` | Tab height 28 or 32 px (pill), 32 or 40 px (line). |
| `className` | `string` |  | Extra classes on the root. |

## Anatomy

1. Tab (`data-part="tab"`): Body 14/20, fg-muted, fg-strong when selected.
2. Tab list (`data-part="list"`): Pill: a sunken track with a 1 px line-subtle ring, padding 4 px, 2 px between tabs, the same track as Segmented control. Line: one 1 px line-subtle rule under the tabs.
3. Indicator (`data-part="indicator"`): Pill: a surface thumb with shadow 1. Line: a 2 px action bar over the rule. One element that moves.
4. Panel (`data-part="panel"`): 16 px below the list, focusable so keyboard users can reach content without controls.

## Motion

| Interaction | Property | Duration | Easing | From the keyboard |
| --- | --- | --- | --- | --- |
| Select a tab | indicator transform, retargeted mid-flight; the line reaches across both tabs | base | out | Arrow keys, Home and End move it at once. |
| Panel change | old panel opacity on top; new panel opacity and translateY 4 px | base | out | Arrow keys swap panels at once. |
| Hover | color | quick | out | Focus shows the ring at once. |

## Accessibility

| Keys | Action |
| --- | --- |
| Tab | Moves focus to the selected tab, then into the panel. |
| Left and Right arrows | Select the previous or next tab, skipping disabled ones. |
| Home and End | Select the first or last tab. |

- tablist, tab and tabpanel roles; each tab has aria-controls and each panel aria-labelledby.
- Automatic activation: moving with the arrows selects, so there is no separate confirm step.
- Only the selected tab is in the tab order (roving tabindex).

## Code

### Tabs.tsx

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

// Nacre Tabs. React plus Tailwind classes only; needs nacre-theme.css and Indicator.tsx (the gliding indicator it
// shares with Segmented control). The indicator glides to the selected tab (base 240, out; the line reaches across
// both tabs on the way), retargeted mid-flight. Panels cross-fade in place: the old one fades out on top (quick 160)
// while the new one, already in the flow, fades in and rises 4 px (base 240), so nothing below jumps twice. Arrow
// keys, Home and End switch at once, with no movement; so do reduced motion and Motion off.

export type TabItem = { value: string; label: string; content: ReactNode; disabled?: boolean }
export type TabsVariant = 'line' | 'pill'
export type TabsSize = 'sm' | 'md'

export type TabsProps = {
  label: string
  items: TabItem[]
  value?: string
  defaultValue?: string
  onValueChange?: (value: string) => void
  variant?: TabsVariant
  size?: TabsSize
  className?: string
}

const tabSize: Record<TabsVariant, Record<TabsSize, string>> = {
  line: { sm: 'h-8 text-label', md: 'h-10 text-body' },
  pill: { sm: 'h-7 px-2.5 text-label', md: 'h-8 px-3.5 text-body' },
}

export function Tabs({ label, items, value, defaultValue, onValueChange, variant = 'pill', size = 'md', className = '' }: TabsProps) {
  const id = useId()
  const [inner, setInner] = useState(defaultValue ?? items.find((i) => !i.disabled)?.value)
  const current = value ?? inner
  const list = useRef<HTMLDivElement>(null)
  const keyboard = useRef(false)
  const thumb = useIndicator(list, current, keyboard, variant === 'line')
  const enabled = items.filter((i) => !i.disabled)
  const index = (v: string) => items.findIndex((i) => i.value === v)
  const tabId = (v: string) => `${id}-tab-${index(v)}`
  const panelId = (v: string) => `${id}-panel-${index(v)}`
  const choose = (v: string) => {
    if (value === undefined) setInner(v)
    onValueChange?.(v)
  }
  const onKey = (e: KeyboardEvent<HTMLButtonElement>) => {
    const n = enabled.length
    const at = enabled.findIndex((i) => i.value === current)
    const to =
      e.key === 'ArrowRight' ? enabled[at < 0 ? 0 : (at + 1) % n]
      : e.key === 'ArrowLeft' ? 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)
    document.getElementById(tabId(to.value))?.focus()
  }
  const line = variant === 'line'

  // The panel that was showing stays on top while it fades out. Keyboard changes and reduced motion skip it.
  const panels = useRef<HTMLDivElement>(null)
  const [shown, setShown] = useState(current)
  const [leaving, setLeaving] = useState<string | undefined>(undefined)
  if (shown !== current) {
    setShown(current)
    setLeaving(shown)
  }
  useLayoutEffect(() => {
    const box = panels.current
    if (!box) return
    // A hidden panel drops what is left of its fade, so it shows at full strength next time.
    for (const p of box.querySelectorAll<HTMLElement>(':scope > [hidden]')) p.getAnimations().forEach((a) => a.cancel())
    const now = box.querySelector<HTMLElement>(':scope > [data-part="panel"]:not([hidden]):not([data-leaving])')
    const old = box.querySelector<HTMLElement>(':scope > [data-leaving]')
    if (!old || !now) return
    if (keyboard.current || !motionOk(box)) return setLeaving(undefined)
    const easing = getComputedStyle(box).getPropertyValue('--nx-ease-out').trim() || 'cubic-bezier(.23, 1, .32, 1)'
    // The panels' box glides between the two heights (base 240 out), so what sits below slides instead of jumping. A
    // switch mid-glide starts from the height drawn now.
    const running = box.getAnimations()
    const fromH = running.length ? box.getBoundingClientRect().height : old.offsetHeight
    running.forEach((a) => a.cancel())
    const toH = now.offsetHeight
    if (fromH !== toH) {
      box.style.overflow = 'hidden'
      const done = () => { box.style.overflow = '' }
      box.animate([{ height: `${fromH}px` }, { height: `${toH}px` }], { duration: tokenMs(box, '--nx-dur-base', 240), easing }).finished.then(done, done)
    }
    // Retarget: start the new panel from the opacity it is drawn at now (it may be mid-fade from a quick switch back).
    const from = now.getAnimations().length ? getComputedStyle(now).opacity : '0'
    now.getAnimations().forEach((a) => a.cancel())
    now.animate([{ opacity: from, transform: 'translateY(4px)' }, { opacity: 1, transform: 'none' }], { duration: tokenMs(box, '--nx-dur-base', 240), easing })
    const fade = old.animate([{ opacity: getComputedStyle(old).opacity }, { opacity: 0 }], { duration: tokenMs(box, '--nx-dur-quick', 160), easing, fill: 'forwards' })
    const name = leaving
    fade.finished.then(() => setLeaving((l) => (l === name ? undefined : l)), () => {})
  }, [leaving])
  return (
    <div
      data-part="root"
      className={`flex min-w-0 flex-col gap-4 ${className}`}
      onKeyDown={() => { keyboard.current = true }}
      onPointerDown={() => { keyboard.current = false }}
    >
      <div
        ref={list}
        role="tablist"
        aria-label={label}
        data-part="list"
        className={`relative flex flex-wrap ${line ? 'gap-x-5 border-b border-line-subtle' : 'w-fit max-w-full gap-0.5 rounded-full bg-sunken p-1 ring-1 ring-line-subtle'}`}
      >
        <span ref={thumb} aria-hidden="true" data-part="indicator" className={`pointer-events-none absolute top-0 left-0 origin-top-left rounded-full opacity-0 ${line ? 'bg-action' : 'bg-surface shadow-1'}`} />
        {items.map((it) => {
          const on = it.value === current
          // Until the indicator is placed ([data-ready] on the list), the selected tab draws its own selection.
          const fallback = line ? 'shadow-[inset_0_-2px_0_var(--nx-action)]' : 'bg-surface shadow-1'
          return (
            <button
              key={it.value}
              id={tabId(it.value)}
              type="button"
              role="tab"
              aria-selected={on}
              aria-controls={panelId(it.value)}
              tabIndex={on ? 0 : -1}
              disabled={it.disabled}
              data-state={on ? 'on' : 'off'}
              data-part="tab"
              onClick={() => choose(it.value)}
              onKeyDown={onKey}
              className={`relative cursor-pointer font-[600] whitespace-nowrap 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 ${line ? 'rounded-xs' : 'rounded-full'} ${tabSize[variant][size]} ${on ? `text-fg-strong ${fallback} [[data-ready]>&]:bg-transparent [[data-ready]>&]:shadow-[0_0_#0000]` : 'text-fg-muted enabled:hover:text-fg-strong'}`}
            >
              {it.label}
            </button>
          )
        })}
      </div>
      <div ref={panels} data-part="panels" className="relative min-w-0">
        {items.map((it) => {
          const out = it.value === leaving
          return (
            <div
              key={it.value}
              id={panelId(it.value)}
              role="tabpanel"
              aria-labelledby={tabId(it.value)}
              tabIndex={out ? -1 : 0}
              hidden={it.value !== current && !out}
              aria-hidden={out || undefined}
              inert={out || undefined}
              data-part="panel"
              data-leaving={out ? '' : undefined}
              className={`min-w-0 rounded-xs text-body text-fg focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus ${out ? 'pointer-events-none absolute inset-x-0 top-0' : ''}`}
            >
              {it.content}
            </div>
          )
        })}
      </div>
    </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="flex min-w-0 flex-col gap-4 ">
  <div role="tablist" aria-label="Project sections" data-part="list" class="relative flex flex-wrap w-fit max-w-full gap-0.5 rounded-full bg-sunken p-1 ring-1 ring-line-subtle">
    <span aria-hidden="true" data-part="indicator" class="pointer-events-none absolute top-0 left-0 origin-top-left rounded-full opacity-0 bg-surface shadow-1"></span>
    <button id="_R_0_-tab-0" type="button" role="tab" aria-selected="true" aria-controls="_R_0_-panel-0" tabindex="0" data-state="on" data-part="tab" class="relative cursor-pointer font-[600] whitespace-nowrap 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 rounded-full h-8 px-3.5 text-body text-fg-strong bg-surface shadow-1 [[data-ready]&gt;&amp;]:bg-transparent [[data-ready]&gt;&amp;]:shadow-[0_0_#0000]">Overview</button>
    <button id="_R_0_-tab-1" type="button" role="tab" aria-selected="false" aria-controls="_R_0_-panel-1" tabindex="-1" data-state="off" data-part="tab" class="relative cursor-pointer font-[600] whitespace-nowrap 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 rounded-full h-8 px-3.5 text-body text-fg-muted enabled:hover:text-fg-strong">Tasks</button>
    <button id="_R_0_-tab-2" type="button" role="tab" aria-selected="false" aria-controls="_R_0_-panel-2" tabindex="-1" data-state="off" data-part="tab" class="relative cursor-pointer font-[600] whitespace-nowrap 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 rounded-full h-8 px-3.5 text-body text-fg-muted enabled:hover:text-fg-strong">Files</button>
  </div>
  <div data-part="panels" class="relative min-w-0">
    <div id="_R_0_-panel-0" role="tabpanel" aria-labelledby="_R_0_-tab-0" tabindex="0" data-part="panel" class="min-w-0 rounded-xs text-body text-fg focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus ">Launch plan for the Q3 release. Next review on Thursday at 10:00.</div>
    <div id="_R_0_-panel-1" role="tabpanel" aria-labelledby="_R_0_-tab-1" tabindex="0" hidden="" data-part="panel" class="min-w-0 rounded-xs text-body text-fg focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus ">12 open tasks, 3 due this week. Ana has the most.</div>
    <div id="_R_0_-panel-2" role="tabpanel" aria-labelledby="_R_0_-tab-2" tabindex="0" hidden="" data-part="panel" class="min-w-0 rounded-xs text-body text-fg focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus ">Brief.pdf, Timeline.fig and 4 more, last changed today.</div>
  </div>
</div>
```

## Related

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