# Dock (`ixfx-dock-host` / `ixfx-dock-panel`)

Dockable, movable panels like VS Code / Photoshop. Drag a panel by its
titlebar (solo) or its tab (tabbed) over another panel; depending on cursor
position it becomes a **tab** in that group or **splits** the target to the
top/bottom/left/right. Infinitely composable, serializable, and restrictable.

```
<ixfx-dock-host layout='{"version":1,"root":{…}}'>
  <ixfx-dock-panel panel-id="explorer" label="Explorer" closable>…</ixfx-dock-panel>
  <ixfx-dock-panel panel-id="editor" label="Editor" closable>…</ixfx-dock-panel>
</ixfx-dock-host>
```

A panel's display text is the `label` attribute (the `title` *property* in
JS). A legacy `title` attribute is adopted once and then removed, so browsers
never show it as a hover tooltip.

## Architecture

- **Flat panel pool + model-driven host.** Panels stay direct light-DOM
  children of the host for their whole life — they are never reparented
  within a host. The host owns an in-memory `DockNode` tree (`dock-model.ts`),
  renders split/tab scaffolding in shadow DOM, and projects panels into leaves
  via `slot="dock-panel-{id}"`. Moving a panel = model mutation → re-render →
  slot reassignment; panel DOM and state are never destroyed.
- **Split nodes** render as a single `ixfx-split-layout` (n-way) with one
  wrapper child per child node. Splits of the *other* direction are emitted as
  nested `<ixfx-split-layout>` directly (the split element recurses into them).
  Per-child weights ride on `size` attributes; stack collapse rides on
  `collapsed` / `when-small` attributes.
- **Stack (leaf) nodes** always render the same chrome: an `ixfx-tab-list`
  strip (with generated `ixfx-tab-list-item`s, one per panel) plus a single
  body slot for the active panel — so titlebars are consistent whether a stack
  holds one panel or many. Docked panels are `presentation="tabbed"`
  (content only); the tab item is the drag handle and carries title / icon /
  close / per-panel toolbar. `ixfx-tab-panels` is deliberately not used — the
  host owns slot projection. Panels outside a host (or not currently docked)
  render `presentation="solo"` with an `ixfx-titlebar` and flat content.

## Data model (`types.ts` / `dock-model.ts`)

```ts
type DockLayout   = { version: 1; root: DockNode };
type DockNode     = DockSplitNode | DockStackNode;
type DockSplitNode = { kind: 'split'; direction: 'row' | 'column';
                       sizes: number[]; children: DockNode[] };
type DockStackNode = { kind: 'stack'; panels: string[]; active: string;
                       name?: string;   // app-defined container name, e.g. 'primary-sidebar'
                       hideLabels?: boolean;   // icon-only tabs (→ ixfx-tab-list hide-labels)
                       collapsed?: boolean; preCollapseSize?: string };
```

`direction` uses `ixfx-split-layout`'s flexbox sense: `row` = side by side,
`column` = stacked. A "split horizontal" drop (horizontal divider, panels
stacked vertically) maps to `direction: "column"`.

`normalize()` runs after every mutation: empty *unnamed* stacks are removed
(named empty stacks are kept so the name stays addressable), ≤1-child
splits dissolve, same-direction child splits flatten into their parent,
`sizes` stays parallel to `children`, and `active` always points at a member.
The tree is plain and mutable, owned exclusively by the host.

