# Switch

A control that allows the user to toggle between checked and not checked.

Source: https://webjs.dev/ui/docs/components/switch

```ts
import { html } from '@webjsdev/core';
import { labelClass } from '#components/ui/label.ts';

export default function SwitchDemo() {
  return html`
    <div class="flex items-center space-x-2">
      <ui-switch input-id="airplane-mode"></ui-switch>
      <label data-slot="label" for="airplane-mode" class=${labelClass()}>Airplane Mode</label>
    </div>
  `;
}
```

## Installation

```bash
npx @webjsdev/ui add switch
```

### Copy and paste the following code into your project.

````ts title="components/ui/switch.ts"
/**
 * Switch: toggle styled as a sliding pill. Tier-1 class helpers. A
 * hidden native `<input type="checkbox" role="switch">` handles form
 * submission + keyboard; a sibling `<span>` provides the visual track +
 * thumb (positioned via the `peer-checked:` variant).
 *
 * shadcn parity:
 *   Switch (size: default | sm)  → <ui-switch size checked name value disabled
 *                                   required aria-label input-id>, which renders
 *                                   shadcn's switch (a `data-slot="switch"` root
 *                                   and a `switch-thumb`) around a real checkbox,
 *                                   so every shadcn style draws it
 *                                 → or, as plain markup, switchInputClass() on a
 *                                   hidden <input> + switchTrackClass({ size }) on
 *                                   a sibling <span> (the default style only)
 *
 * <ui-switch> renders on the server too: its checkbox is a real form control
 * laid transparent over the track, so it submits, takes a <label>, and toggles
 * with JavaScript off. `data-state` follows it, and the data-checked variant
 * also reads the native state (a switch root whose own checkbox is checked, a
 * thumb after a checked checkbox), so the look follows the control without
 * script too. `ui-checked-change` reports a change ({ detail: { checked } }).
 *
 * Design tokens used: --primary, --input, --background, --foreground, --ring,
 * --primary-foreground.
 *
 * A11y (required for accessible output):
 *   Keep `role="switch"` on the native checkbox. That is what makes a screen
 *   reader announce "on / off" rather than "checked / unchecked", and the
 *   browser maps the input's checked state to it for free.
 *   NAME IT. The visible track is a `<span>` and the real control is `sr-only`,
 *   so there is no text on the input at all. Wrapping the whole thing in a
 *   `<label>` (the first example) is the simplest way, since the label's text
 *   then names the input. A STANDALONE switch, one with no wrapping `<label>`
 *   and no `<label for>` pointing at it, has NO accessible name and needs an
 *   explicit `aria-label`, as the second example shows.
 *   The visual track and thumb are presentation only. They carry no text and no
 *   role, so nothing about the state reaches assistive tech through them: it all
 *   comes from the input. Do not move the name onto the track.
 *   Use `disabled` on the input, not on the track: the track styles itself from
 *   the `peer-disabled:` variant, and only the real control can refuse input.
 *
 * @example
 * ```html
 * <ui-switch name="airplane" aria-label="Airplane mode" checked></ui-switch>
 *
 * <!-- With a visible label, which names the switch. -->
 * <label class="inline-flex items-center gap-2">
 *   <ui-switch name="notify"></ui-switch> Notifications
 * </label>
 *
 * <!-- The helpers, for a plain-markup switch. -->
 * <label class="inline-flex items-center gap-2">
 *   <input type="checkbox" role="switch" name="notify" class=${switchInputClass()}>
 *   <span class=${switchTrackClass()}></span>
 *   <span class=${labelClass()}>Notifications</span>
 * </label>
 *
 * <!-- Standalone (no wrapping label), so the name has to be explicit. -->
 * <input type="checkbox" role="switch" name="wifi" aria-label="Wi-Fi"
 *        class=${switchInputClass()}>
 * <span class=${switchTrackClass()}></span>
 *
 * <!-- Small size. -->
 * <input type="checkbox" role="switch" name="x" aria-label="Compact mode"
 *        class=${cn(switchInputClass(), 'peer/sm')}>
 * <span class=${switchTrackClass({ size: 'sm' })}></span>
 * ```
 */
import { WebComponent, html, prop, nothing } from '@webjsdev/core';
import { cn } from '../lib/utils.ts';

/** Hidden native checkbox: handles form value + keyboard activation. */
export const switchInputClass = (): string => 'peer sr-only';

const TRACK_BASE =
  'shrink-0 cursor-pointer rounded-full border border-transparent shadow-xs peer-focus-visible:border-ring peer-focus-visible:ring-[3px] peer-focus-visible:ring-ring/50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50 bg-input dark:bg-input/80 peer-checked:bg-primary data-checked:bg-primary peer group/switch inline-flex items-center transition-all outline-none relative';

