Segmented control
FreeTwo 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.
npx shadcn@latest add @pixilui/segmented-controlPreview
A glass thumb glides to your pick; arrow keys move it at once.
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" />;
}When to use
Use it when
- 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.
Use something else when
- 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.
Installation
Terminal
npx shadcn@latest add @pixilui/segmented-controlAdds segmented-control.tsx, and installs clsx and tailwind-merge. First PixilUI item in this app? Add the registry once, as in Installation.
components/pixilui/segmented-control.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>
);
});
Then npm i clsx tailwind-merge, and add the foundation once per app, as in Installation.
Usage
example.tsx
import { SegmentedControl } from "@/components/pixilui/segmented-control";
<SegmentedControl
aria-label={aria-label}
options={options}
onValueChange={onValueChange}
/>As wide as its labels, never wider than its container. Keep labels short so it fits at 375 wide.
API reference
PropTypeDefault
aria-labelRequiredstring–What the choice is about, for screen readers ("View").optionsRequiredSegmentedControlOption[]–The choices, in order. A string is both the value and the label.valuestring–The chosen value, controlled. Pair with onValueChange.defaultValuestring–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 takes every native <div> attribute except defaultValue, onChange, and a ref.
Keyboard
TabMoves focus to the chosen option; Tab again leaves the control.
← →Chooses the previous or next option and moves focus to it, wrapping at the ends.
↑ ↓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.