# Toggle Group
A row of toggles sharing one value, pressed by a person or an agent.
Source page: https://dinachi.dev/docs/components/toggle-group

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

## Usage
```tsx
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"
import { AlignCenter, AlignLeft, AlignRight } from "lucide-react"

export function Alignment() {
  return (
    <ToggleGroup aria-label="Alignment" defaultValue={["left"]}>
      <ToggleGroupItem value="left" aria-label="Align left">
        <AlignLeft className="h-4 w-4" />
      </ToggleGroupItem>
      <ToggleGroupItem value="center" aria-label="Align center">
        <AlignCenter className="h-4 w-4" />
      </ToggleGroupItem>
      <ToggleGroupItem value="right" aria-label="Align right">
        <AlignRight className="h-4 w-4" />
      </ToggleGroupItem>
    </ToggleGroup>
  )
}
```

## Anatomy
```tsx
<ToggleGroup>
  <ToggleGroupItem />
</ToggleGroup>
```
- `ToggleGroup`: Holds pressed values; moves focus between items.
- `ToggleGroupItem`: One toggle in the group.

## Examples

### Single
One item pressed at a time.
```tsx
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
import { AlignLeft, AlignCenter, AlignRight } from 'lucide-react';

export function Example() {
  return (
    <ToggleGroup defaultValue={["center"]}>
      <ToggleGroupItem value="left" aria-label="Align left">
        <AlignLeft className="h-4 w-4" />
      </ToggleGroupItem>
      <ToggleGroupItem value="center" aria-label="Align center">
        <AlignCenter className="h-4 w-4" />
      </ToggleGroupItem>
      <ToggleGroupItem value="right" aria-label="Align right">
        <AlignRight className="h-4 w-4" />
      </ToggleGroupItem>
    </ToggleGroup>
  );
}
```

### Multiple
Several items can be pressed at once.
```tsx
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
import { Bold, Italic, Underline } from 'lucide-react';

export function Example() {
  return (
    <ToggleGroup multiple>
      <ToggleGroupItem value="bold" aria-label="Toggle bold">
        <Bold className="h-4 w-4" />
      </ToggleGroupItem>
      <ToggleGroupItem value="italic" aria-label="Toggle italic">
        <Italic className="h-4 w-4" />
      </ToggleGroupItem>
      <ToggleGroupItem value="underline" aria-label="Toggle underline">
        <Underline className="h-4 w-4" />
      </ToggleGroupItem>
    </ToggleGroup>
  );
}
```

### Sizes
Small and default items.
```tsx
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
import { Bold, Italic } from 'lucide-react';

export function Example() {
  return (
    <div className="flex flex-col gap-4">
      <ToggleGroup multiple>
        <ToggleGroupItem value="bold" size="sm" aria-label="Bold">
          <Bold className="h-3 w-3" />
        </ToggleGroupItem>
        <ToggleGroupItem value="italic" size="sm" aria-label="Italic">
          <Italic className="h-3 w-3" />
        </ToggleGroupItem>
      </ToggleGroup>
      <ToggleGroup multiple>
        <ToggleGroupItem value="bold" size="default" aria-label="Bold">
          <Bold className="h-4 w-4" />
        </ToggleGroupItem>
        <ToggleGroupItem value="italic" size="default" aria-label="Italic">
          <Italic className="h-4 w-4" />
        </ToggleGroupItem>
      </ToggleGroup>
      <ToggleGroup multiple>
        <ToggleGroupItem value="bold" size="lg" aria-label="Bold">
          <Bold className="h-5 w-5" />
        </ToggleGroupItem>
        <ToggleGroupItem value="italic" size="lg" aria-label="Italic">
          <Italic className="h-5 w-5" />
        </ToggleGroupItem>
      </ToggleGroup>
    </div>
  );
}
```

## Notes

### Defaults
Items default to `variant="outline"` and `size="sm"`; a standalone [Toggle](/docs/components/toggle) defaults to `default` for both.

### Single mode
Without `multiple`, pressing an item replaces the value; pressing the pressed item clears it. Read `value[0]`.

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

