# Alert Dialog

> A modal dialog that asks before something can't be undone. Focus starts on Cancel, and a click outside doesn't close it.

`<slab-alert-dialog>` · Overlays · built on `<dialog role=alertdialog>`

## Install

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

## Usage

### React

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

```jsx
import 'slab-elements/alert-dialog.js';

export function MyAlertDialog() {
  return (
    <slab-alert-dialog
      label="Delete this file?"
      description="It can't be recovered."
    >
      <form method="dialog">
        <button value="delete">Delete</button>
      </form>
    </slab-alert-dialog>
  );
}
```

### Lit

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

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

@customElement('my-alert-dialog')
export class MyAlertDialog extends LitElement {
  render() {
    return html`
      <slab-alert-dialog
        label="Delete this file?"
        description="It can't be recovered."
      >
        <form method="dialog">
          <button value="delete">Delete</button>
        </form>
      </slab-alert-dialog>
    `;
  }
}
```

### Vue

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

```vue
<script setup>
import 'slab-elements/alert-dialog.js';
</script>

<template>
  <slab-alert-dialog
    label="Delete this file?"
    description="It can't be recovered."
  >
    <form method="dialog">
      <button value="delete">Delete</button>
    </form>
  </slab-alert-dialog>
</template>
```

### Svelte

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

```svelte
<script>
  import 'slab-elements/alert-dialog.js';
</script>

<slab-alert-dialog
  label="Delete this file?"
  description="It can't be recovered."
>
  <form method="dialog">
    <button value="delete">Delete</button>
  </form>
</slab-alert-dialog>
```

### Ember

`MyAlertDialog.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/alert-dialog.js';

export const MyAlertDialog = <template>
  <slab-alert-dialog
    label="Delete this file?"
    description="It can't be recovered."
  >
    <form method="dialog">
      <button value="delete">Delete</button>
    </form>
  </slab-alert-dialog>
</template>;
```

### HTML

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

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

<slab-alert-dialog
  label="Delete this file?"
  description="It can't be recovered."
>
  <form method="dialog">
    <button value="delete">Delete</button>
  </form>
</slab-alert-dialog>
```

## Example

Here's a styled version, `<slab-styled-alert-dialog>`. 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
<button class="styled-button styled-button--danger" type="button" data-show-modal="alert-dialog-example">
  Cancel the pour
</button>

<slab-styled-alert-dialog
  id="alert-dialog-example"
  label="Cancel Friday's pour?"
  description="The ready-mix order for Lot 14 is released, and the crew is told to stand down. The plant charges a restocking fee after noon Thursday."
  cancel-label="Keep it"
>
  <form method="dialog">
    <button class="styled-button styled-button--danger" value="cancel-pour">Cancel pour</button>
  </form>
