Components / InputsStable

Select

Picks one value from a list that is too long to show at once: a Nacre list under the mouse, the platform picker on touch and with the keyboard.

View as Markdown

Playground

They get a notification when you save.

Code

Select.tsx
'use client'
import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState, type KeyboardEvent, type PointerEvent, type Ref, type SelectHTMLAttributes } from 'react'
import { motionOk, tokenMs, useIndicator } from './Indicator'
import { Note } from './Note'

// Nacre Select: a native select styled to match Input, so phones, the keyboard and screen readers keep the platform
// picker. Same error API as Input: invalid marks it, error is the message. React plus Tailwind classes only (and
// Indicator.tsx next to it); needs nacre-theme.css.
// A mouse press opens a Nacre list instead of the platform one. It grows out of the field (scale .97 to 1 and opacity,
// quick 160 out, transform-origin on the edge that touches the field, so it opens down or up from it) and one
// highlight glides between the rows under the pointer (base 240 out, retargeted from where it is drawn). In the open
// list the arrow keys, Home and End move the highlight at once, Enter or Space picks, Esc and Tab close. Picking with
// the pointer fades the list out (instant 100); a key closes it at once. The value is always the select's own, so
// forms, refs and onChange work as with any select. Opened by the keyboard or by touch, it is the platform picker,
// with no animation. Reduced motion or [data-nacre-motion="off"]: the list appears and leaves at once.

export type SelectSize = 'sm' | 'md' | 'lg'
export type SelectOption = { value: string; label: string; disabled?: boolean }

export type SelectProps = Omit<SelectHTMLAttributes<HTMLSelectElement>, 'size'> & {
  label: string
  hideLabel?: boolean
  options: SelectOption[]
  placeholder?: string
  hint?: string
  invalid?: boolean
  error?: string
  size?: SelectSize
  ref?: Ref<HTMLSelectElement>
}

const heights: Record<SelectSize, string> = { sm: 'h-9 rounded-sm text-body', md: 'h-11 rounded-md text-body', lg: 'h-12 rounded-md text-body-lg' }
const rows: Record<SelectSize, string> = { sm: 'h-8', md: 'h-9', lg: 'h-10' }
const GAP = 4

type Place = { left: number; width: number; top?: number; bottom?: number; maxHeight: number; up: boolean }

