# Segmented control

Two to five mutually exclusive choices on one glass track, with a thumb that glides to the one you pick and jumps at once when you arrow through them.

Tier: free. Type: component. Category: inputs. Tags: motion, keyboard.

## Install

```bash
npx shadcn@latest add @pixilui/segmented-control
```

One-time setup: add the registry to `components.json`:

```json
{
  "registries": {
    "@pixilui": "https://pixilui.com/r/{name}.json"
  }
}
```

Files: `components/pixilui/segmented-control.tsx`.

## Preview

Live preview: https://pixilui.com/components/segmented-control

Signature: One glass thumb glides to the choice you click, and jumps at once when you arrow through them.

Styles: `quiet` (default), `lively`, set with `data-style` on <html>. The item reads the style through the foundation; it needs no prop. Standalone files: quiet https://pixilui.com/r/standalone/segmented-control.tsx, lively https://pixilui.com/r/standalone/segmented-control.lively.tsx.

## Code

`components/pixilui/segmented-control.tsx`

```tsx
"use client";

import { forwardRef, useEffect, useLayoutEffect, useRef, useState, type ComponentPropsWithoutRef, type KeyboardEvent } from "react";
import { cn } from "./lib/utils";

/*
  The locked segmented control (exploration 04): a glass thumb that glides to the choice. Its look
  and motion live in foundation.css section 7 (pixilui-btn-segmented); this file places the thumb.
  Arrow keys move it at once (data-instant), a click lets it glide.
*/

/** One choice: a plain string is both value and label. */
export type SegmentedControlOption = string | { value: string; label: string };

export type SegmentedControlProps = Omit<ComponentPropsWithoutRef<"div">, "defaultValue" | "onChange" | "children"> & {
  /** The choices, in order. A string is both the value and the label. */
  options: SegmentedControlOption[];
  /** The chosen value, controlled. Pair with onValueChange. */
  value?: string;
  /** The starting value when uncontrolled. Defaults to the first option. */
  defaultValue?: string;
  /** Runs when a choice is made, by click or arrow key. */
  onValueChange?: (value: string) => void | Promise<void>;
  /** What the choice is about, for screen readers ("View"). */
  "aria-label": string;
};

const valueOf = (option: SegmentedControlOption) => (typeof option === "string" ? option : option.value);
const labelOf = (option: SegmentedControlOption) => (typeof option === "string" ? option : option.label);

/** A row of mutually exclusive choices with one glass thumb that glides to the chosen one. */
export const SegmentedControl = forwardRef<HTMLDivElement, SegmentedControlProps>(function SegmentedControl(
  { options, value: valueProp, defaultValue, onValueChange, className, ...rest },
  ref,
) {
  const values = options.map(valueOf);
  const [inner, setInner] = useState(defaultValue ?? values[0] ?? "");
  const value = valueProp ?? inner;
  const [instant, setInstant] = useState(true);
  const thumb = useRef<HTMLSpanElement | null>(null);
  const refs = useRef<(HTMLButtonElement | null)[]>([]);
  const index = values.indexOf(value);

  const choose = (next: string) => {
    if (valueProp === undefined) setInner(next);
    void onValueChange?.(next);
  };

  useLayoutEffect(() => {
    const current = refs.current[index];
    if (!current || !thumb.current) return;
    thumb.current.style.setProperty("--btn-tx", `${current.offsetLeft}px`);
    thumb.current.style.setProperty("--btn-tw", `${current.offsetWidth}px`);
    if (instant) requestAnimationFrame(() => setInstant(false));
  }, [index, instant]);
  useEffect(() => {
    document.fonts?.ready.then(() => {
      const current = refs.current[index];
      if (current && thumb.current) {
        thumb.current.style.setProperty("--btn-tx", `${current.offsetLeft}px`);
        thumb.current.style.setProperty("--btn-tw", `${current.offsetWidth}px`);
      }
    });
    // once, after the font lands
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const onKey = (event: KeyboardEvent<HTMLButtonElement>, at: number) => {
    const step = { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 }[event.key];
    if (!step) return;
    event.preventDefault();
    const next = (at + step + values.length) % values.length;
    setInstant(true);
    choose(values[next]!);
    refs.current[next]?.focus();
  };

  return (
    <div ref={ref} className={cn("pixilui-btn-segmented font-body", className)} role="radiogroup" data-instant={instant ? "" : undefined} {...rest}>
      <span ref={thumb} className="pixilui-btn-segmented-thumb" />
      {options.map((option, at) => {
        const optionValue = valueOf(option);
        return (
          <button
            key={optionValue}
            ref={(node) => {
              refs.current[at] = node;
            }}
            type="button"
            role="radio"
            aria-checked={value === optionValue}
            tabIndex={value === optionValue ? 0 : -1}
            onClick={() => choose(optionValue)}
            onKeyDown={(event) => onKey(event, at)}
          >
            <span className="pixilui-btn-label">{labelOf(option)}</span>
          </button>
        );
      })}
    </div>
  );
});
```

