# Switch

A glass switch for a setting that takes effect at once: the capsule knob springs across, turns into a clear lens while held, and puts itself back if the save fails.

Tier: free. Type: component. Category: selection. Tags: settings, permissions, motion.

## Install

```bash
npx shadcn@latest add https://pixilui.com/r/switch.json
```

One-time setup: add the registry to `components.json`:

```json
{
  "registries": {
    "@pixilui": "https://pixilui.com/r/{name}.json"
  }
}
```

Files: `components/pixilui/switch.tsx`.

## Preview

Live preview: https://pixilui.com/components/switch

Knobs:

- `save`: `instant`, `fails`

Signature: Hold the switch and the knob stretches toward where it will go and clears into a lens, so the color shows through before it springs across.

Styles: `lively` (default), `quiet`, set with `data-style` on <html>. The item reads the style through the foundation; it needs no prop. Standalone files: lively https://pixilui.com/r/standalone/switch.tsx, quiet https://pixilui.com/r/standalone/switch.quiet.tsx.

## Code

`components/pixilui/switch.tsx`

```tsx
"use client";

/*
  The switch, locked 27 Nov 2026 with the toggles (design/explorations/components/locked/toggles). Its
  look and motion are foundation.css section 8 (.pixilui-switch); this file writes the locked markup and
  plays the locked behavior (toggles.js):

  Track     a 44 x 20 pale glass track; on, the candy glass cross-fades in (200ms) with its edge and glow.
  Knob      a 24 x 16 glass capsule that crosses with a small overshoot (300ms); while pressed it widens
            4px toward where it will go and turns into a clear lens.
  Hover     an off switch shows a 22% wash of the color.
  Pending   onCheckedChange may return a promise: the switch shows the new state at once, is aria-busy
            until it settles, and goes back if it rejects. No spinner: the lock rejected it.
  Reduced   instant.
*/

import { forwardRef, useId, useState, type ComponentPropsWithoutRef, type MouseEvent, type ReactNode } from "react";
import { cn } from "./lib/utils";

export type SwitchProps = Omit<ComponentPropsWithoutRef<"button">, "onChange" | "value" | "defaultValue" | "children" | "role"> & {
  /** Controlled: on or off. */
  checked?: boolean;
  /** Uncontrolled: the state on the first render. */
  defaultChecked?: boolean;
  /**
   * Runs with the new state on a click, Space or Enter. Return a promise to save first: the switch shows the
   * new state, is aria-busy until it settles, and goes back if it rejects.
   */
  onCheckedChange?: (checked: boolean) => void | Promise<void>;
  /** A form field name: a hidden input carries value while the switch is on. */
  name?: string;
  /** The value sent with the form while on. */
  value?: string;
};

/** A setting that takes effect at once: a glass track whose capsule knob springs across. Give it an aria-label, or put it in a SwitchRow. */
export const Switch = forwardRef<HTMLButtonElement, SwitchProps>(function Switch(
  { checked, defaultChecked = false, onCheckedChange, name, value = "on", disabled, onClick, className, ...props },
  ref,
) {
  const [own, setOwn] = useState(defaultChecked);
  const [pending, setPending] = useState<boolean | null>(null);
  const shown = pending ?? checked ?? own;
  const flip = async (event: MouseEvent<HTMLButtonElement>) => {
    onClick?.(event);
    if (event.defaultPrevented || disabled || pending !== null) return;
    const next = !shown;
    if (checked === undefined) setOwn(next);
    const result = onCheckedChange?.(next);
    if (!result || typeof (result as Promise<void>).then !== "function") return;
    setPending(next);
    try {
      await result;
    } catch {
      if (checked === undefined) setOwn(!next);
    } finally {
      setPending(null);
    }
  };
  return (
    <>
      <button
        ref={ref}
        type="button"
        role="switch"
        aria-checked={shown ? "true" : "false"}
        aria-busy={pending !== null || undefined}
        disabled={disabled}
        className={cn("pixilui-switch focus-visible:focus-ring", className)}
        onClick={flip}
        {...props}
      >
        <span className="pixilui-switch-knob" aria-hidden="true" />
      </button>
      {name && shown && <input type="hidden" name={name} value={value} />}
    </>
  );
});

export type SwitchRowProps = SwitchProps & {
  /** The row's label: names the switch, and a click on it reaches the switch. */
  label: ReactNode;
  /** A second line under the label. */
  description?: ReactNode;
  /** Sets the second line in the warning color, for a setting with a cost. */
  risk?: boolean;
  /** Class for the row (className goes to the switch). */
  rowClassName?: string;
};

/** A setting row: the label and its second line on the left, the switch on the right; the whole row clicks. */
export const SwitchRow = forwardRef<HTMLButtonElement, SwitchRowProps>(function SwitchRow(
  { label, description, risk, rowClassName, "aria-label": ariaLabel, ...props },
  ref,
) {
  const id = useId();
  return (
    <label className={cn("pixilui-toggle-row font-body", rowClassName)} data-align="end">
      <span className="pixilui-toggle-row-text">
        <b>{label}</b>
        {description && (
          <small id={`${id}-d`} data-tone={risk ? "risk" : undefined}>
            {description}
          </small>
        )}
      </span>
      <Switch ref={ref} aria-label={ariaLabel ?? (typeof label === "string" ? label : undefined)} aria-describedby={description ? `${id}-d` : undefined} {...props} />
    </label>
  );
});
```