Named containers: give a stack leaf `name` (e.g. `"primary-sidebar"`) in the
initial layout JSON. Names must be unique per layout (first match wins),
are saved and restored with the [view state](#view-state), and render as
`data-dock-name` on the leaf. Explicit leaf close still removes the stack.
When a `tabs` drop empties a named stack into an *unnamed* one, the name
(and its content rules) follows the panels to the merged leaf instead of
leaving an empty placeholder behind. Edge splits go the other way: a
permitted split beside a named leaf yields a fresh *unnamed* sibling with no
policy — set `allowEdgeSplit: false` (see Restrictions) to forbid the split
entirely for strict named-area layouts.

Spatial moves: `getNeighbours()` reports what sits above / below / left /
right of a leaf (flat `{ name, path }` lists, most-overlapping first).
`moveLeaf()` swaps one step with the longest-edge neighbour (both leaves keep
their size slots); `moveLeafToEdge()` relocates to a layout edge, keeping the
rest of the tree intact and preserving the leaf's absolute size. Both return
`false` when there is nowhere to go.

## Drop targeting — the 5-zone model

While dragging, the host overlay highlights the resulting region:

| Region | Operation | Result |
|---|---|---|
| leaf centre (~50% box) | `tabs` | insert into that stack (at the hovered strip gap when over the strip) |
| leaf left / right band | `split-vertical` | new stack beside the leaf |
| leaf top / bottom band | `split-horizontal` | new stack above/below the leaf |
| host gutter / edges (outside all leaves) | split **root** | new stack against the whole host |

When the target's parent split already matches the drop direction the new
stack is inserted beside it (50/50 weight split); otherwise the target is
wrapped in a new split. `Escape` or `pointercancel` cancels with no mutation.

## Junction resize

Where a parent gutter line meets a nested split's gutter (T and + crossings
of three or four panels), the host renders a small hover-revealed handle — the
shared `dimpled` spot handle ([docs/infra-handle.md](./infra-handle.md)),
`var(--accent)` tinted. Dragging it
starts the vertical and horizontal gutter drags at once via
`ixfx-split-layout`'s `beginGutterDrag()`, resizing all adjacent panels with
one gesture — as in VS Code. Handle positions are recomputed on renders,
split resizes, and host resizes; handles are hidden during dock drags.

## Restrictions

- Host `accepts` attribute: space-separated `tabs`, `horizontal`, `vertical`,
  convenience `all`; `""` / `none` rejects everything. Default allows all.
- Panel `accepts` attribute: applies when that panel is a **solo** drop
  target. Default unrestricted.
- `host.canAccept = (panelId, op) => boolean` — finest-grained veto, consulted
  per candidate zone.
- Leaf content rules by panel `kind` (default `'any'`, matched literally):
  `setLeafExclusiveContents(name, kinds)` admits only those kinds into the
  named leaf, `setLeafDenyContents(name, kinds)` refuses those kinds.
  `clearLeafContentRestrictions(name)` lifts both; `[]` seals (exclusive) or
  lifts (deny). Rules are host policy — kept across `setViewState()`, never
  serialized; already-docked panels are grandfathered.
- Leaf placement policy — `setLeafPlacementPolicy(name, policy)` is a superset
  of the two calls above (`allowKinds` / `denyKinds`) plus `allowEdgeSplit`
  (default `true`). `allowEdgeSplit: false` enforces **strict named-area
  containment**: the edge drop zones *beside* that named leaf go inert, so a
  panel cannot escape the area by splitting next to it. Fields merge into the
  stored policy; `clearLeafPlacementPolicy(name)` resets. `getLeafPlacementPolicy(name)`
  returns the resolved `{ allowKinds, denyKinds, allowEdgeSplit }`.

- Host `isolated` attribute: panels can be rearranged freely *inside* this
  host but cannot be dragged **out** to another host. It is checked on the
  **source** host only — it does not stop other hosts dropping panels *into*
  an isolated host. To keep unrelated docks from exchanging panels in both
  directions use `family` (below).
- Host `family` attribute (default `""`): two hosts exchange panels by drag
  only when their families are equal. Give an inner dock its own family and
  it neither receives outer-dock panels nor lets its own leave.
- Host `accepts-kinds` attribute / `acceptsKinds` property (space-separated
  panel kinds; default unrestricted): panels arriving from **other** hosts, or
  from another window via `queryDropTarget` / `acceptExternalPanel`, must be of
  one of these kinds. Panels already in the host are unaffected. Combine with
  `family` and `isolated` for a closed two-way exchange of one kind.
