{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "segmented-control",
  "title": "Segmented Control",
  "description": "A switch between two or more options with one thumb that slides to the active one, in three sizes. Never empty.",
  "dependencies": [
    "@radix-ui/react-toggle-group",
    "class-variance-authority"
  ],
  "registryDependencies": [
    "@corsair-ui/utils",
    "@corsair-ui/use-media-query"
  ],
  "files": [
    {
      "path": "registry/default/ui/segmented-control.tsx",
      "content": "\"use client\";\n\nimport * as ToggleGroupPrimitive from \"@radix-ui/react-toggle-group\";\nimport { cva, type VariantProps } from \"class-variance-authority\";\nimport {\n  createContext,\n  useCallback,\n  useContext,\n  useEffect,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n  type ComponentProps,\n  type Ref,\n} from \"react\";\nimport { useMediaQuery } from \"@/registry/default/hooks/use-media-query\";\nimport { cn } from \"@/registry/default/lib/utils\";\n\n// Measuring has to happen before paint in the browser; on the server there is nothing to measure.\nconst useIsomorphicLayoutEffect = typeof window === \"undefined\" ? useEffect : useLayoutEffect;\n\nfunction mergeRefs<T>(...refs: (Ref<T> | undefined)[]) {\n  return (node: T | null) => {\n    for (const ref of refs) {\n      if (typeof ref === \"function\") ref(node);\n      else if (ref) ref.current = node;\n    }\n  };\n}\n\nconst segmentedControlItemVariants = cva(\n  [\n    \"relative z-10 inline-flex shrink-0 cursor-pointer items-center justify-center gap-1.5 rounded-full font-medium whitespace-nowrap\",\n    \"text-muted-foreground hover:text-foreground data-[state=on]:text-foreground\",\n    \"transition-[color,background-color,box-shadow] outline-none motion-reduce:transition-none\",\n    \"focus-visible:ring-ring/50 focus-visible:ring-[3px]\",\n    \"disabled:pointer-events-none disabled:opacity-50\",\n    // Before the thumb is measured (no JavaScript yet), the active item paints the pill itself.\n    \"data-[state=on]:bg-background data-[state=on]:shadow-[0_1px_2px_0_rgb(0_0_0/0.05)]\",\n    \"group-data-[ready]/segmented:data-[state=on]:bg-transparent group-data-[ready]/segmented:data-[state=on]:shadow-none\",\n    \"[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\",\n  ],\n  {\n    variants: {\n      size: {\n        sm: \"h-7 px-2.5 text-xs\",\n        default: \"h-8 px-3 text-sm\",\n        lg: \"h-10 px-4 text-base\",\n      },\n    },\n    defaultVariants: {\n      size: \"default\",\n    },\n  }\n);\n\ntype SegmentedControlSize = NonNullable<VariantProps<typeof segmentedControlItemVariants>[\"size\"]>;\n\ninterface SegmentedControlContextValue {\n  size: SegmentedControlSize;\n  /** Watches an item's size, so a label or font change moves the thumb. Returns the cleanup. */\n  register: (item: HTMLElement) => () => void;\n}\n\nconst SegmentedControlContext = createContext<SegmentedControlContextValue>({\n  size: \"default\",\n  register: () => () => {},\n});\n\ninterface Box {\n  x: number;\n  y: number;\n  width: number;\n  height: number;\n}\n\ninterface ThumbMotion {\n  animate: boolean;\n  duration: number;\n  easing: string;\n}\n\n/** Where the thumb is drawn right now, mid-transition included, read from its computed transform. */\nfunction visibleBox(thumb: HTMLElement, fallback: Box): Box {\n  const match = /^matrix(3d)?\\((.+)\\)$/.exec(getComputedStyle(thumb).transform);\n  if (!match?.[2]) return fallback;\n  const values = match[2].split(\",\").map(Number);\n  const scaleX = values[0];\n  const x = match[1] ? values[12] : values[4];\n  if (scaleX === undefined || x === undefined || !Number.isFinite(scaleX + x)) return fallback;\n  return { ...fallback, x, width: fallback.width * scaleX };\n}\n\nfunction activeItem(root: HTMLElement) {\n  for (const item of root.querySelectorAll<HTMLElement>(\n    '[data-slot=\"segmented-control-item\"][data-state=\"on\"]'\n  )) {\n    if (item.closest('[data-slot=\"segmented-control\"]') === root) return item;\n  }\n  return null;\n}\n\n/**\n * Puts the thumb over the active item. Size changes are applied at once;\n * position changes animate by FLIP: the thumb takes its new size and place,\n * is transformed back onto the old box with no transition, and then\n * transitions the transform to identity. Only `transform` ever animates.\n */\nfunction placeThumb(\n  root: HTMLElement,\n  thumb: HTMLElement,\n  last: { current: Box | null },\n  { animate, duration, easing }: ThumbMotion\n) {\n  const item = activeItem(root);\n  if (!item) {\n    last.current = null;\n    root.removeAttribute(\"data-ready\");\n    return;\n  }\n  // Layout offsets, not client rects: they ignore transforms on ancestors (a dialog zooming in).\n  const next: Box = {\n    x: item.offsetLeft,\n    y: item.offsetTop,\n    width: item.offsetWidth,\n    height: item.offsetHeight,\n  };\n  const previous = last.current;\n  last.current = next;\n  const from = previous && visibleBox(thumb, previous);\n  const rest = `translate3d(${next.x}px, ${next.y}px, 0)`;\n\n  thumb.style.width = `${next.width}px`;\n  thumb.style.height = `${next.height}px`;\n  root.setAttribute(\"data-ready\", \"\");\n\n  const moves = from && (from.x !== next.x || from.width !== next.width);\n  if (!animate || !from || !moves || from.width <= 0 || next.width <= 0 || duration <= 0) {\n    thumb.style.transition = \"none\";\n    thumb.style.transform = rest;\n    return;\n  }\n  thumb.style.transition = \"none\";\n  thumb.style.transform = `translate3d(${from.x}px, ${next.y}px, 0) scaleX(${from.width / next.width})`;\n  // Reading layout commits the inverted transform, so the transition starts from it.\n  thumb.getBoundingClientRect();\n  thumb.style.transition = `transform ${duration}ms ${easing}`;\n  thumb.style.transform = rest;\n}\n\ninterface SegmentedControlProps\n  extends\n    Omit<\n      ToggleGroupPrimitive.ToggleGroupSingleProps,\n      \"type\" | \"value\" | \"defaultValue\" | \"onValueChange\" | \"orientation\"\n    >,\n    VariantProps<typeof segmentedControlItemVariants> {\n  /** The active item, controlled. */\n  value?: string;\n  /** The active item at first, uncontrolled. Give one: the control is never empty once chosen. */\n  defaultValue?: string;\n  /** Called with the newly active item's value. Pressing the active item again does nothing. */\n  onValueChange?: (value: string) => void;\n  /** Classes for the sliding thumb, e.g. `bg-primary` (pair with item text colours). */\n  thumbClassName?: string;\n  /** How long the thumb takes to slide, in ms. */\n  duration?: number;\n  /** Timing function for the slide, any CSS easing. */\n  easing?: string;\n  ref?: Ref<HTMLDivElement>;\n}\n\n/**\n * A switch between two or more options with one thumb that slides to the\n * active one: \"Monthly | Yearly\", \"For players | For venues\". Built on the\n * Radix toggle group (single): it is one Tab stop, the arrow keys move\n * between items and Space or Enter picks one. It never goes empty: pressing\n * the active item again keeps it. Give it an `aria-label`.\n *\n * The thumb moves by transform only (FLIP), and jumps instead with\n * `prefers-reduced-motion` and when the control or a label resizes. Until it\n * has been measured (server HTML, no JavaScript) the active item paints the\n * pill itself, so there is no flash and no layout shift. Horizontal only.\n * For a pill fixed at the bottom on phones, position it with `className`.\n *\n * @example\n * <SegmentedControl\n *   aria-label=\"Audience\"\n *   defaultValue=\"players\"\n *   className=\"max-md:fixed max-md:inset-x-0 max-md:bottom-4 max-md:mx-auto max-md:shadow-lg\"\n * >\n *   <SegmentedControlItem value=\"players\">For players</SegmentedControlItem>\n *   <SegmentedControlItem value=\"venues\">For venues</SegmentedControlItem>\n * </SegmentedControl>\n */\nfunction SegmentedControl({\n  value,\n  defaultValue,\n  onValueChange,\n  size,\n  thumbClassName,\n  duration = 320,\n  easing = \"cubic-bezier(0.16, 1, 0.3, 1)\",\n  className,\n  children,\n  ref,\n  ...props\n}: SegmentedControlProps) {\n  const [uncontrolled, setUncontrolled] = useState(defaultValue);\n  const current = value ?? uncontrolled;\n  const reduced = useMediaQuery(\"(prefers-reduced-motion: reduce)\");\n\n  const root = useRef<HTMLDivElement>(null);\n  const thumb = useRef<HTMLSpanElement>(null);\n  const last = useRef<Box | null>(null);\n  const items = useRef(new Set<HTMLElement>());\n  const observer = useRef<ResizeObserver | null>(null);\n  const motion = useRef({ reduced, duration, easing });\n  const mergedRef = useMemo(() => mergeRefs(ref, root), [ref]);\n\n  useIsomorphicLayoutEffect(() => {\n    motion.current = { reduced, duration, easing };\n  });\n\n  const place = useCallback((animate: boolean) => {\n    if (!root.current || !thumb.current) return;\n    const { reduced, duration, easing } = motion.current;\n    placeThumb(root.current, thumb.current, last, {\n      animate: animate && !reduced,\n      duration,\n      easing,\n    });\n  }, []);\n\n  const register = useCallback((item: HTMLElement) => {\n    items.current.add(item);\n    observer.current?.observe(item);\n    return () => {\n      items.current.delete(item);\n      observer.current?.unobserve(item);\n    };\n  }, []);\n\n  // Resizes of the control or of any item (labels, fonts) jump the thumb, never animate it.\n  useIsomorphicLayoutEffect(() => {\n    if (!root.current || typeof ResizeObserver === \"undefined\") return;\n    const resizes = new ResizeObserver(() => place(false));\n    resizes.observe(root.current);\n    for (const item of items.current) resizes.observe(item);\n    observer.current = resizes;\n    return () => {\n      resizes.disconnect();\n      observer.current = null;\n    };\n  }, [place]);\n\n  // A new value slides the thumb; the first placement jumps.\n  useIsomorphicLayoutEffect(() => {\n    place(true);\n  }, [current, place]);\n\n  const context = useMemo(() => ({ size: size ?? \"default\", register }), [size, register]);\n\n  return (\n    <ToggleGroupPrimitive.Root\n      ref={mergedRef}\n      type=\"single\"\n      orientation=\"horizontal\"\n      value={current ?? \"\"}\n      onValueChange={(next) => {\n        // Radix reports \"\" when the active item is pressed again: stay on it.\n        if (!next) return;\n        if (value === undefined) setUncontrolled(next);\n        onValueChange?.(next);\n      }}\n      data-slot=\"segmented-control\"\n      data-size={size ?? \"default\"}\n      className={cn(\n        \"group/segmented bg-muted relative isolate inline-flex w-fit items-center rounded-full p-1\",\n        className\n      )}\n      {...props}\n    >\n      <span\n        ref={thumb}\n        aria-hidden\n        data-slot=\"segmented-control-thumb\"\n        className={cn(\n          \"bg-background pointer-events-none absolute top-0 left-0 z-0 origin-left rounded-full shadow-[0_1px_2px_0_rgb(0_0_0/0.05)]\",\n          \"opacity-0 group-data-[ready]/segmented:opacity-100\",\n          thumbClassName\n        )}\n      />\n      <SegmentedControlContext.Provider value={context}>\n        {children}\n      </SegmentedControlContext.Provider>\n    </ToggleGroupPrimitive.Root>\n  );\n}\n\ntype SegmentedControlItemProps = ComponentProps<typeof ToggleGroupPrimitive.Item>;\n\n/** One option of a `SegmentedControl`. Its `value` is what `onValueChange` reports. */\nfunction SegmentedControlItem({ className, ref, ...props }: SegmentedControlItemProps) {\n  const { size, register } = useContext(SegmentedControlContext);\n  const item = useRef<HTMLButtonElement>(null);\n  const mergedRef = useMemo(() => mergeRefs(ref, item), [ref]);\n\n  useIsomorphicLayoutEffect(() => {\n    if (!item.current) return;\n    return register(item.current);\n  }, [register]);\n\n  return (\n    <ToggleGroupPrimitive.Item\n      ref={mergedRef}\n      data-slot=\"segmented-control-item\"\n      data-size={size}\n      className={cn(segmentedControlItemVariants({ size }), className)}\n      {...props}\n    />\n  );\n}\n\nexport {\n  SegmentedControl,\n  SegmentedControlItem,\n  segmentedControlItemVariants,\n  type SegmentedControlProps,\n  type SegmentedControlItemProps,\n};\n",
      "type": "registry:ui"
    }
  ],
  "type": "registry:ui"
}