Components / NavigationStable

Tabs

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

View as Markdown

Playground

Launch plan for the Q3 release. Next review on Thursday at 10:00.

Code

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

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

Choose something else when

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

In the Nacre workspace

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 don't

  • DoKeep labels to one or two words and the count of tabs low, up to six.

    Don'tLet tabs wrap onto three lines or scroll sideways.

  • DoKeep the panel content related, so moving between tabs feels like one object.

    Don'tHide a required form step behind a tab people may never open.

Anatomy

Launch plan for the Q3 release. Next review on Thursday at 10:00.
  1. Tab. Body 14/20, fg-muted, fg-strong when selected.
  2. Tab 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. Pill: a surface thumb with shadow 1. Line: a 2 px action bar over the rule. One element that moves.
  4. Panel. 16 px below the list, focusable so keyboard users can reach content without controls.

API

labelType stringDefault -Names the tab list for assistive tech (aria-label).
itemsType TabItem[]Default -value, label, content and optional disabled for each tab.
valueType stringDefault -Controlled selected value.
defaultValueType stringDefault first enabled itemStarting tab when uncontrolled.
onValueChangeType (value: string) => voidDefault -Called with the new value on click or arrow key.
variantType 'pill' | 'line'Default 'pill'Pill is the default: the same sunken track and white thumb as Segmented control. Line is a rule under page sections.
sizeType 'sm' | 'md'Default 'md'Tab height 28 or 32 px (pill), 32 or 40 px (line).
classNameType stringDefault -Extra classes on the root.

Motion

Select a tabProperty indicator transform, retargeted mid-flight; the line reaches across both tabsDuration base 240Easing outKeyboard Arrow keys, Home and End move it at once.
Panel changeProperty old panel opacity on top; new panel opacity and translateY 4 pxDuration base 240Easing outKeyboard Arrow keys swap panels at once.
HoverProperty colorDuration quick 160Easing outKeyboard Focus shows the ring at once.
Launch plan for the Q3 release. Next review on Thursday at 10:00.

Accessibility

Keyboard

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.

ARIA and semantics

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

Contrast

Selected tabfg-strong on pageLight 17.30:1Dark 17.44:1Needs 4.5:1
Other tabsfg-muted on pageLight 5.07:1Dark 7.15:1Needs 4.5:1
Line indicatoraction on pageLight 16.14:1Dark 17.44:1Needs 3:1
Pill tabs on the trackfg-muted on sunkenLight 5.16:1Dark 7.35:1Needs 4.5:1
Selected pill on the thumbfg-strong on surfaceLight 19.01:1Dark 16.29:1Needs 4.5:1