Segmented Control
Segmented control: a pill toggle group with a muted track where a lifted thumb glides to the pressed item, staying still under reduced motion. Horizontal only; values are arrays.
"use client"
import { createContext, useContext, useId, useMemo, useState } from "react"
import { Toggle as TogglePrimitive } from "@base-ui/react/toggle"
import { ToggleGroup as ToggleGroupPrimitive } from "@base-ui/react/toggle-group"
import { cn } from "cn"
import { LayoutGroup, motion, useReducedMotion } from "motion/react"
// value/onValueChange/defaultValue take arrays, per Base UI ToggleGroup.
// className is a string here, not Base UI's state callback: the styling is
// the kit's, and state comes through data-pressed and data-disabled.
type Styled<P> = Omit<P, "className"> & {
/**
* Extra classes, as a string only: Base UI's function form is not
* accepted. On `SegmentedControl` they land on the track, and on
* `SegmentedControlItem` on the toggle button.
*/
className?: string
}
// The group keeps the pressed values so each item knows whether it holds the
// thumb; a controlled value wins over the inner state.
const PressedContext = createContext<{
pressed: Set<string>
group: string
multiple: boolean
}>({ pressed: new Set(), group: "", multiple: false })
/**
* A row of toggle buttons on a rounded track. The pressed one sits on a
* raised thumb that slides over from the last one pressed. Put
* `SegmentedControlItem` parts inside.
*
* It is Base UI's `ToggleGroup`, so `value`, `defaultValue` and
* `onValueChange` use arrays of item values. Without `multiple`, one item is
* always on: pressing the active item again does nothing, and
* `onValueChange` is not called with an empty array. With `multiple`, every
* item can be turned off. It is horizontal only, and `className` takes a
* string.
*/
function SegmentedControl({
className,
value,
defaultValue,
onValueChange,
multiple = false,
...props
}: Styled<Omit<ToggleGroupPrimitive.Props, "orientation">>) {
const group = useId()
const [inner, setInner] = useState<string[]>(
(defaultValue as string[] | undefined) ?? []
)
const current = (value as string[] | undefined) ?? inner
const key = current.join("\u0000")
const context = useMemo(
() => ({
pressed: new Set(key ? key.split("\u0000") : []),
group,
multiple,
}),
[key, group, multiple]
)
return (
<PressedContext.Provider value={context}>
<LayoutGroup id={group}>
<ToggleGroupPrimitive
data-slot="segmented-control"
value={current}
multiple={multiple}
onValueChange={(next, event) => {
// One stays on: a press on the active item is ignored.
if (!multiple && next.length === 0) {
event.cancel()
return
}
// The consumer goes first: event.cancel() keeps the old value.
onValueChange?.(next, event)
if (!event.isCanceled) setInner(next as string[])
}}
className={cn(
// The track: a muted well; in dark a faint lit rim on its top edge.
"inline-flex items-center gap-1 rounded-full bg-muted p-1 ring-1 ring-border",
"dark:bg-foreground/6 dark:shadow-[inset_0_1px_0_rgba(255,255,255,0.05)] dark:ring-foreground/10",
className
)}
{...props}
/>
</LayoutGroup>
</PressedContext.Provider>
)
}
/**
* One option in a `SegmentedControl`, built on Base UI's `Toggle`. Give it a
* string `value`. It is square for one character or an icon and widens to
* fit a word.
*
* The pressed item sits on the thumb, a card-colored pill with a soft shadow
* (a light wash in dark mode) that glides over from the last item pressed;
* reduced motion moves it at once. The other items stay muted and come up
* to full ink on hover. When the control has `multiple`, each pressed item
* gets its own thumb, without the glide.
*/
function SegmentedControlItem({
className,
children,
value,
...props
}: Styled<TogglePrimitive.Props>) {
const { pressed, multiple } = useContext(PressedContext)
const reduce = useReducedMotion()
const on = typeof value === "string" && pressed.has(value)
return (
<TogglePrimitive
data-slot="segmented-control-item"
value={value}
className={cn(
"relative isolate flex h-8 min-w-8 items-center justify-center rounded-full px-2.5 text-sm font-medium text-muted-foreground tabular-nums",
"transition-colors duration-150 ease-out motion-reduce:transition-none",
"hover:text-foreground",
"focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none",
"data-disabled:pointer-events-none data-disabled:opacity-50",
"data-pressed:text-foreground",
className
)}
{...props}
>
{/* The thumb: one shared element per group, so it glides to whichever
item is pressed instead of popping. With several pressed at once
each keeps its own, still. */}
{on && (
<motion.span
aria-hidden="true"
layoutId={multiple ? undefined : "thumb"}
transition={
reduce
? { duration: 0 }
: { type: "spring", stiffness: 520, damping: 42, mass: 0.8 }
}
className="absolute inset-0 -z-10 rounded-full bg-card shadow-xs dark:bg-foreground/15"
/>
)}
{children}
</TogglePrimitive>
)
}
export { SegmentedControl, SegmentedControlItem }
"use client"
import { useState } from "react"
import {
TextAlignCenterIcon,
TextAlignLeftIcon,
TextAlignRightIcon,
} from "@phosphor-icons/react"
import {
SegmentedControl,
SegmentedControlItem,
} from "@/components/toggle/segmented-control"
// Year is disabled, so that state shows beside the live ones.
const RANGES = ["Day", "Week", "Month", "Year"] as const
const ALIGNMENTS = [
{ value: "left", label: "Align left", Icon: TextAlignLeftIcon },
{ value: "center", label: "Align center", Icon: TextAlignCenterIcon },
{ value: "right", label: "Align right", Icon: TextAlignRightIcon },
] as const
export default function SegmentedControlDemo() {
const [range, setRange] = useState<string>("Week")
return (
<div className="flex flex-wrap items-center justify-center gap-8">
{/* Controlled: one item is always on, so there is no empty update. */}
<SegmentedControl
aria-label="Range"
value={[range]}
onValueChange={(next) => {
if (next[0]) setRange(next[0])
}}
>
{RANGES.map((value) => (
<SegmentedControlItem
key={value}
value={value}
disabled={value === "Year"}
>
{value}
</SegmentedControlItem>
))}
</SegmentedControl>
<SegmentedControl aria-label="Text alignment" defaultValue={["left"]}>
{ALIGNMENTS.map(({ value, label, Icon }) => (
<SegmentedControlItem key={value} value={value} aria-label={label}>
<Icon aria-hidden="true" />
</SegmentedControlItem>
))}
</SegmentedControl>
</div>
)
}
Installation
pnpm dlx shadcn@latest add @01orbital/segmented-controlnpx shadcn@latest add @01orbital/segmented-controlyarn dlx shadcn@latest add @01orbital/segmented-controlbunx --bun shadcn@latest add @01orbital/segmented-controlUsage
"use client"
import { useState } from "react"
import {
TextAlignCenterIcon,
TextAlignLeftIcon,
TextAlignRightIcon,
} from "@phosphor-icons/react"
import {
SegmentedControl,
SegmentedControlItem,
} from "@/components/toggle/segmented-control"
// Year is disabled, so that state shows beside the live ones.
const RANGES = ["Day", "Week", "Month", "Year"] as const
const ALIGNMENTS = [
{ value: "left", label: "Align left", Icon: TextAlignLeftIcon },
{ value: "center", label: "Align center", Icon: TextAlignCenterIcon },
{ value: "right", label: "Align right", Icon: TextAlignRightIcon },
] as const
export default function SegmentedControlDemo() {
const [range, setRange] = useState<string>("Week")
return (
<div className="flex flex-wrap items-center justify-center gap-8">
{/* Controlled: one item is always on, so there is no empty update. */}
<SegmentedControl
aria-label="Range"
value={[range]}
onValueChange={(next) => {
if (next[0]) setRange(next[0])
}}
>
{RANGES.map((value) => (
<SegmentedControlItem
key={value}
value={value}
disabled={value === "Year"}
>
{value}
</SegmentedControlItem>
))}
</SegmentedControl>
<SegmentedControl aria-label="Text alignment" defaultValue={["left"]}>
{ALIGNMENTS.map(({ value, label, Icon }) => (
<SegmentedControlItem key={value} value={value} aria-label={label}>
<Icon aria-hidden="true" />
</SegmentedControlItem>
))}
</SegmentedControl>
</div>
)
}This example installs with everything it uses:
pnpm dlx shadcn@latest add @01orbital/segmented-control-demonpx shadcn@latest add @01orbital/segmented-control-demoyarn dlx shadcn@latest add @01orbital/segmented-control-demobunx --bun shadcn@latest add @01orbital/segmented-control-demoExamples
Workshop Formatsegmented-control-workshop-format
Segmented Control example: a control that switches a ceramics workshop between wheel and hand-building details. Shows a tab-like switcher that changes content below.
"use client"
import { Eyebrow } from "@/components/eyebrow/eyebrow"
import { Grain } from "@/components/texture/grain"
import {
SegmentedControl,
SegmentedControlItem,
} from "@/components/toggle/segmented-control"
import {
Card,
CardContent,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card"
import { Separator } from "@/components/ui/separator"
// The copy: change text here, not in the markup.
const COPY = {
eyebrow: "KILN & CO / SATURDAY WORKSHOPS",
title: "What would you like to make?",
label: "Workshop format",
wheel: {
title: "Throw your first bowl",
body: "Two hours on the wheel with Rosa. Includes clay, glazing, and one firing.",
when: "Saturday · 10:00–12:00",
price: "$85 / person",
},
hand: {
title: "Build a breakfast set",
body: "Pinch a cup and shape a small plate with Tomas. Includes clay, glazing, and one firing.",
when: "Saturday · 14:00–16:30",
price: "$70 / person",
},
footnote: "Beginners welcome · Aprons provided · Ages 16+",
} as const
const FORMATS = [
{ value: "wheel", label: "On the wheel" },
{ value: "hand", label: "By hand" },
] as const
/** A Segmented Control that switches a ceramics workshop between wheel and hand-building details. */
export default function SegmentedControlWorkshopFormat() {
return (
<Card className="group relative isolate w-full max-w-md gap-0 overflow-hidden rounded-xl border border-border bg-background text-foreground shadow-none ring-0">
<Grain variant="paper" intensity="fine" />
<CardHeader className="relative gap-4">
<Eyebrow>{COPY.eyebrow}</Eyebrow>
<CardTitle className="text-2xl font-semibold">{COPY.title}</CardTitle>
<SegmentedControl
aria-label={COPY.label}
defaultValue={["wheel"]}
onValueChange={(next, event) => {
if (!next.length) event.cancel()
}}
className="w-full rounded-lg"
>
{FORMATS.map((item) => (
<SegmentedControlItem
key={item.value}
data-format={item.value}
value={item.value}
className="h-10 flex-1"
>
{item.label}
</SegmentedControlItem>
))}
</SegmentedControl>
</CardHeader>
<CardContent className="relative hidden group-has-[[data-format=wheel][data-pressed]]:block">
<h4 className="text-lg font-semibold">{COPY.wheel.title}</h4>
<p className="mt-2 text-sm/6 text-muted-foreground">
{COPY.wheel.body}
</p>
<p className="mt-4 flex justify-between text-sm font-medium">
<span>{COPY.wheel.when}</span>
<span>{COPY.wheel.price}</span>
</p>
</CardContent>
<CardContent className="relative hidden group-has-[[data-format=hand][data-pressed]]:block">
<h4 className="text-lg font-semibold">{COPY.hand.title}</h4>
<p className="mt-2 text-sm/6 text-muted-foreground">{COPY.hand.body}</p>
<p className="mt-4 flex justify-between text-sm font-medium">
<span>{COPY.hand.when}</span>
<span>{COPY.hand.price}</span>
</p>
</CardContent>
<CardFooter className="relative flex-col items-stretch gap-3">
<Separator />
<p className="text-xs text-muted-foreground">{COPY.footnote}</p>
</CardFooter>
</Card>
)
}
import { mergeProps } from "@base-ui/react/merge-props"
import { useRender } from "@base-ui/react/use-render"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "cn"
const eyebrowVariants = cva("text-eyebrow", {
variants: {
/**
* `default` is a 14px/20px label. `icon` adds a row with a 16px icon
* and a 12px gap; put the icon first and give it `aria-hidden`.
* `mono` and `caps` are 12px/20px uppercase labels with 0.12em
* tracking, in the mono and inherited faces respectively.
*/
variant: {
default: "text-sm/5 font-medium text-eyebrow",
icon: "flex items-center gap-3 text-sm/5 font-medium [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
mono: "font-mono text-xs/5 font-medium tracking-[0.12em] uppercase",
caps: "text-xs/5 font-medium tracking-[0.12em] uppercase",
},
},
defaultVariants: { variant: "default" },
})
/**
* A short label above a heading, rendered as a `<p>` at weight 500.
* The default is 14px/20px in the kit's eyebrow color. The surrounding
* layout controls the space to the heading. Use `className` to customize
* the typography or color, and `render` to change the element.
*/
function Eyebrow({
className,
variant = "default",
render,
...props
}: useRender.ComponentProps<"p"> & VariantProps<typeof eyebrowVariants>) {
return useRender({
defaultTagName: "p",
render,
state: { slot: "eyebrow", variant },
props: mergeProps<"p">(
{ className: cn(eyebrowVariants({ variant }), className) },
props
),
})
}
export { Eyebrow, eyebrowVariants }
import { cn } from "cn"
// Paper grain: an SVG turbulence filter as a data URI.
const PAPER_GRAIN = `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='250' height='250' viewBox='0 0 100 100'%3E%3Cfilter id='n' color-interpolation-filters='sRGB'%3E%3CfeTurbulence type='turbulence' baseFrequency='1.4' numOctaves='1' seed='2' stitchTiles='stitch' result='n'/%3E%3CfeComponentTransfer result='g'%3E%3CfeFuncR type='linear' slope='4' intercept='1'/%3E%3CfeFuncG type='linear' slope='4' intercept='1'/%3E%3CfeFuncB type='linear' slope='4' intercept='1'/%3E%3C/feComponentTransfer%3E%3CfeColorMatrix type='saturate' values='0' in='g'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E")`
// Sandpaper grain: an SVG turbulence filter as a data URI.
const SANDPAPER_GRAIN = `url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='200' height='200' viewBox='0 0 100 100'%3E%3Cfilter id='n' color-interpolation-filters='sRGB'%3E%3CfeTurbulence type='turbulence' baseFrequency='2.2' numOctaves='2' seed='5' stitchTiles='stitch' result='n'/%3E%3CfeComponentTransfer result='g'%3E%3CfeFuncR type='linear' slope='2.5' intercept='0.8'/%3E%3CfeFuncG type='linear' slope='2.5' intercept='0.8'/%3E%3CfeFuncB type='linear' slope='2.5' intercept='0.8'/%3E%3C/feComponentTransfer%3E%3CfeColorMatrix type='saturate' values='0' in='g'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E")`
// Single noise: an SVG turbulence filter as a data URI.
const SINGLE_NOISE = `url("data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n' color-interpolation-filters='sRGB'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.8' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E")`
// Square grain: an SVG turbulence filter as a data URI.
const SQUARE_GRAIN = `url("data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns=%22http://www.w3.org/2000/svg%22%20width=%22200%22%20height=%22200%22%20viewBox=%220%200%20100%20100%22%3E%3Cfilter%20id=%22n%22%20color-interpolation-filters=%22sRGB%22%3E%3CfeTurbulence%20type=%22turbulence%22%20baseFrequency=%222.1%22%20numOctaves=%223%22%20seed=%2211%22%20stitchTiles=%22stitch%22%20result=%22n%22/%3E%3CfeComponentTransfer%20result=%22g%22%3E%3CfeFuncR%20type=%22linear%22%20slope=%225.5%22%20intercept=%221.4%22/%3E%3CfeFuncG%20type=%22linear%22%20slope=%225.5%22%20intercept=%221.4%22/%3E%3CfeFuncB%20type=%22linear%22%20slope=%225.5%22%20intercept=%221.4%22/%3E%3C/feComponentTransfer%3E%3CfeColorMatrix%20type=%22saturate%22%20values=%220%22%20in=%22g%22/%3E%3C/filter%3E%3Crect%20width=%22100%%22%20height=%22100%%22%20filter=%22url(%23n)%22/%3E%3C/svg%3E")`
type Intensity = "fine" | "default" | "rich"
// One scale for every texture; `default` is the unscaled value.
const INTENSITY_MULT: Record<Intensity, number> = {
fine: 0.6,
default: 1,
rich: 1.45,
}
const alpha = (base: number, mult: number) => (base * mult).toFixed(4)
// Four grain treatments; each paints a single texture layer.
// Full-bleed art layer — drop inside a `relative` parent; sits behind content.
/** The texture treatment painted by `Grain`. */
type GrainVariant =
// Stylized paper-look variants — heavier filter chain than plain noise.
"paper" | "sandpaper" | "square" | "single"
type Layer = {
src: string
size: string
opacity: number
blend: "overlay" | "soft-light"
}
const BLEND_CLASS: Record<Layer["blend"], string> = {
overlay: "mix-blend-overlay",
"soft-light": "mix-blend-soft-light",
}
const VARIANT_TEXTURES: Record<GrainVariant, Layer> = {
paper: {
src: PAPER_GRAIN,
size: "250px",
opacity: 0.25,
blend: "overlay",
},
sandpaper: {
src: SANDPAPER_GRAIN,
size: "200px",
opacity: 0.25,
blend: "overlay",
},
square: {
src: SQUARE_GRAIN,
size: "200px",
opacity: 0.8,
blend: "soft-light",
},
single: { src: SINGLE_NOISE, size: "200px", opacity: 0.3, blend: "overlay" },
}
/**
* A decorative grain layer that fills a positioned parent without blocking
* clicks. Choose a texture and adjust its strength with `intensity` or
* `opacity`. `className` and other div props land on the outer layer.
*/
function Grain({
variant = "single",
intensity = "default",
opacity,
isolated = false,
className,
...props
}: React.ComponentProps<"div"> & {
/** The grain treatment: `single` (default), `paper`, `sandpaper` or `square`. */
variant?: GrainVariant
/** Multiplies the texture's opacity: `fine` 0.6×, `default` 1×, `rich` 1.45×. */
intensity?: Intensity
/** The texture opacity, from 0 to 1. Takes precedence over `intensity`. */
opacity?: number
/**
* Adds paint containment when true. This creates a stacking context, so
* the texture stops blending with scene layers outside this element.
*/
isolated?: boolean
}) {
const layer = VARIANT_TEXTURES[variant]
const m =
opacity != null ? opacity / layer.opacity : INTENSITY_MULT[intensity]
return (
<div
data-slot="grain"
data-variant={variant}
aria-hidden="true"
className={cn(
"pointer-events-none absolute inset-0",
isolated && "contain-[paint]",
className
)}
{...props}
>
<div
className={cn("absolute inset-0", BLEND_CLASS[layer.blend])}
style={{
backgroundImage: layer.src,
backgroundSize: layer.size,
opacity: layer.opacity * m,
}}
/>
</div>
)
}
export { Grain }
"use client"
import { createContext, useContext, useId, useMemo, useState } from "react"
import { Toggle as TogglePrimitive } from "@base-ui/react/toggle"
import { ToggleGroup as ToggleGroupPrimitive } from "@base-ui/react/toggle-group"
import { cn } from "cn"
import { LayoutGroup, motion, useReducedMotion } from "motion/react"
// value/onValueChange/defaultValue take arrays, per Base UI ToggleGroup.
// className is a string here, not Base UI's state callback: the styling is
// the kit's, and state comes through data-pressed and data-disabled.
type Styled<P> = Omit<P, "className"> & {
/**
* Extra classes, as a string only: Base UI's function form is not
* accepted. On `SegmentedControl` they land on the track, and on
* `SegmentedControlItem` on the toggle button.
*/
className?: string
}
// The group keeps the pressed values so each item knows whether it holds the
// thumb; a controlled value wins over the inner state.
const PressedContext = createContext<{
pressed: Set<string>
group: string
multiple: boolean
}>({ pressed: new Set(), group: "", multiple: false })
/**
* A row of toggle buttons on a rounded track. The pressed one sits on a
* raised thumb that slides over from the last one pressed. Put
* `SegmentedControlItem` parts inside.
*
* It is Base UI's `ToggleGroup`, so `value`, `defaultValue` and
* `onValueChange` use arrays of item values. Without `multiple`, one item is
* always on: pressing the active item again does nothing, and
* `onValueChange` is not called with an empty array. With `multiple`, every
* item can be turned off. It is horizontal only, and `className` takes a
* string.
*/
function SegmentedControl({
className,
value,
defaultValue,
onValueChange,
multiple = false,
...props
}: Styled<Omit<ToggleGroupPrimitive.Props, "orientation">>) {
const group = useId()
const [inner, setInner] = useState<string[]>(
(defaultValue as string[] | undefined) ?? []
)
const current = (value as string[] | undefined) ?? inner
const key = current.join("\u0000")
const context = useMemo(
() => ({
pressed: new Set(key ? key.split("\u0000") : []),
group,
multiple,
}),
[key, group, multiple]
)
return (
<PressedContext.Provider value={context}>
<LayoutGroup id={group}>
<ToggleGroupPrimitive
data-slot="segmented-control"
value={current}
multiple={multiple}
onValueChange={(next, event) => {
// One stays on: a press on the active item is ignored.
if (!multiple && next.length === 0) {
event.cancel()
return
}
// The consumer goes first: event.cancel() keeps the old value.
onValueChange?.(next, event)
if (!event.isCanceled) setInner(next as string[])
}}
className={cn(
// The track: a muted well; in dark a faint lit rim on its top edge.
"inline-flex items-center gap-1 rounded-full bg-muted p-1 ring-1 ring-border",
"dark:bg-foreground/6 dark:shadow-[inset_0_1px_0_rgba(255,255,255,0.05)] dark:ring-foreground/10",
className
)}
{...props}
/>
</LayoutGroup>
</PressedContext.Provider>
)
}
/**
* One option in a `SegmentedControl`, built on Base UI's `Toggle`. Give it a
* string `value`. It is square for one character or an icon and widens to
* fit a word.
*
* The pressed item sits on the thumb, a card-colored pill with a soft shadow
* (a light wash in dark mode) that glides over from the last item pressed;
* reduced motion moves it at once. The other items stay muted and come up
* to full ink on hover. When the control has `multiple`, each pressed item
* gets its own thumb, without the glide.
*/
function SegmentedControlItem({
className,
children,
value,
...props
}: Styled<TogglePrimitive.Props>) {
const { pressed, multiple } = useContext(PressedContext)
const reduce = useReducedMotion()
const on = typeof value === "string" && pressed.has(value)
return (
<TogglePrimitive
data-slot="segmented-control-item"
value={value}
className={cn(
"relative isolate flex h-8 min-w-8 items-center justify-center rounded-full px-2.5 text-sm font-medium text-muted-foreground tabular-nums",
"transition-colors duration-150 ease-out motion-reduce:transition-none",
"hover:text-foreground",
"focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none",
"data-disabled:pointer-events-none data-disabled:opacity-50",
"data-pressed:text-foreground",
className
)}
{...props}
>
{/* The thumb: one shared element per group, so it glides to whichever
item is pressed instead of popping. With several pressed at once
each keeps its own, still. */}
{on && (
<motion.span
aria-hidden="true"
layoutId={multiple ? undefined : "thumb"}
transition={
reduce
? { duration: 0 }
: { type: "spring", stiffness: 520, damping: 42, mass: 0.8 }
}
className="absolute inset-0 -z-10 rounded-full bg-card shadow-xs dark:bg-foreground/15"
/>
)}
{children}
</TogglePrimitive>
)
}
export { SegmentedControl, SegmentedControlItem }
pnpm dlx shadcn@latest add @01orbital/segmented-control-workshop-formatnpx shadcn@latest add @01orbital/segmented-control-workshop-formatyarn dlx shadcn@latest add @01orbital/segmented-control-workshop-formatbunx --bun shadcn@latest add @01orbital/segmented-control-workshop-formatSleep Periodsegmented-control-sleep-period
Segmented Control example: a control in a dark card that swaps a week and month sleep summary. Shows a time range switcher for dashboards.
"use client"
import { Eyebrow } from "@/components/eyebrow/eyebrow"
import {
SegmentedControl,
SegmentedControlItem,
} from "@/components/toggle/segmented-control"
import {
Card,
CardContent,
CardHeader,
CardTitle,
} from "@/components/ui/card"
// The copy: change text here, not in the markup.
const COPY = {
eyebrow: "RESTDAY / SLEEP JOURNAL",
title: "Your nights",
label: "Sleep report period",
week: {
range: "OCTOBER 26 – NOVEMBER 1",
average: "7h 42m",
averageNote: "Average time asleep · 7 nights logged",
bedtime: "Bedtime stayed within 25 minutes on five nights.",
trend: "That’s two more consistent nights than last week.",
},
month: {
range: "OCTOBER 1–31",
average: "7h 18m",
averageNote: "Average time asleep · 28 nights logged",
bedtime: "You logged 18 nights with a consistent bedtime.",
trend: "Friday was your shortest night, averaging 6h 34m.",
},
} as const
const PERIODS = [
{ value: "week", label: "Week" },
{ value: "month", label: "Month" },
] as const
/** A Segmented Control in a dark card that swaps a week and month sleep summary. */
export default function SegmentedControlSleepPeriod() {
return (
<Card className="theme-blue group w-full max-w-md rounded-[1.75rem] border border-border bg-background text-foreground shadow-none ring-0">
<CardHeader className="gap-4">
<Eyebrow>{COPY.eyebrow}</Eyebrow>
<div className="flex flex-wrap items-center justify-between gap-4">
<CardTitle className="text-xl font-semibold">{COPY.title}</CardTitle>
<SegmentedControl
aria-label={COPY.label}
defaultValue={["week"]}
onValueChange={(next, event) => {
if (!next.length) event.cancel()
}}
className="bg-muted"
>
{PERIODS.map((period) => (
<SegmentedControlItem
key={period.value}
data-period={period.value}
value={period.value}
>
{period.label}
</SegmentedControlItem>
))}
</SegmentedControl>
</div>
</CardHeader>
<CardContent className="hidden group-has-[[data-period=week][data-pressed]]:block">
<p className="text-xs text-muted-foreground">{COPY.week.range}</p>
<p className="mt-3 text-4xl font-medium tracking-tight tabular-nums">
{COPY.week.average}
</p>
<p className="mt-2 text-sm text-muted-foreground">
{COPY.week.averageNote}
</p>
<div className="mt-6 border-t border-border pt-4 text-sm/6">
<p>{COPY.week.bedtime}</p>
<p className="mt-2 text-muted-foreground">{COPY.week.trend}</p>
</div>
</CardContent>
<CardContent className="hidden group-has-[[data-period=month][data-pressed]]:block">
<p className="text-xs text-muted-foreground">{COPY.month.range}</p>
<p className="mt-3 text-4xl font-medium tracking-tight tabular-nums">
{COPY.month.average}
</p>
<p className="mt-2 text-sm text-muted-foreground">
{COPY.month.averageNote}
</p>
<div className="mt-6 border-t border-border pt-4 text-sm/6">
<p>{COPY.month.bedtime}</p>
<p className="mt-2 text-muted-foreground">{COPY.month.trend}</p>
</div>
</CardContent>
</Card>
)
}
import { mergeProps } from "@base-ui/react/merge-props"
import { useRender } from "@base-ui/react/use-render"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "cn"
const eyebrowVariants = cva("text-eyebrow", {
variants: {
/**
* `default` is a 14px/20px label. `icon` adds a row with a 16px icon
* and a 12px gap; put the icon first and give it `aria-hidden`.
* `mono` and `caps` are 12px/20px uppercase labels with 0.12em
* tracking, in the mono and inherited faces respectively.
*/
variant: {
default: "text-sm/5 font-medium text-eyebrow",
icon: "flex items-center gap-3 text-sm/5 font-medium [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
mono: "font-mono text-xs/5 font-medium tracking-[0.12em] uppercase",
caps: "text-xs/5 font-medium tracking-[0.12em] uppercase",
},
},
defaultVariants: { variant: "default" },
})
/**
* A short label above a heading, rendered as a `<p>` at weight 500.
* The default is 14px/20px in the kit's eyebrow color. The surrounding
* layout controls the space to the heading. Use `className` to customize
* the typography or color, and `render` to change the element.
*/
function Eyebrow({
className,
variant = "default",
render,
...props
}: useRender.ComponentProps<"p"> & VariantProps<typeof eyebrowVariants>) {
return useRender({
defaultTagName: "p",
render,
state: { slot: "eyebrow", variant },
props: mergeProps<"p">(
{ className: cn(eyebrowVariants({ variant }), className) },
props
),
})
}
export { Eyebrow, eyebrowVariants }
"use client"
import { createContext, useContext, useId, useMemo, useState } from "react"
import { Toggle as TogglePrimitive } from "@base-ui/react/toggle"
import { ToggleGroup as ToggleGroupPrimitive } from "@base-ui/react/toggle-group"
import { cn } from "cn"
import { LayoutGroup, motion, useReducedMotion } from "motion/react"
// value/onValueChange/defaultValue take arrays, per Base UI ToggleGroup.
// className is a string here, not Base UI's state callback: the styling is
// the kit's, and state comes through data-pressed and data-disabled.
type Styled<P> = Omit<P, "className"> & {
/**
* Extra classes, as a string only: Base UI's function form is not
* accepted. On `SegmentedControl` they land on the track, and on
* `SegmentedControlItem` on the toggle button.
*/
className?: string
}
// The group keeps the pressed values so each item knows whether it holds the
// thumb; a controlled value wins over the inner state.
const PressedContext = createContext<{
pressed: Set<string>
group: string
multiple: boolean
}>({ pressed: new Set(), group: "", multiple: false })
/**
* A row of toggle buttons on a rounded track. The pressed one sits on a
* raised thumb that slides over from the last one pressed. Put
* `SegmentedControlItem` parts inside.
*
* It is Base UI's `ToggleGroup`, so `value`, `defaultValue` and
* `onValueChange` use arrays of item values. Without `multiple`, one item is
* always on: pressing the active item again does nothing, and
* `onValueChange` is not called with an empty array. With `multiple`, every
* item can be turned off. It is horizontal only, and `className` takes a
* string.
*/
function SegmentedControl({
className,
value,
defaultValue,
onValueChange,
multiple = false,
...props
}: Styled<Omit<ToggleGroupPrimitive.Props, "orientation">>) {
const group = useId()
const [inner, setInner] = useState<string[]>(
(defaultValue as string[] | undefined) ?? []
)
const current = (value as string[] | undefined) ?? inner
const key = current.join("\u0000")
const context = useMemo(
() => ({
pressed: new Set(key ? key.split("\u0000") : []),
group,
multiple,
}),
[key, group, multiple]
)
return (
<PressedContext.Provider value={context}>
<LayoutGroup id={group}>
<ToggleGroupPrimitive
data-slot="segmented-control"
value={current}
multiple={multiple}
onValueChange={(next, event) => {
// One stays on: a press on the active item is ignored.
if (!multiple && next.length === 0) {
event.cancel()
return
}
// The consumer goes first: event.cancel() keeps the old value.
onValueChange?.(next, event)
if (!event.isCanceled) setInner(next as string[])
}}
className={cn(
// The track: a muted well; in dark a faint lit rim on its top edge.
"inline-flex items-center gap-1 rounded-full bg-muted p-1 ring-1 ring-border",
"dark:bg-foreground/6 dark:shadow-[inset_0_1px_0_rgba(255,255,255,0.05)] dark:ring-foreground/10",
className
)}
{...props}
/>
</LayoutGroup>
</PressedContext.Provider>
)
}
/**
* One option in a `SegmentedControl`, built on Base UI's `Toggle`. Give it a
* string `value`. It is square for one character or an icon and widens to
* fit a word.
*
* The pressed item sits on the thumb, a card-colored pill with a soft shadow
* (a light wash in dark mode) that glides over from the last item pressed;
* reduced motion moves it at once. The other items stay muted and come up
* to full ink on hover. When the control has `multiple`, each pressed item
* gets its own thumb, without the glide.
*/
function SegmentedControlItem({
className,
children,
value,
...props
}: Styled<TogglePrimitive.Props>) {
const { pressed, multiple } = useContext(PressedContext)
const reduce = useReducedMotion()
const on = typeof value === "string" && pressed.has(value)
return (
<TogglePrimitive
data-slot="segmented-control-item"
value={value}
className={cn(
"relative isolate flex h-8 min-w-8 items-center justify-center rounded-full px-2.5 text-sm font-medium text-muted-foreground tabular-nums",
"transition-colors duration-150 ease-out motion-reduce:transition-none",
"hover:text-foreground",
"focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none",
"data-disabled:pointer-events-none data-disabled:opacity-50",
"data-pressed:text-foreground",
className
)}
{...props}
>
{/* The thumb: one shared element per group, so it glides to whichever
item is pressed instead of popping. With several pressed at once
each keeps its own, still. */}
{on && (
<motion.span
aria-hidden="true"
layoutId={multiple ? undefined : "thumb"}
transition={
reduce
? { duration: 0 }
: { type: "spring", stiffness: 520, damping: 42, mass: 0.8 }
}
className="absolute inset-0 -z-10 rounded-full bg-card shadow-xs dark:bg-foreground/15"
/>
)}
{children}
</TogglePrimitive>
)
}
export { SegmentedControl, SegmentedControlItem }
pnpm dlx shadcn@latest add @01orbital/segmented-control-sleep-periodnpx shadcn@latest add @01orbital/segmented-control-sleep-periodyarn dlx shadcn@latest add @01orbital/segmented-control-sleep-periodbunx --bun shadcn@latest add @01orbital/segmented-control-sleep-periodInvoice Intervalsegmented-control-invoice-interval
Segmented Control example: a warm inset billing pill with generous labels and a small annual-saving note, on paper. Shows a monthly and yearly pricing toggle.
The source comes with full access.
One payment of $149 opens the source right here and lets the CLI install every paid component, with lifetime updates.
pnpm dlx shadcn@latest add @01orbital/segmented-control-invoice-intervalnpx shadcn@latest add @01orbital/segmented-control-invoice-intervalyarn dlx shadcn@latest add @01orbital/segmented-control-invoice-intervalbunx --bun shadcn@latest add @01orbital/segmented-control-invoice-intervalNight Desksegmented-control-night-desk
Segmented Control example: a squared track with a filled selection and monospace labels. Shows a sharp-cornered, technical variation of the toggle.
The source comes with full access.
One payment of $149 opens the source right here and lets the CLI install every paid component, with lifetime updates.
pnpm dlx shadcn@latest add @01orbital/segmented-control-night-desknpx shadcn@latest add @01orbital/segmented-control-night-deskyarn dlx shadcn@latest add @01orbital/segmented-control-night-deskbunx --bun shadcn@latest add @01orbital/segmented-control-night-deskReading Listsegmented-control-reading-list
Segmented Control example: terracotta multiple-selection chips, each with its own raised thumb. Shows multi-select filter chips for a reading list.
"use client"
import { Linen } from "@/components/texture/linen"
import {
SegmentedControl,
SegmentedControlItem,
} from "@/components/toggle/segmented-control"
// The copy: change text here, not in the markup.
const COPY = {
title: "Follow your curiosity.",
body: "Choose the subjects you want in your next reading list.",
label: "Reading interests",
} as const
const INTERESTS = [
{ value: "design", label: "Design" },
{ value: "culture", label: "Culture" },
{ value: "nature", label: "Nature" },
] as const
/** Terracotta multiple-selection chips, with individual raised thumbs. */
export default function SegmentedControlReadingList() {
return (
<div className="w-full bg-background text-foreground">
<div className="relative grid min-h-76 w-full content-center gap-6 overflow-hidden rounded-3xl bg-muted p-7 text-foreground">
<Linen intensity="rich" className="" />
<div className="relative">
<h3 className="text-3xl font-medium tracking-tight">{COPY.title}</h3>
<p className="mt-3 text-sm/6">{COPY.body}</p>
</div>
<SegmentedControl
multiple
aria-label={COPY.label}
defaultValue={["design", "culture"]}
className="relative w-full flex-wrap gap-2 bg-transparent p-0 shadow-none ring-0 dark:bg-transparent dark:shadow-none dark:ring-0"
>
{INTERESTS.map((item) => (
<SegmentedControlItem
key={item.value}
value={item.value}
className="h-11 border border-current/35 px-4 [&>span]:bg-card dark:[&>span]:bg-card"
>
{item.label}
</SegmentedControlItem>
))}
</SegmentedControl>
</div>
</div>
)
}
import { cn } from "cn"
type Intensity = "fine" | "default" | "rich"
// One scale for every texture; `default` is the unscaled value.
const INTENSITY_MULT: Record<Intensity, number> = {
fine: 0.6,
default: 1,
rich: 1.45,
}
const alpha = (base: number, mult: number) => (base * mult).toFixed(4)
// Two-direction weave — 1px threads at 0°+90°. 5px and 6px are the thread
// PERIODS, not gaps, and they are coprime, so the weave repeats every 30px.
/** Full-bleed art layer — drop inside a `relative` parent; sits behind content. */
function Linen({
intensity = "default",
className,
...props
}: React.ComponentProps<"div"> & {
/**
* Thread alpha multiplier. Ink is white; set --linen-color on a light ground.
*/
intensity?: Intensity
}) {
const m = INTENSITY_MULT[intensity]
return (
<div
className={cn("pointer-events-none absolute inset-0", className)}
aria-hidden="true"
data-slot="linen"
{...props}
>
<div
className="absolute inset-0"
style={{
backgroundImage: `repeating-linear-gradient(90deg in srgb, transparent 0px, transparent 2px, oklch(from var(--linen-color, oklch(1 0 0)) l c h / ${alpha(0.05, m)}) 2px, oklch(from var(--linen-color, oklch(1 0 0)) l c h / ${alpha(0.02, m)}) 3px, transparent 3px, transparent 6px), repeating-linear-gradient(0deg in srgb, transparent 0px, transparent 2px, oklch(from var(--linen-color, oklch(1 0 0)) l c h / ${alpha(0.06, m)}) 2px, oklch(from var(--linen-color, oklch(1 0 0)) l c h / ${alpha(0.02, m)}) 3px, transparent 3px, transparent 5px)`,
}}
/>
</div>
)
}
export { Linen }
"use client"
import { createContext, useContext, useId, useMemo, useState } from "react"
import { Toggle as TogglePrimitive } from "@base-ui/react/toggle"
import { ToggleGroup as ToggleGroupPrimitive } from "@base-ui/react/toggle-group"
import { cn } from "cn"
import { LayoutGroup, motion, useReducedMotion } from "motion/react"
// value/onValueChange/defaultValue take arrays, per Base UI ToggleGroup.
// className is a string here, not Base UI's state callback: the styling is
// the kit's, and state comes through data-pressed and data-disabled.
type Styled<P> = Omit<P, "className"> & {
/**
* Extra classes, as a string only: Base UI's function form is not
* accepted. On `SegmentedControl` they land on the track, and on
* `SegmentedControlItem` on the toggle button.
*/
className?: string
}
// The group keeps the pressed values so each item knows whether it holds the
// thumb; a controlled value wins over the inner state.
const PressedContext = createContext<{
pressed: Set<string>
group: string
multiple: boolean
}>({ pressed: new Set(), group: "", multiple: false })
/**
* A row of toggle buttons on a rounded track. The pressed one sits on a
* raised thumb that slides over from the last one pressed. Put
* `SegmentedControlItem` parts inside.
*
* It is Base UI's `ToggleGroup`, so `value`, `defaultValue` and
* `onValueChange` use arrays of item values. Without `multiple`, one item is
* always on: pressing the active item again does nothing, and
* `onValueChange` is not called with an empty array. With `multiple`, every
* item can be turned off. It is horizontal only, and `className` takes a
* string.
*/
function SegmentedControl({
className,
value,
defaultValue,
onValueChange,
multiple = false,
...props
}: Styled<Omit<ToggleGroupPrimitive.Props, "orientation">>) {
const group = useId()
const [inner, setInner] = useState<string[]>(
(defaultValue as string[] | undefined) ?? []
)
const current = (value as string[] | undefined) ?? inner
const key = current.join("\u0000")
const context = useMemo(
() => ({
pressed: new Set(key ? key.split("\u0000") : []),
group,
multiple,
}),
[key, group, multiple]
)
return (
<PressedContext.Provider value={context}>
<LayoutGroup id={group}>
<ToggleGroupPrimitive
data-slot="segmented-control"
value={current}
multiple={multiple}
onValueChange={(next, event) => {
// One stays on: a press on the active item is ignored.
if (!multiple && next.length === 0) {
event.cancel()
return
}
// The consumer goes first: event.cancel() keeps the old value.
onValueChange?.(next, event)
if (!event.isCanceled) setInner(next as string[])
}}
className={cn(
// The track: a muted well; in dark a faint lit rim on its top edge.
"inline-flex items-center gap-1 rounded-full bg-muted p-1 ring-1 ring-border",
"dark:bg-foreground/6 dark:shadow-[inset_0_1px_0_rgba(255,255,255,0.05)] dark:ring-foreground/10",
className
)}
{...props}
/>
</LayoutGroup>
</PressedContext.Provider>
)
}
/**
* One option in a `SegmentedControl`, built on Base UI's `Toggle`. Give it a
* string `value`. It is square for one character or an icon and widens to
* fit a word.
*
* The pressed item sits on the thumb, a card-colored pill with a soft shadow
* (a light wash in dark mode) that glides over from the last item pressed;
* reduced motion moves it at once. The other items stay muted and come up
* to full ink on hover. When the control has `multiple`, each pressed item
* gets its own thumb, without the glide.
*/
function SegmentedControlItem({
className,
children,
value,
...props
}: Styled<TogglePrimitive.Props>) {
const { pressed, multiple } = useContext(PressedContext)
const reduce = useReducedMotion()
const on = typeof value === "string" && pressed.has(value)
return (
<TogglePrimitive
data-slot="segmented-control-item"
value={value}
className={cn(
"relative isolate flex h-8 min-w-8 items-center justify-center rounded-full px-2.5 text-sm font-medium text-muted-foreground tabular-nums",
"transition-colors duration-150 ease-out motion-reduce:transition-none",
"hover:text-foreground",
"focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none",
"data-disabled:pointer-events-none data-disabled:opacity-50",
"data-pressed:text-foreground",
className
)}
{...props}
>
{/* The thumb: one shared element per group, so it glides to whichever
item is pressed instead of popping. With several pressed at once
each keeps its own, still. */}
{on && (
<motion.span
aria-hidden="true"
layoutId={multiple ? undefined : "thumb"}
transition={
reduce
? { duration: 0 }
: { type: "spring", stiffness: 520, damping: 42, mass: 0.8 }
}
className="absolute inset-0 -z-10 rounded-full bg-card shadow-xs dark:bg-foreground/15"
/>
)}
{children}
</TogglePrimitive>
)
}
export { SegmentedControl, SegmentedControlItem }
pnpm dlx shadcn@latest add @01orbital/segmented-control-reading-listnpx shadcn@latest add @01orbital/segmented-control-reading-listyarn dlx shadcn@latest add @01orbital/segmented-control-reading-listbunx --bun shadcn@latest add @01orbital/segmented-control-reading-listTraining Logsegmented-control-training-log
Segmented Control example: a training log with three heavy letters, the pressed one on an ink pill. Shows a compact single-select toggle.
The source comes with full access.
One payment of $149 opens the source right here and lets the CLI install every paid component, with lifetime updates.
pnpm dlx shadcn@latest add @01orbital/segmented-control-training-lognpx shadcn@latest add @01orbital/segmented-control-training-logyarn dlx shadcn@latest add @01orbital/segmented-control-training-logbunx --bun shadcn@latest add @01orbital/segmented-control-training-logMedium Filtersegmented-control-medium-filter
Segmented Control Medium Filter: an example of segmented-control.
"use client"
import { useState } from "react"
import { Subheading } from "@/components/subheading/subheading"
import {
SegmentedControl,
SegmentedControlItem,
} from "@/components/toggle/segmented-control"
// The copy: change text here, not in the markup.
const COPY = {
title: "The collection",
label: "Medium",
} as const
const MEDIUMS = [
{ value: "oil", label: "Oil" },
{ value: "ink", label: "Ink" },
{ value: "clay", label: "Clay" },
{ value: "print", label: "Print" },
] as const
const WORKS = [
{ title: "Low Tide, Evening", medium: "oil", year: "2021" },
{ title: "Three Branches", medium: "ink", year: "2023" },
{ title: "Vessel for Salt", medium: "clay", year: "2022" },
{ title: "Harbour at Dusk", medium: "print", year: "2024" },
{ title: "Field Notes in Red", medium: "oil", year: "2020" },
{ title: "Winter Rooftops", medium: "ink", year: "2024" },
] as const
/** A catalogue list filtered by several media at once with a multiple segmented control. */
export default function SegmentedControlMediumFilter() {
const [mediums, setMediums] = useState<string[]>(["oil", "ink"])
const shown = WORKS.filter((w) => mediums.includes(w.medium))
return (
<div className="w-full max-w-md bg-background p-8 text-foreground">
<Subheading
render={<h3 />}
className="[--font-display:var(--font-serif)]"
>
{COPY.title}
</Subheading>
<SegmentedControl
multiple
aria-label={COPY.label}
value={mediums}
onValueChange={(next) => setMediums(next as string[])}
className="mt-6"
>
{MEDIUMS.map((m) => (
<SegmentedControlItem key={m.value} value={m.value} className="px-4">
{m.label}
</SegmentedControlItem>
))}
</SegmentedControl>
<ul className="mt-6 divide-y divide-border border-y border-border">
{shown.map((w) => (
<li
key={w.title}
className="flex items-baseline justify-between gap-6 py-3"
>
<span className="font-serif text-xl">{w.title}</span>
<span className="text-sm text-muted-foreground tabular-nums">
{w.year}
</span>
</li>
))}
</ul>
</div>
)
}
"use client"
import { createContext, useContext, useId, useMemo, useState } from "react"
import { Toggle as TogglePrimitive } from "@base-ui/react/toggle"
import { ToggleGroup as ToggleGroupPrimitive } from "@base-ui/react/toggle-group"
import { cn } from "cn"
import { LayoutGroup, motion, useReducedMotion } from "motion/react"
// value/onValueChange/defaultValue take arrays, per Base UI ToggleGroup.
// className is a string here, not Base UI's state callback: the styling is
// the kit's, and state comes through data-pressed and data-disabled.
type Styled<P> = Omit<P, "className"> & {
/**
* Extra classes, as a string only: Base UI's function form is not
* accepted. On `SegmentedControl` they land on the track, and on
* `SegmentedControlItem` on the toggle button.
*/
className?: string
}
// The group keeps the pressed values so each item knows whether it holds the
// thumb; a controlled value wins over the inner state.
const PressedContext = createContext<{
pressed: Set<string>
group: string
multiple: boolean
}>({ pressed: new Set(), group: "", multiple: false })
/**
* A row of toggle buttons on a rounded track. The pressed one sits on a
* raised thumb that slides over from the last one pressed. Put
* `SegmentedControlItem` parts inside.
*
* It is Base UI's `ToggleGroup`, so `value`, `defaultValue` and
* `onValueChange` use arrays of item values. Without `multiple`, one item is
* always on: pressing the active item again does nothing, and
* `onValueChange` is not called with an empty array. With `multiple`, every
* item can be turned off. It is horizontal only, and `className` takes a
* string.
*/
function SegmentedControl({
className,
value,
defaultValue,
onValueChange,
multiple = false,
...props
}: Styled<Omit<ToggleGroupPrimitive.Props, "orientation">>) {
const group = useId()
const [inner, setInner] = useState<string[]>(
(defaultValue as string[] | undefined) ?? []
)
const current = (value as string[] | undefined) ?? inner
const key = current.join("\u0000")
const context = useMemo(
() => ({
pressed: new Set(key ? key.split("\u0000") : []),
group,
multiple,
}),
[key, group, multiple]
)
return (
<PressedContext.Provider value={context}>
<LayoutGroup id={group}>
<ToggleGroupPrimitive
data-slot="segmented-control"
value={current}
multiple={multiple}
onValueChange={(next, event) => {
// One stays on: a press on the active item is ignored.
if (!multiple && next.length === 0) {
event.cancel()
return
}
// The consumer goes first: event.cancel() keeps the old value.
onValueChange?.(next, event)
if (!event.isCanceled) setInner(next as string[])
}}
className={cn(
// The track: a muted well; in dark a faint lit rim on its top edge.
"inline-flex items-center gap-1 rounded-full bg-muted p-1 ring-1 ring-border",
"dark:bg-foreground/6 dark:shadow-[inset_0_1px_0_rgba(255,255,255,0.05)] dark:ring-foreground/10",
className
)}
{...props}
/>
</LayoutGroup>
</PressedContext.Provider>
)
}
/**
* One option in a `SegmentedControl`, built on Base UI's `Toggle`. Give it a
* string `value`. It is square for one character or an icon and widens to
* fit a word.
*
* The pressed item sits on the thumb, a card-colored pill with a soft shadow
* (a light wash in dark mode) that glides over from the last item pressed;
* reduced motion moves it at once. The other items stay muted and come up
* to full ink on hover. When the control has `multiple`, each pressed item
* gets its own thumb, without the glide.
*/
function SegmentedControlItem({
className,
children,
value,
...props
}: Styled<TogglePrimitive.Props>) {
const { pressed, multiple } = useContext(PressedContext)
const reduce = useReducedMotion()
const on = typeof value === "string" && pressed.has(value)
return (
<TogglePrimitive
data-slot="segmented-control-item"
value={value}
className={cn(
"relative isolate flex h-8 min-w-8 items-center justify-center rounded-full px-2.5 text-sm font-medium text-muted-foreground tabular-nums",
"transition-colors duration-150 ease-out motion-reduce:transition-none",
"hover:text-foreground",
"focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none",
"data-disabled:pointer-events-none data-disabled:opacity-50",
"data-pressed:text-foreground",
className
)}
{...props}
>
{/* The thumb: one shared element per group, so it glides to whichever
item is pressed instead of popping. With several pressed at once
each keeps its own, still. */}
{on && (
<motion.span
aria-hidden="true"
layoutId={multiple ? undefined : "thumb"}
transition={
reduce
? { duration: 0 }
: { type: "spring", stiffness: 520, damping: 42, mass: 0.8 }
}
className="absolute inset-0 -z-10 rounded-full bg-card shadow-xs dark:bg-foreground/15"
/>
)}
{children}
</TogglePrimitive>
)
}
export { SegmentedControl, SegmentedControlItem }
import { mergeProps } from "@base-ui/react/merge-props"
import { useRender } from "@base-ui/react/use-render"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "cn"
// No width of its own: the SectionHeader column (or whatever holds it) is
// the measure. text-pretty keeps a wrapped title from ending on one word.
// font-display follows font-sans unless the block switches it, for example
// with [--font-display:var(--font-serif)].
const subheadingVariants = cva(
"font-display font-[450] tracking-[-0.05em] text-pretty sm:tracking-[-0.06em]",
{
variants: {
/**
* `default` inherits the surrounding display face. `serif` uses
* the kit's serif role, without changing the surrounding font.
*/
variant: {
default: "",
serif: "[--font-display:var(--font-serif)]",
},
/**
* `md` (the default): 32px/40px, capped at 40px/44px from `sm`.
* `lg`: 32px/40px, 40px/48px from `sm`, 48px/56px from `lg`.
* `xl`: 32px/40px, 48px/56px from `sm`, 56px/56px from `lg`.
*/
size: {
md: "text-[2rem]/10 sm:text-[2.5rem]/11",
lg: "text-[2rem]/10 sm:text-[2.5rem]/12 lg:text-5xl/14",
xl: "text-[2rem]/10 sm:text-5xl/14 lg:text-[3.5rem]/14",
},
},
defaultVariants: { variant: "default", size: "md" },
}
)
/**
* The section heading in the display font, which follows `font-sans`
* unless a block switches that role. Rendered as an `<h2>` at weight 450.
* The default `size="md"` steps
* from 32px/40px to 40px/44px at `sm` and stays there. Choose `size="lg"`
* for 32px/40px, 40px/48px at `sm` and 48px/56px at `lg`, or `size="xl"`
* for 32px/40px, 48px/56px at `sm` and 56px/56px at `lg`.
* `variant="serif"` uses the kit's serif role; the default keeps the
* surrounding display face. Both variants support all three sizes.
* Pass `render` to use another heading level. A page's headline is `Heading`.
*/
function Subheading({
className,
variant = "default",
size = "md",
render,
...props
}: useRender.ComponentProps<"h2"> & VariantProps<typeof subheadingVariants>) {
return useRender({
defaultTagName: "h2",
render,
state: { slot: "subheading", variant, size },
props: mergeProps<"h2">(
{
className: cn(subheadingVariants({ variant, size }), className),
},
props
),
})
}
export { Subheading, subheadingVariants }
pnpm dlx shadcn@latest add @01orbital/segmented-control-medium-filternpx shadcn@latest add @01orbital/segmented-control-medium-filteryarn dlx shadcn@latest add @01orbital/segmented-control-medium-filterbunx --bun shadcn@latest add @01orbital/segmented-control-medium-filterAnatomy
Segmented Control is built from 2 parts. In the example they nest like this:
SegmentedControl
└─ SegmentedControlItemSegmentedControl: A row of toggle buttons on a rounded track. The pressed one sits on a raised thumb that slides over from the last one pressed. PutSegmentedControlItemparts inside.SegmentedControlItem: One option in aSegmentedControl, built on Base UI'sToggle. Give it a stringvalue. It is square for one character or an icon and widens to fit a word.
API reference
SegmentedControl
A row of toggle buttons on a rounded track. The pressed one sits on a raised thumb that slides over from the last one pressed. Put SegmentedControlItem parts inside.
It is Base UI's ToggleGroup, so value, defaultValue and onValueChange use arrays of item values. Without multiple, one item is always on: pressing the active item again does nothing, and onValueChange is not called with an empty array. With multiple, every item can be turned off. It is horizontal only, and className takes a string.
Prop
Type
It also accepts the props of the Base UI part it wraps, and the HTML attributes of the element it renders.
SegmentedControlItem
One option in a SegmentedControl, built on Base UI's Toggle. Give it a string value. It is square for one character or an icon and widens to fit a word.
The pressed item sits on the thumb, a card-colored pill with a soft shadow (a light wash in dark mode) that glides over from the last item pressed; reduced motion moves it at once. The other items stay muted and come up to full ink on hover. When the control has multiple, each pressed item gets its own thumb, without the glide.
Prop
Type
It also accepts the props of the Base UI part it wraps, and the HTML attributes of the element it renders.
Dependencies
npm: @base-ui/react, cn, motion. The CLI installs them for you.
Used in blocks
One block is built with Segmented Control.
Last updated on