# Tab layout components

A complete tabbed interface system using several coordinated components:

- **`ixfx-tab-list`** — Tab header bar with tab buttons
- **`ixfx-tab-list-item`** — Individual tab button
- **`ixfx-tab-panel`** — Content panel for a single tab
- **`ixfx-tab-panels`** — Container managing multiple panels

## Basic usage

```html
<ixfx-tab-list>
  <ixfx-tab-list-item id="tab-home" for="panel-home">Home</ixfx-tab-list-item>
  <ixfx-tab-list-item id="tab-profile" for="panel-profile">Profile</ixfx-tab-list-item>
</ixfx-tab-list>

<ixfx-tab-panels>
  <ixfx-tab-panel id="panel-home">Home content</ixfx-tab-panel>
  <ixfx-tab-panel id="panel-profile">Profile content</ixfx-tab-panel>
</ixfx-tab-panels>
```

Wire them together:

```js
const tabList = document.querySelector('ixfx-tab-list');
const tabPanels = document.querySelector('ixfx-tab-panels');
tabList.addEventListener('change', e => {
  tabPanels.selectPanel(e.detail.for);
});
```

Select a tab programmatically — same effect as clicking it (header + content):

```js
tabPanels.syncWithList(tabList);
tabPanels.selectTab('Home');        // by label text
tabPanels.selectTab('panel-home');  // by the panel id a tab's `for` points at
```

---

## `ixfx-tab-list`

Manages tab selection and keyboard navigation.

### Properties / attributes

| Attribute / Property | Type                              | Default        | Description                      |
|---------------------|-----------------------------------|----------------|----------------------------------|
| `orientation`       | `'horizontal' \| 'vertical-stack' \| 'vertical-side'` | `'horizontal'` | Layout direction |
| `flip`              | `boolean`                          | `false`        | Flip indicator to opposite side   |
| `scrollable`        | `boolean`                          | `false`        | Enable scroll overflow. When set, vertical mousewheel on horizontal lists scrolls horizontally (and vice-versa for vertical lists). |
| `shrink`            | `boolean`                          | `false`        | When set, tabs size to content (intrinsic width for horizontal, intrinsic height for vertical) instead of stretching to fill the container |
| `drag-mode`         | `'off' \| 'reorder'`                | `'off'`        | Pointer-driven reordering within the list (sets `grab` cursor on items) |

### Slots

| Slot        | Description                                                                 |
|-------------|-----------------------------------------------------------------------------|
| *(default)* | `ixfx-tab-list-item` elements.                                              |
| `toolbar`   | Toolbar items shown after the tabs. For `orientation="horizontal"` this is right-justified after the tabs and does not scroll with `scrollable`. Put an `ixfx-toolbar` in this slot to get automatic overflow handling. Plain buttons/elements work as well. |

Toolbar example (with overflow):

```html
<ixfx-tab-list>
  <ixfx-tab-list-item selected for="p1">Tab A</ixfx-tab-list-item>
  <ixfx-tab-list-item for="p2">Tab B</ixfx-tab-list-item>

  <ixfx-toolbar slot="toolbar" invisible-groups style="--toolbar-bg:transparent; --toolbar-border:none; --toolbar-padding:0;">
    <ixfx-button>New</ixfx-button>
    <ixfx-button>Save</ixfx-button>
    <ixfx-button>Export</ixfx-button>
  </ixfx-toolbar>
</ixfx-tab-list>
```

For a simple toolbar without overflow, use plain buttons:

```html
<ixfx-tab-list>
  <ixfx-tab-list-item>Tab A</ixfx-tab-list-item>
  <button slot="toolbar" type="button" class="tab-toolbar-btn">Action</button>
</ixfx-tab-list>
```

When `orientation="vertical-stack"` / `vertical-side`, the toolbar slot appears after the tabs in the column direction (below the tabs). It is still outside the scrollable tab area.

### Events

| Event    | Detail                                               | Description               |
|----------|------------------------------------------------------|---------------------------|
| `change` | `{ previous, selected, for }`                       | Tab selection changed     |
| `reorder` | `{ id, fromIndex, toIndex }`                       | Tab reordered (only fired when `drag-mode="reorder"`). Fires after the DOM has been updated. Press <kbd>Esc</kbd> or receive a `pointercancel` while dragging to abort — no `reorder` event fires in that case. |

