# Switch

> An on/off setting that takes effect immediately, with a loading state.

```tsx title="hero.tsx"
import { Field, FieldDescription, FieldLabel } from '@langgenius/dify-ui/field'
import { Switch } from '@langgenius/dify-ui/switch'

const features = [
  {
    name: 'suggestedQuestions',
    label: 'Follow-up suggestions',
    description: 'Suggest three questions after each answer.',
    enabled: true,
  },
  {
    name: 'citations',
    label: 'Citations',
    description: 'Show the knowledge sources behind each answer.',
    enabled: false,
  },
  {
    name: 'speechToText',
    label: 'Speech to text',
    description: 'Let users dictate messages with their microphone.',
    enabled: true,
  },
]

export function SwitchHeroDemo() {
  return (
    <div className="flex w-full max-w-sm flex-col divide-y divide-divider-subtle">
      {features.map((feature) => (
        <Field key={feature.name} name={feature.name} className="gap-0.5 py-3 first:pt-0 last:pb-0">
          <FieldLabel className="flex w-full items-center justify-between gap-4">
            {feature.label}
            <Switch defaultChecked={feature.enabled} />
          </FieldLabel>
          <FieldDescription>{feature.description}</FieldDescription>
        </Field>
      ))}
    </div>
  )
}
```

## Usage guidelines

- Use `Switch` for an on/off setting that takes effect immediately. Use `Checkbox` for a boolean value saved with its form, and `Toggle` for the pressed state of a button.
- Label the switch with a visible `FieldLabel` that wraps it. Use `aria-label` only when no visible label exists.
- When the change is saved remotely, control `checked` and set `loading` while the request is pending. `loading` blocks interaction, sets `aria-busy` and shows a spinner at `md` and `lg` sizes; update `checked` once the save succeeds.
- While the saved value itself is still loading, render `SwitchSkeleton` at the same `size` instead of a switch with a guessed value.
- Use `disabled` for a setting the user cannot change, and say why in `FieldDescription`.
- `Switch` takes either `checked` or `defaultChecked`, not both.

## Anatomy

```tsx
import { Field, FieldDescription, FieldLabel } from '@langgenius/dify-ui/field'
import { Switch, SwitchSkeleton } from '@langgenius/dify-ui/switch'
```

```tsx
<Field>
  <FieldLabel>
    Label
    <Switch />
  </FieldLabel>
  <FieldDescription />
</Field>
```

`Switch` renders its own thumb and loading spinner. `SwitchSkeleton` is a standalone placeholder with the same sizes.

## Examples

### Sizes

`xs`, `sm`, `md` (the default) and `lg` match the density of the surrounding row.

```tsx title="sizes.tsx"
import { Field, FieldLabel } from '@langgenius/dify-ui/field'
import { Switch } from '@langgenius/dify-ui/switch'

const sizes = ['xs', 'sm', 'md', 'lg'] as const

export function SwitchSizesDemo() {
  return (
    <div className="flex flex-wrap items-center gap-x-6 gap-y-3">
      {sizes.map((size) => (
        <Field key={size} name={`switch-${size}`}>
          <FieldLabel className="flex items-center gap-2">
            <Switch size={size} defaultChecked />
            {size}
          </FieldLabel>
        </Field>
      ))}
    </div>
  )
}
```

### Loading

The switch keeps its current value and ignores further presses while the change is saved. It moves only when the save succeeds; a failed save leaves it in place and shows the error. The first attempt in this demo fails.

```tsx title="loading.tsx"
import { Field, FieldDescription, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { Switch } from '@langgenius/dify-ui/switch'
import * as React from 'react'

export function SwitchLoadingDemo() {
  const [enabled, setEnabled] = React.useState(false)
  const [pending, setPending] = React.useState(false)
  const [saveFailed, setSaveFailed] = React.useState(false)
  const attemptsRef = React.useRef(0)
  const timerRef = React.useRef<ReturnType<typeof setTimeout> | undefined>(undefined)

  React.useEffect(() => {
    return () => clearTimeout(timerRef.current)
  }, [])

  function handleCheckedChange(nextEnabled: boolean) {
    if (pending) return
    attemptsRef.current += 1
    const shouldFail = attemptsRef.current === 1
    setSaveFailed(false)
    setPending(true)

    clearTimeout(timerRef.current)
    timerRef.current = setTimeout(() => {
      setPending(false)
      if (shouldFail) {
        setSaveFailed(true)
      } else {
        setEnabled(nextEnabled)
      }
    }, 1200)
  }

  return (
    <Field name="webAppAccess" invalid={saveFailed} className="w-full max-w-sm gap-0.5">
      <FieldLabel className="flex w-full items-center justify-between gap-4">
        Public web app
        <Switch checked={enabled} loading={pending} onCheckedChange={handleCheckedChange} />
      </FieldLabel>
      <FieldDescription>Anyone with the link can chat with this app.</FieldDescription>
      <FieldError match={saveFailed}>The change was not saved. Try again.</FieldError>
    </Field>
  )
}
```

### Skeleton

Render `SwitchSkeleton` at the matching `size` while the saved preference is still loading, rather than guessing an initial value.