</slab-styled-alert-dialog>
```

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.

It's [Dialog](dialog.md) for a question that needs an answer, such as
confirming a delete. Screenreaders announce it as an alert dialog and read its
description along with its label as it opens.

Its Cancel button is built in, and focus starts there, so Enter pressed out of
habit doesn't do the thing it's asking about. Put the action that does it in the
default slot, usually a `<form method="dialog">` button: when it closes,
`returnValue` is that button's `value`, or empty when it was canceled. Slot an
`[autofocus]` element in instead when the dialog asks for something typed.

A click outside doesn't close it, so `closedby="any"` is treated as
"closerequest".

## Keyboard

| Key            | What it does                                                                                              |
| -------------- | --------------------------------------------------------------------------------------------------------- |
| Tab, Shift+Tab | Moves focus between Cancel and the dialog's other controls. The rest of the page is inert.                |
| Escape         | Closes the dialog, as Cancel does, unless `closedby` is "none". "cancel" can be canceled to keep it open. |
| Enter, Space   | On Cancel, closes the dialog with an empty `returnValue`.                                                 |

## Behavior

A dialog with no visual styles that asks for a decision before anything else can happen: "Delete this file?". It's Dialog, with a `[role=alertdialog]` on its `<dialog>`, so screenreaders announce it as urgent, and the description is read along with the label as it opens.

It always has a Cancel button, built in, and that's where focus goes when it opens. The APG puts initial focus on the least destructive control, so Enter pressed out of habit doesn't delete anything. An `[autofocus]` element in it wins over the Cancel button, for a dialog that asks for something typed. Cancel closes it with an empty `returnValue`. Slot the action that does what the dialog asks into the default slot, usually as a `<form method="dialog">` button, so its `value` becomes `returnValue` as it does with Dialog.

There's no light dismiss. A click outside it does nothing, because an alert dialog wants an answer. `closedby="any"` is treated as "closerequest". Escape still closes it, as Cancel does, and dispatches "cancel", which can be canceled to keep it open. Set `closedby="none"` to turn Escape off where the browser supports it.

Everything else is Dialog's: `open`, `returnValue`, `close(returnValue)`, the label, and "cancel" and "close" from the host.

## API

### `<slab-alert-dialog>`

#### Attributes

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `cancel-label` | `string` |  | The Cancel button's text and so its accessible name. "Cancel" in English when unset. |
| `closedby` | `'any' \| 'closerequest' \| 'none'` |  | Passed to the `<dialog>`. "none" keeps Escape from closing it where the browser supports that. "any" is treated as "closerequest", since an alert dialog doesn't close on a click outside it. |
| `description` | `string` |  | What the dialog is asking, read with the label when it opens. Plain text. Slot into "description" for more. |
| `hide-label` | `boolean` | `false` | Hides the label visually and leaves it as the accessible name, for a design that shows the label some other way. |
| `label` | `string` |  | Names it. It's the accessible name, and the visible label where there is one. |
| `modal` | `boolean` | `false` | Opens it as a modal when `open` is set, as `showModal()` does, for a modal opened declaratively. Not on a native `<dialog>`, where `open` always opens a non-modal one. `show()` and `showModal()` open it as they say whatever it is, and a change while it's open waits for it to open again. |
| `open` | `boolean` | `false` | Whether it's open. Setting it opens it non-modally, as `open` does on a `<dialog>`, unless `modal` is set. |

#### Properties

| Name | Type | Description |
| --- | --- | --- |
| `returnValue` | `string` | The `<dialog>`'s, so `close(returnValue)` and a `<form method="dialog">` set it the way they do natively. |

#### Methods

| Signature | Description |
| --- | --- |
| `close(returnValue?: string): void` | Closes it, setting `returnValue` to the value given, as a native dialog's `close()` does. |
| `requestClose(returnValue?: string): void` | Asks it to close, as a native dialog's `requestClose()` does: "cancel" first, then a close that sets `returnValue` to the value given, unless "cancel" is canceled. |
| `show(): void` | Opens it non-modally, as a native dialog's `show()` does, whether or not `modal` is set. The rest of the page stays interactive. |
| `showModal(): void` | Opens it as a modal, as a native dialog's `showModal()` does, whether or not `modal` is set. |

#### Events

| Name | Type | Description |
| --- | --- | --- |
| `cancel` | `Event` | When something asks it to close: Escape, a click outside with `closedby="any"`, or `requestClose()`. Cancel it to keep it open, as a native dialog's. |
| `toggle` | `ToggleEvent` | When it opens or closes, as a `ToggleEvent` with `oldState` and `newState` that doesn't bubble, as a popover's does. |
| `close` | `Event` | When it closes, as a native dialog's does. |

#### Slots

| Name | Type | Description |
| --- | --- | --- |
| `description` | `Element \| string` | Text that describes it, such as a hint or what the validity message means. It's its accessible description. |
| `(default)` | `Element \| string` | The action that does what the dialog asks, such as a Delete button in a form with method="dialog". |
| `label` | `Element \| string` | Its heading, in place of `label` |

#### CSS parts

| Name | Description |
| --- | --- |
| `cancel` | The Cancel button. Closes the dialog with an empty returnValue |
| `description` | The description |
| `dialog` | The native dialog. A modal one's backdrop is its ::backdrop |
| `label` | The label |

#### CSS states

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

## Copy and own it

`<slab-styled-alert-dialog>` 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.

#### alert-dialog.ts

```ts
import { customElement } from 'lit/decorators.js';
import AlertDialog from 'slab-elements/alert-dialog.js';
import dialog from './dialog.styles.js';
import styles from './alert-dialog.styles.js';
import tokens from './tokens.styles.js';

declare global {
  interface HTMLElementTagNameMap {
    'slab-styled-alert-dialog': StyledAlertDialog;
  }
}

