# Segmented control

> Capsule of up to four choices with a liquid indicator that stretches as it slides to the new segment.

Docs: https://plumbago.ochotzas.com/components/segmented-control

## Installation

```sh
npx plumbago add segmented-control
```

This copies `components/ui/segmented-control.tsx` into your project, along with `cn`, and installs `@base-ui/react`.

## Usage

```tsx
import { SegmentedControl, SegmentedControlItem } from "@/components/ui/segmented-control"

<SegmentedControl aria-label="Order type" defaultValue="dine-in">
  <SegmentedControlItem value="dine-in">Dine in</SegmentedControlItem>
  <SegmentedControlItem value="takeaway">Takeaway</SegmentedControlItem>
</SegmentedControl>
```

## Examples

### Preview

```tsx
import { BlurSwap } from "@/lib/blur-swap"
import { SegmentedControl, SegmentedControlItem } from "@/components/ui/segmented-control"
import { useState } from "react"

export default function SegmentedControlDemo() {
  const [service, setService] = useState("dine-in")
  return (
    <div className="flex w-full max-w-xs flex-col gap-2">
      <SegmentedControl aria-label="Order type" value={service} onValueChange={(value) => setService(String(value))} className="w-full">
        <SegmentedControlItem value="dine-in">Dine in</SegmentedControlItem>
        <SegmentedControlItem value="takeaway">Takeaway</SegmentedControlItem>
      </SegmentedControl>
      <BlurSwap
        text={service === "dine-in" ? "Table 12 · served at the table" : "Ready for pickup in 20 min"}
        live
        className="px-1 text-footnote font-medium text-ink-2"
      />
    </div>
  )
}
```

### With panels

```tsx
import { SegmentedControlItem, SegmentedControlList, SegmentedControlPanel, SegmentedControlPanels, SegmentedControlRoot } from "@/components/ui/segmented-control"

const ranges = [
  { value: "day", label: "Day", booked: 86, seats: 120, note: "Friday, 16 October · 34 walk-ins" },
  { value: "week", label: "Week", booked: 540, seats: 840, note: "12 to 18 October · busiest on Saturday" },
  { value: "month", label: "Month", booked: 2310, seats: 3600, note: "October · the best night was Saturday the 24th, with 168 covers and a full terrace" },
]

export default function SegmentedControlWithPanels() {
  return (
    <SegmentedControlRoot defaultValue="day" className="w-full max-w-sm">
      <SegmentedControlList aria-label="Range" className="w-full">
        {ranges.map((range) => (
          <SegmentedControlItem key={range.value} value={range.value}>
            {range.label}
          </SegmentedControlItem>
        ))}
      </SegmentedControlList>
      <SegmentedControlPanels>
        {ranges.map((range) => (
          <SegmentedControlPanel key={range.value} value={range.value} className="flex flex-col gap-1 px-1">
            <p className="flex items-baseline gap-2">
              <span className="text-stat font-bold tabular-nums">{range.booked.toLocaleString("en-GB")}</span>
              <span className="text-footnote font-medium text-ink-2">of {range.seats.toLocaleString("en-GB")} seats booked</span>
            </p>
            <p className="text-footnote font-medium text-ink-2">{range.note}</p>
          </SegmentedControlPanel>
        ))}
      </SegmentedControlPanels>
    </SegmentedControlRoot>
  )
}
```

### Inside an island

```tsx
import { Island } from "@/components/ui/island"
import { SegmentedControl, SegmentedControlItem } from "@/components/ui/segmented-control"

const sections = ["All", "Food", "Bar", "Wine"]

export default function SegmentedControlInsideAnIsland() {
  return (
    <Island className="w-full max-w-md">
      <SegmentedControl aria-label="Menu section" defaultValue="All" className="w-full">
        {sections.map((name) => (
          <SegmentedControlItem key={name} value={name}>
            {name}
          </SegmentedControlItem>
        ))}
      </SegmentedControl>
    </Island>
  )
}
```

### Disabled

```tsx
import { SegmentedControl, SegmentedControlItem } from "@/components/ui/segmented-control"

export default function SegmentedControlDisabled() {
  return (
    <div className="flex w-full max-w-sm flex-col gap-2">
      <SegmentedControl aria-label="Order type" defaultValue="pickup" className="w-full">
        <SegmentedControlItem value="pickup">Pickup</SegmentedControlItem>
        <SegmentedControlItem value="delivery" disabled aria-describedby="delivery-note">
          Delivery
        </SegmentedControlItem>
      </SegmentedControl>
      <p id="delivery-note" className="px-1 text-footnote font-medium text-ink-2">
        Delivery opens again at 18:00.
      </p>
    </div>
  )
}
```

## Built on Base UI

Segmented control wraps these Base UI parts and keeps their props:

- [Tabs](https://base-ui.com/react/components/tabs)

## Source

```tsx
import { Tabs } from "@base-ui/react/tabs"
import { cn } from "@/lib/cn"
import { type ComponentProps, type CSSProperties, type ReactNode, useLayoutEffect, useRef, useState } from "react"

const movingLeft = "left var(--pb-dur-spring-fast) var(--pb-spring-fast), right var(--pb-dur-spring-slow) var(--pb-spring-slow)"
const movingRight = "left var(--pb-dur-spring-slow) var(--pb-spring-slow), right var(--pb-dur-spring-fast) var(--pb-spring-fast)"
const reducedMotion = "left var(--pb-dur-base) var(--pb-ease-out), right var(--pb-dur-base) var(--pb-ease-out)"

export type SegmentedControlRootProps = Omit<ComponentProps<typeof Tabs.Root>, "className"> & {
  className?: string
}

export function SegmentedControlRoot({ className, ...props }: SegmentedControlRootProps) {
  return <Tabs.Root data-slot="segmented-control" className={cn("flex flex-col gap-4", className)} {...props} />
}

export type SegmentedControlListProps = Omit<ComponentProps<typeof Tabs.List>, "className"> & {
  className?: string
}

export function SegmentedControlList({ activateOnFocus = true, className, children, ...props }: SegmentedControlListProps) {
  return (
    <Tabs.List
      data-slot="segmented-control-list"
      activateOnFocus={activateOnFocus}
      className={cn("relative isolate inline-grid max-w-full auto-cols-[minmax(0,1fr)] grid-flow-col rounded-full bg-track p-1", className)}
      {...props}
    >
      <Tabs.Indicator
        data-slot="segmented-control-indicator"
        className={cn(
          "pointer-events-none absolute top-(--active-tab-top) h-(--active-tab-height) left-(--active-tab-left) right-(--active-tab-right) -z-10 rounded-full bg-surface shadow-[0_1px_3px_rgba(0,0,0,0.08)]",
          "data-[activation-direction=left]:[transition:var(--moving-left)] data-[activation-direction=right]:[transition:var(--moving-right)]",
          "motion-reduce:data-[activation-direction]:[transition:var(--reduced-motion)]",
        )}
        style={{ "--moving-left": movingLeft, "--moving-right": movingRight, "--reduced-motion": reducedMotion } as CSSProperties}
      />
      {children}
    </Tabs.List>
  )
}

export type SegmentedControlItemProps = Omit<ComponentProps<typeof Tabs.Tab>, "className"> & {
  className?: string
}

export function SegmentedControlItem({ className, children, ...props }: SegmentedControlItemProps) {
  return (
    <Tabs.Tab
      data-slot="segmented-control-item"
      className={cn(
        "group/segment relative flex h-9 after:absolute after:inset-x-0 after:-inset-y-1 after:content-[''] min-w-0 cursor-pointer items-center justify-center rounded-full px-3 text-[15px] font-medium whitespace-nowrap text-ink-2 select-none [-webkit-tap-highlight-color:transparent]",
        "transition-colors duration-base ease-out hover:not-data-active:not-data-disabled:text-ink",
        "data-active:text-ink data-disabled:cursor-default data-disabled:opacity-40",
        className,
      )}
      {...props}
    >
      <span className="grid min-w-0">
        <span className="col-start-1 row-start-1 truncate group-data-active/segment:font-semibold">{children}</span>
        <span aria-hidden="true" className="invisible col-start-1 row-start-1 truncate font-semibold">
          {children}
        </span>
      </span>
    </Tabs.Tab>
  )
}

export type SegmentedControlPanelsProps = Omit<ComponentProps<"div">, "className"> & {
  className?: string
}

const panelSwapWindow = 700

export function SegmentedControlPanels({ className, ...props }: SegmentedControlPanelsProps) {
  const inner = useRef<HTMLDivElement | null>(null)
  const [height, setHeight] = useState<number | null>(null)
  const [swapping, setSwapping] = useState(false)

  useLayoutEffect(() => {
    const element = inner.current
    if (!element) return
    let swapTimer: ReturnType<typeof setTimeout> | undefined
    const observer = new ResizeObserver(() => {
      if (element.querySelector(":scope > [data-starting-style], :scope > [data-ending-style]")) {
        setSwapping(true)
        clearTimeout(swapTimer)
        swapTimer = setTimeout(() => setSwapping(false), panelSwapWindow)
      }
      setHeight(element.offsetHeight)
    })
    observer.observe(element)
    return () => {
      observer.disconnect()
      clearTimeout(swapTimer)
    }
  }, [])

  return (
    <div
      data-slot="segmented-control-panels"
      className={cn(swapping && "transition-[height] duration-spring ease-spring motion-reduce:transition-none")}
      style={height === null ? undefined : { height }}
    >
      <div ref={inner} className={cn("relative grid grid-cols-[minmax(0,1fr)]", className)} {...props} />
    </div>
  )
}

export type SegmentedControlPanelProps = Omit<ComponentProps<typeof Tabs.Panel>, "className"> & {
  className?: string
}

export function SegmentedControlPanel({ className, ...props }: SegmentedControlPanelProps) {
  return (
    <Tabs.Panel
      data-slot="segmented-control-panel"
      className={cn(
        "col-start-1 row-start-1 outline-none",
        "transition-[opacity,filter,translate,scale] delay-[120ms] duration-spring ease-spring",
        "data-starting-style:opacity-0 motion-safe:data-starting-style:translate-y-1.5 motion-safe:data-starting-style:scale-98 motion-safe:data-starting-style:blur-[8px]",
        "data-ending-style:pointer-events-none data-ending-style:absolute data-ending-style:inset-x-0 data-ending-style:top-0 data-ending-style:opacity-0 data-ending-style:delay-0 data-ending-style:duration-[160ms] data-ending-style:ease-in",
        "motion-safe:data-ending-style:-translate-y-1 motion-safe:data-ending-style:scale-98 motion-safe:data-ending-style:blur-[8px]",
        className,
      )}
      {...props}
    />
  )
}

export type SegmentedControlProps = Omit<SegmentedControlRootProps, "children"> & {
  children: ReactNode
  "aria-label"?: string
}

export function SegmentedControl({ children, className, "aria-label": label, ...props }: SegmentedControlProps) {
  return (
    <Tabs.Root data-slot="segmented-control" className="contents" {...props}>
      <SegmentedControlList aria-label={label} className={className}>
        {children}
      </SegmentedControlList>
    </Tabs.Root>
  )
}
```
