# Radio
One option from a short visible set, for people and agents.
Source page: https://dinachi.dev/docs/components/radio

## Installation
```bash
npx @dinachi/cli@latest add radio
```
Adds to your project:
- `components/ui/radio/radio.tsx`
- `components/ui/radio/index.ts`
Installs:
- `@base-ui/react` ^1.9.0

## Usage
```tsx
import { Radio, RadioGroup } from "@/components/ui/radio"

export function PlanPicker() {
  return (
    <RadioGroup aria-label="Plan" defaultValue="free">
      <label className="flex items-center gap-2">
        <Radio value="free" />
        Free
      </label>
      <label className="flex items-center gap-2">
        <Radio value="pro" />
        Pro
      </label>
    </RadioGroup>
  )
}
```

## Anatomy
```tsx
<RadioGroup>
  <Radio>
    <RadioIndicator />
  </Radio>
</RadioGroup>
```
- `RadioGroup`: Holds the chosen value.
- `Radio`: One option. Renders its own indicator.
- `RadioIndicator`: The dot shown when the radio is checked.

## Examples

### Default
Three options with one chosen to start.
```tsx
import { Radio, RadioGroup } from '@/components/ui/radio';

export function Example() {
  return (
    <RadioGroup defaultValue="comfortable">
      <label className="flex items-center gap-2">
        <Radio value="default" />
        <span className="text-sm font-medium">Default</span>
      </label>
      <label className="flex items-center gap-2">
        <Radio value="comfortable" />
        <span className="text-sm font-medium">Comfortable</span>
      </label>
      <label className="flex items-center gap-2">
        <Radio value="compact" />
        <span className="text-sm font-medium">Compact</span>
      </label>
    </RadioGroup>
  );
}
```

### Controlled
The value lives in state and is shown below.
```tsx
import React from 'react';
import { Radio, RadioGroup } from '@/components/ui/radio';

export function Example() {
  const [value, setValue] = React.useState('email');

  return (
    <div className="space-y-3">
      <RadioGroup value={value} onValueChange={setValue}>
        <label className="flex items-center gap-2">
          <Radio value="email" />
          <span className="text-sm font-medium">Email</span>
        </label>
        <label className="flex items-center gap-2">
          <Radio value="sms" />
          <span className="text-sm font-medium">SMS</span>
        </label>
        <label className="flex items-center gap-2">
          <Radio value="push" />
          <span className="text-sm font-medium">Push Notification</span>
        </label>
      </RadioGroup>
      <p className="text-sm text-muted-foreground">Selected: {value}</p>
    </div>
  );
}
```

### Disabled
The whole group is blocked.
```tsx
import { Radio, RadioGroup } from '@/components/ui/radio';

export function Example() {
  return (
    <RadioGroup defaultValue="active" disabled>
      <label className="flex items-center gap-2 text-muted-foreground">
        <Radio value="active" />
        <span className="text-sm font-medium">Active</span>
      </label>
      <label className="flex items-center gap-2 text-muted-foreground">
        <Radio value="inactive" />
        <span className="text-sm font-medium">Inactive</span>
      </label>
    </RadioGroup>
  );
}
```

## Notes

### Radio labels
Wrap each `Radio` and its text in a `<label>`. Clicking the text picks the radio, and the agent reads the text as the option's name. Without a label it falls back to `aria-label`, then the value.

### Built-in indicator
`Radio` already renders a `RadioIndicator`; do not add one inside it. The export is for custom radios built on the Base UI primitive.

## API reference
Props marked **agent** change what an agent reads or may do.

### RadioGroup
Holds the chosen value.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value` | `Value` | - | Controlled value. |
| `defaultValue` | `Value` | - | Starting value when uncontrolled. |
| `onValueChange` **agent** | `(value, details) => void` | - | Runs for people and agents. `details.cancel()` refuses the change. |
| `aria-label` **agent** | `string` | - | Names the group, as does aria-labelledby. The agent reads it. |
| `disabled` **agent** | `boolean` | `false` | Blocks people and agents. |
| `readOnly` **agent** | `boolean` | `false` | Shows the value, refuses any change. |
| `name` | `string` | - | Submits the value with a form. |
| `required` | `boolean` | `false` | Must have a value before the form submits. |

### Radio
One option. Renders its own indicator.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value` **agent** | `Value` | - | What `onValueChange` receives. Required for the agent to list the radio. |
| `disabled` **agent** | `boolean` | `false` | Skipped by the keyboard, refused for agents. |
| `render` | `ReactElement` | - | Swap the element, keep the behaviour. |

### RadioIndicator
The dot shown when the radio is checked.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `keepMounted` | `boolean` | `false` | Keeps the dot mounted while unchecked, for exit animations. |

