{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "radio-group",
  "type": "registry:ui",
  "title": "Radio Group",
  "description": "An accessible React radio group for Next.js forms, where the selected dot travels to the new choice, built on Radix Radio Group.",
  "author": "FewTone <https://fewtone.com>",
  "dependencies": [
    "class-variance-authority@^0.7.1",
    "motion@^14.0.0",
    "radix-ui@^1.7.0"
  ],
  "registryDependencies": [
    "https://ui.fewtone.com/r/tokens.json",
    "https://ui.fewtone.com/r/motion.json"
  ],
  "files": [
    {
      "path": "registry/fewtone/ui/radio-group.tsx",
      "type": "registry:ui",
      "content": "\"use client\";\n\nimport { duration, spring } from \"@/lib/motion\";\nimport { cn } from \"@/lib/utils\";\nimport { cva } from \"class-variance-authority\";\nimport {\n  type AnimationPlaybackControls,\n  animate,\n  motion,\n  useMotionValue,\n  useReducedMotion,\n} from \"motion/react\";\nimport { RadioGroup as RadioGroupPrimitive } from \"radix-ui\";\nimport {\n  type ComponentProps,\n  createContext,\n  useContext,\n  useEffect,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from \"react\";\n\n/*\n * Radio Group (owner, 2026-10-15; chosen in the Lab).\n * - The selection travels: when the choice changes, the dot leaves the old radio and lands in the new one.\n *   Two ways (`travel`), both chosen by the owner:\n *   - slide (the default): straight across on spring.snappy\n *   - stretch: the front leaves first and the back follows a moment later, so it stretches into a capsule\n *     for the trip and lands round, like Switch's thumb\n * - At rest each dot sits inside its own radio, so nothing is measured until the choice changes. For a\n *   trip, one shared dot moves at the group's level, placed with offsets (layout numbers, so a zoomed or\n *   scaled preview doesn't double the movement), then hands back to the new radio's own dot in the same\n *   frame.\n * - Nothing animates on first paint. With reduced motion the dot moves at once.\n */\n\nexport type RadioGroupTravel = \"slide\" | \"stretch\";\ntype Size = \"sm\" | \"md\";\n\ntype GroupContextValue = {\n  value: string;\n  /** The radio the shared dot is on its way to; its own dot waits until it lands */\n  arriving: string | null;\n  size: Size;\n  register: (value: string, node: HTMLElement | null) => void;\n};\n\nconst GroupContext = createContext<GroupContextValue | null>(null);\n\nconst radioGroupItemVariants = cva(\n  [\n    \"peer relative inline-flex shrink-0 cursor-pointer items-center justify-center rounded-full border border-input bg-transparent\",\n    \"transition-colors duration-(--duration-fast) ease-out data-[state=checked]:border-primary data-[state=unchecked]:enabled:hover:border-ring\",\n    \"outline-ring focus-visible:outline-(length:--focus-ring-width) focus-visible:outline-offset-(--focus-ring-offset)\",\n    \"aria-invalid:border-destructive aria-invalid:outline-destructive\",\n    \"disabled:cursor-not-allowed disabled:opacity-(--opacity-disabled)\",\n  ],\n  {\n    // The same sizes as Checkbox and Switch (16 and 20px)\n    variants: { size: { sm: \"size-4\", md: \"size-5\" } },\n    defaultVariants: { size: \"md\" },\n  },\n);\n\nconst dotSize = { sm: \"size-1.5\", md: \"size-2\" } as const;\n\n/** A radio's centre in the group, in layout pixels (offsets, so transforms and zoom don't count) */\nfunction centreOf(node: HTMLElement, root: HTMLElement) {\n  let x = node.offsetWidth / 2;\n  let y = node.offsetHeight / 2;\n  let element: HTMLElement | null = node;\n  while (element && element !== root) {\n    x += element.offsetLeft;\n    y += element.offsetTop;\n    element = element.offsetParent as HTMLElement | null;\n  }\n  return element === root ? { x, y } : null;\n}\n\nexport type RadioGroupProps = ComponentProps<typeof RadioGroupPrimitive.Root> & {\n  /** 16 or 20px radios */\n  size?: Size;\n  /** How the dot travels to the new choice: straight across, or stretching on the way */\n  travel?: RadioGroupTravel;\n};\n\n/**\n * One choice from a few, built on Radix Radio Group (role=\"radiogroup\", arrow keys move and select).\n * Give each RadioGroupItem a visible label (`<label htmlFor>`).\n */\nfunction RadioGroup({\n  className,\n  size = \"md\",\n  travel = \"slide\",\n  value,\n  defaultValue,\n  onValueChange,\n  children,\n  ref,\n  ...props\n}: RadioGroupProps) {\n  const [uncontrolled, setUncontrolled] = useState(defaultValue ?? \"\");\n  const current = value ?? uncontrolled;\n  const reduce = useReducedMotion() ?? false;\n  const root = useRef<HTMLDivElement>(null);\n  const items = useRef(new Map<string, HTMLElement>());\n  const [arriving, setArriving] = useState<string | null>(null);\n  // The shared dot's diameter while it travels\n  const [trip, setTrip] = useState<number | null>(null);\n\n  // The shared dot: its back end (x, y), its length along the trip (width) and the trip's angle\n  const x = useMotionValue(0);\n  const y = useMotionValue(0);\n  const width = useMotionValue(0);\n  const angle = useMotionValue(0);\n  const running = useRef<AnimationPlaybackControls[]>([]);\n  const tripId = useRef(0);\n  const previous = useRef(current);\n\n  // Unmounting mid-trip stops the animations\n  useEffect(\n    () => () => {\n      for (const animation of running.current) animation.stop();\n    },\n    [],\n  );\n\n  // A new choice: send the shared dot from where it is (the old radio, or mid-trip) to the new radio\n  // biome-ignore lint/correctness/useExhaustiveDependencies: only a change of choice starts a trip\n  useLayoutEffect(() => {\n    const from = previous.current;\n    previous.current = current;\n    if (from === current) return;\n\n    const box = root.current;\n    const start = items.current.get(from);\n    const end = items.current.get(current);\n    const a = box && start ? centreOf(start, box) : null;\n    const b = box && end ? centreOf(end, box) : null;\n    const shape = end?.querySelector<HTMLElement>(\"[data-slot=radio-group-indicator]\");\n    for (const animation of running.current) animation.stop();\n    running.current = [];\n    if (reduce || !a || !b || !shape) {\n      setTrip(null);\n      setArriving(null);\n      return;\n    }\n\n    // Mid-trip, it leaves from where its front is now\n    const size = shape.offsetWidth;\n    const midTrip = trip !== null;\n    const radians = (angle.get() * Math.PI) / 180;\n    const origin = midTrip\n      ? {\n          x: x.get() + Math.cos(radians) * (width.get() - size),\n          y: y.get() + Math.sin(radians) * (width.get() - size),\n        }\n      : a;\n    const dx = b.x - origin.x;\n    const dy = b.y - origin.y;\n    const distance = Math.hypot(dx, dy);\n\n    // Placed with jump(), not set(): set() counts the move from 0 (or the last trip) as speed, and the\n    // slide's spring started with it, so the first trip overshot (owner, 2026-10-15). A slide turned\n    // mid-trip keeps its speed, so it curves to the new radio smoothly.\n    if (travel === \"stretch\" || !midTrip) {\n      x.jump(origin.x);\n      y.jump(origin.y);\n    }\n    width.jump(size);\n    angle.jump((Math.atan2(dy, dx) * 180) / Math.PI);\n    setTrip(size);\n    setArriving(current);\n\n    const id = ++tripId.current;\n    let trips: AnimationPlaybackControls[];\n    if (travel === \"stretch\") {\n      // The front leaves first and the back follows a moment later\n      const ends = { front: 0, back: 0 };\n      const update = () => {\n        x.set(origin.x + dx * ends.back);\n        y.set(origin.y + dy * ends.back);\n        width.set(size + Math.max(0, ends.front - ends.back) * distance);\n      };\n      trips = [\n        animate(0, 1, {\n          ...spring.snappy,\n          onUpdate: (value) => {\n            ends.front = value;\n            update();\n          },\n        }),\n        animate(0, 1, {\n          ...spring.snappy,\n          delay: duration.instant,\n          onUpdate: (value) => {\n            ends.back = value;\n            update();\n          },\n        }),\n      ];\n    } else {\n      trips = [animate(x, b.x, spring.snappy), animate(y, b.y, spring.snappy)];\n    }\n    running.current = trips;\n    Promise.all(trips).then(() => {\n      if (id !== tripId.current) return;\n      running.current = [];\n      setTrip(null);\n      setArriving(null);\n    });\n  }, [current]);\n\n  return (\n    <GroupContext.Provider\n      value={{\n        value: current,\n        arriving,\n        size,\n        register: (name, node) => {\n          if (node) items.current.set(name, node);\n          else items.current.delete(name);\n        },\n      }}\n    >\n      <RadioGroupPrimitive.Root\n        ref={(node) => {\n          root.current = node;\n          if (typeof ref === \"function\") ref(node);\n          else if (ref) ref.current = node;\n        }}\n        data-slot=\"radio-group\"\n        value={current}\n        onValueChange={(next) => {\n          if (value === undefined) setUncontrolled(next);\n          onValueChange?.(next);\n        }}\n        className={cn(\"relative isolate grid gap-3\", className)}\n        {...props}\n      >\n        {children}\n        {trip !== null ? (\n          // The shared dot: a zero-size point at its back end, turned towards the new radio, with the dot\n          // (or, while stretching, the capsule) drawn out from it\n          <motion.span\n            aria-hidden\n            data-slot=\"radio-group-travelling-dot\"\n            className=\"pointer-events-none absolute top-0 left-0 z-10 size-0\"\n            style={{ x, y, rotate: angle, originX: 0, originY: 0 }}\n          >\n            <motion.span\n              className=\"absolute rounded-full bg-primary\"\n              style={{ left: -trip / 2, top: -trip / 2, height: trip, width }}\n            />\n          </motion.span>\n        ) : null}\n      </RadioGroupPrimitive.Root>\n    </GroupContext.Provider>\n  );\n}\n\nexport type RadioGroupItemProps = ComponentProps<typeof RadioGroupPrimitive.Item>;\n\n/** One radio. Its dot shows while it's chosen, except while the shared dot is still on its way. */\nfunction RadioGroupItem({ className, value, ref, ...props }: RadioGroupItemProps) {\n  const group = useContext(GroupContext);\n  const size = group?.size ?? \"md\";\n  const shown = group?.value === value && group.arriving !== value;\n\n  return (\n    <RadioGroupPrimitive.Item\n      ref={(node) => {\n        group?.register(value, node);\n        if (typeof ref === \"function\") ref(node);\n        else if (ref) ref.current = node;\n      }}\n      data-slot=\"radio-group-item\"\n      value={value}\n      className={cn(radioGroupItemVariants({ size }), className)}\n      {...props}\n    >\n      {/* Appears and goes at once, handing over to and from the shared dot */}\n      <span\n        aria-hidden\n        data-slot=\"radio-group-indicator\"\n        className={cn(\n          \"pointer-events-none rounded-full bg-primary\",\n          dotSize[size],\n          shown ? \"scale-100\" : \"scale-0\",\n        )}\n      />\n    </RadioGroupPrimitive.Item>\n  );\n}\n\nexport { RadioGroup, RadioGroupItem, radioGroupItemVariants };\n"
    }
  ],
  "categories": [
    "forms"
  ],
  "docs": "Usage and examples: https://ui.fewtone.com/components/radio-group"
}
