# Toggle Button

> One button that stays pressed until it's pressed again, for a setting that's on or off.

`<slab-toggle-button>` · Selection · built on `<button aria-pressed>`

## Install

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

## Usage

### React

`MyToggleButton.jsx`. React 19 or later, which sets props on custom elements as properties.

```jsx
import 'slab-elements/toggle-button.js';

export function MyToggleButton() {
  return (
    <slab-toggle-button label="Mute">
      <svg aria-hidden="true" viewBox="0 0 24 24" width="16" height="16"><path d="M4 9h4l5-4v14l-5-4H4z" fill="currentColor" /></svg>
    </slab-toggle-button>
  );
}
```

### Lit

`my-toggle-button.ts`. Slab is built on Lit, so its elements are at home in Lit's templates.

```ts
import 'slab-elements/toggle-button.js';
import { html, LitElement } from 'lit';
import { customElement } from 'lit/decorators.js';

@customElement('my-toggle-button')
export class MyToggleButton extends LitElement {
  render() {
    return html`
      <slab-toggle-button label="Mute">
        <svg aria-hidden="true" viewBox="0 0 24 24" width="16" height="16"><path d="M4 9h4l5-4v14l-5-4H4z" fill="currentColor" /></svg>
      </slab-toggle-button>
    `;
  }
}
```

### Vue

`MyToggleButton.vue`. Let Vue's compiler know slab- tags are custom elements with isCustomElement.

```vue
<script setup>
import 'slab-elements/toggle-button.js';
</script>

<template>
  <slab-toggle-button label="Mute">
    <svg aria-hidden="true" viewBox="0 0 24 24" width="16" height="16"><path d="M4 9h4l5-4v14l-5-4H4z" fill="currentColor" /></svg>
  </slab-toggle-button>
</template>
```

### Svelte

`MyToggleButton.svelte`. Svelte binds properties and events to custom elements like any other element.

```svelte
<script>
  import 'slab-elements/toggle-button.js';
</script>

<slab-toggle-button label="Mute">
  <svg aria-hidden="true" viewBox="0 0 24 24" width="16" height="16"><path d="M4 9h4l5-4v14l-5-4H4z" fill="currentColor" /></svg>
</slab-toggle-button>
```

### Ember

`MyToggleButton.gjs`. Ember sets attributes, and a dynamic value like {{this.max}} sets the property when the element has one. {{on}} listens for any event by its name.

```gjs
import 'slab-elements/toggle-button.js';

export const MyToggleButton = <template>
  <slab-toggle-button label="Mute">
    <svg aria-hidden="true" viewBox="0 0 24 24" width="16" height="16"><path d="M4 9h4l5-4v14l-5-4H4z" fill="currentColor" /></svg>
  </slab-toggle-button>
</template>;
```

### HTML

`index.html`. Any bundler (or an import map) takes care of the imports.

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

<slab-toggle-button label="Mute">
  <svg aria-hidden="true" viewBox="0 0 24 24" width="16" height="16"><path d="M4 9h4l5-4v14l-5-4H4z" fill="currentColor" /></svg>