- A host whose `accepts` allows no splits (e.g. `accepts="tabs"`) treats the
  whole leaf as the tabs drop zone, instead of leaving the edge bands inert.

A zone lights up only if every applicable rule allows it; disallowed zones
are inert. Content rules govern tabbing *into* a leaf (`tabs` drops,
`addPanel`, re-homing). Edge splits beside a leaf stay allowed **unless** that
named leaf's policy sets `allowEdgeSplit: false` — the gate is enforced on
every placement route (pointer preview and drop, `queryDropTarget` /
`previewExternalDrop`, `addPanel` with a split `op`). A *permitted* edge split
still creates an **unnamed, unconstrained** leaf — the area policy is not
propagated to it. Programmatic fallbacks (`addPanel` without a target,
external panels, leaf-close re-homing) use the first stack admitting the
panel's kind.

## Hiding the strip of a lone tab

`hide-single-tab-strip` (host attribute, `hideSingleTabStrip` property) drops
a leaf's tab strip while it holds exactly one panel; the strip appears when a
second panel arrives and goes again when one leaves. `DockStackNode.hideSingleTabStrip`
overrides it per stack (serialized with the layout). The leaf's outer box is
fixed by its split, so only the body shifts by one tab height when the strip
appears — the strip never reserves height while hidden.

While hidden:

- **Drops.** During a drag the host overlays a compact stand-in strip (part
  `drop-hint`) on the leaf — only if that leaf would accept the dragged panel —
  with a caret showing the insertion gap. It takes no layout space. Dropping on
  it, or on the leaf centre, adds a tab; the real strip then appears.
- **Dragging the lone panel.** There is no tab to grab, so call
  `host.beginPanelDrag(panelId, pointerEvent)` from your own handle's
  `pointerdown`. It returns `false` for an unknown panel or non-primary press.
  The drag starts after a few pixels of movement and is identical to a tab
  drag (ghost, drop zones, `dock-panel-drag-*`, cross-host adoption,
  tear-out). Prefer `touch-action: none` and `user-select: none` on the handle.
- **Toolbars.** Panel toolbars and `toolbar-<name>` slots live in the strip, so
  they are not shown while it is hidden.

## Events

