{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"segmented-control","type":"registry:component","title":"Segmented control","description":"One of a few options side by side: the thumb is thrown to the new segment while its width eases to the new label.","author":"Hairline UI","dependencies":[],"files":[{"path":"registry/segmented-control.tsx","type":"registry:component","content":"// Hairline UI · segmented-control · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { EASE_OUT, EASE_THROW, INTERACTION_FOCUS, useInteractionReducedMotion } from \"./ui-interaction-motion\";\n\n/* ─────────────────────────────────────────────────────────\n * SEGMENTED CONTROL: one of a few, side by side\n *\n *   pick     the thumb is thrown to the new segment with a slight\n *            overshoot while its width eases to the new label\n *   press    the thumb gives a little under the finger\n *   keys     a radiogroup: arrows move and select, Home/End jump;\n *            one tab stop for the whole control\n * ───────────────────────────────────────────────────────── */\n\nexport interface SegmentOption {\n  value: string;\n  label: React.ReactNode;\n  icon?: React.ReactNode;\n  /** Required when `label` isn't text (icon-only segments). */\n  ariaLabel?: string;\n  disabled?: boolean;\n}\n\nexport interface SegmentedControlProps {\n  options: SegmentOption[];\n  value?: string;\n  defaultValue?: string;\n  onValueChange?: (value: string) => void;\n  /** Accessible name of the group. */\n  label: string;\n  /** 28px, 34px, or 40px tall (matches tactile sliders). */\n  size?: \"sm\" | \"md\" | \"lg\";\n  /** Stretch to the parent's width with equal segments. */\n  block?: boolean;\n  className?: string;\n  /** Corner radius: \"full\" (pill, default) or \"rounded\" (concentric rounded container). */\n  radius?: \"full\" | \"rounded\";\n}\n\ntype Mark = { x: number; w: number };\n\nexport function SegmentedControl({\n  options,\n  value,\n  defaultValue,\n  onValueChange,\n  label,\n  size = \"md\",\n  block,\n  className = \"\",\n  radius = \"full\",\n}: SegmentedControlProps) {\n  const reduced = useInteractionReducedMotion();\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const [own, setOwn] = React.useState(defaultValue ?? options[0]?.value);\n  const current = value !== undefined ? value : own;\n  const [mark, setMark] = React.useState<Mark | null>(null);\n  const [ready, setReady] = React.useState(false);\n  const [pressing, setPressing] = React.useState(false);\n\n  React.useLayoutEffect(() => {\n    const root = rootRef.current;\n    if (!root) return;\n    const measure = () => {\n      const el = current ? root.querySelector<HTMLElement>(`[data-segment=\"${CSS.escape(current)}\"]`) : null;\n      if (!el) return setMark(null);\n      const next = { x: el.offsetLeft, w: el.offsetWidth };\n      setMark((p) => (p && p.x === next.x && p.w === next.w ? p : next));\n    };\n    measure();\n    const ro = new ResizeObserver(measure);\n    ro.observe(root);\n    root.querySelectorAll(\"[data-segment]\").forEach((el) => ro.observe(el));\n    return () => ro.disconnect();\n  }, [current, options]);\n\n  React.useEffect(() => {\n    if (!mark || ready) return;\n    const frame = requestAnimationFrame(() => setReady(true));\n    return () => cancelAnimationFrame(frame);\n  }, [mark, ready]);\n\n  const pick = (v: string) => {\n    if (value === undefined) setOwn(v);\n    onValueChange?.(v);\n  };\n\n  const onKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {\n    const enabled = options.filter((o) => !o.disabled);\n    const index = enabled.findIndex((o) => o.value === current);\n    let next = -1;\n    if (e.key === \"ArrowRight\" || e.key === \"ArrowDown\") next = (index + 1) % enabled.length;\n    else if (e.key === \"ArrowLeft\" || e.key === \"ArrowUp\") next = (index - 1 + enabled.length) % enabled.length;\n    else if (e.key === \"Home\") next = 0;\n    else if (e.key === \"End\") next = enabled.length - 1;\n    if (next < 0) return;\n    e.preventDefault();\n    const v = enabled[next].value;\n    pick(v);\n    rootRef.current?.querySelector<HTMLElement>(`[data-segment=\"${CSS.escape(v)}\"]`)?.focus();\n  };\n\n  const isLg = size === \"lg\";\n  const isSm = size === \"sm\";\n  const isPill = radius === \"full\";\n\n  // Concentric corner radius matching compact slider geometry\n  const rootRadius = isPill ? \"rounded-full\" : isLg ? \"rounded-[13px]\" : isSm ? \"rounded-[9px]\" : \"rounded-[11px]\";\n  const itemRadius = isPill ? \"rounded-full\" : isLg ? \"rounded-[9px]\" : isSm ? \"rounded-[7px]\" : \"rounded-[9px]\";\n\n  // Proportional sizing: \"md\" is compact 34px, \"lg\" is 40px, \"sm\" is 28px\n  const rootPadding = isLg ? \"p-1\" : \"p-0.5\";\n  const rootHeight = isLg ? \"h-10\" : isSm ? \"h-7\" : \"h-8.5\";\n  const indicatorInset = isLg ? \"top-1 bottom-1\" : \"top-0.5 bottom-0.5\";\n  const itemHeightClass = isLg\n    ? \"h-8 px-3 text-[13px]\"\n    : isSm\n    ? \"h-6 px-2 text-[11.5px]\"\n    : \"h-[30px] px-2.5 text-[12px]\";\n\n  return (\n    <div\n      ref={rootRef}\n      role=\"radiogroup\"\n      aria-label={label}\n      onKeyDown={onKeyDown}\n      className={`relative isolate select-none items-center ${rootHeight} ${rootRadius} ${rootPadding} border border-border bg-background ${\n        block ? \"flex w-full\" : \"inline-flex\"\n      } ${className}`}\n    >\n      <span\n        aria-hidden=\"true\"\n        className={`pointer-events-none absolute left-0 ${indicatorInset} ${itemRadius} bg-[color-mix(in_oklab,var(--foreground)_8%,var(--background))]`}\n        style={{\n          transform: `translate3d(${mark?.x ?? 0}px, 0, 0) scale(${pressing && !reduced ? 0.97 : 1})`,\n          width: mark?.w ?? 0,\n          opacity: mark ? 1 : 0,\n          transition: reduced || !ready ? \"none\" : `transform 440ms ${EASE_THROW}, width 400ms ${EASE_OUT}, opacity 200ms ${EASE_OUT}`,\n        }}\n      />\n      {options.map((option) => {\n        const on = option.value === current;\n        return (\n          <button\n            key={option.value}\n            type=\"button\"\n            role=\"radio\"\n            aria-checked={on}\n            aria-label={option.ariaLabel}\n            data-segment={option.value}\n            disabled={option.disabled}\n            tabIndex={on ? 0 : -1}\n            onClick={() => pick(option.value)}\n            onPointerDown={() => on && setPressing(true)}\n            onPointerUp={() => setPressing(false)}\n            onPointerLeave={() => setPressing(false)}\n            className={`relative z-10 inline-flex items-center justify-center gap-1.5 whitespace-nowrap ${itemRadius} font-medium cursor-pointer transition-colors duration-200 disabled:cursor-default disabled:opacity-40 [&_svg]:size-3.5 ${itemHeightClass} ${\n              block ? \"flex-1\" : \"\"\n            } ${on ? \"text-foreground font-semibold\" : \"text-muted-foreground hover:text-foreground\"} ${INTERACTION_FOCUS}`}\n          >\n            {option.icon}\n            {option.label}\n          </button>\n        );\n      })}\n    </div>\n  );\n}\n\nexport default SegmentedControl;\n"},{"path":"registry/ui-interaction-motion.ts","type":"registry:component","content":"// Hairline UI · segmented-control · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n'use client';\n\nimport * as React from 'react';\n\nexport const EASE_OUT = 'cubic-bezier(0.16, 1, 0.3, 1)';\nexport const EASE_SETTLE = 'cubic-bezier(0.22, 1.18, 0.36, 1)';\n/** Thrown things (indicators, thumbs): a slight overshoot on transform only. */\nexport const EASE_THROW = 'cubic-bezier(0.34, 1.36, 0.64, 1)';\n/**\n * The press every button primitive shares: a 3% give that eases in and settles back.\n * Tailwind v4's scale-* writes the `scale` property, so `scale` has to be in the list\n * or the press snaps.\n */\nexport const INTERACTION_PRESS =\n  'transition-[background-color,color,box-shadow,opacity,scale] duration-200 ease-[cubic-bezier(0.16,1,0.3,1)] active:scale-[0.97] motion-reduce:transition-none motion-reduce:active:scale-100';\nexport const INTERACTION_FOCUS ='focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background';\n\nconst query = '(prefers-reduced-motion: reduce)';\nconst subscribe = (notify: () => void) => {\n  const media = window.matchMedia(query);\n  media.addEventListener('change', notify);\n  return () => media.removeEventListener('change', notify);\n};\nexport const useInteractionReducedMotion = () => React.useSyncExternalStore(subscribe, () => window.matchMedia(query).matches, () => false);\n\nexport function useInteractionActivity<T extends Element>() {\n  const ref = React.useRef<T>(null);\n  const [visible, setVisible] = React.useState(false);\n  const [hidden, setHidden] = React.useState(false);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const observer = new IntersectionObserver(([entry]) => setVisible(entry.isIntersecting));\n    observer.observe(el);\n    const visibility = () => setHidden(document.hidden);\n    visibility(); document.addEventListener('visibilitychange', visibility);\n    return () => { observer.disconnect(); document.removeEventListener('visibilitychange', visibility); };\n  }, []);\n  return { ref, active: visible && !hidden };\n}\n\nexport function interactionIcon(on: boolean, reduced: boolean): React.CSSProperties {\n  return { opacity: on ? 1 : 0, transform: on ? 'none' : 'scale(0.6)', filter: on ? 'blur(0px)' : 'blur(3px)', transition: reduced ? 'none' : `opacity 220ms ${EASE_OUT}, transform 380ms ${EASE_OUT}, filter 220ms ${EASE_OUT}` };\n}\n\n/** A raised object: one tight contact shadow, one short ambient, a hairline of light on its top edge. */\nexport const MATERIAL_LIFT =\n  'shadow-[0_1px_1.5px_rgb(0_0_0/0.07),0_3px_8px_-2px_rgb(0_0_0/0.1),inset_0_0.5px_0_rgb(255_255_255/0.8)] dark:shadow-[0_1px_2px_rgb(0_0_0/0.5),0_4px_10px_-2px_rgb(0_0_0/0.35),inset_0_0.5px_0_rgb(255_255_255/0.1)]';\n/** A trough something sits in, shaded from above, lit along its bottom edge. */\nexport const MATERIAL_RECESS =\n  'shadow-[inset_0_1px_2.5px_rgb(0_0_0/0.09),inset_0_-0.5px_0_rgb(255_255_255/0.7)] dark:shadow-[inset_0_1px_3px_rgb(0_0_0/0.45),inset_0_-0.5px_0_rgb(255_255_255/0.07)]';\n\nexport type SpringConfig = { stiffness: number; damping: number; mass?: number };\nexport interface Spring {\n  get(): number;\n  getVelocity(): number;\n  getTarget(): number;\n  /** Aim somewhere new from wherever it is now, keeping its speed. */\n  set(target: number): void;\n  /** Add speed (units per second), on top of what it already has. */\n  push(velocity: number): void;\n  /** Be there now, at rest. */\n  jump(value: number): void;\n  configure(config: SpringConfig): void;\n  stop(): void;\n}\n\n// Every moving spring on the page shares one frame loop, which sleeps when the last one rests. Each spring's onFrame runs\n// once per frame after all of them have stepped, so several springs that draw one shape paint it once.\nconst SPRING_STEP = 1 / 240;\ntype Running = { step: () => void };\nconst runningSprings = new Set<Running>();\nconst springPainters = new Set<() => void>();\nlet springFrame = 0;\nlet springLast = 0;\nlet springSpare = 0;\n\nfunction springTick(now: number) {\n  // A hidden tab stops the frames, so the first one back must not count the whole gap as time passed.\n  springSpare += Math.min((now - springLast) / 1000, 0.05);\n  springLast = now;\n  while (springSpare >= SPRING_STEP) {\n    runningSprings.forEach((spring) => spring.step());\n    springSpare -= SPRING_STEP;\n  }\n  const painters = [...springPainters];\n  springPainters.clear();\n  painters.forEach((paint) => paint());\n  springFrame = runningSprings.size ? requestAnimationFrame(springTick) : 0;\n}\n\nfunction wakeSprings(spring: Running) {\n  runningSprings.add(spring);\n  if (springFrame) return;\n  springSpare = 0;\n  springFrame = requestAnimationFrame((now) => {\n    springLast = now - 1000 / 60;\n    springTick(now);\n  });\n}\n\n/**\n * A spring that carries its speed: re-aim it mid-flight and it curves on from where it is, push it while it swings and the\n * push adds to the swing. Use it for anything that can be interrupted; a curve restarts from a standstill every time.\n * `onFrame` should write straight to the DOM. `precision` is how close counts as there, in the value's own units.\n */\nexport function createSpring(initial: number, config: SpringConfig, onFrame: () => void, precision = 0.01): Spring {\n  let value = initial;\n  let velocity = 0;\n  let target = initial;\n  let { stiffness, damping, mass = 1 } = config;\n  const running: Running = {\n    step() {\n      velocity += ((-stiffness * (value - target) - damping * velocity) / mass) * SPRING_STEP;\n      value += velocity * SPRING_STEP;\n      if (Math.abs(value - target) < precision && Math.abs(velocity) < precision * 10) {\n        value = target;\n        velocity = 0;\n        runningSprings.delete(running);\n      }\n      springPainters.add(onFrame);\n    },\n  };\n  return {\n    get: () => value,\n    getVelocity: () => velocity,\n    getTarget: () => target,\n    set(next) {\n      if (next === target && !runningSprings.has(running)) return;\n      target = next;\n      wakeSprings(running);\n    },\n    push(speed) {\n      velocity += speed;\n      wakeSprings(running);\n    },\n    jump(next) {\n      value = next;\n      target = next;\n      velocity = 0;\n      runningSprings.delete(running);\n      onFrame();\n    },\n    configure(next) {\n      ({ stiffness, damping, mass = 1 } = next);\n    },\n    stop() {\n      runningSprings.delete(running);\n    },\n  };\n}\n\n/** Sample recent movement rather than averaging a long drag and losing its release velocity. */\nexport type PointerSample = { x: number; time: number };\nexport function samplePointer(samples: PointerSample[], x: number, time: number) {\n  samples.push({ x, time });\n  while (samples.length > 2 && time - samples[0].time > 100) samples.shift();\n}\nexport function releaseVelocity(samples: PointerSample[], now: number) {\n  if (samples.length < 2 || now - samples[samples.length - 1].time > 100) return 0;\n  const first = samples[0], last = samples[samples.length - 1];\n  return (last.x - first.x) / Math.max(1, last.time - first.time);\n}\n\n/** Smooth Apple/rational rubber-band curve: continuous exponential-like resistance without linear kinks. */\nexport function rubberBand(overshoot: number, dimension = 320, constant = 0.55): number {\n  const d = dimension || 320;\n  const abs = Math.abs(overshoot);\n  return Math.sign(overshoot) * (1 - 1 / ((abs * constant) / d + 1)) * d;\n}\n\n/** Projects resting travel from release velocity (velocity in px/ms; time in seconds). */\nexport function projectInertia(distance: number, velocity: number, time = 0.12): number {\n  return distance + velocity * 1000 * time;\n}\n\n/** Smooths incoming release velocity toward a boundary so springs don't slam or clip into walls. */\nexport function softenVelocity(velocity: number, distanceToTarget: number, factor = 10): number {\n  const maxAllowed = Math.abs(distanceToTarget) * factor;\n  return Math.sign(velocity) * Math.min(Math.abs(velocity), maxAllowed);\n}\n\n/** A damped spring sampled by WAAPI: tuned for organic lightness with a hint of life (3% breath). */\nexport function springFrames(\n  from: number,\n  to: number,\n  velocity = 0,\n  duration = 480,\n  config: { omega?: number; damping?: number; steps?: number } = {},\n) {\n  const { omega = 16, damping = 0.74, steps = 36 } = config;\n  const damped = omega * Math.sqrt(Math.max(0.001, 1 - damping * damping));\n  const displacement = from - to;\n  const coefficient = (velocity * 1000 + damping * omega * displacement) / damped;\n  return Array.from({ length: steps + 1 }, (_, i) => {\n    const t = (i / steps) * (duration / 1000);\n    const value = to + Math.exp(-damping * omega * t) * (displacement * Math.cos(damped * t) + coefficient * Math.sin(damped * t));\n    return { value: i === steps ? to : value, offset: i / steps };\n  });\n}\n\n"}],"css":{},"docs":"Docs and live preview: https://hairlineui.com/ui/segmented-control. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}