# Menu Infrastructure

A custom menu system built on native HTML popovers with keyboard navigation, tickled focus management, and command routing.

## Components

| Component | Description |
|------------|-------------|
| `ixfx-menu-bar` | Horizontal container for menu triggers; handles arrow-key navigation between top-level menus; while a menu is open, hovering another top-level trigger switches to its menu |
| `ixfx-menu-trigger` | Button or slot that opens a menu popover. Modes: `trigger` (button), `dropdown` (slot-only), `context` (right-click) |
| `ixfx-menu-container` | The popover panel holding menu items; manages keyboard focus and tickled state |
| `ixfx-menu-item` | Basic menu item that dispatches a `command` event |
| `ixfx-menu-check-item` | Toggle checkbox item; dispatches `command` with `checked` state |
| `ixfx-menu-radio-item` | Radio button item for use inside `ixfx-menu-radio-group` |
| `ixfx-menu-radio-group` | Groups radio items; dispatches `radio-change` when selection changes |
| `ixfx-menu-sub-trigger` | Menu item that reveals a nested submenu on hover or ArrowRight |
| `ixfx-menu-separator` | Visual divider between menu sections |
| `ixfx-menu-header` | Section label header |

## Architecture

Menus are built on the native HTML `<popover>` API. `ixfx-menu-trigger` owns a `<popover>` element and uses `showPopover()`/`hidePopover()` to open/close it. `ixfx-menu-container` is slotted into the popover and handles:

- **Tickled focus management** — tracks which item should be focused based on keyboard vs mouse input
- **Keyboard navigation** — Arrow keys, Home/End, Enter/Space to activate
- **Icon section alignment** — detects whether any item in a section has an icon and pads all items consistently

## Usage

### Declarative Style

Static menu markup in HTML:

```html
<ixfx-menu-bar>
  <ixfx-menu-trigger label="File" @menu-command=${handleCommand}>
    <ixfx-menu-container slot="menu">
      <ixfx-menu-item command="new" label="New"></ixfx-menu-item>
      <ixfx-menu-item command="open" label="Open"></ixfx-menu-item>
      <ixfx-menu-separator></ixfx-menu-separator>
      <ixfx-menu-item command="exit" label="Exit"></ixfx-menu-item>
    </ixfx-menu-container>
  </ixfx-menu-trigger>

  <ixfx-menu-trigger label="Edit" @menu-command=${handleCommand}>
    <ixfx-menu-container slot="menu">
      <ixfx-menu-check-item command="bold" label="Bold" checked></ixfx-menu-check-item>
      <ixfx-menu-check-item command="italic" label="Italic"></ixfx-menu-check-item>
    </ixfx-menu-container>
  </ixfx-menu-trigger>
</ixfx-menu-bar>
```

### Imperative Style

Building menus programmatically via Lit templates:

```ts
import { html } from 'lit';
import { MenuItem } from './menu/menu-item.js';
import { MenuContainer } from './menu/menu-container.js';
import { MenuTrigger } from './menu/menu-trigger.js';
import { MenuSeparator } from './menu/menu-separator.js';
import { MenuCheckItem } from './menu/menu-check-item.js';

function buildEditMenu(onCommand: (cmd: string) => void) {
  return html`
    <ixfx-menu-container slot="menu">
      <ixfx-menu-check-item
        command="bold"
        label="Bold"
        @command=${(e: CustomEvent) => onCommand(e.detail.command)}
      ></ixfx-menu-check-item>
      <ixfx-menu-check-item
        command="italic"
        label="Italic"
        @command=${(e: CustomEvent) => onCommand(e.detail.command)}
      ></ixfx-menu-check-item>
    </ixfx-menu-container>
  `;
}

const trigger = document.createElement('ixfx-menu-trigger');
trigger.label = 'Edit';
trigger.addEventListener('menu-command', (e) => console.log(e.detail));
trigger.appendChild(buildEditMenu(myHandler));
```

### Building Menus from TreeNode Structure

Use `menuFromTree()` or `menuFromTreeToElements()` to construct menus from a `TreeNode[]` array:

```ts
import { menuFromTree, menuFromTreeToElements } from './menu/menu-from-tree.js';
import type { TreeNode } from './tree/types.js';

const nodes: TreeNode[] = [
  { item: { key: 'new', label: 'New' } },
  { item: { key: 'open', label: 'Open...' } },
  { item: { key: 'sep1', label: '-' } }, // becomes separator
  { item: { key: 'sep2', label: '# File' } }, // becomes header "File"
  {
    item: { key: 'submenu', label: 'Submenu' },
    children: [
      { item: { key: 'action1', label: 'Action 1' } },
      { item: { key: 'action2', label: 'Action 2' } },
    ],
  },
  { item: { key: 'quit', label: 'Quit' } },
];
```