/**
 * Alert Dialog, styled: Dialog's slab, with the Cancel button and the slotted
 * action in a row along its base.
 */
@customElement('slab-styled-alert-dialog')
export default class StyledAlertDialog extends AlertDialog {
  static override styles = [tokens, dialog, styles];
}
```

#### dialog.styles.ts

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

export default css`
  /*
    A closed dialog isn't displayed, so the animation runs again each time it
    opens.
  */
  [part~='dialog'] {
    animation: rise 200ms ease-out;
    background-color: var(--paper);
    border: 3px solid var(--ink);
    box-shadow: 10px 10px 0 var(--ember);
    box-sizing: border-box;
    color: var(--ink);
    font-family: var(--font-body);
    inline-size: min(32rem, 100% - 2rem);

    /*
      Where a modal one is already, in the top layer. A non-modal one isn't
      there, so it's fixed in the middle of the viewport too, rather than left
      where it is in the page, and raised over what's around it. Drawer's
      styles, which come after, put it at an edge instead.
    */
    inset: 0;
    line-height: 1.5;
    margin: auto;
    padding: 0 1.5rem 1.5rem;
    position: fixed;
    z-index: 1;

    &::backdrop {
      animation: fade 200ms ease-out;

      /*
        Not a token. A backdrop doesn't inherit custom properties from the
        dialog in every browser, but it does take its color scheme.
      */
      background-color: light-dark(rgb(28 28 28 / 70%), rgb(0 0 0 / 75%));
    }
  }

  /*
    The header. It's pulled out to the dialog's edges, which its padding would
    otherwise keep it from.
  */
  [part~='label'] {
    /*
      Ink in the light. In the dark, ink is the light color, so the header is
      the raised surface instead, rather than a bright bar.
    */
    background-color: light-dark(var(--ink), var(--chalk));
    border-block-end: 6px solid var(--ember);
    color: light-dark(var(--paper), var(--ink));
    font-family: var(--font-display);
    font-size: 1.5rem;
    font-weight: 600;
    margin-block-end: 1.25rem;
    margin-inline: -1.5rem;
    padding: 1rem 1.5rem;
  }

  @keyframes rise {
    from {
      opacity: 0;
      translate: 0 1rem;
    }
  }

  @keyframes fade {
    from {
      opacity: 0;
    }
  }

  @media (prefers-reduced-motion: reduce) {
    [part~='dialog'],
    [part~='dialog']::backdrop {
      animation: none;
    }
  }
`;
```

#### alert-dialog.styles.ts

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

/*
  Dialog's styles, then these. The label and description span the slab, and
  the Cancel button and the slotted action sit in a row under them, at its
  end edge, with Cancel first.
*/
export default css`
  /*
    On the open host only. A closed dialog isn't displayed, and "display: grid"
    would show it.
  */
  :host([open]) [part~='dialog'] {
    column-gap: 1rem;
    display: grid;
    grid-template-columns: minmax(0, 1fr) auto auto;
  }

  [part~='label'],
  [part~='description'] {
    grid-column: 1 / -1;
  }

  [part~='description'] {
    margin-block-end: 1.5rem;
  }

  [part~='cancel'] {
    background-color: var(--paper);
    border: var(--border);
    box-shadow: 4px 4px 0 var(--ink);
    color: var(--ink);
    cursor: pointer;
    font-family: var(--font-display);
    font-size: 1rem;
    font-weight: 600;
    grid-column: 2;
    padding: 0.5rem 1.125rem;
    transition:
      background-color 150ms ease-out,
      box-shadow 150ms ease-out;

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

    &:active {
      box-shadow: 1px 1px 0 var(--ink);
      transition-duration: 50ms;
    }

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

  ::slotted(:not([slot])) {
    grid-column: 3;
  }

  @media (prefers-reduced-motion: reduce) {
    [part~='cancel'] {
      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-alert-dialog>` 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 `alert-dialog.js` once, such as in your root layout, and use `<slab-alert-dialog>` 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.

#### AlertDialog.jsx

```jsx
import 'slab-elements/alert-dialog.js';
import './alert-dialog.css';

export function AlertDialog(props) {
  return <slab-alert-dialog {...props} />;
}
```

#### AlertDialog.vue

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

