# Switch
An on/off setting that applies at once.
Source page: https://dinachi.dev/docs/components/switch

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

## Usage
```tsx
import { Switch, SwitchThumb } from "@/components/ui/switch"

export function AirplaneMode() {
  return (
    <label className="flex items-center gap-2">
      <Switch>
        <SwitchThumb />
      </Switch>
      Airplane Mode
    </label>
  )
}
```

## Anatomy
```tsx
<Switch>
  <SwitchThumb />
</Switch>
```
- `Switch`: The track. Holds the checked state.
- `SwitchThumb`: The sliding knob.

## Examples

### Default
A switch named by the label around it.
```tsx
import { Switch, SwitchThumb } from '@/components/ui/switch';

export function Example() {
  return (
    <label className="flex items-center space-x-2">
      <Switch>
        <SwitchThumb />
      </Switch>
      <span className="text-sm font-medium">Airplane Mode</span>
    </label>
  );
}
```

### Controlled
Hold the checked state to show it elsewhere.
```tsx
import React from 'react';
import { Switch, SwitchThumb } from '@/components/ui/switch';

export function Example() {
  const [enabled, setEnabled] = React.useState(false);

  return (
    <div className="space-y-3">
      <label className="flex items-center space-x-2">
        <Switch checked={enabled} onCheckedChange={setEnabled}>
          <SwitchThumb />
        </Switch>
        <span className="text-sm font-medium">Dark Mode</span>
      </label>
      <p className="text-sm text-muted-foreground">
        Status: {enabled ? 'Enabled' : 'Disabled'}
      </p>
    </div>
  );
}
```

### States
On, off and disabled.
```tsx
import { Switch, SwitchThumb } from '@/components/ui/switch';

export function Example() {
  return (
    <div className="space-y-4">
      <label className="flex items-center space-x-2">
        <Switch defaultChecked>
          <SwitchThumb />
        </Switch>
        <span className="text-sm font-medium">Notifications (on)</span>
      </label>
      <label className="flex items-center space-x-2">
        <Switch>
          <SwitchThumb />
        </Switch>
        <span className="text-sm font-medium">Marketing emails (off)</span>
      </label>
      <label className="flex items-center space-x-2 text-muted-foreground">
        <Switch disabled>
          <SwitchThumb />
        </Switch>
        <span className="text-sm font-medium">Disabled</span>
      </label>
    </div>
  );
}
```

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

### Switch
The track. Holds the checked state.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `checked` | `boolean` | - | Controlled checked state. |
| `defaultChecked` | `boolean` | `false` | Starting state when uncontrolled. |
| `onCheckedChange` **agent** | `(checked, details) => void` | - | Runs for people and agents. `details.cancel()` refuses the change. |
| `disabled` **agent** | `boolean` | `false` | Blocks people and agents. |
| `readOnly` **agent** | `boolean` | `false` | Shows the state, refuses any change. |
| `name` | `string` | - | Submits the switch with a form. |
| `value` | `string` | - | Submitted while on. The browser sends `on` without it. |
| `uncheckedValue` | `string` | - | Submitted while off. Without it, nothing is sent. |
| `required` | `boolean` | `false` | Must be on before the form submits. |
| `nativeButton` | `boolean` | `false` | Set when `render` swaps in a real `<button>`. |

### SwitchThumb
The sliding knob.

Takes the props of the element it renders.

## Agent
Inside an `AgentProvider`, Switch appears in `agent.snapshot()` as `switch`.
Reads:
- `label`: The label around the switch, or its aria-label.
- `checked`: Whether the switch is on.
- `disabled`: True when the switch is blocked.
Actions:
- `toggle()`: Flips the switch.
- `setChecked(true)`: Sets it on or off. The current state is a no-op.
An agent's change runs through `onCheckedChange`. `isAgentChange(details)` is true for it; `details.cancel()` refuses it and the agent is told. Disabled or `readOnly` switches refuse on their own.
```ts
await agent.act({
  steps: [{ ref: "Airplane Mode", action: "setChecked", args: [true] }],
})
```

## Accessibility
- The track has `role="switch"` and `aria-checked`; a hidden checkbox submits the value.
- Name every switch with a wrapping `<label>` or aria-label; the agent reads it.
- `readOnly` and required are exposed as `aria-readonly` and `aria-required`.
- Reduced motion drops the thumb's slide.
### Keyboard
| Keys | Does |
| --- | --- |
| `Space` / `Enter` | Turns the switch on or off |

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

import * as React from "react"
import { Switch as SwitchPrimitive } from "@base-ui/react/switch"
import { cn } from "@/lib/utils"
import { agentChecked, changeAsAgent, useAgentControl, useAgentState, useMergedRef } from "@/components/ui/agent"

type SwitchProps = React.ComponentPropsWithoutRef<typeof SwitchPrimitive.Root>

/**
 * Base UI's switch, holding its own checked state so an agent can flip it the way a parent
 * would. Controlled use is unchanged, and `onCheckedChange` sees the agent's changes first
 * and can cancel them.
 */
const Switch = React.forwardRef<
  React.ComponentRef<typeof SwitchPrimitive.Root>,
  SwitchProps
>(({ className, checked: checkedProp, defaultChecked = false, onCheckedChange, ...props }, ref) => {
  const [checked, change] = useAgentState<boolean, SwitchPrimitive.Root.ChangeEventDetails>(
    checkedProp,
    defaultChecked,
    onCheckedChange
  )
  const element = React.useRef<HTMLElement | null>(null)
  const mergedRef = useMergedRef(ref, element)

  useAgentControl(() => {
    const set = (next: boolean) => {
      if (props.readOnly) return "The switch is read-only."
      return next === checked ? undefined : changeAsAgent(change, next)
    }
    return {
      kind: "switch",
      element: element.current,
      checked,
      disabled: props.disabled,
      actions: {
        toggle: () => set(!checked),
        setChecked: (value: unknown) => set(agentChecked(value)),
      },
    }
  })

  return (
  <span className="relative inline-flex [&>input]:!absolute">
    <SwitchPrimitive.Root
      ref={mergedRef}
      data-slot="switch"
      className={cn(
        "inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors duration-[var(--motion-duration-fast,150ms)]",
        "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
        "disabled:cursor-not-allowed disabled:opacity-50",
        "data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50",
        "data-[checked]:bg-primary data-[unchecked]:bg-input",
        className
      )}
      {...props}
      checked={checked}
      onCheckedChange={change}
    />
  </span>
  )
})
Switch.displayName = "Switch"

const SwitchThumb = React.forwardRef<
  React.ComponentRef<typeof SwitchPrimitive.Thumb>,
  React.ComponentPropsWithoutRef<typeof SwitchPrimitive.Thumb>
>(({ className, ...props }, ref) => (
  <SwitchPrimitive.Thumb
    ref={ref}
    data-slot="switch-thumb"
    className={cn(
      "pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0",
      "transition-transform duration-[var(--motion-duration-fast,150ms)] ease-[var(--motion-ease-out,cubic-bezier(0.23,1,0.32,1))]",
      "motion-reduce:transition-none",
      "data-[checked]:translate-x-5 data-[unchecked]:translate-x-0",
      "data-[disabled]:opacity-80",
      className
    )}
    {...props}
  />
))
SwitchThumb.displayName = "SwitchThumb"

export { Switch, SwitchThumb }
```
