# Dialog

> A modal dialog built on the native `<dialog>`. Focus stays inside, Escape closes it, and the rest of the page goes inert — the platform does the heavy lifting.

`<slab-dialog>` · Overlays · built on `<dialog> (modal)`

## Install

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

## Usage

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

<slab-dialog label="Delete this file?">
  <p>It can't be recovered.</p>

  <form method="dialog">
    <button value="cancel">Cancel</button>
    <button value="delete">Delete</button>
  </form>
</slab-dialog>
```

## Example

Here's a styled version, `<slab-styled-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">
  Strip forms
</button>

<slab-styled-dialog id="dialog-example" label="Strip the forms?" closedby="any">
  <p>
    It's day 2 of 7. Concrete reaches about 70% of its strength in a week,
    and stripping the forms now can crack the edges.
  </p>

  <form class="actions" method="dialog">
    <button class="styled-button" value="cancel">Wait</button>
    <button class="styled-button styled-button--danger" value="strip">Strip anyway</button>
  </form>
</slab-styled-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.

Open it by setting `open`. When it closes, `returnValue` tells you which
button did it — same as a `<dialog>`.

## Keyboard

| Key            | What it does                                                                      |
| -------------- | --------------------------------------------------------------------------------- |
| Tab, Shift+Tab | Moves focus between the dialog's controls. The rest of the page is inert.         |
| Escape         | Closes the dialog and dispatches "cancel", which can be canceled to keep it open. |

## Behavior

A modal dialog with no visual styles, around a native `<dialog>` opened with `showModal()`, so it traps focus, closes on Escape, has a `::backdrop`, and makes the rest of the page inert the way one does.

`open` reflects, and it stays true to the dialog: when the dialog closes itself, on Escape or through a `<form method="dialog">`, `open` goes false along with it. `close(returnValue)` and a `<form method="dialog">`'s submitter both set `returnValue`, as they do on a `<dialog>`.

The dialog is named by its label: the `label` attribute or the `label` slot. The label isn't a heading, because a heading's level is the page's to choose. Plain `label` text names the dialog without being one. For a heading, slot your own at whatever level fits: `<h2 slot="label">`.

Light dismiss is the platform's or nothing. `closedby="any"` is passed through to the `<dialog>`, which closes on a backdrop click where the browser supports it and ignores the attribute where it doesn't. Nothing here listens for clicks on the backdrop to fake it.

Style it through its parts, and the backdrop through `::part(dialog)::backdrop`.

## API

### `<slab-dialog>`

#### Attributes

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `closedby` | `'any' \| 'closerequest' \| 'none'` |  | Passed to the `<dialog>`. "any" closes it on a click outside it where the browser supports that. Browsers that don't ignore it. |
| `hide-label` | `boolean` | `false` |  |
| `label` | `string` |  |  |
| `open` | `boolean` | `false` |  |
| `version` | `string` |  |  |

#### 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` |  |
| `show(): void` |  |

#### Events

| Name | Type | Description |
| --- | --- | --- |
| `cancel` | `Event` |  |
| `close` | `Event` |  |

#### Slots

| Name | Type | Description |
| --- | --- | --- |
| `label` | `Element \| string` |  |
| `(default)` | `Element \| string` |  |

#### CSS parts

| Name | Description |
| --- | --- |
| `dialog` | The native dialog. A modal one's backdrop is its ::backdrop |
| `label` | The label |

## Copy and own it

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

### dialog.ts

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

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

/**
 * Dialog, styled: a paper slab under an ink header with an ember base, casting
 * an ember shadow over a dimmed page.
 */
@customElement('slab-styled-dialog')
export default class StyledDialog extends Dialog {
  static override styles = [tokens, 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);
    line-height: 1.5;
    padding: 0 1.5rem 1.5rem;

    &::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;
    }
  }
`;
```

### 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);
  }
`;
```
