# Toggle

A two-state button that can be either on or off.

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

```ts
import { html } from '@webjsdev/core';
import { BookmarkIcon } from '#lib/ui/lucide.ts';

export default function ToggleDemo() {
  return html`
    <ui-toggle aria-label="Toggle bookmark" size="sm" variant="outline">
      ${BookmarkIcon('group-data-[state=on]/toggle:fill-foreground')}
      Bookmark
    </ui-toggle>
  `;
}
```

## Installation

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

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

````ts title="components/ui/toggle.ts"
/**
 * Toggle: pressable on / off button. Ships both as a Tier-1 class helper
 * (for callers that want to own pressed state on a native `<button>`)
 * and as the Tier-2 `<ui-toggle>` custom element (for callers that want
 * state managed for them).
 *
 * shadcn parity:
 *   Toggle (variant: default | outline)
 *          (size:    default | sm | lg)
 *                                 → toggleClass({ variant, size })  (class helper)
 *                                 → <ui-toggle pressed variant size>  (custom element)
 *
 * Attributes on <ui-toggle>:
 *   `pressed`:  boolean (reflected). Active state.
 *   `variant`:  "default" (default) | "outline".
 *   `size`:     "default" (default) | "sm" | "lg".
 *   `disabled`: boolean (reflected). Disables click + focus.
 *
 * Events:
 *   `ui-pressed-change` on <ui-toggle>: `{ detail: { pressed } }` after a click.
 *
 * Keyboard: native button. Enter / Space activates (via the inner <button>).
 *
 * A11y (required for accessible output):
 *   `<ui-toggle>` renders a native `<button>` inside itself, and that button is
 *   the focusable control whose accessible name a screen reader announces. An
 *   `aria-label` on the host would not reach it (a name on a generic-role
 *   element does not contribute to a descendant's name), so the element
 *   FORWARDS the host's `aria-label` / `aria-labelledby` onto the inner button.
 *   Put the name on the host, as the icon-only example below does, and the
 *   element wires the rest. An icon-only toggle needs one; a text toggle takes
 *   its name from the slotted text and needs nothing.
 *   Set the name as an ATTRIBUTE on the host in your markup
 *   (`aria-label="Toggle bold"`), not as a property.
 *   LIMITATION, and it is a real one: `aria-label` / `aria-labelledby` are not
 *   reactive properties of this element, so they are not observed attributes.
 *   The name is read during render(), which means markup present at first paint
 *   works, but a LATER `el.setAttribute('aria-label', ...)` does not re-render
 *   and so does not reach the inner button until something else happens to
 *   trigger a render. If your name is computed after mount, set it on the inner
 *   button yourself (`el.querySelector('button').setAttribute('aria-label',
 *   name)`). Do NOT reach for "flip a reactive prop to force a re-render":
 *   adding or removing the name switches which of the three templates below is
 *   used, and a template swap REBUILDS the button, so doing it on a click would
 *   destroy the control the user is focused on and drop focus to <body>.
 *   Using the Tier-1 `toggleClass()` helper on your own `<button>` instead? Then
 *   the name is entirely yours: give an icon-only button an `aria-label`, and
 *   carry the pressed state on `aria-pressed` + `data-state` as the example does.
 *
 * Design tokens used: --muted, --muted-foreground, --accent, --accent-foreground,
 * --input, --background, --ring, --destructive.
 *
 * @example
 * ```html
 * <!-- Tier-1 class helper, caller owns state. -->
 * <button class=${toggleClass()} data-state="off" aria-pressed="false"
 *         onclick="this.dataset.state = this.dataset.state==='on'?'off':'on'">
 *   <svg class="size-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M14 12a4 4 0 0 0 0-8H6v8" /><path d="M15 20a4 4 0 0 0 0-8H6v8Z" /></svg>
 * </button>
 *
 * <!-- Tier-2 custom element, state managed. -->
 * <ui-toggle aria-label="Toggle bold">
 *   <svg class="size-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M14 12a4 4 0 0 0 0-8H6v8" /><path d="M15 20a4 4 0 0 0 0-8H6v8Z" /></svg>
 * </ui-toggle>
 *
 * <!-- Controlled or initial state. -->
 * <ui-toggle variant="outline" size="sm" pressed>B</ui-toggle>
 * ```
 */
import { WebComponent, html, prop } from '@webjsdev/core';
import { cn } from '../lib/utils.ts';