### Methods

| Method             | Argument | Returns | Description            |
|--------------------|----------|---------|------------------------|
| `getSelectedElement()` | — | `TabListItemElement \| undefined` | Get currently selected tab |
| `selectElement(el)` | `HTMLElement` | `void` | Programmatically select a tab |

### CSS custom properties

| Property           | Default          | Description               |
|--------------------|------------------|---------------------------|
| `--activated-colour` | `var(--accent)` | Active tab color          |
| `--colour`          | `var(--surface-4)` | Inactive tab background |
| `--scroll-max-height` | `200px`      | Max height when scrollable |

---

## `ixfx-tab-list-item`

Individual tab button within the tab list.

### Properties / attributes

| Attribute / Property  | Type     | Default | Description                    |
|-----------------------|----------|---------|--------------------------------|
| `closeable`           | `boolean`| `false` | Show close button               |
| `iconName`            | `string \| undefined` | `undefined` | Icon to display      |
| `description`         | `string \| undefined` | `undefined` | Tooltip description |
| `commandActive`       | `string \| undefined` | `undefined` | Command ID that triggers click |
| `registry`            | `CommandRegistry \| undefined` | `undefined` | Command registry for `commandActive` |

### Slots

| Slot        | Description                                                                 |
|-------------|-----------------------------------------------------------------------------|
| *(default)* | Tab label text                                                              |
| `toolbar`   | Buttons or controls shown right-aligned when the tab is **selected**, before the close button. Multiple elements may use `slot="toolbar"`. |

Toolbar buttons should use a plain icon-button style so they blend with the tab chrome. Clicks on toolbar content do not stop propagation — because the toolbar is only visible when the tab is already selected, this has no side-effect on tab switching.

```html
<!-- Single icon button in toolbar -->
<ixfx-tab-list-item selected for="panel-home" closeable>
  Home
  <button slot="toolbar" type="button" class="tab-toolbar-btn" aria-label="Refresh">
    <ixfx-icon name="refresh"></ixfx-icon>
  </button>
</ixfx-tab-list-item>
```

Multiple elements can occupy the toolbar slot:

```html
<ixfx-tab-list-item for="panel-sources" closeable>
  Sources
  <button slot="toolbar" type="button" class="tab-toolbar-btn" aria-label="Refresh">
    <ixfx-icon name="refresh"></ixfx-icon>
  </button>
  <button slot="toolbar" type="button" class="tab-toolbar-btn" aria-label="Filter">
    <ixfx-icon name="filter"></ixfx-icon>
  </button>
  <button slot="toolbar" type="button" class="tab-toolbar-btn" aria-label="Settings">
    <ixfx-icon name="settings"></ixfx-icon>
  </button>
</ixfx-tab-list-item>
```

Use `ixfx-menu-trigger` with `slot="trigger"` to add a popup menu to the toolbar:

```html
<ixfx-tab-list-item for="panel-console" closeable>
  Console
  <ixfx-menu-trigger slot="toolbar" placement="bottom-start">
    <button slot="trigger" type="button" class="tab-toolbar-btn" aria-label="Console options">
      <ixfx-icon name="filter"></ixfx-icon>
    </button>
    <ixfx-menu-container slot="menu">
      <ixfx-menu-item command="console-clear" label="Clear console"></ixfx-menu-item>
      <ixfx-menu-separator></ixfx-menu-separator>
      <ixfx-menu-item command="console-filter-errors" label="Errors only"></ixfx-menu-item>
      <ixfx-menu-item command="console-filter-all" label="Show all"></ixfx-menu-item>
    </ixfx-menu-container>
  </ixfx-menu-trigger>
</ixfx-tab-list-item>
```

A recommended `.tab-toolbar-btn` style for the page stylesheet:

```css
.tab-toolbar-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  background: none;
  border: none;
  cursor: pointer;
  padding: var(--space-xs);
  color: inherit;
  border-radius: var(--radius-s);
  opacity: var(--prominence-idle-opacity);
  transition: opacity var(--transition, 0.15s), background var(--transition, 0.15s);
}
.tab-toolbar-btn:hover {
  background: var(--surface-5);
  opacity: var(--prominence-tickled-opacity);
}
```