</slab-toggle-button>
```

## Example

Here's a styled version, `<slab-styled-toggle-button>`. 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-toggle-button pressed>Grid lines</slab-styled-toggle-button>
  <slab-styled-toggle-button>Snap to grid</slab-styled-toggle-button>
  <slab-styled-toggle-button disabled>Rebar</slab-styled-toggle-button>
</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.

For a setting that's applied as soon as it changes, such as a preference, a Switch reads more clearly. For a row of these, such as Bold, Italic and Underline, use Toggle Group, so Tab reaches them once and the arrow keys move between them.

## Keyboard

| Key          | What it does                                            |
| ------------ | ------------------------------------------------------- |
| Enter, Space | Presses the button, or releases it, as on a `<button>`. |

## Behavior

A toggle button with no visual styles, around a native `<button>` with `aria-pressed`, for one setting that's on or off, such as Bold or Mute.

A click, Space or Enter presses it or releases it, and dispatches "input" and "change". Setting `pressed` doesn't dispatch either. A click your own capturing handler cancels doesn't press anything.

Its name is what's slotted into it. Set `label` when that doesn't name it, such as when it holds only an icon, and keep the label the same whether it's pressed or not: `aria-pressed` already says which it is. A label that flips from "Mute" to "Unmute" is read as "Unmute, pressed", which says the opposite. For several buttons that belong together, use Toggle Group, so Tab reaches them once.

Style it through its part and `:state(pressed)`.

## API

### `<slab-toggle-button>`

#### Attributes

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `disabled` | `boolean` | `false` | Disables it, as `disabled` does a native control: the user can't focus or use it, and a form control's value isn't submitted. |
| `label` | `string` |  | Names the button when what's in it doesn't, such as when it holds only an icon. |
| `pressed` | `boolean` | `false` | Like a native checkbox's `checked`, the attribute is the default state and the property is the current one. Style `:state(pressed)` rather than `[pressed]`. |

#### Methods

| Signature | Description |
| --- | --- |
| `click(): void` | Clicks it, as a native element's `click()` does. |
| `focus(options?: FocusOptions): void` | Focuses it, or the part of it that takes focus. |

#### Events

| Name | Type | Description |
| --- | --- | --- |
| `input` | `Event` | As the user changes its value, as a native control's does. Setting it from code doesn't dispatch it. |
| `change` | `Event` | When the user changes its value, as a native control's does. Setting it from code doesn't dispatch it. |

#### Slots

| Name | Type | Description |
| --- | --- | --- |
| `(default)` | `Element \| string` | The label, plus anything else a design puts in a button |

#### CSS parts

| Name | Description |
| --- | --- |
| `button` | The button |

#### CSS states

| Name | Description |
| --- | --- |
| `:state(disabled)` | While it's disabled. |
| `:state(pressed)` | While it's pressed. |

## Copy and own it

`<slab-styled-toggle-button>` isn't in the package. It's an example — copy it into your project and change whatever you want. 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.

### Lit

Under the hood, it's just the headless element, subclassed, with `styles` set. That's it. 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.

#### toggle-button.ts

```ts
import { customElement } from 'lit/decorators.js';
import ToggleButton from 'slab-elements/toggle-button.js';
import styles from './toggle-button.styles.js';
import tokens from './tokens.styles.js';

declare global {
  interface HTMLElementTagNameMap {
    'slab-styled-toggle-button': StyledToggleButton;
  }
}

/**
 * Toggle Button, styled: uppercase slab type in an ink border, filled in
 * ember when it's pressed.
 */
@customElement('slab-styled-toggle-button')
export default class StyledToggleButton extends ToggleButton {
  static override styles = [tokens, styles];
}
```

#### toggle-button.styles.ts

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

export default css`
  [part~='button'] {
    align-items: center;
    background-color: var(--paper);
    border: var(--border);
    color: var(--ink);
    cursor: pointer;
    display: inline-flex;
    font-family: var(--font-display);
    font-size: 0.9375rem;
    font-weight: 600;
    gap: 0.5rem;
    letter-spacing: 0.04em;
    padding: 0.5rem 0.875rem;
    text-transform: uppercase;
    transition:
      background-color 100ms,
      color 100ms;

    &:hover {
      background-color: var(--chalk);
    }

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

    &:disabled {
      border-color: var(--ash);
      color: var(--ash);
      cursor: not-allowed;
      text-decoration: line-through;
    }
  }

  /*
    After the hover above, so a pressed button keeps its ember while it's
    hovered. Paper text on "--ember-deep" is 5.7:1 and 7.4:1, where on
    "--ember" it would fall short for small text.
  */
  :host(:state(pressed)) [part~='button'] {
    background-color: var(--ember-deep);
    border-color: var(--ember-deep);
    color: var(--paper);

    &:disabled {
      background-color: var(--chalk);
      border-color: var(--ash);
      color: var(--ash);
    }
  }

  @media (prefers-reduced-motion: reduce) {
    [part~='button'] {
      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);
  }

  /*
    Forced colors, such as Windows' contrast themes, replace every color that
    isn't a system color, so ember fills and paper marks all become the same
    background, and a checked Checkbox looks like an unchecked one. The palette
    becomes the user's system colors instead, which are kept. Ember is the
    highlight, the color of what's selected, and ember-deep, being for text and
    for paper text on it, is the text color.
  */
  @media (forced-colors: active) {
    :host {
      --ash: GrayText;
      --chalk: Canvas;
      --ember: Highlight;
      --ember-deep: CanvasText;
      --ink: CanvasText;
      --paper: Canvas;
    }
  }
