# Switch

> An on and off toggle built on a native checkbox with the switch role.

`<slab-switch>` · Form · built on `<input type=checkbox role=switch>`

## Install

```sh
pnpm add slab-elements lit
```

## Usage

```html
<script type="module">
  import 'slab-elements/switch.js';
</script>

<slab-switch label="Notifications" name="notifications" checked></slab-switch>
```

## Example

Here's a styled version, `<slab-styled-switch>`. It's not in the package — it's an example of what you can build with the headless element. Copy it and make it yours at the bottom of this page.

```html
<div class="stack">
  <slab-styled-switch label="Vapor barrier" checked>
    <span slot="description">A plastic sheet under the slab keeps ground moisture out.</span>
  </slab-styled-switch>
  <slab-styled-switch label="Cold-weather blankets">
    <span slot="description">Keep the slab above 50 °F while it cures.</span>
  </slab-styled-switch>
</div>
```

Swap `slab-styled-` for `slab-` in that markup and you've got the same example as it ships: the headless elements with no CSS at all. That's your starting point.

## Keyboard

| Key   | What it does        |
| ----- | ------------------- |
| Space | Turns it on or off. |

## Behavior

A switch with no visual styles, around a native checkbox, so it is checked, focused, and read the way one is.

The label and the switch are both in the shadow root, so a plain `for` reference names it without crossing out of one. The host delegates focus, so clicking anywhere on it, or a `<label for>` pointing at it, focuses the switch.

Style it through its parts and through `:state(checked)`, `:state(disabled)`, and `:state(required)`. Where the label sits relative to the switch is layout, so it's left to the styles around it.

## API

### `<slab-switch>`

#### Attributes

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `label` (required) | `string` |  |  |
| `checked` | `boolean` | `false` | Like a native checkbox, the attribute is the default state and the property is the current one, so the attribute doesn't change as the switch is toggled. Style `:state(checked)` rather than `[checked]`. |
| `disabled` | `boolean` | `false` |  |
| `hide-label` | `boolean` | `false` |  |
| `name` | `string` | `''` |  |
| `required` | `boolean` | `false` |  |
| `value` | `string` | `'on'` |  |
| `version` | `string` |  |  |

#### Properties

| Name | Type | Description |
| --- | --- | --- |
| `form` (read-only) | `HTMLFormElement \| null` |  |
| `validity` (read-only) | `ValidityState` |  |

#### Methods

| Signature | Description |
| --- | --- |
| `checkValidity(): boolean` |  |
| `click(): void` |  |
| `focus(options?: FocusOptions): void` |  |
| `reportValidity(): boolean` |  |

#### Events

| Name | Type | Description |
| --- | --- | --- |
| `input` | `Event` |  |
| `change` | `Event` |  |

#### Slots

| Name | Type | Description |
| --- | --- | --- |
| `description` | `Element \| string` | Text about the switch, such as a hint or an error |

#### CSS parts

| Name | Description |
| --- | --- |
| `description` | Text about the switch, such as a hint or an error |
| `input` |  |
| `label` | The label |
| `switch` | The switch itself |

## Copy and own it

`<slab-styled-switch>` isn't in the package. It's an example — copy it into your project and change whatever you want. Under the hood, it's just the headless element, subclassed, with `styles` set. That's it. Keyboard, focus, ARIA, forms, and events all come from the headless element, and the styles only reach in through `::part()` and `:state()`, same as yours would.

To use it, copy these files, swap the tag in `@customElement()` for one of your own, and import it. `tokens.styles.ts` holds the colors and fonts every styled example shares, so you only need it once.

### TypeScript