### ToggleGroup
Holds pressed values; moves focus between items.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value` | `string[]` | - | Controlled pressed values. Always an array. |
| `defaultValue` | `string[]` | `[]` | Starting values when uncontrolled. |
| `onValueChange` **agent** | `(value, details) => void` | - | Runs for people and agents. `details.cancel()` refuses the change. |
| `multiple` **agent** | `boolean` | `false` | Allows several pressed items. Agents also get `setValue`. |
| `disabled` **agent** | `boolean` | `false` | Blocks people and agents. |
| `orientation` | `"horizontal" \| "vertical"` | `"horizontal"` | Which arrow keys move focus. Vertical also stacks the items. |
| `loopFocus` | `boolean` | `true` | Wraps focus from the last item to the first. |

### ToggleGroupItem
One toggle in the group.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value` | `string` | - | Added to the group's value while pressed. |
| `variant` | `"default" \| "outline"` | `"outline"` | Outline adds a border. |
| `size` | `"default" \| "sm" \| "lg"` | `"sm"` | Height and padding. |
| `disabled` **agent** | `boolean` | `false` | Blocks this item, for agents too. |
| `aria-label` **agent** | `string` | - | The item's name; required for icon-only items. The agent picks by it. |

## Agent
Inside an `AgentProvider`, Toggle Group appears in `agent.snapshot()` as `toggle-group`.
Reads:
- `label`: The group's aria-label.
- `value`: The pressed item's label, or a list of labels when multiple.
- `items`: Every item's label.
- `multiple`: Present when several items can be pressed.
- `disabled`: True when the whole group is blocked.
Actions:
- `select("Align center")`: Picks by label, then by value. Replaces in single mode, adds in multiple. A miss lists the items.
- `setValue(["Toggle bold", "Toggle italic"])`: Replaces the whole value. Only when multiple.
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 item and a disabled group refuse on their own.
```ts
await agent.act({
  steps: [{ ref: "toggle-group", action: "select", args: ["Align right"] }],
})
```

## Accessibility
- The group has role group; each item is a button with aria-pressed.
- Name the group with aria-label. Without one the agent lists it as `toggle-group`.
- Icon-only items each need an aria-label. The agent reads these as item names.
- Disabled items stay in the group but cannot be pressed.
### Keyboard
| Keys | Does |
| --- | --- |
| `←` / `→` | Moves focus between items, or ↑ ↓ when vertical |
| `Home` / `End` | Moves focus to the first or last item |
| `Space` / `Enter` | Presses or releases the focused item |
| `Tab` | Moves focus into and out of the group as one stop |