**Rules:**
- `label === "-"` → separator
- `label.startsWith("# ")` → header (prefix stripped)
- Node has `children` → submenu trigger (no command)
- Leaf node → menu item with `command = item.key`

**In Lit templates** (declarative):
```ts
// Inside a Lit component's render()
return html`
  <ixfx-menu-trigger label="File">
    <ixfx-menu-container slot="menu">
      ${menuFromTree(nodes, { onCommand: this.handleCommand, registry: this.registry })}
    </ixfx-menu-container>
  </ixfx-menu-trigger>
`;
```

**Imperatively** (using DOM):
```ts
const elements = menuFromTreeToElements(nodes, { onCommand: handleCommand });
for (const el of elements) {
  container.appendChild(el);
}
```

### Programmatic Open/Close

```ts
const trigger = document.querySelector('ixfx-menu-trigger');

// Open
trigger.openMenu();

// Close
trigger.closeMenu();

// Check state
console.log(trigger.isOpen);
```

### Submenus

Use `ixfx-menu-sub-trigger` with a nested `ixfx-menu-container` in its `submenu` slot:

```html
<ixfx-menu-item command="view" label="View">
  <ixfx-menu-container slot="submenu">
    <ixfx-menu-item command="zoom-in" label="Zoom In"></ixfx-menu-item>
    <ixfx-menu-item command="zoom-out" label="Zoom Out"></ixfx-menu-item>
  </ixfx-menu-container>
</ixfx-menu-item>
```

### Radio Groups

```html
<ixfx-menu-radio-group name="alignment" value="left" @radio-change=${handleAlign}>
  <ixfx-menu-radio-item value="left" label="Left"></ixfx-menu-radio-item>
  <ixfx-menu-radio-item value="center" label="Center"></ixfx-menu-radio-item>
  <ixfx-menu-radio-item value="right" label="Right"></ixfx-menu-radio-item>
</ixfx-menu-radio-group>
```

### Context Menu Mode

Set `mode="context"` on the trigger. The menu opens at the cursor position when the user right-clicks. Put the surface that should respond to right-clicks (a list, canvas or whole panel) in the `context-target` slot. It replaces the `trigger` slot for this mode:

```html
<div class="panel"> <!-- e.g. display: flex; flex-direction: column; height: 300px -->
  <ixfx-menu-trigger mode="context" @menu-command=${handleContextMenu}>
    <ul slot="context-target" class="file-list"> <!-- e.g. overflow: auto -->
      <li>…</li>
    </ul>
    <ixfx-menu-container slot="menu">
      <ixfx-menu-item command="cut" label="Cut"></ixfx-menu-item>
      <ixfx-menu-item command="copy" label="Copy"></ixfx-menu-item>
      <ixfx-menu-item command="paste" label="Paste"></ixfx-menu-item>
    </ixfx-menu-container>
  </ixfx-menu-trigger>
</div>
```

How it behaves:
- **No extra button.** When a `context-target` is slotted, the default trigger button isn't rendered. A left click goes to your surface as normal and doesn't open the menu. If you slot only `menu`, a default button is still shown.
- **Layout.** When a `context-target` is slotted, the trigger's host and its inner wrapper both use `display: contents`. That makes the slotted surface the item in the parent's flex or grid layout, as if the trigger weren't there. In a height-constrained flex column, a surface with `overflow: auto` is clipped and scrolls on its own. You don't need extra CSS for this.
- **Focus.** Escape or Tab closes the menu and moves focus back to the element that had it when the menu opened, such as a row inside the surface.
- **Events.** `menu-trigger-open` and `menu-trigger-close` fire for context opens too.

To keep a real box instead (for example, a visible trigger mixed with a context target), use these properties:

| Variable | Default | Description |
|----------|---------|-------------|
| `--menu-trigger-display` | `contents` | `display` of the host when a `context-target` is slotted |
| `--menu-trigger-area-display` | `contents` | `display` of the inner trigger wrapper in context mode |
| `--menu-trigger-area-flex` | `initial` | `flex` of the inner trigger wrapper in context mode |

### Command Registry Integration

Pass a `CommandRegistry` to the trigger and/or container. Items resolve their label and icon from the registry if not explicitly set:

```ts
import { CommandRegistry } from '@clinth/ui-commands';

const registry = new CommandRegistry();
registry.register('bold', { label: 'Bold', icon: 'bold' });
registry.register('italic', { label: 'Italic', icon: 'italic' });

trigger.registry = registry;
container.registry = registry;
```

```html
<!-- label and icon resolved from registry -->
<ixfx-menu-item command="bold"></ixfx-menu-item>
<ixfx-menu-item command="italic"></ixfx-menu-item>
```

### Keyboard Shortcuts

Pass a `KeyboardManager` to display shortcuts next to menu items:

```ts
import { KeyboardManager } from '@clinth/ui-commands';

keyboardManager.bind('bold', { key: 'b', modifiers: ['ctrl'] });
keyboardManager.bind('italic', { key: 'i', modifiers: ['ctrl'] });

trigger.keyboardManager = keyboardManager;
```

## Styling

### CSS Custom Properties

`ixfx-menu-item` and `ixfx-menu-check-item` use the generic "Item States" variable family documented in `user-theming.md` (`--item-bg`, `--item-bg-tickled`, `--item-border`, `--item-border-tickled`, `--item-text-tickled`, etc.) — the same family used by other list/item components such as `ixfx-vertical-list` and `ixfx-select-horiz`.

The trigger button and menu bar additionally expose a couple of underscore-prefixed variables — the underscore marks these as narrowly-scoped internal tuning knobs (unlike the generic `--item-*` family above, they have no effect outside the trigger/bar):

| Variable | Default | Description |
|----------|---------|-------------|
| `--_trigger-hover-bg` | `var(--surface-4)` | Trigger button hover background |
| `--_trigger-hover-opacity` | `1` | Trigger button hover opacity |

Public layout variables:

| Variable | Default | Description |
|----------|---------|-------------|
| `--ixfx-button-padding` | `var(--space-s) var(--space-m)` | Padding of the default trigger button |
| `--menu-max-height` | `min(60vh, 400px)` | Max height of a menu panel; taller menus scroll, with an edge fade |
| `--menu-popup-offset` | `var(--space-xs)` | Distance between a trigger and its menu popup |
| `--menu-bar-gap` | `var(--space-xs)` | Gap between top-level triggers in `ixfx-menu-bar` |
| `--menu-bar-padding` | `var(--space-xs)` | Padding around the items in `ixfx-menu-bar` |

The popup surface uses these from `popupSurfaceStyles`:

| Variable | Description |
|----------|-------------|
| `--surface-5` | Menu background |
| `--surface-6` | Menu border |
| `--surface-5-text` | Menu text color |
| `--shadow-m` | Box shadow |

### Custom Item Background Colors

```css
/* Apply to ixfx-menu-container, or globally on :root */
ixfx-menu-container {
  --item-bg-tickled: #ffcccc;
}
```

### Custom Trigger Styling

```css
ixfx-menu-trigger {
  --_trigger-hover-bg: #eeeeee;
  --_trigger-hover-opacity: 0.8;
}
```

### Per-Item Styling

Style menu items from the outside by targeting their tag name or by attaching a class attribute and selecting within:

```css
ixfx-menu-item[command="delete"] .item {
  color: red;
}

/* Target a specific menu via a wrapper */
.file-menu ixfx-menu-item .item {
  font-weight: bold;
}
```

## Events

| Event | Detail | Description |
|-------|--------|-------------|
| `command` | `{ command, args }` | Fired by `ixfx-menu-item` |
| `command` | `{ command, args, checked }` | Fired by `ixfx-menu-check-item` |
| `radio-select` | `{ value }` | Fired by `ixfx-menu-radio-item` |
| `radio-change` | `{ name, value }` | Fired by `ixfx-menu-radio-group` when selection changes |
| `menu-command` | `{ command, args, checked }` | Bubbles up from `ixfx-menu-trigger`, re-dispatching a `command`/`checked` event's detail verbatim — `args` is always present, `checked` only from a check-item |
| `menu-command` | `{ command, value }` | Bubbles up from `ixfx-menu-trigger`, built from a `radio-change` event — `value` only appears on this radio-group path, never alongside `args`/`checked` |
| `menu-trigger-open` | — | Fired by `ixfx-menu-trigger` when its menu opens (any mode, including right-click in `context` mode) |
| `menu-trigger-close` | — | Fired by `ixfx-menu-trigger` when its menu closes |

## `ixfx-menu-command-controller`

A helper class that listens for `command` events and invokes a `CommandRegistry`:

```ts
import { MenuCommandController } from './menu/menu-command-controller.js';

const ctrl = new MenuCommandController({ registry, target: document });
ctrl.start();

// Now any menu item with a matching command will invoke the registry
```

## Mode Reference

`ixfx-menu-trigger` supports three `mode` values:

| Mode | Trigger Behavior |
|------|-----------------|
| `trigger` | Shows a button labeled with the `label` property |
| `dropdown` | No button shown; expects a custom trigger in the `trigger` slot |
| `context` | Opens at cursor position on right-click. Put the right-clickable surface in the `context-target` slot |

## Placement

The `placement` attribute controls popover anchoring:

| Value | Position |
|-------|----------|
| `bottom-start` | Below trigger, left edge aligned (default) |
| `bottom-end` | Below trigger, right edge aligned |
| `right-start` | To the right of trigger, top edge aligned |