These files are TypeScript, and `@customElement()` is one of Lit's decorators (TypeScript's experimental flavor). You'll need two options in your tsconfig, per [Lit's docs](https://lit.dev/docs/components/decorators/#decorators-typescript): `experimentalDecorators` to compile them, and `useDefineForClassFields` turned off so class fields don't stomp on the accessors Lit sets up.

```json
{
  "compilerOptions": {
    "experimentalDecorators": true,
    "useDefineForClassFields": false
  }
}
```

Using plain JavaScript? Drop the types and register the class with `customElements.define()` instead of the decorator.

### switch.ts

```ts
import { customElement } from 'lit/decorators.js';
import Switch from 'slab-elements/switch.js';
import styles from './switch.styles.js';
import tokens from './tokens.styles.js';

declare global {
  interface HTMLElementTagNameMap {
    'slab-styled-switch': StyledSwitch;
  }
}

/**
 * Switch, styled: a settings row with the label on the left and a square
 * thumb that slides across a track, which turns ember when it's on.
 */
@customElement('slab-styled-switch')
export default class StyledSwitch extends Switch {
  static override styles = [tokens, styles];
}
```

### switch.styles.ts

```ts
import { css } from 'lit';

export default css`
  :host {
    align-items: center;
    color: var(--ink);
    column-gap: 1rem;
    display: grid;
    font-family: var(--font-body);
    grid-template-columns: 1fr auto;
  }

  :host(:state(disabled)) {
    color: var(--ash);
  }

  [part~='label'] {
    cursor: pointer;
    font-family: var(--font-display);
    font-size: 1.0625rem;
    font-weight: 600;
  }

  :host(:state(required)) [part~='label']::after {
    color: var(--ember-deep);
    content: ' *' / '';
  }

  [part~='switch'] {
    display: flex;
  }

  /*
    The input is the track, and the thumb is a square of background drawn on
    it, so there's nothing to position and nothing else to focus.
  */
  [part~='input'] {
    appearance: none;
    background:
      linear-gradient(var(--ink), var(--ink)) no-repeat 0.25rem 50% / 1.125rem
        1.125rem,
      var(--paper);
    block-size: 1.75rem;
    border: var(--border);
    cursor: pointer;
    inline-size: 3.25rem;
    margin: 0;
    transition: background 150ms;

    &:focus-visible {
      outline: 3px solid var(--ember);
      outline-offset: 2px;
    }

    &:checked {
      background:
        linear-gradient(var(--paper), var(--paper)) no-repeat
          calc(100% - 0.25rem) 50% / 1.125rem 1.125rem,
        var(--ember);
    }

    &:disabled {
      border-style: dashed;
      cursor: not-allowed;
      opacity: 0.5;
    }
  }

  [part~='description'] {
    color: var(--ash);
    display: block;
    font-size: 0.875rem;
    grid-column: 1 / -1;
  }

  @media (prefers-reduced-motion: reduce) {
    [part~='input'] {
      transition: none;
    }
  }
`;
```

### tokens.styles.ts

```ts
import { css } from 'lit';

/*
  The styled components' palette and type, taken from the logo: ink for the
  courses, ember for the base, paper behind them.

  Each is a short alias for a "--slab-styled-*" property, with the default as
  its fallback. Retheming is "--slab-styled-ember" and the rest on ":root",
  which every shadow root inherits. Were the defaults declared under those
  names here instead, each host's own declaration would shadow the page's.

  Each default is "light-dark()", so the components follow the page's
  "color-scheme": "dark" for dark, "light" for light, and "light dark" to
  follow the operating system. Ink and paper trade places in the dark, so
  ink is always the text and paper always what's behind it. Contrast is given
  as light, then dark.
*/
export default css`
  :host {
    /* Secondary text. 6.8:1 and 6.9:1 on paper. */
    --ash: var(--slab-styled-ash, light-dark(#5e5a55, #a8a19a));
    --border: 2px solid var(--ink);

    /* Behind disabled and read-only controls, and hovered rows. */
    --chalk: var(--slab-styled-chalk, light-dark(#f4f1ec, #2b2926));

    /*
      The logo's orange, brighter in the dark. 4.25:1 and 5.2:1 on paper is
      enough for borders, fills and large text, but not always for small text,
      which takes "--ember-deep".
    */
    --ember: var(--slab-styled-ember, light-dark(#d9492a, #ec5f3b));

    /*
      Orange for small text on paper, and for paper text on it. 5.7:1 and
      7.4:1.
    */
    --ember-deep: var(--slab-styled-ember-deep, light-dark(#b3381a, #ff8566));
    --font-body: var(
      --slab-styled-font-body,
      'IBM Plex Sans',
      system-ui,
      sans-serif
    );
    --font-display: var(
      --slab-styled-font-display,
      'Zilla Slab',
      rockwell,
      'Roboto Slab',
      serif
    );
    --font-mono: var(
      --slab-styled-font-mono,
      'IBM Plex Mono',
      ui-monospace,
      monospace
    );
    --ink: var(--slab-styled-ink, light-dark(#1c1c1c, #f4f1ec));
    --paper: var(--slab-styled-paper, light-dark(#fff, #1a1918));

    /* The hard, offset shadow a raised surface casts. */
    --shadow: 4px 4px 0 var(--ink);
  }
`;
```
