# Context Menu

> Menu's Menu Items, opened where the user right-clicks or long-presses, or from the keyboard, in place of the browser's own menu.

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

## Install

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

## Usage

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

<slab-context-menu label="File">
  <div slot="target" tabindex="0">Right-click me</div>

  <slab-menu-item>Rename</slab-menu-item>
  <slab-menu-item>Duplicate</slab-menu-item>
  <slab-menu-item disabled>Delete</slab-menu-item>
</slab-context-menu>
```

## Example

Here's a styled version, `<slab-styled-context-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-context-menu label="Pour actions">
  <div slot="target" tabindex="0">Right-click or long-press the pour</div>

  <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-context-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". Make the target focusable, or put something focusable in it, so the keyboard can open the menu too. Prevent the default of a "contextmenu" in part of the target to keep the menu from opening there.

On iOS, a long-press on text also starts selecting it. Give the target `user-select: none` if that gets in the way.

## Keyboard

| Key             | What it does                                                                  |
| --------------- | ----------------------------------------------------------------------------- |
| Shift+F10, Menu | In the target, opens the menu below what has focus, at the first 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 where it was.                            |
| Tab             | Closes the menu and moves focus on.                                           |

## Behavior

### `<slab-context-menu>`

A context menu with no visual styles: a list of Menu Items that opens over whatever is slotted into `target`, where the user asks for it, in place of the browser's own.

It opens on a right-click, and on Control-click on a Mac, at the pointer. It opens on a long-press with a finger or a pen too, where it was pressed. And it opens on Shift+F10 or the Menu key, below whatever in the target has focus. The browser's menu doesn't open for any of them. A "contextmenu" whose default a consumer has already prevented is left alone, so a part of the target, or a Context Menu nested in it, can have a menu of its own.

Its Menu Items are Menu's, in a `[role=menu]` element in a native `[popover]`, and the keyboard is Menu's. 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. Enter, Space and a click click the Menu Item and close the menu. Escape and Tab close it, Escape returning focus to where it was.

It's kept on screen, opening up or back from the pointer when there isn't room below or after it, as the operating system's do.

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-context-menu>`

#### Attributes

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `label` (required) | `string` |  | Names the menu. |
| `open` | `boolean` | `false` |  |
| `version` | `string` |  |  |

#### Properties

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

#### Methods

| Signature | Description |
| --- | --- |
| `hide(): void` |  |
| `show(position?: { x: number; y: number }): void` | Opens the menu at `x` and `y`, in the viewport's coordinates, or below whatever in the target has focus when they're left out. |

#### Slots

| Name | Type | Description |
| --- | --- | --- |
| `target` | `Element` | Where a right-click, a long-press, or Shift+F10 opens the menu |
| `(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-context-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.

### context-menu.ts

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

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

/**
 * Context Menu, styled: Menu's paper panel with an ink border and a hard
 * shadow, over a dashed target.
 */
@customElement('slab-styled-context-menu')
export default class StyledContextMenu extends ContextMenu {
  static override styles = [tokens, styles];
}
```

### context-menu.styles.ts

```ts
import { css } from 'lit';
import menu from './menu.styles.js';

export default [
  menu,
  css`
    /* Menu's drops from its anchor. This one opens at a point, so no margin. */
    [part~='popover'] {
      margin: 0;
    }

    ::slotted([slot='target']) {
      border: 2px dashed var(--ash);
      display: grid;
      min-block-size: 8rem;
      padding: 1rem;
      place-items: center;
      user-select: 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);
  }
`;
```