### Events

| Event    | Detail | Description                |
|----------|--------|----------------------------|
| `close`  | —      | Fired when close button clicked; item removes itself from DOM |

### Command activation

Tabs can be programmatically activated via the `CommandRegistry` system. This is useful for keyboard shortcuts (e.g. `Alt+1` to switch to tab 1).

1. Create a `CommandRegistry` and register commands for each tab:
```js
import { CommandRegistry } from '@clinth/ui-commands';

const commands = new CommandRegistry();
commands.register({ id: 'tab-home', label: 'Home', description: 'Switch to Home tab', execute: () => {} });
commands.register({ id: 'tab-profile', label: 'Profile', description: 'Switch to Profile tab', execute: () => {} });
```

2. Bind keyboard shortcuts to the commands using `KeyboardManager`:
```js
import { KeyboardManager } from '@clinth/ui-commands';

const keyboard = new KeyboardManager();
keyboard.bind({ key: '1', modifiers: new Set(['alt']), commandId: 'tab-home' });
keyboard.bind({ key: '2', modifiers: new Set(['alt']), commandId: 'tab-profile' });
keyboard.onKeyEvent((commandId) => commands.invoke(commandId));
keyboard.attach(document.body);
```

3. Set the `command-active` attribute and assign the registry to each tab item:
```html
<ixfx-tab-list>
  <ixfx-tab-list-item command-active="tab-home">Home</ixfx-tab-list-item>
  <ixfx-tab-list-item command-active="tab-profile">Profile</ixfx-tab-list-item>
</ixfx-tab-list>
```

```js
for (const item of document.querySelectorAll('ixfx-tab-list-item[command-active]')) {
  item.registry = commands;
}
```

When a command is invoked (via keyboard shortcut or `commands.invoke('tab-home')`), the associated tab will be activated as if clicked.

### CSS custom properties

All `--ixfx-*` properties use internal bridge variables to work across the Shadow DOM boundary.

| Property                          | Default               | Description                                                                 |
|-----------------------------------|----------------------|-----------------------------------------------------------------------------|
| `--ixfx-selected-tab-color`       | `var(--surface-2-text)` | Text color when selected. Can be set on `ixfx-tab-list` or individual items |
| `--ixfx-selected-tab-icon-color`  | `var(--accent)` | Leading icon color when selected (close/toolbar icons unaffected). Can be set on `ixfx-tab-list` or individual items |
| `--ixfx-selected-tab-border-width`| `1px`                | Border width when selected                                                   |
| `--ixfx-selected-tab-weight`     | `bold`               | Font weight when selected                                                   |
| `--ixfx-selected-tab-text-decoration` | `none`           | Text decoration when selected (e.g. `underline`)                           |
| `--ixfx-selected-tab-text-decoration-color` | `var(--accent)` | Color of the text decoration when selected                                   |
| `--ixfx-selected-tab-text-decoration-thickness` | `0px`        | Thickness of the text decoration line when selected                          |
| `--ixfx-selected-tab-text-decoration-offset` | `2px`     | Space between text and text decoration when selected                         |
| `--ixfx-tab-selected-background`  | `var(--surface-5)`   | Background when selected. Can be set on `ixfx-tab-list` or individual items |
| `--ixfx-tab-hover-background`     | *(resting background)* | Background on hover. Unset by default, so each state keeps its resting background. Can be set on `ixfx-tab-list` or individual items |
| `--ixfx-tab-padding`              | `var(--space-m)`     | Inner padding of each tab. Can be set on `ixfx-tab-list` or individual items |

Example — set custom padding on a single tab:

```html
<ixfx-tab-list-item style="--ixfx-tab-padding: var(--space-l);">
  Wide Tab
</ixfx-tab-list-item>
```

Example — set custom padding for all tabs in a list:

```html
<ixfx-tab-list style="--ixfx-tab-padding: var(--space-xs);">
  <ixfx-tab-list-item>Compact</ixfx-tab-list-item>
  <ixfx-tab-list-item>Compact</ixfx-tab-list-item>
</ixfx-tab-list>
```

Example — thick text underline instead of a border indicator:

