# Checkbox Group
Several checkboxes whose ticked values form one list.
Source page: https://dinachi.dev/docs/components/checkbox-group

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

## Usage
```tsx
import { Checkbox } from "@/components/ui/checkbox"
import { CheckboxGroup } from "@/components/ui/checkbox-group"

const toppings = [
  { value: "cheese", label: "Cheese" },
  { value: "olives", label: "Olives" },
  { value: "peppers", label: "Peppers" },
]

export function ToppingsPicker() {
  return (
    <div>
      <p id="toppings-label" className="text-sm font-medium">Toppings</p>
      <CheckboxGroup aria-labelledby="toppings-label" defaultValue={["cheese"]}>
        {toppings.map((t) => (
          <div key={t.value} className="flex items-center gap-2">
            <Checkbox id={t.value} value={t.value} />
            <label htmlFor={t.value} className="text-sm">{t.label}</label>
          </div>
        ))}
      </CheckboxGroup>
    </div>
  )
}
```

## Anatomy
```tsx
<CheckboxGroup>
  <Checkbox />
  <Checkbox />
</CheckboxGroup>
```
- `CheckboxGroup`: Holds the ticked values of its Checkboxes.

## Examples

### Controlled
The ticked values live in your state.
```tsx
import { CheckboxGroup } from '@/components/ui/checkbox-group';
import { Checkbox } from '@/components/ui/checkbox';
import { useState } from 'react';

export function Example() {
  const [selected, setSelected] = useState<string[]>(["react"]);

  return (
    <div className="space-y-3">
      <label className="text-sm font-medium text-foreground">
        Select frameworks you know
      </label>
      <CheckboxGroup value={selected} onValueChange={setSelected}>
        <div className="flex items-center space-x-2">
          <Checkbox id="react" name="frameworks" value="react" />
          <label htmlFor="react" className="text-sm text-foreground">React</label>
        </div>
        <div className="flex items-center space-x-2">
          <Checkbox id="vue" name="frameworks" value="vue" />
          <label htmlFor="vue" className="text-sm text-foreground">Vue</label>
        </div>
        <div className="flex items-center space-x-2">
          <Checkbox id="angular" name="frameworks" value="angular" />
          <label htmlFor="angular" className="text-sm text-foreground">Angular</label>
        </div>
      </CheckboxGroup>
      <p className="text-sm text-muted-foreground">
        Selected: {selected.length > 0 ? selected.join(", ") : "None"}
      </p>
    </div>
  );
}
```

### Default
An uncontrolled group with one value ticked.
```tsx
import { CheckboxGroup } from '@/components/ui/checkbox-group';
import { Checkbox } from '@/components/ui/checkbox';

export function Example() {
  return (
    <div className="space-y-3">
      <label className="text-sm font-medium text-foreground">
        Select your interests
      </label>
      <CheckboxGroup defaultValue={["design"]}>
        <div className="flex items-center space-x-2">
          <Checkbox id="design" name="interests" value="design" />
          <label htmlFor="design" className="text-sm text-foreground">Design</label>
        </div>
        <div className="flex items-center space-x-2">
          <Checkbox id="development" name="interests" value="development" />
          <label htmlFor="development" className="text-sm text-foreground">Development</label>
        </div>
        <div className="flex items-center space-x-2">
          <Checkbox id="marketing" name="interests" value="marketing" />
          <label htmlFor="marketing" className="text-sm text-foreground">Marketing</label>
        </div>
      </CheckboxGroup>
    </div>
  );
}
```

### Horizontal
The group laid out in a row.
```tsx
import { CheckboxGroup } from '@/components/ui/checkbox-group';
import { Checkbox } from '@/components/ui/checkbox';

export function Example() {
  return (
    <div className="space-y-3">
      <label className="text-sm font-medium text-foreground">
        Notification preferences
      </label>
      <CheckboxGroup defaultValue={["email"]} className="flex flex-row gap-6">
        <div className="flex items-center space-x-2">
          <Checkbox id="email-notif" name="notifications" value="email" />
          <label htmlFor="email-notif" className="text-sm text-foreground">Email</label>
        </div>
        <div className="flex items-center space-x-2">
          <Checkbox id="sms-notif" name="notifications" value="sms" />
          <label htmlFor="sms-notif" className="text-sm text-foreground">SMS</label>
        </div>
        <div className="flex items-center space-x-2">
          <Checkbox id="push-notif" name="notifications" value="push" />
          <label htmlFor="push-notif" className="text-sm text-foreground">Push</label>
        </div>
      </CheckboxGroup>
    </div>
  );
}
```

### Disabled
A group that blocks every checkbox.
```tsx
import { CheckboxGroup } from '@/components/ui/checkbox-group';
import { Checkbox } from '@/components/ui/checkbox';

export function Example() {
  return (
    <div className="space-y-3">
      <label className="text-sm font-medium text-muted-foreground">
        Plan features (upgrade to enable)
      </label>
      <CheckboxGroup disabled defaultValue={["basic"]}>
        <div className="flex items-center space-x-2">
          <Checkbox id="basic" name="features" value="basic" />
          <label htmlFor="basic" className="text-sm text-muted-foreground">Basic features</label>
        </div>
        <div className="flex items-center space-x-2">
          <Checkbox id="advanced" name="features" value="advanced" />
          <label htmlFor="advanced" className="text-sm text-muted-foreground">Advanced features</label>
        </div>
      </CheckboxGroup>
    </div>
  );
}
```

## Notes

### Checkbox values
A [Checkbox](/docs/components/checkbox) joins the group through its `value`. Without one it is not in the group's list or the agent's items.