<template>
  <slab-alert-dialog><slot /></slab-alert-dialog>
</template>
```

#### alert-dialog.js

```js
import 'slab-elements/alert-dialog.js';
import './alert-dialog.css';
```

#### AlertDialog.gjs

```gjs
import 'slab-elements/alert-dialog.js';
import './alert-dialog.css';

export const AlertDialog = <template>
  <slab-alert-dialog ...attributes>{{yield}}</slab-alert-dialog>
</template>;
```

#### alert-dialog.css

```css
/*
  A closed dialog isn't displayed, so the animation runs again each time it
  opens.
*/
slab-alert-dialog::part(dialog) {
  animation: slab-alert-dialog-rise 200ms ease-out;
  background-color: var(--paper);
  border: 3px solid var(--ink);
  box-shadow: 10px 10px 0 var(--ember);
  box-sizing: border-box;
  color: var(--ink);
  font-family: var(--font-body);
  inline-size: min(32rem, 100% - 2rem);
  /*
    Where a modal one is already, in the top layer. A non-modal one isn't
    there, so it's fixed in the middle of the viewport too, rather than left
    where it is in the page, and raised over what's around it. Drawer's
    styles, which come after, put it at an edge instead.
  */
  inset: 0;
  line-height: 1.5;
  margin: auto;
  padding: 0 1.5rem 1.5rem;
  position: fixed;
  z-index: 1;
}

slab-alert-dialog::part(dialog)::backdrop {
  animation: slab-alert-dialog-fade 200ms ease-out;
  /*
    Not a token. A backdrop doesn't inherit custom properties from the
    dialog in every browser, but it does take its color scheme.
  */
  background-color: light-dark(rgb(28 28 28 / 70%), rgb(0 0 0 / 75%));
}

/*
  The header. It's pulled out to the dialog's edges, which its padding would
  otherwise keep it from.
*/
/*
  Ink in the light. In the dark, ink is the light color, so the header is
  the raised surface instead, rather than a bright bar.
*/
slab-alert-dialog::part(label) {
  background-color: light-dark(var(--ink), var(--chalk));
  border-block-end: 6px solid var(--ember);
  color: light-dark(var(--paper), var(--ink));
  font-family: var(--font-display);
  font-size: 1.5rem;
  font-weight: 600;
  margin-block-end: 1.25rem;
  margin-inline: -1.5rem;
  padding: 1rem 1.5rem;
}

@keyframes slab-alert-dialog-rise {
  from {
    opacity: 0;
    translate: 0 1rem;
  }
}

@keyframes slab-alert-dialog-fade {
  from {
    opacity: 0;
  }
}

@media (prefers-reduced-motion: reduce) {
  slab-alert-dialog::part(dialog),
  slab-alert-dialog::part(dialog)::backdrop {
    animation: none;
  }
}

/*
  On the open host only. A closed dialog isn't displayed, and "display: grid"
  would show it.
*/
slab-alert-dialog[open]::part(dialog) {
  column-gap: 1rem;
  display: grid;
  grid-template-columns: minmax(0, 1fr) auto auto;
}

slab-alert-dialog::part(label),
slab-alert-dialog::part(description) {
  grid-column: 1 / -1;
}

slab-alert-dialog::part(description) {
  margin-block-end: 1.5rem;
}

slab-alert-dialog::part(cancel) {
  background-color: var(--paper);
  border: var(--border);
  box-shadow: 4px 4px 0 var(--ink);
  color: var(--ink);
  cursor: pointer;
  font-family: var(--font-display);
  font-size: 1rem;
  font-weight: 600;
  grid-column: 2;
  padding: 0.5rem 1.125rem;
  transition:
    background-color 150ms ease-out,
    box-shadow 150ms ease-out;
}

slab-alert-dialog::part(cancel):hover {
  background-color: var(--chalk);
}

slab-alert-dialog::part(cancel):active {
  box-shadow: 1px 1px 0 var(--ink);
  transition-duration: 50ms;
}

slab-alert-dialog::part(cancel):focus-visible {
  outline: 3px solid var(--ember);
  outline-offset: 3px;
}

slab-alert-dialog > :not([slot]) {
  grid-column: 3;
}

@media (prefers-reduced-motion: reduce) {
  slab-alert-dialog::part(cancel) {
    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;
  }
}
```
