# Hyperbolic Tree

`<ixfx-hyperbolictree-list>` — a hyperbolic (Poincaré disk) browser over tree data. The focused node sits at the disk's center; its neighbourhood fans outward, shrinking toward the edge with tree-graph distance. Clicking a node re-centers the disk on it with an animated Möbius transform — the underlying layout never changes, only the projection.

It implements the shared `TreeComponent` interface (see [`src/tree/README.md`](./tree.md)), so `TreeDataModel`, `IncrSearchTreeController`, and any `TreeComponent`-typed code work unmodified.

---

## Contents

1. [Differences from `ixfx-tree-list`](#differences-from-ixfx-tree-list)
2. [Data model](#data-model)
3. [Properties](#properties)
4. [Node shapes](#node-shapes)
5. [Zoom vs. curvature](#zoom-vs-curvature)
6. [Weighting](#weighting)
7. [Targeting a specific node or edge](#targeting-a-specific-node-or-edge)
8. [Custom edge rendering](#custom-edge-rendering)
9. [Focus, selection, navigation](#focus-selection-navigation)
10. [View state](#view-state)
11. [Events](#events)
12. [Keyboard / pointer interaction](#keyboard--pointer-interaction)
13. [CSS variables and parts](#css-variables-and-parts)
14. [Types reference](#types-reference)

---

## Differences from `ixfx-tree-list`

- **Expand/collapse is reinterpreted as focus change.** Every loaded node is always laid out; there's no expanded/collapsed state. `expand`/`collapse` still fire — when the new focus is a descendant/ancestor of the previous one — for interop with existing `TreeComponent` listeners.
- **`interactionMode` drops `'checked'`** — no checkbox affordance at disk-edge node scale.
- **`exclusivity` is accepted but ignored** — nothing is independently open.
- **`filterPredicate` dims** non-matching nodes instead of hiding them.
- Dragging empty disk space **pans** the view without changing focus or selection.
- Drag-and-drop and `checkboxRenderer` are out of scope.

## Data model

Same `TreeNode` / `TreeItem` shapes as the rest of the tree family (see [`src/tree/README.md`](./tree.md#data-model)), including `root`, `model` (`TreeDataModel`), and `loadChildren` for lazy loading.

Keys only need to be unique **among siblings**: internally each node is identified by its key *path* from the root (`HyperbolicLayoutNode.id`), so data like a file system — where `readme.md` recurs in many folders — lays out and focuses correctly. Key-based lookups that can't know the path (`focusedKey` when given a bare key, `revealKey`, `::part(node-<key>)`) match the first node, depth-first, carrying that key.

```typescript
el.root = {
  item: { key: 'root', label: 'My Files' },
  children: [
    { item: { key: 'docs', label: 'Documents' }, children: [] },
    { item: { key: 'img', label: 'Images', isLeaf: true } },
  ],
};
```

## Properties

| Property (attribute) | Type | Default | Description |
|---|---|---|---|
| `root` | `TreeNode \| undefined` | `undefined` | Root node of the tree |
| `model` | `TreeDataModel \| undefined` | `undefined` | Shared data model; takes precedence over `loadChildren` |
| `loadChildren` | `LoadChildrenCallback \| undefined` | `undefined` | Callback for lazy child loading |
| `restoreLoads` | `boolean` | `true` | Whether restoring a saved `center` may load its unloaded ancestors. See [View state](#view-state) |
| `interactionMode` (`interaction-mode`) | `'implicit' \| 'standard' \| 'manual'` | `'standard'` | Gesture mapping — see [`src/tree/README.md`](./tree.md#interactionmode-ixfx-tree-list--ixfx-miller-list) (`'checked'` is unsupported here) |
| `selectionFilter` (`selection-filter`) | `'none' \| 'leaf' \| 'branch' \| 'all'` | `'all'` | Which node kinds can be selected |
| `exclusivity` | `TreeExclusivity` | `'none'` | Accepted for interface compatibility, ignored |
| `filterPredicate` | `TreeFilterPredicate \| undefined` | `undefined` | Non-matching nodes (and branches with no matching descendant) are dimmed, not hidden |
| `maxRadius` (`max-radius`) | `number` | `4` | Tree-graph steps from the focus to lay out and render |
| `nodeShape` (`node-shape`) | `'dot' \| 'box'` | `'dot'` | How nodes are drawn. See [Node shapes](#node-shapes) |
| `boxMaxChars` (`box-max-chars`) | `number` | `24` | `box` mode: truncate longer labels with `…` (`0` disables) |
| `minLabelSize` (`min-label-size`) | `number` | `9` | `box` mode: smallest on-screen label size (CSS px) worth drawing; smaller labels become markers |
| `colorByBranch` (`color-by-branch`) | `boolean` | `false` | Tint each top-level branch (each child of the root, and its subtree) its own hue. See [Branch colours](#branch-colours) |
| `nodeRadius` (`node-radius`) | `number` | `0.05` | Base node dot radius at the disk center, as a fraction of the disk radius. Shrinks by the disk's conformal factor `1 − \|z\|²` away from the focus, and is capped to stay clear of the nearest neighbouring node |
| `minNodeRadius` (`min-node-radius`) | `number` | `0.015` | Nodes whose scaled radius falls below this render without a label |
| `minWeightScale` (`min-weight-scale`) | `number` | `0.6` | Radius multiplier for a node with `weight` at the low end of the currently-visible range |
| `maxWeightScale` (`max-weight-scale`) | `number` | `1.6` | Radius multiplier for a node with `weight` at the high end of the currently-visible range |
| `zoom` | `number` | `1` | Post-layout (Euclidean) magnification; updated by zoom gestures. See [Zoom vs. curvature](#zoom-vs-curvature) |
| `curvature` | `number` | `1` | Hyperbolic distance placed between generations — how curved the space itself is. See [Zoom vs. curvature](#zoom-vs-curvature) |
| `disableZoomGestures` (`disable-zoom-gestures`) | `boolean` | `false` | Turn off zoom gestures — see [Zoom gestures](#zoom-gestures) |
| `disableRadialLabels` (`disable-radial-labels`) | `boolean` | `false` | Turn off radial labels — every label horizontal. See [Label legibility](#label-legibility) |
| `disableChildPreview` (`disable-child-preview`) | `boolean` | `false` | Turn off the hover preview of a crowded node's children — see [Child preview](#child-preview) |
| `siblingSpacing` (`sibling-spacing`) | `number` | `0.5` | Minimum hyperbolic distance between adjacent siblings — see [Crowded fans](#crowded-fans). `0` disables |
| `focusAnimationDuration` (`focus-animation-duration`) | `number` | `400` | Duration (ms) of the animated re-center on focus change; `0` snaps instantly. Respects `prefers-reduced-motion` |
| `edgeRenderer` | `HyperbolicEdgeRenderer \| undefined` | `undefined` | Custom renderer for edges, in place of the default geodesic-arc path |
| `disableKeyboardNavigation` (`disable-keyboard-navigation`) | `boolean` | `false` | Disables the keyboard handlers below |
| `searchModes` (`search-modes`) | `string \| undefined` | `undefined` | Space-separated subset of `navigate select filter` — see [`src/tree/README.md`](./tree.md#incremental-search) |
| `selectedNode` | `TreeNode \| undefined` | `undefined` | Primary (most recent) selected node |
| `selectedNodes` | `ReadonlySet<TreeNode>` | `{}` | Full selection set (read-only) |
| `focusedNode` | `TreeNode \| undefined` (read-only) | true root | The node currently centered on the disk. Pure view-state — `root` is never mutated by focus changes |

---

## Node shapes

| `nodeShape` | Rendering |
|---|---|
| `'dot'` (default) | A filled circle with the label beside it. Labels are greedily thinned where nodes crowd together |
| `'box'` | A rectangle containing the label, centered on the node. The box scales with the disk's conformal factor (`1 − \|z\|²`), floored at 45% so nearby rings stay readable |

```html
<ixfx-hyperbolictree-list node-shape="box"></ixfx-hyperbolictree-list>
```

### Label legibility

Both shapes place labels greedily: the focus first, then selected nodes, then larger (nearer-the-center) nodes. A label is dropped if it would overlap an already-placed one by more than 3% of its area, or — in `box` mode — if it would render below `minLabelSize` px. A box without a label is drawn as a small marker. Hovering (or keyboard-tickling) any node always shows its label, drawn on top, and every node has its full label as a native tooltip.

`--hyperbolictree-font-size` is in **screen px**: the component converts it using its own rendered size, so text is the same size however large the element is. It also stays constant under `zoom`, so zooming in spreads crowded labels apart until they fit, rather than magnifying the overlap.

**Radial labels** (on by default; `disable-radial-labels` turns them off): each label runs along its node's incoming edge, from the neighbour one step nearer the focus. A fan of siblings then only needs room for each label's *height*, not its width, so far more of a crowd stays labelled. Labels on the left half are turned 180° so text never reads upside-down. The focus itself stays horizontal.

### Zoom gestures

On by default; `disable-zoom-gestures` turns them all off. Each one zooms around the pointer, like a map, and updates `zoom`:

| Gesture | When |
|---|---|
| Trackpad pinch / Ctrl-⌘-scroll | Whenever the pointer is over the tree |
| Plain scroll | Only once the tree has keyboard focus (click it first), so scrolling the page past it isn't hijacked. This follows the library's focus-gated wheel convention |
| Two-finger touch pinch | On empty disk space |

Labels keep their on-screen size while zooming, so zooming in spreads a crowd apart. Boxes that were shrunk towards the edge grow back towards full size, until their labels are legible. Focusing a node pans a zoomed view back so the new focus lands in the middle of the element.

### Child preview

On by default; `disable-child-preview` turns it off. Hovering or keyboard-tickling a node whose children aren't all legible, and resting there for 600ms, opens a popover listing them. That means some children had their labels culled, or sit beyond `maxRadius`. It shows up to 12 children, then "+N more". Clicking an entry focuses that child and selects it, per `interactionMode`. The popover stays open while the pointer moves onto it, and Escape closes it. Starting a drag (pan) cancels a pending preview and closes an open one. Style it with `::part(child-preview)`. Nodes that can show a preview drop their native `<title>` tooltip so the two don't stack. With the preview disabled, every node keeps its tooltip.

### Crowded fans

Panning is a hyperbolic *isometry*: it moves nodes to where the disk magnifies more, but it can never change the hyperbolic distance between them. So if a bushy node's children were laid out nearly on top of each other, no amount of dragging would separate them.

`siblingSpacing` guarantees a minimum hyperbolic distance between adjacent siblings. A child with a thin angular slice is placed further from its parent: `sinh(L) = sinh(spacing/2) / sin(slice/2)`, never less than `curvature`. In the overview, a crowd sits further out, as a neat fan of markers rather than a pile. Dragging it towards the center always spreads it out until the labels fit. Raise `siblingSpacing` if your labels are long and still collide when centered. Lower it to keep crowds closer in the overview.

### Branch colours

`color-by-branch` spreads hues evenly around the colour wheel, one per child of the root, and mixes each into the normal node, box and edge colours. Mixing rather than replacing keeps it in step with the theme, and selected/tickled states still override it. Each node and edge carries `--branch-index` and `--branch-count` (unset on the root) for custom CSS, and these knobs tune the palette:

| Variable | Default |
|---|---|
| `--hyperbolictree-branch-hue-start` | `250` |
| `--hyperbolictree-branch-chroma` | `0.13` |
| `--hyperbolictree-branch-lightness` | `62%` |
| `--hyperbolictree-branch-mix` | `55%` |

Style boxes via `--hyperbolictree-box-color` / `--hyperbolictree-box-text` / `--hyperbolictree-box-border`, or `::part(box)` directly.

## Zoom vs. curvature

Two independent knobs affect how much of the tree is visible and how it's magnified — neither mutates `root`:

| | What it changes | Effect |
|---|---|---|
| `zoom` | A post-layout SVG `scale()`, applied after everything else | Uniformly magnifies/shrinks the rendered disk around the focus. Node positions relative to each other are unchanged — it's a camera zoom, not a re-layout. |
| `curvature` | The minimum hyperbolic distance placed between each generation (default `1`, matching the standard Poincaré-disk layout; bushy nodes' children go further — see `siblingSpacing`) | Raising it pushes each generation further out in hyperbolic terms, so the disk's own `tanh` compression crowds distant generations toward the boundary faster — a stronger fisheye. This *reshapes* the layout (relative sizes/spacing of near vs. far nodes change), which is why increasing it reads as "zooming in" on the focus even at `zoom: 1`. Lowering it spreads generations out more evenly, flattening the view toward a Euclidean-feeling layout. |
| `maxRadius` | How many tree-graph rings are laid out at all | Independent of both — a window over the tree, not a projection change. |

```html
<ixfx-hyperbolictree-list zoom="1.5" curvature="1.8"></ixfx-hyperbolictree-list>
```

## Weighting

Set `TreeItem.weight` (a plain `number`, any range) on nodes to influence their visuals:

```typescript
el.root = {
  item: { key: 'root', label: 'Root', weight: 10 },
  children: [
    { item: { key: 'big', label: 'Big folder', weight: 8 } },
    { item: { key: 'small', label: 'Small file', weight: 1 } },
  ],
};
```

Weight is normalized to `0..1` **against whichever nodes are currently visible** (the ring window `maxRadius` selects) — not the whole tree — and exposed as CSS custom properties:

| Custom property | Where | Value |
|---|---|---|
| `--node-weight` | Each node's `<g part="node">` | Normalized `0..1` (defaults to `0.5` if the node, or the whole visible set, has no weight) |
| `--node-weight-raw` | Each node's `<g part="node">` | The raw `item.weight` value, when set (otherwise unset) |
| `--edge-weight` | Each edge's `<path part="edge">` | Average of the two endpoint nodes' `--node-weight` |

By default this:

- Scales node radius between `minWeightScale`× and `maxWeightScale`× (default `0.6`–`1.6`).
- Tints node fill toward `--accent` as weight increases (`color-mix` on `--node-weight`).
- Thickens edge strokes as `--edge-weight` increases.

Override any of it with plain CSS — `::part(dot)`, `::part(edge)`, or the custom properties themselves:

```css
ixfx-hyperbolictree-list::part(dot) {
  fill: color-mix(in oklch, gray, red calc(var(--node-weight, 0.5) * 100%));
}
```

> **Gotcha:** because normalization is per-*visible-window*, a node whose weight is small relative to something merely nearby in the tree (e.g. a giant sibling subtree, or the root itself, both often in view) can still normalize close to `0` even if it's "big" in absolute terms. If your weight metric has a wide dynamic range (e.g. raw descendant counts across a deep tree), compress it — `Math.log2(x + 1)` rather than `x` — before assigning it to `item.weight`, or the visible spread of sizes/colours will collapse toward one end.

## Targeting a specific node or edge

Each node and edge exports extra `part` tokens keyed by node identity, so a single one can be styled from outside the shadow root:

| Element | Exported parts |
|---|---|
| Node `<g>` | `node`, `node-<key>` |
| Edge `<path>` | `edge`, `edge-to-<key>`, `edge-from-<key>` |

(Non-identifier characters in a key are replaced with `-` to keep the token CSS-selectable.)

```css
/* Give the edge leading to "library" a distinct dashed line. */
ixfx-hyperbolictree-list::part(edge-to-library) {
  stroke: var(--accent);
  stroke-dasharray: 8 4;
}
```

A plain attribute selector — `[data-to="library"]` — **cannot** reach across the shadow boundary from page-level CSS; only `::part()` can. Each edge does carry `data-from`/`data-to` attributes (and each node a `data-key` attribute), but those are for JS introspection (`el.shadowRoot.querySelectorAll(...)`), not CSS.

## Custom edge rendering

For styling `::part()`/CSS can't express (arbitrary shapes, gradients per edge, etc.), replace the default geodesic-arc path entirely:

```typescript
import { svg } from 'lit';
import type { HyperbolicEdgeRenderContext } from '@ixfx/components';

el.edgeRenderer = ({ edge, fromNode, toNode }: HyperbolicEdgeRenderContext) => {
  // Authored against the layout's native -1..1 disk coordinates —
  // the component scales this up to match its internal render scale.
  return svg`<line x1=${edge.from.x} y1=${edge.from.y} x2=${edge.to.x} y2=${edge.to.y} stroke="red" />`;
};
```

`edge.weightNormalized` is available on `edge` for weight-driven custom rendering.

## Focus, selection, navigation

```typescript
// Re-center the disk on a node (animated Möbius transform; fires `focus`, plus
// `expand`/`collapse` when relevant)
el.focusOn(node);

// Selection — same contract as ixfx-tree-list
el.select(node);
el.deselect(node);
el.clearSelection();
el.selectAll();
el.deselectAll();

// Navigate by key path or predicate — focuses + selects the match
el.navigateTo(['root', 'documents', 'readme.md']);
el.navigateToNode(n => n.item.key === 'readme.md');

// Snapshot of every currently laid-out node (within maxRadius of the focus),
// including the focused node itself, in ring-major order
const nodes = el.getNodes(); // ReadonlyArray<{ node: TreeNode; depth: number }>
```

## View state

Implements the shared view-state API (`getViewState()` / `setViewState()` / `clearPendingViewState()` / `view-state-change`) — see [`docs/infra-view-state.md`](./infra-view-state.md). `kind` is `hyperbolictree-list`.

```typescript
type HyperbolicTreeListViewState = ViewStateBase & {
  center?: string[]; // key path from the root's children to the centred node; [] = root
  zoom?: number;     // visual magnification (the `zoom` property)
};
```

| Field | Meaning |
|---|---|
| `selected` | Selected item keys. |
| `focus` | Keyboard cursor key — only recorded when the cursor was moved by keyboard or search navigation. |
| `center` | The centred node, as a key path. A path rather than a lone key because keys may repeat across branches here (e.g. `readme.md` in many folders). |
| `zoom` | Magnification. Not keyed: it doesn't depend on the data. |

- **What isn't saved:** a free pan (dragging empty space) and the disk's rotation are raw transforms in the centred node's local frame — they break as soon as the data changes, so they are left out. A restored view sits exactly on `center`, unpanned.
- **Data changes keep state.** A new `root`, a model `root` / `invalidate` event or a lazy load re-applies state by key. If the centred node goes away the view falls back to the root silently and `center` stays pending; selected nodes that go away are deselected silently and their keys stay pending.
- **Lazy data.** With `restoreLoads` (default `true`), a saved `center` whose ancestors aren't loaded is reached by loading each one in turn via `loadChildren` / `model`.
- **Events.** A restored selection fires `select`; a restored centre fires `focus` (no `expand`/`collapse`) and snaps rather than animating.
- An explicit `focusOn()` (click, key, navigation) drops a pending `center`; any explicit selection change drops pending `selected`.
- With repeated keys, a saved selection resolves to the first node (depth-first) with that key.

## Events

All events **bubble** and are **composed**.

| Event | Detail type | When fired |
|---|---|---|
| `focus` | `HyperbolicFocusDetail` — `{ node: TreeNode; previous: TreeNode \| undefined }` | The focused (centered) node changes |
| `select` | `TreeSelectDetail` | Selection set changes |
| `tickle` | `TreeTickleDetail` | An item enters cursor focus (pointer hover or keyboard cursor) |
| `activate` | `TreeActivateDetail` | Enter key or double-click |
| `item-click` | `{ node: TreeNode; depth: number }` | Raw pointer click on any item |
| `item-dblclick` | `TreeItemDblClickDetail` | Double-click (also fires `activate`) |
| `expand` | `{ node: TreeNode; depth: number }` | New focus is a descendant of the previous one |
| `collapse` | `{ node: TreeNode; depth: number }` | New focus is an ancestor of the previous one |

## Keyboard / pointer interaction

The element must be focused before keyboard navigation works (`disableKeyboardNavigation` turns it off entirely). Any pointer interaction — pressing a node, or starting a pan — moves keyboard focus to the tree, so you can follow a click or drag straight away with the arrow keys.

| Key | Action |
|---|---|
| `Arrow Up` | Focus the child closest to screen-"up" |
| `Arrow Down` | Focus the parent |
| `Arrow Left` / `Arrow Right` | Cycle siblings of the focused node |
| `Enter` | Select (unless `interactionMode="manual"`) and activate the focused node |
| `Escape` | Return focus to the root |

Pointer: click a node to focus (and select, per `interactionMode`) it; drag empty disk space to pan. Panning is a true hyperbolic translation — the grabbed point tracks the pointer and the tree never distorts. Focusing a node animates it to the center along the geodesic, keeping the current orientation (no spin).

Any pointer interaction also moves keyboard focus to the tree — see [Keyboard / pointer interaction](#keyboard--pointer-interaction). Ctrl/⌘-scroll or pinch zooms; see [Zoom gestures](#zoom-gestures).

Positions are always computed outward from the focus, one parent→child hop at a time, never from root-anchored coordinates. Root-anchored coordinates run out of floating-point precision about 14 hyperbolic units from the root (depth 5 at `curvature` 3), where whole subtrees would collapse onto one point. Focus-relative positions stay exact however deep you browse.

## CSS variables and parts

| Variable | Default | Description |
|---|---|---|
| `--hyperbolictree-node-color` | `var(--surface-4)` | Base node fill |
| `--hyperbolictree-node-text` | `var(--surface-3-text)` | Label text colour |
| `--hyperbolictree-edge-color` | `var(--surface-6)` | Edge stroke colour |
| `--hyperbolictree-boundary-color` | `var(--border-subtle)` | Disk boundary stroke colour |
| `--hyperbolictree-font-size` | `13px` | Label font size in screen px (in `box` mode, the size at the focus) |
| `--hyperbolictree-box-color` | `var(--hyperbolictree-node-color)` | `box` mode fill |
| `--hyperbolictree-box-text` | `var(--surface-4-text)` | `box` mode label colour. Selected/tickled boxes use `--item-text-selected` / `--item-text-tickled`, paired with their `--item-bg-*` fills |
| `--hyperbolictree-box-border` | `var(--surface-2)` | `box` mode border |
| `--node-weight` / `--node-weight-raw` | — | See [Weighting](#weighting) |
| `--edge-weight` | — | See [Weighting](#weighting) |

| Part | Element | Notes |
|---|---|---|
| `boundary` | Disk-edge circle | |
| `edges` / `nodes` | Group wrappers | |
| `edge`, `edge-to-<key>`, `edge-from-<key>` | Each edge `<path>` | See [Targeting a specific node or edge](#targeting-a-specific-node-or-edge) |
| `node`, `node-<key>` | Each node `<g>` | |
| `hit` | Invisible larger hit-target circle per node | `dot` mode only |
| `dot` | The visible node circle | `dot` mode only |
| `box` | The node rectangle | `box` mode only |
| `label` | Node label `<text>` | |
| `child-preview` | The hover popover listing a crowded node's children | See [Child preview](#child-preview) |

---

## Types reference

```typescript
type HyperbolicInteractionMode = 'implicit' | 'standard' | 'manual';

type HyperbolicNodeShape = 'dot' | 'box';

type HyperbolicFocusDetail = {
  readonly node: TreeNode;
  readonly previous: TreeNode | undefined;
};

type HyperbolicEdgeRenderContext = {
  readonly edge: HyperbolicLayoutEdge;
  readonly fromNode: TreeNode;
  readonly toNode: TreeNode;
};

type HyperbolicEdgeRenderer = (context: HyperbolicEdgeRenderContext) => unknown;

type HyperbolicLayoutNode = {
  readonly node: TreeNode;
  readonly key: string;          // node.item.key — may repeat across branches
  readonly id: string;           // key-path id, unique across the tree
  readonly depth: number;        // absolute depth from the true root
  readonly ring: number;         // tree-graph steps from the focus (0 = focus itself)
  readonly parentKey: string | undefined;
  readonly parentId: string | undefined;
  readonly position: Point;      // Poincaré-disk position, focus projected to the origin
  readonly angularShare: number; // angular width (radians) allocated by the parent's partition
  readonly weight: number | undefined;
  readonly weightNormalized: number; // 0..1, normalized across the visible node set
};

type HyperbolicLayoutEdge = {
  readonly fromKey: string;
  readonly toKey: string;
  readonly fromId: string;
  readonly toId: string;
  readonly from: Point;
  readonly to: Point;
  readonly weightNormalized: number; // average of the two endpoints'
};
```

See [`src/tree/README.md`](./tree.md) for `TreeNode`, `TreeItem` (including `weight`), `TreeDataModel`, `TreeComponent`, and incremental search — all shared with the rest of the tree family.