export function Select({ label, hideLabel = false, options, placeholder, hint, error, invalid = false, size = 'md', disabled, id, value, defaultValue, className = '', onPointerDown, onKeyDown, ref, ...rest }: SelectProps) {
  const auto = useId()
  const selectId = id ?? auto
  const listId = `${selectId}-list`
  const bad = invalid || Boolean(error)
  const note = error || hint
  const noteId = `${selectId}-note`
  // With a placeholder and no value, start on the placeholder instead of silently picking the first option.
  const start = value === undefined && defaultValue === undefined && placeholder !== undefined ? '' : defaultValue
  const describedBy = [rest['aria-describedby'], note ? noteId : undefined].filter(Boolean).join(' ') || undefined
  const field = disabled ? 'border-line-subtle bg-sunken' : bad ? 'border-error bg-surface' : 'border-line bg-surface hover:border-line-strong has-focus-visible:border-line-strong'

  const select = useRef<HTMLSelectElement | null>(null)
  const fieldRef = useRef<HTMLDivElement>(null)
  const pop = useRef<HTMLDivElement>(null)
  const list = useRef<HTMLDivElement>(null)
  const keyboard = useRef(false)
  const [open, setOpen] = useState(false)
  const [place, setPlace] = useState<Place | null>(null)
  const [current, setCurrent] = useState('')
  const [active, setActive] = useState<string | undefined>()
  const thumb = useIndicator(list, open ? active : undefined, keyboard)
  const enabled = options.filter((o) => !o.disabled)

  const measure = useCallback(() => {
    const f = fieldRef.current
    if (!f) return
    const r = f.getBoundingClientRect()
    const below = innerHeight - r.bottom - GAP * 2
    const above = r.top - GAP * 2
    const want = Math.min(288, options.length * 40 + 8)
    const up = below < want && above > below
    setPlace({ left: r.left, width: r.width, maxHeight: Math.max(96, Math.min(288, up ? above : below)), up, ...(up ? { bottom: innerHeight - r.top + GAP } : { top: r.bottom + GAP }) })
  }, [options.length])

  const close = useCallback((fade: boolean) => {
    const p = pop.current
    if (fade && p && motionOk(p)) {
      p.getAnimations().forEach((a) => a.cancel())
      p.animate([{ opacity: 1 }, { opacity: 0 }], { duration: tokenMs(p, '--nx-dur-instant', 100), easing: 'cubic-bezier(.23, 1, .32, 1)', fill: 'forwards' })
        .finished.then(() => setOpen(false), () => {})
    } else setOpen(false)
  }, [])

  const openList = () => {
    const s = select.current
    if (!s) return
    measure()
    setCurrent(s.value)
    setActive(enabled.some((o) => o.value === s.value) ? s.value : enabled[0]?.value)
    keyboard.current = false
    setOpen(true)
  }

  const pick = (v: string) => {
    const s = select.current
    if (s && s.value !== v) {
      s.value = v
      s.dispatchEvent(new Event('input', { bubbles: true }))
      s.dispatchEvent(new Event('change', { bubbles: true }))
    }
  }

  // Open: the list enters the top layer and grows out of the field on the edge it touches.
  useLayoutEffect(() => {
    const p = pop.current
    if (!open || !p) return
    if (!p.matches(':popover-open')) p.showPopover?.()
    p.getAnimations().forEach((a) => a.cancel())
    if (!motionOk(p)) return
    p.animate([{ opacity: 0, transform: 'scale(.97)' }, { opacity: 1, transform: 'none' }], { duration: tokenMs(p, '--nx-dur-quick', 160), easing: 'cubic-bezier(.23, 1, .32, 1)' })
    list.current?.querySelector('[data-state="on"]')?.scrollIntoView({ block: 'nearest' })
  }, [open])

  // While open: a press outside closes it; scrolling or resizing keeps it on the field.
  useEffect(() => {
    if (!open) return
    const down = (e: globalThis.PointerEvent) => {
      const t = e.target as Node
      if (!pop.current?.contains(t) && !fieldRef.current?.contains(t)) close(false)
    }
    const move = (e: Event) => { if (!(e.target instanceof Node && pop.current?.contains(e.target))) measure() }
    document.addEventListener('pointerdown', down, true)
    window.addEventListener('scroll', move, true)
    window.addEventListener('resize', move)
    return () => {
      document.removeEventListener('pointerdown', down, true)
      window.removeEventListener('scroll', move, true)
      window.removeEventListener('resize', move)
    }
  }, [open, close, measure])

  const pointerDown = (e: PointerEvent<HTMLSelectElement>) => {
    onPointerDown?.(e)
    // Touch and pen keep the platform picker; so does a modified or secondary press.
    if (e.defaultPrevented || disabled || e.pointerType !== 'mouse' || e.button !== 0) return
    e.preventDefault()
    e.currentTarget.focus({ preventScroll: true })
    if (open) close(false)
    else openList()
  }

  const keyDown = (e: KeyboardEvent<HTMLSelectElement>) => {
    onKeyDown?.(e)
    if (!open || e.defaultPrevented) return
    keyboard.current = true
    const at = enabled.findIndex((o) => o.value === active)
    const go = (i: number) => {
      const o = enabled[Math.max(0, Math.min(enabled.length - 1, i))]
      if (!o) return
      setActive(o.value)
      requestAnimationFrame(() => list.current?.querySelector('[data-state="on"]')?.scrollIntoView({ block: 'nearest' }))
    }
    if (e.key === 'ArrowDown') go(at + 1)
    else if (e.key === 'ArrowUp') go(at - 1)
    else if (e.key === 'Home' || e.key === 'PageUp') go(0)
    else if (e.key === 'End' || e.key === 'PageDown') go(enabled.length - 1)
    else if (e.key === 'Enter' || e.key === ' ') {
      if (active !== undefined) pick(active)
      close(false)
    } else if (e.key === 'Escape') close(false)
    else if (e.key === 'Tab') return close(false)
    else if (e.key.length === 1 && !e.metaKey && !e.ctrlKey && !e.altKey) {
      const k = e.key.toLowerCase()
      const from = enabled.slice(at + 1).concat(enabled.slice(0, at + 1))
      const hit = from.find((o) => o.label.toLowerCase().startsWith(k))
      if (hit) go(enabled.indexOf(hit))
    } else return
    e.preventDefault()
  }

  return (
    <div data-part="root" className={`flex flex-col gap-1.5 ${className}`}>
      <label data-part="label" htmlFor={selectId} className={hideLabel ? 'sr-only' : `text-label ${disabled ? 'text-fg-disabled' : 'text-fg-strong'}`}>
        {label}
      </label>
      <div
        ref={fieldRef}
        data-part="field"
        className={`relative flex items-center border transition-[border-color] duration-(--nx-dur-quick) ease-out has-focus-visible:outline-none has-focus-visible:shadow-[0_0_0_3px_color-mix(in_oklab,var(--nx-fg-muted)_16%,transparent)] ${heights[size]} ${field}`}
      >
        <select
          ref={(el) => {
            select.current = el
            if (typeof ref === 'function') ref(el)
            else if (ref) ref.current = el
          }}
          id={selectId}
          value={value}
          defaultValue={start}
          disabled={disabled}
          data-part="control"
          className="h-full w-full min-w-0 cursor-pointer appearance-none bg-transparent pr-9 pl-3.5 text-fg-strong outline-none has-[option[value='']:checked]:text-fg-muted [&_option]:text-fg-strong disabled:cursor-not-allowed disabled:text-fg-disabled"
          {...rest}
          onPointerDown={pointerDown}
          onKeyDown={keyDown}
          aria-invalid={bad || undefined}
          aria-describedby={describedBy}
        >
          {placeholder !== undefined && <option value="" disabled>{placeholder}</option>}
          {options.map((o) => <option key={o.value} value={o.value} disabled={o.disabled}>{o.label}</option>)}
        </select>
        <svg
          data-part="chevron"
          aria-hidden="true"
          viewBox="0 0 16 16"
          fill="none"
          stroke="currentColor"
          strokeWidth="1.5"
          strokeLinecap="round"
          strokeLinejoin="round"
          className={`pointer-events-none absolute right-3 size-4 text-icon-muted transition-[rotate] duration-(--nx-dur-quick) ease-out ${open ? 'rotate-180' : ''}`}
        >
          <path d="m4 6 4 4 4-4" />
        </svg>
      </div>
      {open && place && (
        // The pointer list is a shortcut over the select, which stays the control assistive tech and the keyboard use.
        <div
          ref={pop}
          id={listId}
          popover="manual"
          aria-hidden="true"
          data-part="popover"
          data-side={place.up ? 'top' : 'bottom'}
          style={{ left: place.left, width: place.width, top: place.top ?? 'auto', bottom: place.bottom ?? 'auto', maxHeight: place.maxHeight }}
          className={`fixed right-auto m-0 overflow-y-auto overscroll-contain rounded-md border border-line bg-surface p-1 text-fg-strong shadow-3 ${place.up ? 'origin-bottom' : 'origin-top'}`}
        >
          <div ref={list} data-part="list" className="relative isolate flex flex-col">
            <span ref={thumb} aria-hidden="true" className="pointer-events-none absolute top-0 left-0 -z-10 rounded-sm bg-sunken opacity-0 shadow-[inset_0_0_0_1px_var(--nx-line-subtle)]" />
            {options.map((o) => (
              <div
                key={o.value}
                data-part="option"
                data-value={o.value}
                data-state={o.value === active ? 'on' : undefined}
                aria-disabled={o.disabled || undefined}
                onPointerMove={() => {
                  if (o.disabled || o.value === active) return
                  keyboard.current = false
                  setActive(o.value)
                }}
                onPointerUp={(e) => {
                  if (o.disabled || e.button !== 0) return
                  pick(o.value)
                  close(true)
                }}
                className={`flex shrink-0 cursor-pointer items-center justify-between gap-3 rounded-sm px-2.5 ${rows[size]} ${o.disabled ? 'cursor-not-allowed text-fg-disabled' : ''}`}
              >
                <span className="truncate">{o.label}</span>
                {o.value === current && (
                  <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" className="size-4 shrink-0 text-fg-strong">
                    <path d="M3.5 8.5l3 3 6-7" />
                  </svg>
                )}
              </div>
            ))}
          </div>
        </div>
      )}
      <Note part={error ? 'error' : 'hint'} id={noteId}>{error || hint}</Note>
    </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
}
Note.tsx
'use client'
import { useEffect, useRef, useState, type ReactNode } from 'react'

// Nacre Note: the hint, error or success line under a field. It rolls out: the row grows from 0 to its height (base 240
// out) while the words fade and rise 4 px into place, so the fields below glide down instead of jumping. On the way out
// it keeps its last words on screen while the row rolls back up (quick 160), then unmounts the words. reserve keeps one
// line of space even when there is nothing to say, for a field whose message is likely to appear (no layout shift at all).
// With motion off or reduced, it changes at once. Parts: data-part="hint" (muted), "error" and "success" (their tone).
// React plus Tailwind classes only; needs nacre-theme.css. --nx-note-gap (default 6 px) is the gap the parent puts above
// the note, so the collapsed row cancels it.
export type NoteProps = {
  id?: string
  part: 'hint' | 'error' | 'success'
  children?: ReactNode
  className?: string
  as?: 'p' | 'span'
  /** Keep one line of space while empty. */
  reserve?: boolean
}

const tone = { hint: 'text-fg-muted', error: 'text-error-strong', success: 'text-success-strong' } as const

export function Note({ id, part, children, className = '', as: Tag = 'p', reserve = false }: NoteProps) {
  const has = children !== undefined && children !== null && children !== false && children !== ''
  const [last, setLast] = useState<ReactNode>(children)
  const el = useRef<HTMLElement>(null)
  const [leaving, setLeaving] = useState(false)
  const [seen, setSeen] = useState(has)
  if (has !== seen) {
    setSeen(has)
    setLeaving(!has)
  }
  if (has && children !== last) setLast(children)
  useEffect(() => {
    if (!leaving) return
    const node = el.current
    const raw = node ? getComputedStyle(node).transitionDuration.split(',')[0] : '0s'
    const ms = parseFloat(raw) * (raw.endsWith('ms') ? 1 : 1000)
    if (!ms) {
      setLeaving(false)
      return
    }
    const t = setTimeout(() => setLeaving(false), ms)
    return () => clearTimeout(t)
  }, [leaving])
  const Element = 'span' as unknown as 'p'
  const open = has
  const hasWords = has || leaving
  // The row: a one-cell grid whose track animates 0fr to 1fr. The negative margin cancels the parent's gap while closed.
  const wrap = open || reserve ? 'grid-rows-[1fr]' : 'grid-rows-[0fr] mt-[calc(var(--nx-note-gap,6px)*-1)]'
  const Wrap = Tag as 'p'
  return (
    <Wrap
      data-part="note"
      aria-hidden={hasWords ? undefined : true}
      className={`grid transition-[grid-template-rows,margin-top] ease-out ${open ? 'duration-(--nx-dur-base)' : 'duration-(--nx-dur-quick)'} ${wrap} ${className}`}
    >
      <span className="block min-h-0 overflow-hidden">
        {hasWords && (
          <Element
            ref={el as React.Ref<HTMLParagraphElement>}
            data-part={part}
            id={id}
            aria-hidden={has ? undefined : true}
            className={`block text-caption ${tone[part]} transition-[opacity,translate] duration-(--nx-dur-quick) ease-out starting:-translate-y-1 starting:opacity-0 ${has ? '' : '-translate-y-1 opacity-0'}`}
          >
            {has ? children : last}
          </Element>
        )}
        {reserve && !hasWords && <span className="block text-caption" aria-hidden="true">&nbsp;</span>}
      </span>
    </Wrap>
  )
}

Usage

When to use

  • Six to about fifteen known options: assignee, project, time zone.
  • Forms where space is tight and the current value matters more than the alternatives.

Choose something else when

  • There are two to five options and room to show them: use Radio.
  • The choice switches a view at once: use Segmented control.
  • The list is long enough to need search: use a searchable combobox.

In the Nacre workspace

Assign a task

The task sheet has an Assignee Select listing the project team. It starts on Choose a teammate, so nobody is assigned by accident.

Meeting time zone

In the calendar event form, the time zone Select shows the current value; on a phone it opens the native wheel.

Do and don't

  • DoStart on a placeholder when there is no sensible default.

    Don'tPreselect the first option and let people save it without noticing.

  • DoSort options in an order people expect: alphabetical names, chronological times.

    Don'tSort by internal id.

Anatomy

They get a notification when you save.

  1. Label. Label 13/16 at weight 600, 6 px above the field.
  2. Chevron. 16 px icon-muted chevron, 12 px from the right edge. Not interactive.
  3. Field. The same field as Input: radius md (sm at the sm size), 1 px line border (line-strong on hover and focus), surface fill.
  4. Value. Body 14/20 in fg-strong, fg-muted while the placeholder shows.
  5. Hint or error. Caption 12/16 under the field.

API

labelType stringDefault -Always required, tied to the select.
hideLabelType booleanDefault falseHides the label visually, keeps it for assistive tech.
optionsType SelectOption[]Default -value, label and optional disabled for each option.
placeholderType stringDefault -A first, disabled option shown until something is chosen.
hintType stringDefault -Help text under the field, linked with aria-describedby.
errorType stringDefault -The message: replaces the hint, turns the border to the error colour, sets aria-invalid and is linked with aria-describedby.
invalidType booleanDefault falseError border and aria-invalid without a message, for a field whose message an error summary owns.
sizeType 'sm' | 'md' | 'lg'Default 'md'Height 36, 44 or 48 px, radius sm at sm and md (18 px) above.
disabledType booleanDefault falseSunken field, no choice.
refType Ref<HTMLSelectElement>Default -Reaches the select element. React 19 passes ref as a plain prop, so no forwardRef wrapper is needed.
...restType SelectHTMLAttributesDefault -Any native select attribute: value, defaultValue, onChange, name, required.

Motion

Hover and errorProperty border-colorDuration quick 160Easing outKeyboard Same, colour only.
List opens (mouse)Property scale .97 to 1 and opacity, from the edge that touches the fieldDuration quick 160Easing outKeyboard The keyboard opens the platform picker, with no animation.
Highlight follows the pointerProperty transform (FLIP), retargeted from where it is drawnDuration base 240Easing outKeyboard Arrow keys, Home and End move it at once.
ChevronProperty rotate 180 while the list is openDuration quick 160Easing outKeyboard Same.
List closesProperty opacity after a pointer pickDuration instant 100Easing outKeyboard Enter, Space, Esc and Tab close it at once.
Hint or error appearsProperty opacityDuration quick 160Easing outKeyboard Same, a fade only.

They get a notification when you save.

Accessibility

Keyboard

Tab
Moves focus to the select.
Space or Alt+Down
Opens the platform list.
Arrows, Home, End, a letter
In the list opened by the mouse: move the highlight at once.
Enter or Space; Esc or Tab
In that list: pick the highlighted option; close without picking.
Up and Down arrows
Change the value.
A letter
Jumps to the first option that starts with it.

ARIA and semantics

  • A native select: the platform provides the listbox, its keyboard model and its announcements. The keyboard and touch open the platform picker.
  • A mouse press opens a Nacre list over the page instead. It is a visual shortcut (aria-hidden): focus stays on the select, a pick sets the select value and fires change, so the value is announced like any other change.
  • invalid or error sets aria-invalid; the error message is linked with aria-describedby.
  • The placeholder option is disabled, so it cannot be chosen again once a value is set.

Contrast

Selected valuefg-strong on surfaceLight 19.01:1Dark 16.29:1Needs 4.5:1
Placeholderfg-muted on surfaceLight 5.57:1Dark 6.68:1Needs 4.5:1
Chevronicon-muted on surfaceLight 5.57:1Dark 6.68:1Needs 3:1
Error messageerror-strong on pageLight 5.46:1Dark 11.77:1Needs 4.5:1