// shadcn's base form, verbatim, so it sets no cursor. On a native <button> the
// browser supplies one (the default arrow), and new-york adds cursor-pointer
// plus select-none on `.cn-toggle` as the kit's own convention.
// <ui-toggle-group-item>, whose host is the button, gets no browser default, so
// it takes its cursor from `.cn-toggle-group-item` (styles/supplement.json).
const BASE =
  "cursor-pointer gap-2 rounded-md text-sm font-medium select-none transition-[color,box-shadow] hover:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground dark:aria-invalid:ring-destructive/40 [&_svg:not([class*='size-'])]:size-4 group/toggle inline-flex items-center justify-center whitespace-nowrap outline-none hover:bg-muted focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0";

const VARIANTS = {
  default: 'bg-transparent',
  outline: 'border border-input bg-transparent shadow-xs hover:bg-accent hover:text-accent-foreground',
} as const;

const SIZES = {
  default: 'h-9 min-w-9 px-2',
  sm: 'h-8 min-w-8 px-1.5',
  lg: 'h-10 min-w-10 px-2.5',
} as const;

export type ToggleVariant = keyof typeof VARIANTS;
export type ToggleSize = keyof typeof SIZES;

export function toggleClass(opts: { variant?: ToggleVariant; size?: ToggleSize } & { className?: string } = {}): string {
  return cn(BASE, VARIANTS[opts.variant ?? 'default'], SIZES[opts.size ?? 'default'], opts.className);
}

/**
 * shadcn's name for {@link toggleClass}, so shadcn code ports verbatim
 * (`toggleVariants({ ... })` is shadcn's `cva` export for `Toggle`). Like cva, it
 * merges a `className` into the result.
 */
export function toggleVariants(opts: { variant?: ToggleVariant; size?: ToggleSize } & { className?: string } = {}): string {
  return toggleClass(opts);
}

// --------------------------------------------------------------------------
// <ui-toggle> wraps a native <button> and tracks pressed state. Native
// <button> handles Enter/Space → click + focus + disabled semantics for
// free; we only own the pressed-state toggle on click. Authored children
// project through the default slot inside the inner button.
// --------------------------------------------------------------------------

export class UiToggle extends WebComponent({
  pressed: prop(Boolean, { reflect: true }),
  variant: prop<ToggleVariant>(String, { reflect: true }),
  size: prop<ToggleSize>(String, { reflect: true }),
  disabled: prop(Boolean, { reflect: true }),
}) {
  constructor() {
    super();
    this.pressed = false;
    this.variant = 'default';
    this.size = 'default';
    this.disabled = false;
  }

  // Read a host attribute defensively. render() runs server-side too, where
  // webjs shims the attribute methods; the typeof guard stays for any other
  // renderer that does not.
  _hostAttr(name: string): string | null {
    if (typeof this.getAttribute !== 'function') return null;
    return this.getAttribute(name);
  }

  render() {
    // The focusable control is the inner <button>, so its accessible name is
    // what a screen reader announces. `aria-label` on the host cannot supply
    // that (the host has a generic role, and a name there does not contribute
    // to a descendant's name), and the documented icon-only shape slots an
    // aria-hidden SVG, which contributes nothing either. Forward the host's
    // name source onto the button so the documented shape ships named.
    //
    // The name is BRANCHED into three templates rather than carried in one
    // hole, because a null hole does NOT omit an attribute on the server: the
    // server renderer stringifies the value, so `aria-label=${null}` ships
    // `aria-label=""` while the client renderer removes it. On an unlabelled
    // toggle that would put an empty name on the very control whose name is
    // supposed to come from its slotted text, and disagree with the hydrated
    // DOM on the exact attribute this forwarding exists to get right.
    const labelledBy = this._hostAttr('aria-labelledby');
    const label = this._hostAttr('aria-label');
    const cls = toggleClass({ variant: this.variant, size: this.size });
    const pressed = String(this.pressed);
    const state = this.pressed ? 'on' : 'off';
    // aria-labelledby beats aria-label per accname, so it is checked first and
    // only ONE of the two is ever emitted.
    if (labelledBy) {
      return html`<button
        type="button"
        data-slot="toggle"
        class=${cls}
        aria-pressed=${pressed}
        aria-labelledby=${labelledBy}
        data-state=${state}
        ?disabled=${this.disabled}
        @click=${this._onClick}
      ><slot></slot></button>`;
    }
    if (label) {
      return html`<button
        type="button"
        data-slot="toggle"
        class=${cls}
        aria-pressed=${pressed}
        aria-label=${label}
        data-state=${state}
        ?disabled=${this.disabled}
        @click=${this._onClick}
      ><slot></slot></button>`;
    }
    return html`<button
      type="button"
      data-slot="toggle"
      class=${cls}
      aria-pressed=${pressed}
      data-state=${state}
      ?disabled=${this.disabled}
      @click=${this._onClick}
    ><slot></slot></button>`;
  }

  _onClick = (): void => {
    this.pressed = !this.pressed;
    this.dispatchEvent(
      new CustomEvent('ui-pressed-change', { detail: { pressed: this.pressed }, bubbles: true }),
    );
  };
}
UiToggle.register('ui-toggle');
````

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