## Agent
Inside an `AgentProvider`, Radio appears in `agent.snapshot()` as `radio-group`.
Reads:
- `label`: The group's aria-label or aria-labelledby.
- `value`: The checked radio's label, or an empty string.
- `items`: Every radio's label, in document order.
- `disabled`: True when the whole group is blocked.
Actions:
- `select("Compact")`: Picks by label, then by value. A miss lists the options.
An agent's change runs through `onValueChange`. `isAgentChange(details)` is true for it, and `details.cancel()` refuses it; the agent is told the app refused. A disabled radio, a disabled group and `readOnly` refuse on their own.
```ts
await agent.act({
  steps: [{ ref: "radio-group", action: "select", args: ["Compact"] }],
})
```

## Accessibility
- The group is a radiogroup; each radio is a radio with aria-checked.
- Name the group with aria-label or aria-labelledby. The agent reads the same name.
- Enter does not check a radio; only Space and the arrow keys do.
- A hidden input submits the value with a native form.
### Keyboard
| Keys | Does |
| --- | --- |
| `Tab` | Moves focus into the group, onto the checked radio |
| `↑` / `↓` / `←` / `→` | Moves to the next or previous radio and checks it |
| `Space` | Checks the focused radio |

## Source
`components/ui/radio/radio.tsx`
```tsx
"use client"

import * as React from "react"
import { Radio as RadioPrimitive } from "@base-ui/react/radio"
import { RadioGroup as RadioGroupPrimitive } from "@base-ui/react/radio-group"
import { cn } from "@/lib/utils"
import {
  agentChoicesOf,
  changeAsAgent,
  matchAgentChoice,
  sameAgentValue,
  useAgentControl,
  useAgentItem,
  useAgentState,
  useHasAgent,
  useMergedRef,
  type AgentItems,
} from "@/components/ui/agent"

type RadioItems = AgentItems

const RadioAgentContext = React.createContext<RadioItems | null>(null)

/**
 * Base UI's group, holding its own value so an agent can choose a radio the way a parent
 * would. Controlled use is unchanged, and `onValueChange` sees the agent's choice first
 * and can cancel it.
 */
const RadioGroup = React.forwardRef<
  React.ComponentRef<typeof RadioGroupPrimitive>,
  React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive>
>(({ className, value: valueProp, defaultValue, onValueChange, ...props }, ref) => {
  const [value, change] = useAgentState<unknown, RadioGroupPrimitive.ChangeEventDetails>(
    valueProp,
    defaultValue ?? null,
    onValueChange
  )
  const element = React.useRef<HTMLDivElement | null>(null)
  const mergedRef = useMergedRef(ref, element)
  const [items] = React.useState<RadioItems>(() => new Map())

  const choose = (wanted: unknown) => {
    if (props.readOnly) return "The radio group is read-only."
    const match = matchAgentChoice(agentChoicesOf(items), wanted)
    return typeof match === "string" ? match : changeAsAgent(change, match.value)
  }

  useAgentControl(() => {
    const choices = agentChoicesOf(items)
    return {
      kind: "radio-group",
      element: choices.length ? element.current : null,
      value: choices.find((c) => sameAgentValue(c.value, value))?.label ?? "",
      items: choices.map((c) => c.label),
      disabled: props.disabled,
      actions: { select: choose },
    }
  })

  return (
    <RadioAgentContext.Provider value={useHasAgent() ? items : null}>
      <RadioGroupPrimitive
        ref={mergedRef}
        data-slot="radio-group"
        className={cn("grid gap-2", className)}
        {...props}
        value={value}
        onValueChange={change}
      />
    </RadioAgentContext.Provider>
  )
})
RadioGroup.displayName = "RadioGroup"

const RadioIndicator = React.forwardRef<
  React.ComponentRef<typeof RadioPrimitive.Indicator>,
  React.ComponentProps<typeof RadioPrimitive.Indicator>
>(({ className, ...props }, ref) => (
  <RadioPrimitive.Indicator
    ref={ref}
    data-slot="radio-indicator"
    className={cn(
      "flex items-center justify-center",
      "after:h-2.5 after:w-2.5 after:rounded-full after:bg-current",
      className
    )}
    {...props}
  />
))
RadioIndicator.displayName = "RadioIndicator"

const Radio = React.forwardRef<
  React.ComponentRef<typeof RadioPrimitive.Root>,
  React.ComponentPropsWithoutRef<typeof RadioPrimitive.Root>
>(({ className, ...props }, ref) => {
  const items = React.useContext(RadioAgentContext)
  const element = React.useRef<React.ComponentRef<typeof RadioPrimitive.Root> | null>(null)
  const mergedRef = useMergedRef(ref, element)
  useAgentItem(items, element, props.value)

  return (
  <span className="relative inline-flex [&>input]:!absolute">
    <RadioPrimitive.Root
      ref={mergedRef}
      data-slot="radio"
      className={cn(
        "flex items-center justify-center aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background",
        "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
        "data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50",
        "data-[checked]:border-primary data-[unchecked]:border-muted-foreground",
        className
      )}
      {...props}
    >
      <RadioIndicator />
    </RadioPrimitive.Root>
  </span>
  )
})
Radio.displayName = "Radio"

export { Radio, RadioGroup, RadioIndicator }
```