## Usage

When to use:

- Switching the view of the same data: Day, Week, Month on a usage chart, or List and Board on a run queue.
- Short labels, two to five of them, where every choice fits on one row.

When not to use:

- Navigating between pages or panels with their own content: use tabs.
- Turning one thing on or off: use a toggle button or a switch.
- More than five choices or long labels: use a select.

```tsx
import { SegmentedControl } from "@/components/pixilui/segmented-control";

// One finished element, no rows: the control is itself the choice.
export const knobs = {} as const;

export default function SegmentedControlDemo() {
  return <SegmentedControl aria-label="View" options={["Day", "Week", "Month"]} defaultValue="Day" />;
}
```

## Examples

None.

## API

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `aria-label` (required) | `string` |  | What the choice is about, for screen readers ("View"). |
| `options` (required) | `SegmentedControlOption[]` |  | The choices, in order. A string is both the value and the label. |
| `value` | `string` |  | The chosen value, controlled. Pair with onValueChange. |
| `defaultValue` | `string` |  | The starting value when uncontrolled. Defaults to the first option. |
| `onValueChange` | `(value: string) => void \| Promise<void>` |  | Runs when a choice is made, by click or arrow key. |

Also accepts every native `<div>` attribute except `defaultValue`, `onChange`, and a ref to it.

## Keyboard

- `Tab`: Moves focus to the chosen option; Tab again leaves the control.
- `ArrowLeft` + `ArrowRight`: Chooses the previous or next option and moves focus to it, wrapping at the ends.
- `ArrowUp` + `ArrowDown`: The same as left and right.

## Accessibility

- A radiogroup of radio buttons with aria-checked; aria-label names the group and is required.
- Roving tabindex: only the chosen option is in the tab order.
- The thumb is decoration; the checked state carries the meaning.

## Motion

- A click lets the thumb glide to the new choice on the snappy spring, its width following the label.
- Arrow keys move the thumb at once, so scanning by keyboard never waits on motion.
- The thumb is placed again after the font loads, so it never sits on the fallback font's widths.
- Reduced motion: the thumb moves at once.

## Responsive

- As wide as its labels, never wider than its container. Keep labels short so it fits at 375 wide.

## Performance

- The thumb moves by two custom properties (offset and width) on one element; no layout animation.

## Notes for AI

- Pass options as strings, or { value, label } when the value is a machine name. Control it with value and onValueChange, or start it with defaultValue.
- aria-label is required: name what the choice changes ("View", "Range").
- The look is the locked recipe in foundation.css section 7 (pixilui-btn-segmented); do not restyle the thumb with utilities.

## Related

- [Icon button](https://pixilui.com/components/icon-button/markdown): An icon-only button in every style, that can hold on or off as a toggle (bold, italic, a thumbs up) and name itself in a tooltip with its key.
- [Button group](https://pixilui.com/components/button-group/markdown): Icon buttons on one glass tray, each named by a tooltip with its key hint, with arrow keys to move along the row: the toolbar under a composer or an editor.
- [Button](https://pixilui.com/components/button/markdown): The PixilUI button in four main styles and four more, five sizes from 24 to 44, with icons, loading, disabled, a count and a shortcut.