## Usage

Importing the module registers `<ui-toggle>`, which keeps its own pressed state.

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

```html
<ui-toggle>Toggle</ui-toggle>
```

## Outline

Use `variant="outline"` for an outline style.

```ts
import { html } from '@webjsdev/core';
import { BoldIcon, ItalicIcon } from '#lib/ui/lucide.ts';

export default function ToggleOutline() {
  return html`
    <div class="flex flex-wrap items-center gap-2">
      <ui-toggle variant="outline" aria-label="Toggle italic">
        ${ItalicIcon()}
        Italic
      </ui-toggle>
      <ui-toggle variant="outline" aria-label="Toggle bold">
        ${BoldIcon()}
        Bold
      </ui-toggle>
    </div>
  `;
}
```

## With Text

```ts
import { html } from '@webjsdev/core';
import { ItalicIcon } from '#lib/ui/lucide.ts';

export default function ToggleText() {
  return html`
    <ui-toggle aria-label="Toggle italic">
      ${ItalicIcon()}
      Italic
    </ui-toggle>
  `;
}
```

## Size

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

```ts
import { html } from '@webjsdev/core';

export default function ToggleSizes() {
  return html`
    <div class="flex flex-wrap items-center gap-2">
      <ui-toggle variant="outline" aria-label="Toggle small" size="sm">
        Small
      </ui-toggle>
      <ui-toggle variant="outline" aria-label="Toggle default" size="default">
        Default
      </ui-toggle>
      <ui-toggle variant="outline" aria-label="Toggle large" size="lg">
        Large
      </ui-toggle>
    </div>
  `;
}
```

## Disabled

```ts
import { html } from '@webjsdev/core';

export default function ToggleDisabled() {
  return html`
    <div class="flex flex-wrap items-center gap-2">
      <ui-toggle aria-label="Toggle disabled" disabled>
        Disabled
      </ui-toggle>
      <ui-toggle variant="outline" aria-label="Toggle disabled outline" disabled>
        Disabled
      </ui-toggle>
    </div>
  `;
}
```

## RTL

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

```ts
import { html } from '@webjsdev/core';
import { BookmarkIcon } from '#lib/ui/lucide.ts';

const translations = {
  en: {
    dir: 'ltr',
    values: {
      label: 'Bookmark',
    },
  },
  ar: {
    dir: 'rtl',
    values: {
      label: 'إشارة مرجعية',
    },
  },
  he: {
    dir: 'rtl',
    values: {
      label: 'סימנייה',
    },
  },
};

// The provider is the dir attribute: the toggle styles itself with logical
// properties, so dir="rtl" on it flips the icon and the label.
export default function ToggleRtl() {
  const lang = 'ar';
  const { dir, values: t } = translations[lang];

  return html`
    <ui-toggle aria-label="Toggle bookmark" size="sm" variant="outline" dir=${dir} lang=${lang}>
      ${BookmarkIcon('group-data-[state=on]/toggle:fill-foreground')}
      ${t.label}
    </ui-toggle>
  `;
}
```

## API Reference

### ui-toggle

A pressable on and off button. It renders a native `<button>` and forwards the host's `aria-label` to it, so an icon-only toggle is named on the host.

| Attribute | Type | Default |
| --- | --- | --- |
| `pressed` | `boolean` | `false` |
| `variant` | `"default" \| "outline"` | `"default"` |
| `size` | `"default" \| "sm" \| "lg"` | `"default"` |
| `disabled` | `boolean` | `false` |

It dispatches `ui-pressed-change` with `{ detail: { pressed } }` after a click.

### toggleClass

`toggleClass()` returns the toggle's classes for a native `<button>` whose pressed state you own, carried on `aria-pressed` and `data-state`. `toggleVariants()` is an alias of `toggleClass()` that also merges a `className`.

| Option | Type | Default |
| --- | --- | --- |
| `variant` | `"default" \| "outline"` | `"default"` |
| `size` | `"default" \| "sm" \| "lg"` | `"default"` |