## Source
`components/ui/toggle-group/toggle-group.tsx`
```tsx
"use client"

import * as React from "react"
import { ToggleGroup as ToggleGroupPrimitive } from "@base-ui/react/toggle-group"
import { Toggle as TogglePrimitive } from "@base-ui/react/toggle"
import { cva } from "class-variance-authority"
import { cn } from "@/lib/utils"
import {
  agentChoicesOf,
  changeAsAgent,
  matchAgentChoice,
  sameAgentValue,
  useAgentControl,
  useAgentItem,
  useAgentState,
  useHasAgent,
  useMergedRef,
  type AgentChoice,
  type AgentItems,
} from "@/components/ui/agent"

type ToggleItems = AgentItems<string>

const ToggleAgentContext = React.createContext<ToggleItems | null>(null)

function matchAll(choices: AgentChoice[], wanted: unknown): string[] | string {
  const values: string[] = []
  for (const one of Array.isArray(wanted) ? wanted : [wanted]) {
    const match = matchAgentChoice(choices, one)
    if (typeof match === "string") return match
    values.push(match.value as string)
  }
  return values
}

type ToggleGroupItemProps = React.ComponentPropsWithoutRef<typeof TogglePrimitive> & {
  variant?: "default" | "outline"
  size?: "default" | "sm" | "lg"
}

const toggleGroupItemVariants = cva(
  [
    "inline-flex items-center justify-center rounded-md text-sm font-medium",
    "ring-offset-background transition-colors",
    "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
    "disabled:pointer-events-none disabled:opacity-50",
    "data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
    "data-[pressed]:bg-accent data-[pressed]:text-accent-foreground",
  ],
  {
    variants: {
      variant: {
        default: "bg-transparent hover:bg-muted hover:text-muted-foreground",
        outline:
          "border border-input bg-transparent hover:bg-accent hover:text-accent-foreground data-[pressed]:border-accent",
      },
      size: {
        default: "h-10 px-3",
        sm: "h-9 px-2.5 text-xs",
        lg: "h-11 px-5",
      },
    },
    defaultVariants: {
      variant: "outline",
      size: "sm",
    },
  }
)

const ToggleGroup = React.forwardRef<
  React.ComponentRef<typeof ToggleGroupPrimitive>,
  React.ComponentPropsWithoutRef<typeof ToggleGroupPrimitive>
>(({ className, value: valueProp, defaultValue, onValueChange, ...props }, ref) => {
  const [value, change] = useAgentState<readonly string[], ToggleGroupPrimitive.ChangeEventDetails>(
    valueProp,
    defaultValue ?? [],
    onValueChange as ((value: readonly string[], details: ToggleGroupPrimitive.ChangeEventDetails) => void) | undefined
  )
  const element = React.useRef<HTMLDivElement | null>(null)
  const mergedRef = useMergedRef(ref, element)
  const [items] = React.useState<ToggleItems>(() => new Map())

  const pick = (wanted: unknown, add: boolean) => {
    const values = matchAll(agentChoicesOf(items), wanted)
    if (typeof values === "string") return values
    const fresh = values.filter((v) => !value.some((w) => sameAgentValue(v, w)))
    if (!fresh.length && (add || values.length === value.length)) return undefined
    return changeAsAgent(change, add ? [...value, ...fresh] : values)
  }

  const add = (wanted: unknown) => pick(wanted, true)
  const replace = (wanted: unknown) => pick(wanted, false)
  const actions: Record<string, typeof add> = props.multiple ? { select: add, setValue: replace } : { select: replace }

  useAgentControl(() => {
    const choices = agentChoicesOf(items)
    const labels = value.map((v) => choices.find((c) => sameAgentValue(c.value, v))?.label ?? String(v))
    return {
      kind: "toggle-group",
      element: choices.length ? element.current : null,
      value: props.multiple ? labels : (labels[0] ?? ""),
      items: choices.map((c) => c.label),
      multiple: props.multiple || undefined,
      disabled: props.disabled,
      actions,
    }
  })

  return (
    <ToggleAgentContext.Provider value={useHasAgent() ? items : null}>
      <ToggleGroupPrimitive
        ref={mergedRef}
        data-slot="toggle-group"
        className={cn(
          "inline-flex items-center justify-center gap-1",
          "data-[orientation=vertical]:flex-col",
          className
        )}
        {...props}
        value={value}
        onValueChange={change}
      />
    </ToggleAgentContext.Provider>
  )
})
ToggleGroup.displayName = "ToggleGroup"

const ToggleGroupItem = React.forwardRef<
  React.ComponentRef<typeof TogglePrimitive>,
  ToggleGroupItemProps
>(({ className, variant = "outline", size = "sm", ...props }, ref) => {
  const items = React.useContext(ToggleAgentContext)
  const element = React.useRef<HTMLButtonElement | null>(null)
  const mergedRef = useMergedRef(ref, element)
  useAgentItem(items, element, props.value as string | undefined)

  // Inside AgentProvider the group reports its items, so the buttons stay out of the
  // snapshot rather than appearing twice.
  return (
    <TogglePrimitive
      ref={mergedRef}
      data-slot="toggle-group-item"
      data-agent-part={items ? "" : undefined}
      className={cn(toggleGroupItemVariants({ variant, size }), className)}
      {...props}
    />
  )
})
ToggleGroupItem.displayName = "ToggleGroupItem"

export { ToggleGroup, ToggleGroupItem }
```