const TRACK_SIZES = {
  default: 'h-[1.15rem] w-8',
  sm: 'h-3.5 w-6',
} as const;

const THUMB_SIZES = {
  default: 'after:size-4 after:translate-x-px rtl:after:-translate-x-px peer-checked:after:translate-x-[calc(100%-2px)] rtl:peer-checked:after:-translate-x-[calc(100%-2px)]',
  sm: 'after:size-3 after:translate-x-px rtl:after:-translate-x-px peer-checked:after:translate-x-[calc(100%-1px)] rtl:peer-checked:after:-translate-x-[calc(100%-1px)]',
} as const;

const THUMB_BASE =
  'after:pointer-events-none after:absolute after:start-0 after:rounded-full after:bg-background after:transition-transform peer-checked:after:bg-primary-foreground dark:after:bg-foreground';

export type SwitchSize = keyof typeof TRACK_SIZES;

export function switchTrackClass(opts: { size?: SwitchSize } = {}): string {
  const size = opts.size ?? 'default';
  return cn(TRACK_BASE, TRACK_SIZES[size], THUMB_BASE, THUMB_SIZES[size]);
}

// --------------------------------------------------------------------------
// <ui-switch>
// --------------------------------------------------------------------------

/**
 * shadcn's Switch: a root and a thumb around a real checkbox. The authored
 * attributes that belong to the control (`name`, `value`, `checked`,
 * `disabled`, `required`, `aria-label`, `aria-labelledby`,
 * `aria-describedby`, `aria-invalid`, and `input-id` for a `<label for>`) are
 * passed to it. `aria-invalid` also lands on the root, where every style draws
 * the error ring (shadcn's root is the control itself).
 */
export class UiSwitch extends WebComponent({
  size: prop<SwitchSize>(String, { reflect: true }),
  checked: prop(Boolean),
  disabled: prop(Boolean),
  required: prop(Boolean),
  name: prop(String),
  value: prop(String),
  inputId: prop(String, { attribute: 'input-id' }),
  // Observed so a re-validation that sets or clears it re-renders the switch.
  invalid: prop(String, { attribute: 'aria-invalid' }),
}) {
  constructor() {
    super();
    this.size = 'default';
    this.checked = false;
    this.disabled = false;
    this.required = false;
    this.name = '';
    this.value = '';
    this.inputId = '';
    this.invalid = '';
  }

  _attr(name: string): string | null {
    return typeof this.getAttribute === 'function' ? this.getAttribute(name) : null;
  }

  _onChange = (e: Event): void => {
    const input = e.target as HTMLInputElement;
    this.checked = input.checked;
    this.dispatchEvent(new CustomEvent('ui-checked-change', { detail: { checked: input.checked }, bubbles: true }));
  };

  // The focus ring sits on the root and keys on the checkbox inside having
  // keyboard focus: in shadcn the focused element IS the root (a Radix
  // button), here it is the real checkbox the root contains.
  // The root is the box, as shadcn's root (a Radix button) is: a flex item
  // its row centres. A block host around it added a line box of its own and
  // sat the switch a few pixels high, so the host is display: contents,
  // through its style, which the server serves.
  render() {
    if (typeof this.getAttribute === 'function' && !this.getAttribute('style')) this.setAttribute('style', 'display: contents');
    const size = this.size === 'sm' ? 'sm' : 'default';
    const state = this.checked ? 'checked' : 'unchecked';
    return html`<span
      data-slot="switch"
      data-size=${size}
      data-state=${state}
      aria-invalid=${this.invalid === 'true' ? 'true' : nothing}
      ?data-disabled=${this.disabled}
      class=${cn('shrink-0 cursor-pointer rounded-full border border-transparent shadow-xs peer-focus-visible:border-ring peer-focus-visible:ring-[3px] peer-focus-visible:ring-ring/50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50 bg-input dark:bg-input/80 peer-checked:bg-primary data-checked:bg-primary peer group/switch relative inline-flex items-center transition-all outline-none after:absolute after:-inset-x-3 after:-inset-y-2 data-disabled:cursor-not-allowed data-disabled:opacity-50 has-[>input:focus-visible]:ring-[3px] has-[>input:focus-visible]:ring-ring/50', TRACK_SIZES[size])}
    ><input
      type="checkbox"
      role="switch"
      id=${this.inputId || nothing}
      name=${this.name || nothing}
      value=${this.value || nothing}
      ?checked=${this.checked}
      ?disabled=${this.disabled}
      ?required=${this.required}
      aria-label=${this._attr('aria-label') ?? nothing}
      aria-labelledby=${this._attr('aria-labelledby') ?? nothing}
      aria-describedby=${this._attr('aria-describedby') ?? nothing}
      aria-invalid=${this.invalid === 'true' ? 'true' : nothing}
      class="peer absolute inset-0 z-10 m-0 size-full cursor-pointer appearance-none opacity-0 disabled:cursor-not-allowed"
      @change=${this._onChange}
    ><span
      data-slot="switch-thumb"
      data-state=${state}
      class=${cn('after:pointer-events-none after:absolute after:start-0 after:rounded-full after:bg-background after:transition-transform peer-checked:after:bg-primary-foreground dark:after:bg-foreground size-4 rounded-full bg-background translate-x-px rtl:-translate-x-px data-checked:translate-x-[calc(100%-2px)] rtl:data-checked:-translate-x-[calc(100%-2px)] dark:bg-foreground dark:data-checked:bg-primary-foreground group-data-[size=sm]/switch:size-3 group-data-[size=sm]/switch:data-checked:translate-x-[calc(100%-1px)] rtl:group-data-[size=sm]/switch:data-checked:-translate-x-[calc(100%-1px)] after:hidden pointer-events-none block ring-0 transition-transform', THUMB_SIZES[size])}
    ></span></span>`;
  }
}
UiSwitch.register('ui-switch');
````