`ixfx-dock-host`: `dock-change` (`{ layout }` after structural mutations),
`view-state-change` (debounced, see [View state](#view-state)), `dock-panel-added`, `dock-panel-removed`, `dock-panel-activated`,
`dock-panel-drag-start`, `dock-panel-moved`, `dock-stack-empty`,
`dock-tab-contextmenu`, `dock-panel-maximized`.

- `dock-panel-added` — `{ panelId, sourceHost, targetHost }`. `sourceHost` is
  the host the panel came from (`null` when new or from another window).
- `dock-panel-removed` — `{ panelId, sourceHost, targetHost }`. `targetHost` is
  the host it moved to, `null` when it is gone (closed, detached, torn out).
- `dock-panel-moved` — `{ panelId, sourceHost, targetHost }`, fired on the
  target host once a cross-host drop completes. A move therefore fires
  `removed` (source), `added` (target), then `moved` (target), and the source
  now also emits `dock-change`.
- `dock-stack-empty` — `{ name, hostEmpty }` when a stack loses its last panel
  (`name` is the container name or `null`). `hostEmpty` is true when the host
  holds no panels at all — the cue to close an owning group. Fires before the
  matching `dock-change`; not fired by `setViewState()`.
- `dock-panel-maximized` — `{ panelId, previousPanelId }`. `panelId` is the panel
  now filling the host, `null` when it was restored (also when the maximized
  panel is removed).
- `dock-tab-contextmenu` — `{ panelId, clientX, clientY }`, cancelable
  (`preventDefault()` suppresses the native menu). Visible tabs only; with a
  hidden strip handle `contextmenu` on your own element.

All of these bubble and are composed, so a nested host's events also reach
outer hosts and their listeners — compare `targetHost` / `sourceHost` to the
host you care about. A nested host's drags are owned by the nearest host only.

Cross-window (see [Cross-window docking](#cross-window-docking-electron-etc)):
`dock-panel-drag-out` / `dock-panel-drag-in`
(`{ panelId, clientX, clientY, screenX, screenY }`) when the drag pointer
leaves / re-enters every host's bounds, and `dock-panel-tear-out`
(`{ panelId, snapshot, clientX, clientY, screenX, screenY }`) when a panel is
released with no host under the pointer.

`ixfx-dock-panel`: `dock-panel-drag-start` (`{ panelId, pointerId, clientX,
clientY }`), plus `close` / `toggle` forwarded from its `ixfx-titlebar`.
The panel removes itself on close; the host's pool sync routes that through
the model and emits `dock-panel-removed` + `dock-change`.

The host consumes `ixfx-split-layout` events: `ixfx-split-resize` /
`ixfx-split-change` (live gutter weights folded into `DockSplitNode.sizes`),
`ixfx-split-collapse` / `ixfx-split-expand` (→ `DockStackNode.collapsed`), and
  `ixfx-split-close` (cancelable — prevented and rerouted so panel elements
  survive, re-homed into the first other stack admitting each kind).

## Public API — `ixfx-dock-host`

```ts
getViewState(options?): DockHostViewState   // { v, kind: 'dock-host', layout }; folds live split weights
setViewState(state: Partial<DockHostViewState>): void
clearPendingViewState(): void               // drops placeholders (panels the host doesn't hold)
saveLayout(): DockLayout                    // deprecated alias of getViewState().layout
loadLayout(layout: DockLayout): void        // deprecated alias of setViewState({ layout })
maximizePanel(panelId: string): boolean     // leaf fills the host; panel element is not moved
restoreMaximized(): boolean                 // false when nothing was maximized
get maximizedPanelId(): string | null
addPanel(panel: DockPanelElement | DockPanelInit, target?: DockAddPanelTarget): boolean
type DockAddPanelTarget = {
  container?: string;   // named stack leaf — takes precedence over `stack`
  stack?: string;       // a panel-id in the target stack (legacy lookup)
  index?: number; op?: DockOperation
}                                // false when the target container denies the panel kind
removePanel(panelId: string): boolean    // removes the element from the DOM too
activatePanel(panelId: string): boolean
getPanelIds(): string[]
setLeafExclusiveContents(name: string, kinds: string[]): void
setLeafDenyContents(name: string, kinds: string[]): void
setLeafPlacementPolicy(name: string, policy: DockLeafPlacementPolicy): void
type DockLeafPlacementPolicy = {
  allowKinds?: string[];   // = setLeafExclusiveContents
  denyKinds?: string[];    // = setLeafDenyContents
  allowEdgeSplit?: boolean; // default true; false = strict named-area containment
}                                // omitted fields merge into the stored policy
clearLeafContentRestrictions(name: string): void
clearLeafPlacementPolicy(name: string): void            // alias of the above
getLeafContentRestrictions(name: string): DockLeafContentRules | null
getLeafPlacementPolicy(name: string): DockLeafPlacementPolicyResolved | null
getContainerNames(): string[]
getContainer(name: string): { name: string; panels: string[]; active: string } | null
getContainerPanels(name: string): string[]              // ids in tab order
getContainerElements(name: string): DockPanelElement[]  // iterate children
// Spatial: leaves by `name` or numeric `path`; neighbours are `{ name, path }`
getNeighbours(leaf: DockLeafRef): DockNeighbours | null
moveLeaf(leaf: DockLeafRef, direction: 'up' | 'down' | 'left' | 'right'): boolean
moveLeafToEdge(leaf: DockLeafRef, edge: 'top' | 'bottom' | 'left' | 'right'): boolean
canAccept?: (panelId: string, op: DockOperation) => boolean
placeholderLabel?: (panelId: string) => string   // tab label for placeholders (default: the id)

// Cross-window hooks (serializable in/out; no element handoff)
getPanelSnapshot(panelId: string): DockPanelSnapshot | null
detachPanel(panelId: string): DockPanelSnapshot | null   // snapshot + removePanel
queryDropTarget(x: number, y: number, panelId?: string): DockDropTarget | null
previewExternalDrop(x: number, y: number, panelId?: string): DockDropTarget | null
endExternalDrop(): void
acceptExternalPanel(snap: DockPanelSnapshot | DockPanelInit,
                    at?: { clientX: number; clientY: number }): DockPanelElement | null
```

The optional `layout` attribute accepts `DockLayout` JSON as the initial
layout; without it, all pooled panels go into one root stack in source order.
Panels present in the pool but missing from a loaded layout are appended to
the first stack.

### Maximizing a panel

`maximizePanel(id)` activates the panel and promotes its leaf (tab strip,
toolbars and body included) to the browser's top layer, sized to the host's
box and kept in step with host resizes. Nothing is reparented, so the panel
keeps its DOM and state; `restoreMaximized()` puts the leaf back. Maximizing
another panel restores the first. Style the backdrop of the leaf with
`--dock-maximized-background` (default `var(--surface-2)`). It is not part of
the view state: a restored layout starts un-maximized.

## Leaf toolbars

The host renders no strip chrome of its own. To add toolbar items to a leaf,
give it a name in the layout and provide light-DOM content in the matching
`toolbar-<name>` slot — the host forwards it into that leaf's tab-strip
toolbar (unnamed leaves have no toolbar target):

```html
<ixfx-dock-host layout='{"version":1,"root":{"kind":"stack","panels":["a"],"active":"a","name":"editor"}}'>
  <ixfx-dock-panel panel-id="a" label="A">…</ixfx-dock-panel>
  <div slot="toolbar-editor">
    <ixfx-menu-trigger label="+" placement="bottom-end">
      <ixfx-menu-container slot="menu">
        <ixfx-menu-item command="new-document" label="New document"></ixfx-menu-item>
      </ixfx-menu-container>
    </ixfx-menu-trigger>
  </div>
</ixfx-dock-host>
```

Menu commands surface as bubbling `menu-command` events (`{ command, checked,
args }`) — listen on the host. Multiple elements may share one toolbar slot;
content for unknown names is inert until a leaf with that name appears.

## Cross-host drags

Panels can be dragged between hosts (register via the shared drag
coordinator automatically). The source host releases the panel from its model
and the target host adopts the element — the one sanctioned reparent
(`connectedCallback` re-runs on the panel; it holds no per-host state).
`panel-id` must be unique across all hosts that can exchange panels.

This works only *within one document*. The drag coordinator is module state, so
it never spans separate windows (`BrowserWindow` / `WebContentsView` / a popped
`window.open`). Moving a panel across that boundary is described next.

## Cross-window docking (Electron, etc.)

The dock deliberately ships **no** window/IPC/Node dependency. Instead it
exposes the events and methods an outer coordinator (your Electron main
process, a `SharedWorker`, `BroadcastChannel`, `postMessage`…) needs to move a
panel between windows. Nothing DOM crosses the boundary — you transport a
plain, structured-clone-safe **`DockPanelSnapshot`** and rebuild the panel on
the far side.

```ts
interface DockPanelSnapshot {           // structured-clone safe
  panelId: string; title: string; iconName: string;
  closable: boolean; collapsible: boolean; kind: string; accepts: string;
  contentHTML: string;   // best-effort innerHTML snapshot; see note below
}
interface DockDropTarget {              // serializable hit-test result
  operation: 'tabs' | 'split-horizontal' | 'split-vertical';
  targetPath: number[];  // stack path in the target host model; [] = root
  side: 'before' | 'after';
  gapIndex?: number;
}
```

> **`contentHTML`** is a convenience for panels whose body is static markup.
> If a panel holds live state, framework-managed DOM, canvas/WebGL, or running
> timers, ignore it and rebuild the body from your own model in the new window
> (you already do this to render the panel the first time). The snapshot is
> identity + chrome; content ownership stays with your app.

### 1. Panel → new window (tear-out)

While a drag is in progress the host fires boundary events as the pointer
leaves and re-enters the union of all host rects:

| Event | When | Use |
|---|---|---|
| `dock-panel-drag-out` | pointer left every host | start a native drag image / detached preview window that follows the cursor |
| `dock-panel-drag-in`  | pointer came back over a host | tear down that preview; the in-page drop overlay takes over again |
| `dock-panel-tear-out` | released with no host under the pointer | create the real window and move the panel |

All three carry `clientX/clientY` (source viewport) **and** `screenX/screenY`
(desktop) so the receiver can place a window. `dock-panel-tear-out` also
carries a ready-made `snapshot`.

```ts
host.addEventListener('dock-panel-tear-out', (e) => {
  const { snapshot, screenX, screenY } = e.detail;
  window.dockBridge.openPanelWindow({ snapshot, screenX, screenY });   // → main process
  host.detachPanel(snapshot.panelId);   // snapshot already taken; drop it here
});
```

```ts
// main process
ipcMain.handle('dock:open-panel-window', (_e, { snapshot, screenX, screenY }) => {
  const win = new BrowserWindow({ x: screenX - 40, y: screenY - 20, width: 480, height: 360, /* … */ });
  win.loadFile('panel-window.html');
  win.webContents.once('did-finish-load', () =>
    win.webContents.send('dock:mount-panel', snapshot));
});
```

```ts
// panel-window.html renderer — a host that starts empty
ipcRenderer.on('dock:mount-panel', (_e, snapshot) => {
  document.querySelector('ixfx-dock-host').acceptExternalPanel(snapshot);
});
```

Because `pointerup` outside the OS window is not reliably delivered to a
renderer, prefer starting a native follow-the-cursor window on
`dock-panel-drag-out` and finalising from the **main** process on the global
mouse-up, rather than depending on `dock-panel-tear-out` firing. `tear-out`
is the best-effort path for release inside the window but between hosts.

### 2. Window → this host (tear-in)

Detecting an OS-level window drag is the app's job — Electron gives you the
screen cursor (`screen.getCursorScreenPoint()`) and window bounds
(`win.getBounds()`), so the main process can tell, per frame, when a dragged
panel-window is hovering another window and where. Forward that to the target
renderer, which drives the host imperatively:

```ts
// target renderer, fed pointer position + the dragged panel's snapshot over IPC
ipcRenderer.on('dock:external-drag-move', (_e, { snapshot, clientX, clientY }) => {
  host.previewExternalDrop(clientX, clientY, snapshot.panelId);   // lights the overlay
});
ipcRenderer.on('dock:external-drag-leave', () => host.endExternalDrop());
ipcRenderer.on('dock:external-drag-drop', (_e, { snapshot, clientX, clientY }) => {
  const placed = host.acceptExternalPanel(snapshot, { clientX, clientY });
  if (placed) ipcRenderer.send('dock:close-source-window');   // panel now lives here
});
```

`previewExternalDrop` / `queryDropTarget` return the `DockDropTarget` that a
drop at that point would produce (or `null` when the point misses the host or
the zone is vetoed by `accepts` / `canAccept`), so the coordinator can also
show a yes/no cursor on the source side. `acceptExternalPanel` honours the
same restrictions and falls back to the first stack when `at` is omitted or
outside the host.

### Coordinate spaces

Events give you both. `client*` is the source renderer's viewport;
`screen*` is the desktop. To convert a desktop point into a target renderer's
viewport, the app subtracts that window's content bounds (main process:
`win.getContentBounds()`), accounting for `devicePixelRatio`. Keep the
conversion in the coordinator — the component only ever speaks the two spaces
it can measure.

### Identity

`panelId` must be unique across every host that can exchange panels, in every
window. `acceptExternalPanel` returns `null` if that id is already docked in
the target host (adopt / focus it yourself instead).

## View state

The dock implements the shared view-state API
([docs/infra-view-state.md](./infra-view-state.md)). The component
never persists anything; the host does, e.g. with `bindViewState()`:

```ts
import { bindViewState } from '@ixfx/components';

bindViewState(dock, {
  load: () => JSON.parse(localStorage.getItem(`workspace`) ?? `null`),
  save: s => localStorage.setItem(`workspace`, JSON.stringify(s)),
});
```

| Field | Type | Meaning |
|---|---|---|
| `layout` | `DockLayout` | The whole tree: splits with `sizes`, stacks with tab order, `active`, `name`, `collapsed` / `preCollapseSize`, strip flags. Keyed by panel id. |

The dock layout is close to structure, so the saved state *is* the tree
(collapse and the active tab stay inside it rather than in separate
`expanded` / `selected` fields).

- `getViewState()` folds live gutter weights from each rendered
  `ixfx-split-layout` (via `getSizes()`) into `DockSplitNode.sizes` first, so
  a save → drag → save round-trip preserves user adjustments.
- **Panels not in the host yet.** `setViewState()` keeps every panel id the
  layout names, held or not. One the host doesn't hold is a *placeholder*:
  it keeps its place in the tree (shown as a tab labelled by the
  `placeholderLabel(panelId)` property, or its id when unset) and
  the panel slots into that place when it arrives — appended as a light-DOM
  child, `addPanel()` **without** a target, `acceptExternalPanel()` without
  `at`, or a cross-host adoption. An explicit `addPanel()` target still wins.
  Placeholders are saved by `getViewState()`; `includePending: false` leaves
  them out (stacks they empty are dropped unless named). Remove one with
  `removePanel(id)`, or all of them with `clearPendingViewState()`.
- **Persisting with the default keeps stale ids.** A placeholder for a panel
  that no longer exists is saved again on every `getViewState()`, so it never
  goes away. Apps whose panels can disappear between save and restore should
  call `clearPendingViewState()` once they have added the panels they hold,
  or save with `includePending: false`.
- Pooled panels the layout doesn't name are appended to the first stack
  admitting their kind.
- A panel that is closed / removed (`removePanel`, close button, removed from
  the DOM, moved to another host) leaves the layout — closing is a structural
  change, so its place is not remembered.
- State set before the host is connected wins over the `layout` attribute.
- A malformed `layout` (or a state for another `kind`) is ignored with a
  warning.
- `view-state-change` fires (debounced) after structural changes (drops,
  add / remove, close, leaf moves), gutter resizes, collapse / expand and
  tab activation. `reason` is `data` when the pool changed under the host,
  `restore` for `setViewState()`. The dock's internal split layouts' own
  `view-state-change` events don't escape the host.

## CSS variables

| Variable | Purpose | Default |
|---|---|---|
| `--dock-drop-zone-color` | drop highlight colour | `var(--accent)` |
| `--dock-drop-zone-opacity` | drop highlight opacity | `0.25` |
| `--dock-collapsed-size` | collapsed stack track size | `40px` |
| `--dock-tab-height` | tab item height, uniform across all leaf strips | `30px` |
| `--dock-split-bar-size` | thickness of the split-layout bars between leaves | `2px` |
| `--dock-leaf-body-padding` | padding inside leaf body | `var(--space-s)` |

The junction resize handle is the shared handle primitive — theme it with
`--ixfx-handle-*` (see [docs/infra-handle.md](./infra-handle.md)).

Splitter styling delegates to `ixfx-split-layout` (`--split-*`); solo panel
chrome delegates to `ixfx-titlebar` — including its `title-context` slot, so
content such as an `ixfx-led` can sit beside the title — and the leaf body is
the docked panel surface. Tabbed presentation has no titlebar, so
`title-context` content is only shown in solo mode. Each leaf carries a
hairline border (`var(--border-subtle)`) with slight rounding
(`var(--radius-m)`). An empty host renders a placeholder; replace its content
with `<div slot="empty">…</div>`.

## Implementation notes from the Electron demo

A standalone Electron app demonstrates cross-window docking at
`../electron-dock-demo/`. Key insights:

### Ghost window pattern

For tear-out, create a frameless, transparent, always-on-top `BrowserWindow`
that follows the cursor. The renderer sends `dock-panel-drag-out` (pointer left
every host) and you open the ghost; subsequent `pointermove` updates its
position. `dock-panel-tear-out` (released over empty space) creates the real
panel window and tells the source to detach.

### Tear-out verdict

The **source keeps its panel** until the main process replies with a verdict:

| Drop point | Verdict | Effect |
|---|---|---|
| Inside another window | `transferred` | target hosts the panel; source detaches |
| Inside another window, but vetoed | `floated` | spawn panel window; source detaches |
| Over empty desktop | `floated` | spawn panel window; source detaches |
| Over source window's non-host chrome | `cancelled` | panel stays put; nothing happens |

This prevents losing a panel when a target vetoes the drop — the source still
has it. The renderer checks for `bridge.onTearOutVerdict` to know whether to
wait for a verdict or fall back to direct detach.

### Tear-in (panel window → another window)

Electron's `BrowserWindow` fires `move` on drag and `moved` on drop. The main
process hit-tests the cursor against every other window's content bounds:

```ts
// main process
win.on('move', () => {
  const point = screen.getCursorScreenPoint();
  const target = windowAt(point, win.id);  // hit-test vs other windows
  if (target) {
    target.webContents.send('dock:external-drag-move', { snapshot, clientX, clientY });
  }
});
win.on('moved', () => finishDrag(win));
```

**Platform quirk:** Windows/Linux may not fire `moved`. Use a fallback timer
(≈180ms) to detect drag end:

```ts
win.on('move', () => {
  if (dragIn.endTimer) clearTimeout(dragIn.endTimer);
  dragIn.endTimer = setTimeout(() => finishDrag(win), 180);
});
```

### Coordinates

- `screen.getCursorScreenPoint()` + `win.getContentBounds()` are **DIP** (device
  independent pixels)
- `PointerEvent.clientX/Y` are **CSS px**
- Equal at `devicePixelRatio: 1`; on fractional displays expect a few px of
  slop in ghost position.

### IPC bridge

Use a preload script with `contextBridge.exposeInMainWorld` to expose a typed
bridge. The renderer calls imperative methods (`dragOut`, `dragMove`,
`tearOut`, `accepted`, `rejected`) and the main process pushes events
(`dock:external-drag-move`, `dock:external-drag-drop`, etc.).

### Content snapshots

`DockPanelSnapshot.contentHTML` captures `innerHTML`. For **stateful panels**
(e.g., live input edits), mirror the value back into the attribute — a
`input` event listener on the panel body keeps the attribute in sync across
body replacements. Better: rebuild content from your own model on the receiving
side instead of relying on DOM snapshotting.

## Deviations from the original plan (and why)

- **Tab-strip reorder** is handled by the dock drag coordinator (gap-index
  insertion) rather than `ixfx-tab-list`'s own `drag-mode="reorder"` — running
  both would race two ghosts for the same pointer. The gap computation
  reuses the tab-list midpoint rule.
- **Closing a leaf via `ixfx-split-close`** re-homes its panels into the first
  other stack admitting each kind (or the pool if none) instead of dropping
  them on the floor.
- **No default strip chrome.** The plan's per-strip split buttons are gone;
  leaves expose `toolbar-<name>` slots instead (see [Leaf
  toolbars](#leaf-toolbars)), so apps own their strip actions.