```html
<ixfx-tab-list style="
  --ixfx-selected-tab-border-width: 0;
  --ixfx-selected-tab-text-decoration: underline;
  --ixfx-selected-tab-text-decoration-thickness: 3px;
  --ixfx-selected-tab-text-decoration-offset: 4px;
">
  <ixfx-tab-list-item selected>Overview</ixfx-tab-list-item>
  <ixfx-tab-list-item>Details</ixfx-tab-list-item>
</ixfx-tab-list>
```

### Sliding indicator and view transitions

Each selected item draws an indicator bar (the item's `::after`). It sits on the bottom edge (top with `flip`; right/left for vertical orientations). It and its animation are **off by default** and are controlled with CSS variables, set on `ixfx-tab-list` (or any ancestor):

| Property | Default | Description |
|----------|---------|-------------|
| `--ixfx-tab-indicator-thickness` | `0px` | Indicator thickness. `0px` turns the indicator off |
| `--ixfx-tab-indicator-colour` | `var(--accent)` | Indicator colour |
| `--ixfx-tab-indicator-radius` | `0px` | Corner radius |
| `--ixfx-tab-indicator-inset` | `0px` | Inset from both ends of the tab edge |
| `--ixfx-tab-indicator-offset` | `0px` | Distance from the tab edge (negative values move it outside) |
| `--ixfx-tab-transition-duration` | *(unset)* | Animate selection changes with the View Transitions API. Unset or `0ms` turns animation off |
| `--ixfx-tab-transition-easing` | `cubic-bezier(0.3333, 0, 0.6667, 1)` | Easing for the indicator's movement. The default is a smoothstep curve (3t² − 2t³) |

```html
<ixfx-tab-list style="
  --ixfx-selected-tab-border-width: 0;
  --ixfx-tab-indicator-thickness: 3px;
  --ixfx-tab-transition-duration: 250ms;
">
```

Notes:

- The indicator is drawn in addition to the existing border indicator; set `--ixfx-selected-tab-border-width: 0` to use only the sliding one.
- Animation applies to user-initiated changes (click, arrow keys). The click selection and the `change` event run inside the same transition, so a panel swapped in a `change` listener animates with the header (a page-wide cross-fade). Programmatic `selectElement()` stays synchronous and instant.
- Under a view transition the browser applies the `selected` change on the next frame rather than synchronously, so code reading `getSelectedElement()` immediately after a click may see the previous tab; listen for `change` instead.
- Browsers without `document.startViewTransition`, and users with `prefers-reduced-motion: reduce`, get an instant change.
- While a transition runs the page is rendered from snapshots, so it is not interactive for the duration. Keep it short.

### CSS parts

| Part       | Description              |
|------------|--------------------------|
| `item`     | The tab item container   |
| `label`    | Label text span          |

---

## `ixfx-tab-panel`

Single content panel. Hidden unless it has the `selected` attribute.

### CSS

When `selected`, displays as `display: block` with `background: var(--surface-3)`. Otherwise uses `display: none`.

---

## `ixfx-tab-panels`

Manages multiple `ixfx-tab-panel` children, selecting one at a time.

### Properties / attributes

| Property              | Type                        | Description                        |
|-----------------------|-----------------------------|------------------------------------|
| `onUnselectedPanel`   | `(id, el) => void`          | Callback when panel is de-selected |
| `onSelectingPanel`    | `(id, el) => void`          | Callback before panel is selected  |
| `onSelectedPanel`     | `(id, el) => void`          | Callback after panel is selected   |

### Methods

| Method              | Argument | Returns | Description                      |
|---------------------|----------|---------|----------------------------------|
| `getSelectedElement()` | —      | `TabPanelElement \| undefined` | Get currently selected panel |
| `selectPanel(id)`  | `string` | `boolean` | Select panel by ID; returns true if found |
| `selectTab(nameOrTitle)` | `string` | `boolean` | Select a tab as if it was clicked: activates the matching header (via the list associated with `syncWithList`) and shows its panel. `nameOrTitle` can be a tab's label text (case-insensitive) or the panel id its `for` attribute points at. Returns true if a panel was found |
| `syncWithList(el)`  | `TabListElement` | `void` | Associates this panels element with a tab list, syncing panel selection to it. Must be called before `selectTab()` if the tab header should be activated |

---

## `TabController`

A class that wires an `ixfx-tab-list` to an `ixfx-tab-panels` container. It keeps track of the tabs, mirrors the selected header into the panels, and offers an API to select, add, remove, rename and reorder tabs.

### Setup

```js
import { TabController } from '@ixfx/components';

const controller = new TabController(
  document.querySelector('ixfx-tab-list'),
  document.querySelector('ixfx-tab-panels'),
  {
    onSelect: (tab, previous) => console.log(`selected ${tab.id}`),
  },
);
controller.connect();
```

Call `connect()` to start wiring; `disconnect()` removes listeners, observers and commands.

### Options

| Option | Type | Description |
|--------|------|-------------|
| `commands` | `CommandRegistry \| undefined` | When provided, a command is registered per tab (id = tab id). Invoking `commands.invoke(id)` selects the tab |
| `onSelect` | `(tab, previous) => void` | Fired after a tab is selected (click or programmatic) |
| `onAdd` | `(tab) => void` | Fired after a tab is added |
| `onRemove` | `(tab) => void` | Fired after a tab is removed |
| `onReorder` | `(tabs) => void` | Fired after tabs are reordered |

### Methods

| Method | Argument | Returns | Description |
|--------|----------|---------|-------------|
| `connect()` | — | `void` | Wire the list and panels, register commands |
| `disconnect()` | — | `void` | Remove listeners, observers and commands |
| `selectTab(sel)` | `string \| TabListItemElement` | `boolean` | Select a tab as if it was clicked. `sel` may be a tab id, the panel id its `for` points at, its label text (case-insensitive), or the item element |
| `selectNext()` | — | `boolean` | Select the next tab (wraps) |
| `selectPrevious()` | — | `boolean` | Select the previous tab (wraps) |
| `getSelected()` | — | `Tab \| undefined` | Currently selected tab |
| `getTabs()` | — | `Tab[]` | All managed tabs |
| `getTab(id)` | `string` | `Tab \| undefined` | Tab by id |
| `addTab(opts)` | `TabAddOptions` | `Tab` | Add a tab (item + panel) |
| `removeTab(sel)` | `string \| TabListItemElement` | `boolean` | Remove a tab; selects an adjacent tab if the removed one was selected |
| `renameTab(sel, label)` | `string \| TabListItemElement, string` | `boolean` | Change a tab's label |
| `setTabIcon(sel, iconName?)` | `string \| TabListItemElement, string \| undefined` | `boolean` | Set or clear a tab's icon |

A `Tab` is `{ id, forId, item, panel, label, iconName? }` where `item` is the `ixfx-tab-list-item` and `panel` the `ixfx-tab-panel`.

### `TabAddOptions`

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `label` | `string` | *(required)* | Tab label |
| `id` | `string` | derived from label | id for the tab item |
| `forId` | `string` | derived from label | id for the panel (and the item's `for`) |
| `iconName` | `string` | — | Icon to display |
| `description` | `string` | — | Tooltip description |
| `closeable` | `boolean` | `true` | Show the close button |
| `toolbar` | `HTMLElement[]` | — | Elements to slot into `slot="toolbar"` |
| `content` | `Node \| string \| (panel) => void` | — | Panel content |
| `select` | `boolean` | `true` | Select the new tab immediately |
| `index` | `number` | append | Insertion index among existing tabs |

```js
controller.addTab({
  label: 'Console',
  iconName: 'debug',
  content: (panel) => { panel.append('Console output'); },
});
```

### Keyboard shortcuts via commands

Pass a `CommandRegistry` to the options and bind shortcuts with `KeyboardManager`. Command ids equal the tab ids:

```js
import { CommandRegistry, KeyboardManager } from '@clinth/ui-commands';

const commands = new CommandRegistry();
const controller = new TabController(list, panels, { commands });

const keyboard = new KeyboardManager();
keyboard.bind({ key: '1', modifiers: new Set(['alt']), commandId: 'tab-home' });
keyboard.bind({ key: '2', modifiers: new Set(['alt']), commandId: 'tab-profile' });
keyboard.onKeyEvent((commandId) => commands.invoke(commandId));
keyboard.attach(document.body);
```

Commands are unregistered when their tab is removed or the controller disconnects.