### Update the import paths to match your project setup.

## Usage

```ts
import '#components/ui/switch.ts';
```

```ts
<ui-switch aria-label="Airplane mode"></ui-switch>
```

## Description

```ts
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import {
  fieldClass, fieldContentClass, fieldLabelClass, fieldDescriptionClass,
} from '#components/ui/field.ts';

export default function SwitchDescription() {
  return html`
    <div role="group" data-slot="field" data-orientation="horizontal" class=${cn(fieldClass({ orientation: 'horizontal' }), 'max-w-sm')}>
      <div data-slot="field-content" class=${fieldContentClass()}>
        <label data-slot="field-label" for="switch-focus-mode" class=${fieldLabelClass()}>
          Share across devices
        </label>
        <p data-slot="field-description" class=${fieldDescriptionClass()}>
          Focus is shared across devices, and turns off when you leave the app.
        </p>
      </div>
      <ui-switch input-id="switch-focus-mode"></ui-switch>
    </div>
  `;
}
```

## Choice Card

Card-style selection where the field label wraps the entire field for a clickable card pattern.

```ts
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import {
  fieldGroupClass, fieldClass, fieldContentClass, fieldLabelClass,
  fieldTitleClass, fieldDescriptionClass,
} from '#components/ui/field.ts';

// The whole card is the <label>, so a click anywhere on it flips the switch.
export default function SwitchChoiceCard() {
  return html`
    <div data-slot="field-group" class=${cn(fieldGroupClass(), 'w-full max-w-sm')}>
      <label data-slot="field-label" for="switch-share" class=${fieldLabelClass()}>
        <div role="group" data-slot="field" data-orientation="horizontal" class=${fieldClass({ orientation: 'horizontal' })}>
          <div data-slot="field-content" class=${fieldContentClass()}>
            <div data-slot="field-label" class=${fieldTitleClass()}>Share across devices</div>
            <p data-slot="field-description" class=${fieldDescriptionClass()}>
              Focus is shared across devices, and turns off when you leave the
              app.
            </p>
          </div>
          <ui-switch input-id="switch-share"></ui-switch>
        </div>
      </label>
      <label data-slot="field-label" for="switch-notifications" class=${fieldLabelClass()}>
        <div role="group" data-slot="field" data-orientation="horizontal" class=${fieldClass({ orientation: 'horizontal' })}>
          <div data-slot="field-content" class=${fieldContentClass()}>
            <div data-slot="field-label" class=${fieldTitleClass()}>Enable notifications</div>
            <p data-slot="field-description" class=${fieldDescriptionClass()}>
              Receive notifications when focus mode is enabled or disabled.
            </p>
          </div>
          <ui-switch input-id="switch-notifications" checked></ui-switch>
        </div>
      </label>
    </div>
  `;
}
```

## Disabled

Add the `disabled` attribute to `<ui-switch>` to disable the switch. Add the `data-disabled` attribute to the field for styling.

```ts
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { fieldClass, fieldLabelClass } from '#components/ui/field.ts';

export default function SwitchDisabled() {
  return html`
    <div role="group" data-slot="field" data-orientation="horizontal" data-disabled="true" class=${cn(fieldClass({ orientation: 'horizontal' }), 'w-fit')}>
      <ui-switch input-id="switch-disabled-unchecked" disabled></ui-switch>
      <label data-slot="field-label" for="switch-disabled-unchecked" class=${fieldLabelClass()}>Disabled</label>
    </div>
  `;
}
```

## Invalid

Add the `aria-invalid` attribute to `<ui-switch>` to indicate an invalid state. Add the `data-invalid` attribute to the field for styling.