## Usage

When to use:

- A setting that applies the moment it flips: alerts, retries, sharing.
- A settings list, label and second line on the left, the switch on the right (SwitchRow).

When not to use:

- A choice saved later with a form's submit: use Checkbox.
- One choice among several: use Radio group or a segmented control.

```tsx
import { useState } from "react";
import { SwitchRow } from "@/components/pixilui/switch";

// The first option of each knob is the demo's default; the docs preview starts there.
export const knobs = {
  save: ["instant", "fails"],
} as const;

const settings = [
  { id: "alerts", label: "Approval alerts", note: "Tell me when a run is waiting on me", on: true },
  { id: "summary", label: "Weekly usage summary", note: "Every Monday at 9:00 am", on: false },
  { id: "retry", label: "Retry failed runs", note: "Up to 2 times, then it waits for you", on: true },
  { id: "share", label: "Share runs with the workspace", note: "Your admin turned this off", on: false, disabled: true },
];

/** A notifications card; "fails" makes every save reject after 700ms so the switch puts itself back. */
export default function SwitchDemo({ save = "instant" }: KnobValues<typeof knobs>) {
  return (
    <div className="w-full max-w-md rounded-panel bg-surface px-5 py-3 elevation-raised">
      {settings.map((s) => (
        <Setting key={`${s.id}-${save}`} {...s} fails={save === "fails"} />
      ))}
    </div>
  );
}

function Setting({ label, note, on, disabled, fails }: { id: string; label: string; note: string; on: boolean; disabled?: boolean; fails: boolean }) {
  const [checked, setChecked] = useState(on);
  return (
    <SwitchRow
      label={label}
      description={note}
      disabled={disabled}
      checked={checked}
      onCheckedChange={(next) => {
        if (!fails) return setChecked(next);
        return new Promise<void>((_, reject) => setTimeout(() => reject(new Error("Not saved")), 700));
      }}
    />
  );
}
```

## Examples

None.

## API

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `name` | `string` |  | A form field name: a hidden input carries value while the switch is on. |
| `defaultChecked` | `boolean` | `false` | Uncontrolled: the state on the first render. |
| `checked` | `boolean` |  | Controlled: on or off. |
| `onCheckedChange` | `(checked: boolean) => void \| Promise<void>` |  | Runs with the new state on a click, Space or Enter. Return a promise to save first: the switch shows the new state, is aria-busy until it settles, and goes back if it rejects. |
| `value` | `string` | `"on"` | The value sent with the form while on. |

Also accepts every native `<button>` attribute except `onChange`, `value`, `defaultValue`, `role`, and a ref to it.

## Keyboard

- `Tab`: Moves to each switch in turn.
- `Space` + `Enter`: Flips the focused switch.

## Accessibility

- A button with role="switch" and aria-checked.
- In a SwitchRow the label names it and the second line describes it (aria-describedby); alone, give it an aria-label.
- The row is a label, so a click on the words flips it once.
- While a returned promise is pending the switch is aria-busy and keeps its focus.

## Motion

- The knob crosses in 300ms with a small overshoot; the candy glass cross-fades in over 200ms with its edge and glow.
- Held, the knob widens 4px toward where it will go and turns into a clear lens in 150ms.
- Hover on an off switch shows a 22% wash of the color.
- Reduced motion: instant.

## Responsive

- 44 by 20 at every width; a row's words wrap and the switch stays at the end.

## Performance

- The look and motion are CSS in the foundation (section 8); the component writes one button and the knob.

## Notes for AI

- <SwitchRow label="Retry failed runs" description="Up to 2 times, then it waits for you" checked={on} onCheckedChange={save} />.
- Return a promise from onCheckedChange to save: the switch flips at once and flips back if it rejects. There is no spinner by design.
- Alone, <Switch aria-label="Approval alerts" />.
- Pass name (and value) to send it with a native form.

## Related

- [Checkbox](https://pixilui.com/components/checkbox/markdown): A glass checkbox whose tick draws itself, with a mixed state for a parent, rows that click anywhere, and a save that can fail and put itself back.
- [Radio group](https://pixilui.com/components/radio-group/markdown): One choice among a few, as glass radio rows whose white bead springs in, with arrow keys that skip what can't be picked and a risky option set in the warning color.
- [Segmented control](https://pixilui.com/components/segmented-control/markdown): One choice from two to five on a grey track: the picked pill slides to your next pick, its words changing color as it passes, and a time-boxed option says when it ends and switches back.