`;
```

### React, Vue, Svelte and Ember

The same styles, written from outside the element, so there's nothing to subclass. The CSS styles every `<slab-toggle-button>` on the page. Import `tokens.css`, the colors and fonts every styled example shares, once, wherever your global styles go.

In React and Vue, each component registers its headless element and imports its CSS. Use it like the element: its props are the element's attributes and properties.

In Svelte, import `toggle-button.js` once, such as in your root layout, and use `<slab-toggle-button>` as is. A Svelte component around it would take `slot="…"` content as its own slot and drop it.

In Ember, each component registers its headless element and imports its CSS. Use it like the element: its attributes and its content go to the element.

#### ToggleButton.jsx

```jsx
import 'slab-elements/toggle-button.js';
import './toggle-button.css';

export function ToggleButton(props) {
  return <slab-toggle-button {...props} />;
}
```

#### ToggleButton.vue

```vue
<script setup>
import 'slab-elements/toggle-button.js';
import './toggle-button.css';
</script>

<template>
  <slab-toggle-button><slot /></slab-toggle-button>
</template>
```

#### toggle-button.js

```js
import 'slab-elements/toggle-button.js';
import './toggle-button.css';
```

#### ToggleButton.gjs

```gjs
import 'slab-elements/toggle-button.js';
import './toggle-button.css';

export const ToggleButton = <template>
  <slab-toggle-button ...attributes>{{yield}}</slab-toggle-button>
</template>;
```

#### toggle-button.css

```css
slab-toggle-button::part(button) {
  align-items: center;
  background-color: var(--paper);
  border: var(--border);
  color: var(--ink);
  cursor: pointer;
  display: inline-flex;
  font-family: var(--font-display);
  font-size: 0.9375rem;
  font-weight: 600;
  gap: 0.5rem;
  letter-spacing: 0.04em;
  padding: 0.5rem 0.875rem;
  text-transform: uppercase;
  transition:
    background-color 100ms,
    color 100ms;
}

slab-toggle-button::part(button):hover {
  background-color: var(--chalk);
}

slab-toggle-button::part(button):focus-visible {
  outline: 3px solid var(--ember);
  outline-offset: 2px;
}

slab-toggle-button::part(button):disabled {
  border-color: var(--ash);
  color: var(--ash);
  cursor: not-allowed;
  text-decoration: line-through;
}

/*
  After the hover above, so a pressed button keeps its ember while it's
  hovered. Paper text on "--ember-deep" is 5.7:1 and 7.4:1, where on
  "--ember" it would fall short for small text.
*/
slab-toggle-button:state(pressed)::part(button) {
  background-color: var(--ember-deep);
  border-color: var(--ember-deep);
  color: var(--paper);
}

slab-toggle-button:state(pressed)::part(button):disabled {
  background-color: var(--chalk);
  border-color: var(--ash);
  color: var(--ash);
}

@media (prefers-reduced-motion: reduce) {
  slab-toggle-button::part(button) {
    transition: none;
  }
}
```

#### tokens.css

```css
:root {
  /* 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);
}

/*
  Forced colors, such as Windows' contrast themes, replace every color that
  isn't a system color, so ember fills and paper marks all become the same
  background, and a checked Checkbox looks like an unchecked one. The palette
  becomes the user's system colors instead, which are kept. Ember is the
  highlight, the color of what's selected, and ember-deep, being for text and
  for paper text on it, is the text color.
*/
@media (forced-colors: active) {
  :host {
    --ash: GrayText;
    --chalk: Canvas;
    --ember: Highlight;
    --ember-deep: CanvasText;
    --ink: CanvasText;
    --paper: Canvas;
  }
}
```
