# Menu

> A button that opens a list of actions. It's the APG's menu button, keyboard and all.

`<slab-menu>` · Navigation · built on `[role=menu] + [popover]`

## Install

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

## Usage

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

<slab-menu label="File">
  <button slot="anchor">File</button>

  <slab-menu-item>New</slab-menu-item>
  <slab-menu-item>Open…</slab-menu-item>
  <slab-menu-item disabled>Save</slab-menu-item>
</slab-menu>
```

## Example

Here's a styled version, `<slab-styled-menu>`. 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
<slab-styled-menu label="Job actions">
  <button class="styled-button" slot="anchor" type="button">Actions</button>

  <slab-styled-menu-item>Schedule a pour</slab-styled-menu-item>
  <slab-styled-menu-item>Duplicate job</slab-styled-menu-item>
  <slab-styled-menu-item>Export report</slab-styled-menu-item>
  <slab-styled-menu-item disabled>Call the inspector</slab-styled-menu-item>
</slab-styled-menu>
```

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.

To do something when a Menu Item is chosen, listen for its "click".

## Keyboard

| Key                | What it does                                                                  |
| ------------------ | ----------------------------------------------------------------------------- |
| Enter, Space, Down | On the anchor, opens the menu at the first Menu Item.                         |
| Up                 | On the anchor, opens the menu at the last Menu Item.                          |
| Up, Down           | Moves to the previous or next Menu Item, wrapping and skipping disabled ones. |
| Home, End          | Moves to the first or last Menu Item.                                         |
| A character        | Moves to the next Menu Item whose label starts with what's typed.             |
| Enter, Space       | Clicks the active Menu Item and closes the menu.                              |
| Escape             | Closes the menu and returns focus to the anchor.                              |
| Tab                | Closes the menu and moves focus on.                                           |

## Behavior

### `<slab-menu>`

A menu with no visual styles: a button that opens a list of Menu Items, to act on one.

It's the APG's menu button. There's no native menu, so the Menu Items are in a `[role=menu]` element in a native `[popover="auto"]`, opened from whatever is slotted into `anchor`. A click on the anchor, or Enter or Space, opens it at the first Menu Item, and the Up arrow opens it at the last.

Focus moves to the menu while it's open, and its `aria-activedescendant` points at the active Menu Item. The Up and Down arrows move through the Menu Items, wrapping and skipping disabled ones, Home and End go to the first and last, and typing moves to the next one whose label starts with what was typed. Hovering a Menu Item makes it the active one, as in the APG's examples. Enter, Space and a click click the Menu Item and close the menu. Escape and Tab close it, Escape returning focus to the anchor.

The popover is placed beside the anchor with CSS anchor positioning, the way Popover's is. `placement` picks the side and nothing else.

Style it through its parts and `:state(open)`, and each Menu Item through the states Menu Item sets.

### `<slab-menu-item>`

A Menu Item with no visual styles. The host is the menu item, so style it directly.

Listen for "click" on it to act on it. Its Menu clicks it for Enter and Space, the way a button is clicked from the keyboard, and closes once it has. A disabled Menu Item isn't clicked, again like a button.

It's never focused. Focus stays on its Menu, which points at the active Menu Item with `aria-activedescendant`.

Its Menu sets `:state(active)`. It sets `:state(disabled)` itself.

## API

### `<slab-menu>`

#### Attributes

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `label` (required) | `string` |  | Names the menu. |
| `open` | `boolean` | `false` |  |
| `placement` | `'bottom' \| 'left' \| 'right' \| 'top'` | `'bottom'` | The side of its anchor it opens on, when there's room. It flips when there isn't. |
| `version` | `string` |  |  |

#### Properties

| Name | Type | Description |
| --- | --- | --- |
| `items` (read-only) | `MenuItem[]` |  |

#### Methods

| Signature | Description |
| --- | --- |
| `hide(): void` |  |
| `show(): void` |  |

#### Slots

| Name | Type | Description |
| --- | --- | --- |
| `anchor` | `Element` | What opens the menu, usually a \`<button>\` |
| `(default)` | `MenuItem` |  |

#### CSS parts

| Name | Description |
| --- | --- |
| `menu` | The Menu Items |
| `popover` | What the menu opens in |

### `<slab-menu-item>`

#### Attributes

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `label` | `string` |  | Names the Menu Item in place of its text, and is what typeahead matches against. |
| `disabled` | `boolean` | `false` |  |
| `version` | `string` |  |  |

#### Properties

| Name | Type | Description |
| --- | --- | --- |
| `text` (read-only) | `string` | What the user reads as the Menu Item's name: its label, or its text when it has no label. |

#### Slots

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

## Copy and own it

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

### menu.ts

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

declare global {
  interface HTMLElementTagNameMap {
    'slab-styled-menu': StyledMenu;
  }
}

/**
 * Menu, styled: its Menu Items in a paper panel with an ink border and a hard
 * shadow.
 */
@customElement('slab-styled-menu')
export default class StyledMenu extends Menu {
  static override styles = [tokens, styles];
}
```

### menu.styles.ts

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

export default css`
  /* A closed popover isn't displayed, so this runs each time it opens. */
  [part~='popover'] {
    animation: drop 150ms ease-out;
    background-color: var(--paper);
    border: var(--border);
    box-shadow: var(--shadow);
    color: var(--ink);
    font-family: var(--font-body);
    margin: 0.5rem 0;
    min-inline-size: 12rem;
    padding: 0.25rem 0;
  }

  /*
    The menu is focused for as long as it's open, and the active Menu Item is
    what shows where the keyboard is, so the menu itself has no outline.
  */
  [part~='menu']:focus {
    outline: none;
  }

  @keyframes drop {
    from {
      opacity: 0;
      translate: 0 -0.375rem;
    }
  }

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

### menu.item.ts

```ts
import { customElement } from 'lit/decorators.js';
import MenuItem from 'slab-elements/menu.item.js';
import styles from './menu.item.styles.js';
import tokens from './tokens.styles.js';

declare global {
  interface HTMLElementTagNameMap {
    'slab-styled-menu-item': StyledMenuItem;
  }
}

/**
 * Menu Item, styled: a row that inverts to paper on ink while it's active,
 * with an ember bar on its edge, as Option does. Hovering makes it active.
 */
@customElement('slab-styled-menu-item')
export default class StyledMenuItem extends MenuItem {
  static override styles = [tokens, styles];
}
```

### menu.item.styles.ts

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

export default css`
  :host {
    border-inline-start: 4px solid transparent;
    cursor: pointer;
    padding: 0.5rem 0.875rem 0.5rem 0.75rem;
    transition:
      background-color 100ms,
      border-color 100ms,
      color 100ms;
  }

  :host(:state(active)) {
    background-color: var(--ink);
    border-inline-start-color: var(--ember);
    color: var(--paper);
  }

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

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

  @media (prefers-reduced-motion: reduce) {
    :host {
      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);
  }
`;
```