### Parent checkbox
Pass `allValues` and add a `<Checkbox parent />`. It ticks or clears every child and shows mixed when some are ticked. Disabled children are left alone.

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

### CheckboxGroup
Holds the ticked values of its Checkboxes.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value` | `string[]` | - | Controlled list of ticked values. |
| `defaultValue` | `string[]` | `[]` | Starting list when uncontrolled. |
| `onValueChange` **agent** | `(value, details) => void` | - | Runs for people and agents. `details.cancel()` refuses the change. |
| `allValues` **agent** | `string[]` | - | Every checkbox's value. Required for a `parent` checkbox. |
| `disabled` **agent** | `boolean` | `false` | Blocks every checkbox, for people and agents. |
| `className` | `string` | - | Merged over the vertical stack, for example to lay out a row. |

## Agent
Inside an `AgentProvider`, Checkbox Group appears in `agent.snapshot()` as `checkbox-group`.
Reads:
- `label`: The group's aria-label or aria-labelledby. Unnamed groups go by checkbox-group.
- `value`: The labels of the ticked checkboxes.
- `items`: Every checkbox's label, in order.
- `multiple`: Always true.
- `disabled`: True when the whole group is blocked.
Actions:
- `setValue(["React", "Vue"])`: Ticks exactly these, by label then by value. A miss lists the options. Disabled checkboxes keep their state.
Each checkbox is also listed and takes toggle and `setChecked`, which run through the group's `onValueChange` like `setValue`. `isAgentChange(details)` is true there; `details.cancel()` refuses and tells the agent. Naming a disabled checkbox fails; a disabled group refuses on its own.
```ts
await agent.act({
  steps: [{ ref: "checkbox-group", action: "setValue", args: [["React", "Vue"]] }],
})
```

## Accessibility
- Renders role="group". Name it with aria-labelledby or aria-label; the agent reads the same name.
- Each checkbox needs its own label, also its name in the agent's items.
- A parent checkbox reports mixed while some children are ticked.
### Keyboard
| Keys | Does |
| --- | --- |
| `Tab` | Moves between the checkboxes |
| `Space` | Toggles the focused checkbox |

## Source
`components/ui/checkbox-group/checkbox-group.tsx`
```tsx
import * as React from "react";
import { CheckboxGroup as BaseCheckboxGroup } from "@base-ui/react/checkbox-group";
import { cn } from "@/lib/utils";
import {
  AgentGroupContext,
  agentChoicesOf,
  changeAsAgent,
  matchAgentChoice,
  useAgentControl,
  useAgentLatest,
  useAgentState,
  useHasAgent,
  useMergedRef,
  type AgentChoice,
  type AgentGroup,
} from "@/components/ui/agent";

type Details = BaseCheckboxGroup.ChangeEventDetails;

function valuesFor(choices: AgentChoice<string>[], value: string[], wanted: unknown): string[] | string {
  const next = value.filter((v) => !choices.some((c) => c.value === v && !c.disabled));
  for (const one of Array.isArray(wanted) ? wanted : [wanted]) {
    const match = matchAgentChoice(choices, one);
    if (typeof match === "string") return match;
    if (!next.includes(match.value)) next.push(match.value);
  }
  return next;
}

/**
 * Base UI's group, holding its own value so an agent can check boxes the way a parent
 * would. Controlled use is unchanged, and `onValueChange` sees the agent's changes first
 * and can cancel them.
 */
const CheckboxGroup = React.forwardRef<
  React.ComponentRef<typeof BaseCheckboxGroup>,
  React.ComponentPropsWithoutRef<typeof BaseCheckboxGroup>
>(({ className, value: valueProp, defaultValue, onValueChange, ...props }, ref) => {
  const [value, change] = useAgentState<string[], Details>(valueProp, defaultValue ?? [], onValueChange);
  const element = React.useRef<HTMLDivElement | null>(null);
  const mergedRef = useMergedRef(ref, element);
  const latest = useAgentLatest({ value, change, allValues: props.allValues });

  const [agent] = React.useState<AgentGroup>(() => {
    const items: AgentGroup["items"] = new Map();
    return {
      items,
      set(item, checked) {
        const { value: now, change: commit, allValues = [] } = latest.current;
        // The parent checkbox leaves disabled children as they are, as Base UI's does.
        const disabled = [...items].filter(([el]) => el.hasAttribute("data-disabled")).map(([, v]) => v);
        const changed = item === undefined ? allValues.filter((v) => !disabled.includes(v)) : [item];
        if (!changed.length) return undefined;
        const next = checked ? [...new Set([...now, ...changed])] : now.filter((v) => !changed.includes(v));
        return changeAsAgent(commit, next);
      },
    };
  });

  useAgentControl(() => {
    const choices = agentChoicesOf(agent.items);
    const setValue = (wanted: unknown) => {
      const next = valuesFor(choices, value, wanted);
      return typeof next === "string" ? next : changeAsAgent(change, next);
    };
    return {
      kind: "checkbox-group",
      element: choices.length ? element.current : null,
      value: choices.filter((c) => value.includes(c.value)).map((c) => c.label),
      items: choices.map((c) => c.label),
      multiple: true,
      disabled: props.disabled,
      actions: { setValue },
    };
  });

  return (
    <AgentGroupContext.Provider value={useHasAgent() ? agent : null}>
      <BaseCheckboxGroup
        ref={mergedRef}
        data-slot="checkbox-group"
        className={cn("flex flex-col items-start gap-1", className)}
        {...props}
        value={value}
        onValueChange={change}
      />
    </AgentGroupContext.Provider>
  );
});
CheckboxGroup.displayName = "CheckboxGroup";

export { CheckboxGroup };
```