```ts
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import {
  fieldClass, fieldContentClass, fieldLabelClass, fieldDescriptionClass,
} from '#components/ui/field.ts';

export default function SwitchInvalid() {
  return html`
    <div role="group" data-slot="field" data-orientation="horizontal" data-invalid="true" class=${cn(fieldClass({ orientation: 'horizontal' }), 'max-w-sm')}>
      <div data-slot="field-content" class=${fieldContentClass()}>
        <label data-slot="field-label" for="switch-terms" class=${fieldLabelClass()}>
          Accept terms and conditions
        </label>
        <p data-slot="field-description" class=${fieldDescriptionClass()}>
          You must accept the terms and conditions to continue.
        </p>
      </div>
      <ui-switch input-id="switch-terms" aria-invalid="true"></ui-switch>
    </div>
  `;
}
```

## Size

Use the `size` attribute to change the size of the switch.

```ts
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { fieldGroupClass, fieldClass, fieldLabelClass } from '#components/ui/field.ts';

export default function SwitchSizes() {
  return html`
    <div data-slot="field-group" class=${cn(fieldGroupClass(), 'w-full max-w-[10rem]')}>
      <div role="group" data-slot="field" data-orientation="horizontal" class=${fieldClass({ orientation: 'horizontal' })}>
        <ui-switch input-id="switch-size-sm" size="sm"></ui-switch>
        <label data-slot="field-label" for="switch-size-sm" class=${fieldLabelClass()}>Small</label>
      </div>
      <div role="group" data-slot="field" data-orientation="horizontal" class=${fieldClass({ orientation: 'horizontal' })}>
        <ui-switch input-id="switch-size-default" size="default"></ui-switch>
        <label data-slot="field-label" for="switch-size-default" class=${fieldLabelClass()}>Default</label>
      </div>
    </div>
  `;
}
```

## RTL

To enable RTL support, see the [RTL configuration guide](https://webjs.dev/ui/docs/rtl).

```ts
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import {
  fieldClass, fieldContentClass, fieldLabelClass, fieldDescriptionClass,
} from '#components/ui/field.ts';

const translations = {
  en: {
    dir: 'ltr',
    values: {
      label: 'Share across devices',
      description:
        'Focus is shared across devices, and turns off when you leave the app.',
    },
  },
  ar: {
    dir: 'rtl',
    values: {
      label: 'المشاركة عبر الأجهزة',
      description:
        'يتم مشاركة التركيز عبر الأجهزة، ويتم إيقاف تشغيله عند مغادرة التطبيق.',
    },
  },
  he: {
    dir: 'rtl',
    values: {
      label: 'שיתוף בין מכשירים',
      description: 'המיקוד משותף בין מכשירים, וכבה כשאתה עוזב את האפליקציה.',
    },
  },
};

export default function SwitchRtl() {
  const lang = 'ar';
  const { dir, values: t } = translations[lang];

  return html`
    <div role="group" data-slot="field" data-orientation="horizontal" dir=${dir} lang=${lang} class=${cn(fieldClass({ orientation: 'horizontal' }), 'max-w-sm')}>
      <div data-slot="field-content" class=${fieldContentClass()}>
        <label data-slot="field-label" for="switch-focus-mode-rtl" class=${fieldLabelClass()}>
          ${t.label}
        </label>
        <p data-slot="field-description" class=${fieldDescriptionClass()}>${t.description}</p>
      </div>
      <ui-switch input-id="switch-focus-mode-rtl"></ui-switch>
    </div>
  `;
}
```

## API Reference

### ui-switch

`<ui-switch>` renders a switch, a root and a thumb, around a real `<input type="checkbox" role="switch">`. The checkbox is rendered on the server, so the switch submits with its form, takes a `<label for>`, and toggles with JavaScript off.

| Attribute | Type | Default |
| --- | --- | --- |
| `size` | `"default" \| "sm"` | `"default"` |
| `checked` | `boolean` | `false` |
| `disabled` | `boolean` | `false` |
| `required` | `boolean` | `false` |
| `name` | `string` | - |
| `value` | `string` | - |
| `input-id` | `string` | - |

`input-id` becomes the checkbox's `id`, for a `<label for>`. `aria-label`, `aria-labelledby` and `aria-describedby` on the element are passed to the checkbox. A switch with no label pointing at it needs an `aria-label`.

| Event | Detail |
| --- | --- |
| `ui-checked-change` | `{ checked: boolean }` |

### switchInputClass and switchTrackClass

For a switch as plain markup, put `switchInputClass()` on a hidden `<input type="checkbox" role="switch">` and `switchTrackClass({ size })` on the `<span>` after it. `size` is `"default"` or `"sm"`.
