Install
One command installs the files and packages this item needs.
npx shadcn@latest add https://dsui.vercel.app/r/segmented-control.jsonFiles
components/arc/segmented-control/segmented-control.module.csscomponents/arc/segmented-control/segmented-control.tsx
npm packages
motion@^14.2.0
Registry items it pulls in
- v1.1.0Added the liquid-glass variant.
- v1.0.0First release.
/* The frame can shrink below its content inside flex and grid parents; the track then scrolls inside it. */
.root { display: inline-flex; min-width: 0; max-width: 100%; flex-shrink: 1; border-radius: var(--radius-pill); background: var(--surface-muted); }
/* The track owns the stacking context so the gliding highlight passes under every label, not over earlier ones. */
.track { --fade-start: 0px; --fade-end: 0px; isolation: isolate; display: flex; min-width: 0; gap: 2px; overflow-x: auto; overscroll-behavior-x: contain; padding: 3px; border-radius: inherit; scrollbar-width: none; -webkit-mask-image: linear-gradient(to right, transparent, #000 var(--fade-start), #000 calc(100% - var(--fade-end)), transparent); mask-image: linear-gradient(to right, transparent, #000 var(--fade-start), #000 calc(100% - var(--fade-end)), transparent); }
.track::-webkit-scrollbar { display: none; }
.track[data-fade-start] { --fade-start: 20px; }
.track[data-fade-end] { --fade-end: 20px; }
/* The highlight travels and the label color follows it. An idle item lights a soft pill on hover and sinks a little on press. */
.button { position: relative; flex: 0 0 auto; min-height: var(--control-height-sm); border: 0; border-radius: var(--radius-pill); padding: 0 var(--space-4); background: transparent; color: var(--text-muted); font: inherit; font-size: var(--label-md); font-weight: var(--label-weight); white-space: nowrap; cursor: pointer; -webkit-tap-highlight-color: transparent; transition: color var(--duration-fast) var(--ease-standard), background var(--duration-fast) var(--ease-standard), transform var(--duration-spring) var(--ease-spring); }
@media (hover: hover) and (pointer: fine) { .button:hover:not([aria-pressed="true"]) { color: var(--foreground); background: var(--control-track-hover); } }
.button:active, .button[aria-pressed="true"] { color: var(--foreground); }
.button:active { transform: scale(.94); }
.selection { position: absolute; z-index: -1; inset: 0; border: 1px solid var(--border); border-radius: inherit; background: var(--surface); box-shadow: var(--shadow-resting); }
/* Liquid glass: the layer paints the frame and shapes the selection as a lens. */
/* In light the lens is a white pill with the resting shadow, so the chosen option reads at a glance even where the glass is quiet. */
.glass .selection { border-color: transparent; background: var(--surface); box-shadow: var(--shadow-resting); }
/* Dark keeps an ink tint instead: a white lens there would outshine the glass. The OS rule mirrors the explicit switch, as in foundation.css. */
:global(:root[data-theme="dark"]) .glass .selection, :global(:root.dark) .glass .selection { border-color: color-mix(in oklab, var(--foreground) 24%, transparent); background: color-mix(in oklab, var(--foreground) 14%, transparent); box-shadow: none; }
@media (prefers-color-scheme: dark) { :global(:root:not([data-theme="light"]):not([data-theme="dark"]):not(.light):not(.dark)) .glass .selection { border-color: color-mix(in oklab, var(--foreground) 24%, transparent); background: color-mix(in oklab, var(--foreground) 14%, transparent); box-shadow: none; } }
.glass .button { color: color-mix(in oklab, var(--foreground) 58%, transparent); }
.glass .button:hover, .glass .button[aria-pressed="true"] { color: var(--foreground); background: transparent; }
.label { position: relative; z-index: 1; display: inline-flex; align-items: center; gap: 6px; }
@media (max-width: 380px) { .button { padding: 0 10px; } }
@media (prefers-reduced-motion: reduce) { .button { transition: none; } .button:active { transform: none; } }
"use client";
import { useEffect, useId, useLayoutEffect, useRef, type KeyboardEvent, type ReactNode } from "react";
import { LayoutGroup, motion } from "motion/react";
import { useReducedMotion } from "../lib/use-reduced-motion";
import { motionTokens } from "../lib/motion-tokens";
import styles from "./segmented-control.module.css";
import { playUiSound } from "../sound/play";
import { LiquidGlassLayer, liquidGlassHost } from "../liquid-glass/liquid-glass-layer";
export interface Segment { value: string; label: string; /** Optional content after the label, such as a badge. */ accessory?: ReactNode; }
export interface SegmentedControlProps {
options: Segment[];
value: string;
onValueChange: (value: string) => void;
label?: string;
/** Called when the pointer or focus reaches an option, before it is chosen. Use it to start loading what that option shows. */
onOptionIntent?: (value: string) => void;
className?: string;
/** `liquid-glass` draws the control as glass with the selection as a raised lens. */
variant?: "default" | "liquid-glass";
}
export default function SegmentedControl({ options, value, onValueChange, label, onOptionIntent, className, variant = "default" }: SegmentedControlProps) {
const id = useId();
const glass = variant === "liquid-glass";
const reduced = useReducedMotion();
const track = useRef<HTMLDivElement>(null);
// When the options are wider than the container, the track scrolls inside itself. Edges fade only on the side with more to see.
useLayoutEffect(() => {
const node = track.current;
if (!node) return;
const edges = () => {
const rest = node.scrollWidth - node.clientWidth - node.scrollLeft;
node.toggleAttribute("data-fade-start", node.scrollLeft > 1);
node.toggleAttribute("data-fade-end", rest > 1);
};
edges();
node.addEventListener("scroll", edges, { passive: true });
const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(edges);
observer?.observe(node);
return () => { node.removeEventListener("scroll", edges); observer?.disconnect(); };
}, [options.length]);
// The selected option is always scrolled fully into view, with a little room so it clears the fade.
const first = useRef(true);
useEffect(() => {
const node = track.current;
const button = node?.querySelector<HTMLElement>('[aria-pressed="true"]');
if (!node || !button || node.scrollWidth <= node.clientWidth) { first.current = false; return; }
const room = 20, start = button.offsetLeft - room, end = button.offsetLeft + button.offsetWidth + room - node.clientWidth;
const left = node.scrollLeft > start ? start : node.scrollLeft < end ? end : node.scrollLeft;
if (left !== node.scrollLeft) node.scrollTo({ left: Math.max(0, left), behavior: first.current || reduced ? "auto" : "smooth" });
first.current = false;
}, [value, reduced]);
// Arrow keys, Home and End move the selection like a tab list; only the selected option is a tab stop.
const selectedIndex = Math.max(0, options.findIndex(option => option.value === value));
const onKeyDown = (event: KeyboardEvent<HTMLButtonElement>) => {
const last = options.length - 1;
const target = event.key === "ArrowRight" || event.key === "ArrowDown" ? (selectedIndex === last ? 0 : selectedIndex + 1)
: event.key === "ArrowLeft" || event.key === "ArrowUp" ? (selectedIndex === 0 ? last : selectedIndex - 1)
: event.key === "Home" ? 0 : event.key === "End" ? last : -1;
if (target < 0 || !options[target]) return;
event.preventDefault();
playUiSound("tick");
onValueChange(options[target].value);
track.current?.querySelector<HTMLElement>(`[data-value="${CSS.escape(options[target].value)}"]`)?.focus({ preventScroll: true });
};
return <div className={[styles.root, glass ? `${liquidGlassHost} ${styles.glass}` : "", className].filter(Boolean).join(" ")} role="group" aria-label={label}>
{glass ? <LiquidGlassLayer preset="tabs" lens="[data-glass-lens]" /> : null}
<LayoutGroup id={id}><motion.div ref={track} layoutScroll className={styles.track}>
{options.map((option, index) => <button key={option.value} id={`${id}-${option.value}`} className={styles.button} type="button" data-value={option.value} aria-pressed={value === option.value} tabIndex={index === selectedIndex ? 0 : -1} onClick={() => { if (value !== option.value) playUiSound("tick"); onValueChange(option.value); }} onKeyDown={onKeyDown} onPointerEnter={onOptionIntent ? () => onOptionIntent(option.value) : undefined} onFocus={onOptionIntent ? () => onOptionIntent(option.value) : undefined}>
{value === option.value && <motion.span className={styles.selection} data-glass-lens="" layoutId="selection" layoutDependency={value} transition={reduced ? { duration: 0 } : motionTokens.spring.morph} aria-hidden="true" />}
<span className={styles.label}>{option.label}{option.accessory}</span>
</button>)}
</motion.div></LayoutGroup>
</div>;
}
Used items
- Liquid glassComponent
A glass surface with refraction, dispersion and flowing caustics. Wrap your own content or fill a word with glass.
Used by
- Contact sectionBlock
A contact section offering a validated form, channel list, or offices with live local time.
- CTA sectionBlock
A call to action section in centered, split, and dismissible banner variants.
- Demo frameBlock
A resizable preview stage with device presets and a drag handle.
- Docs sidebarBlock
A documentation sidebar with a filter, a scope row and folding categories.
- FAQ sectionBlock
An FAQ section in accordion, categorized columns, and live search variants.
- Hero sectionBlock
A full-screen hero in centered, split, and minimal variants with animated visuals.
- Newsletter signupBlock
A subscribe form with an issue stack preview, in inline and card variants.
- Plan comparisonBlock
A two-plan comparison with a monthly and yearly billing switch.
- Settings panelBlock
A drawer that gathers sound, color mode, season theme, text size and motion, and takes extra groups such as language or account.
- Settings stepsBlock
A settings block in two steps: a list of groups first, then the chosen group's own page sliding in from the right with a back button.
- Site footerBlock
A site footer in columns, minimal, and large logo variants with an optional newsletter.
- Site headerBlock
A site navigation header in simple, centered, and mega menu variants.
- Stats bandBlock
A band of key numbers that count up as they come into view.