```tsx title="skeleton.tsx"
import { Field, FieldDescription, FieldLabel } from '@langgenius/dify-ui/field'
import { Switch, SwitchSkeleton } from '@langgenius/dify-ui/switch'

export function SwitchSkeletonDemo() {
  return (
    <div className="flex w-full max-w-sm flex-col divide-y divide-divider-subtle">
      <Field name="citations" className="gap-0.5 pb-3">
        <FieldLabel className="flex w-full items-center justify-between gap-4">
          Citations
          <Switch defaultChecked />
        </FieldLabel>
        <FieldDescription>Show the knowledge sources behind each answer.</FieldDescription>
      </Field>
      <div className="grid gap-0.5 pt-3">
        <div className="flex items-center justify-between gap-4">
          <span className="py-1 system-sm-medium text-text-secondary">Speech to text</span>
          <SwitchSkeleton aria-hidden="true" className="animate-pulse motion-reduce:animate-none" />
        </div>
        <p className="py-0.5 body-xs-regular text-text-tertiary">Loading saved setting…</p>
      </div>
    </div>
  )
}
```

### Disabled

Set `disabled` on `Field` to disable the switch and its label together.

```tsx title="disabled.tsx"
import { Field, FieldDescription, FieldLabel } from '@langgenius/dify-ui/field'
import { Switch } from '@langgenius/dify-ui/switch'

export function SwitchDisabledDemo() {
  return (
    <div className="flex w-full max-w-sm flex-col divide-y divide-divider-subtle">
      <Field name="ssoEnforced" disabled className="gap-0.5 pb-3">
        <FieldLabel className="flex w-full items-center justify-between gap-4">
          Enforce SSO sign-in
          <Switch defaultChecked />
        </FieldLabel>
        <FieldDescription>Only workspace owners can change this setting.</FieldDescription>
      </Field>
      <Field name="memberInvites" disabled className="gap-0.5 pt-3">
        <FieldLabel className="flex w-full items-center justify-between gap-4">
          Invite members by email
          <Switch defaultChecked={false} />
        </FieldLabel>
        <FieldDescription>Available on the Team plan.</FieldDescription>
      </Field>
    </div>
  )
}
```

## Keyboard

| Key     | Action                                                         |
| ------- | -------------------------------------------------------------- |
| `Space` | Toggles the focused switch.                                    |
| `Enter` | Toggles the focused switch.                                    |
| `Tab`   | Moves focus to the next control. A disabled switch is skipped. |

## API reference

### Switch

A toggle switch control supporting controlled, uncontrolled, and loading states. Renders a `<span>` element and a hidden `<input>` beside.

Pair with a visible `FieldLabel` or `<label>`; setting `loading` disables interaction, sets `aria-busy`, and shows a spinner at `md` and `lg` sizes.

**Props**

| Prop              | Type                           | Default | Description                                                                                                                      |
| ----------------- | ------------------------------ | ------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `size?`           | `'lg' \| 'md' \| 'sm' \| 'xs'` | `'md'`  | The size of the switch.                                                                                                          |
| `defaultChecked?` | `boolean`                      | `false` | Whether the switch is initially active. To render a controlled switch, use the `checked` prop instead.                           |
| `checked?`        | `boolean`                      | —       | Whether the switch is currently active. To render an uncontrolled switch, use the `defaultChecked` prop instead.                 |
| `loading?`        | `boolean`                      | `false` | Whether the switch shows a pending state. Disables interaction and sets `aria-busy`; a spinner shows at the `md` and `lg` sizes. |

Valid prop combinations:

- `defaultChecked?: boolean`, `checked?: undefined`
- `checked: boolean`, `defaultChecked?: undefined`

Inherits `className`, `render`, `style`, `nativeButton`, `id`, `disabled`, `inputRef`, `name`, `form`, `onCheckedChange`, `readOnly`, `required`, `value`, `uncheckedValue` from [Base UI Switch.Root](https://base-ui.com/react/components/switch#root).

**Data attributes**

| Attribute        | Description                                                                  |
| ---------------- | ---------------------------------------------------------------------------- |
| `data-checked`   | Present when the switch is checked.                                          |
| `data-unchecked` | Present when the switch is not checked.                                      |
| `data-disabled`  | Present when the switch is disabled.                                         |
| `data-readonly`  | Present when the switch is readonly.                                         |
| `data-required`  | Present when the switch is required.                                         |
| `data-valid`     | Present when the switch is in a valid state (when wrapped in Field.Root).    |
| `data-invalid`   | Present when the switch is in an invalid state (when wrapped in Field.Root). |
| `data-touched`   | Present when the switch has been touched (when wrapped in Field.Root).       |
| `data-dirty`     | Present when the switch's value has changed (when wrapped in Field.Root).    |
| `data-filled`    | Present when the switch is active (when wrapped in Field.Root).              |
| `data-focused`   | Present when the switch is focused (when wrapped in Field.Root).             |

### SwitchSkeleton

**Props**

| Prop    | Type                           | Default | Description                                        |
| ------- | ------------------------------ | ------- | -------------------------------------------------- |
| `size?` | `'lg' \| 'md' \| 'sm' \| 'xs'` | `'md'`  | The size of the switch the skeleton stands in for. |
