Skip to content

@jsvision/ui / Tree

Class: Tree<T>

Documented in: Tree

Defined in: ui/src/tree/tree.ts:94

A focusable, virtual-scrolling, expandable outline (file tree, nav tree, etc.). It renders a forest of TreeNode roots as indented rows with │├└─ connector guides and a +/ marker, and only paints its visible window, so it stays fast over large trees.

Expand state is owned by the tree, keyed on node object identity — the node data stays plain, and the same node can live in more than one tree with independent expand state. Mutate it with expand/collapse/toggle/expandAll/collapseAll/ expandSubtree; each re-flattens and repaints.

Keyboard: ↑↓ move focus, PgUp/PgDn page, Home/End, Ctrl+PgUp/PgDn jump to ends, +/- expand or collapse the focused node, * expand its whole subtree, ←/→ collapse-or-parent / expand-or-child, Enter activate. Mouse: click a node's guide zone to toggle it, double-click its text to activate.

Because a plain Group is not itself a focus target, focus the exposed Tree.rows renderer, not the tree.

Example

ts
import { Group, Tree, createEventLoop, signal } from '@jsvision/ui';
import type { TreeNode } from '@jsvision/ui';

// A leaf is `children: []`.
const n = (value: string, children: TreeNode<string>[] = []): TreeNode<string> => ({ value, children });

const roots = signal<TreeNode<string>[]>([
  n('src', [n('index.ts'), n('engine', [n('buffer.ts')])]),
  n('README.md'),
]);

const tree = new Tree<string>({
  roots,
  getText: (name) => name,
  command: 'open',
  markerStyle: 'brackets', // `[+]`/`[-]` expand markers instead of the default `+`/`─`
  onSelect: (_i, node) => console.log('opened', node.value),
});
tree.layout = { position: 'absolute', rect: { x: 0, y: 0, width: 28, height: 10 } };

const root = new Group();
root.add(tree);
const loop = createEventLoop({ width: 28, height: 10 });
loop.mount(root);
loop.focusView(tree.rows); // focus the rows renderer, not the tree
tree.expandAll();

Extends

Type Parameters

T

T

Constructors

Constructor

new Tree<T>(opts): Tree<T>

Defined in: ui/src/tree/tree.ts:121

Parameters

opts

TreeOptions<T>

The tree configuration — see TreeOptions.

Returns

Tree<T>

Overrides

Group.constructor

Properties

background?

optional background?: keyof Theme

Defined in: ui/src/view/group.ts:64

Optional background theme role filled before children compose, so overlap never leaks cells.

Inherited from

Group.background


bar

protected readonly bar: ScrollBar

Defined in: ui/src/tree/tree.ts:100

The owned vertical scroll bar (its value is the shared focused signal).


bounds

bounds: Rect

Defined in: ui/src/view/view.ts:65

Parent-relative integer rect; written by the layout pass — read it in draw/hit-testing.

Inherited from

Group.bounds


castsShadow

castsShadow: boolean = false

Defined in: ui/src/view/view.ts:78

When true, the renderer paints a drop shadow on the cells just below and to the right of this view, in paint order (a later sibling's shadow falls over an earlier one). Default false. The Desktop sets it per window.

Inherited from

Group.castsShadow


centered

centered: boolean = false

Defined in: ui/src/view/view.ts:86

When true, the layout pass recentres this view within its parent after layout — origin = (parent - self) / 2 on both axes. Intended for absolutely-placed views (a modal dialog, a message box) whose size is fixed and whose origin would otherwise be placed by the caller. Default false; Dialog sets it when centered.

Inherited from

Group.centered


children

readonly children: View[] = []

Defined in: ui/src/view/group.ts:62

Ordered children; array order is paint order (back-to-front).

Inherited from

Group.children


command?

protected readonly optional command?: string

Defined in: ui/src/tree/tree.ts:108

Command name emitted on activation.


expandedSet

protected readonly expandedSet: Set<TreeNode<T>>

Defined in: ui/src/tree/tree.ts:112

View-owned expand state: a set of expanded nodes keyed on object identity.


expandVersion

protected readonly expandVersion: Signal<number>

Defined in: ui/src/tree/tree.ts:114

Bumped on every expand-state mutation so the flatten computed re-runs (the set itself is untracked).


flattened

protected readonly flattened: () => FlatRow<T>[]

Defined in: ui/src/tree/tree.ts:116

The flattened-visible rows (recomputes on a roots or expand-state change).

Returns

FlatRow<T>[]


focusable

focusable: boolean = false

Defined in: ui/src/view/view.ts:94

Whether this view can receive keyboard focus. Effective focusability also requires the view to be visible and enabled with no hidden/disabled ancestor. Default false; the focus manager drives the state.focused flag.

Inherited from

Group.focusable


focused

readonly focused: Signal<number>

Defined in: ui/src/tree/tree.ts:102

The focused-index signal (shared with the bar), exposed for binding.


layout

layout: LayoutProps

Defined in: ui/src/tree/tree.ts:96

Lay the children out horizontally: rows on the left, the scroll bar on the right.

Overrides

Group.layout


onSelect?

protected readonly optional onSelect?: (index, node) => void

Defined in: ui/src/tree/tree.ts:110

Activation callback.

Parameters

index

number

node

TreeNode<T>

Returns

void


postProcess

postProcess: boolean = false

Defined in: ui/src/view/view.ts:98

Take part in the post-process sweep (after the focused view sees the event).

Inherited from

Group.postProcess


preProcess

preProcess: boolean = false

Defined in: ui/src/view/view.ts:96

Take part in the pre-process sweep (root→down, before the focused view sees the event).

Inherited from

Group.preProcess


roots

protected readonly roots: Signal<TreeNode<T>[]>

Defined in: ui/src/tree/tree.ts:106

The forest of roots.


rows

readonly rows: TreeRows<T>

Defined in: ui/src/tree/tree.ts:98

The focusable rows renderer — focus this (a plain Group is not itself a focus target).


selected

readonly selected: Signal<number>

Defined in: ui/src/tree/tree.ts:104

The selected-index signal, exposed for binding (-1 = none).


state

readonly state: ViewState

Defined in: ui/src/view/view.ts:67

Draw-against flags. The object reference is fixed; individual fields mutate (e.g. focused).

Inherited from

Group.state

Methods

accelerators()

accelerators(): readonly string[]

Defined in: ui/src/view/view.ts:114

The Alt+hotkey accelerator characters (lowercase) this view claims in its focus scope, for duplicate-accelerator detection. The base returns none; accelerator-bearing widgets (Button/Label/CheckGroup/RadioGroup) override it to report their ~X~ hotkey(s).

Returns

readonly string[]

The claimed accelerator chars, or an empty list when the view claims none.

Inherited from

Group.accelerators


add()

add(child): void

Defined in: ui/src/view/group.ts:88

Add a child, appending it on top (later in the array draws in front). If this group is already mounted, the child mounts immediately — its scope nested under this group's — and a reflow is scheduled for the new layout; otherwise the child mounts when this group itself mounts.

Parameters

child

View

The view to append.

Returns

void

Inherited from

Group.add


addDynamic()

addDynamic(build): void

Defined in: ui/src/view/group.ts:135

Add children reactively from a Show/For accessor, so the set of children updates itself as signals change. When the group is mounted, an effect reads the accessor, mounts any newly produced views, unmounts any that disappeared (firing their onCleanup), and schedules a reflow on change. Pass a factory that builds the combinator inside itself, not an already-built accessor — this lets the group own and dispose the combinator's reactive nodes on unmount.

Parameters

build

DynamicBuilder

A factory that constructs the combinator, e.g. () => Show(cond, then) or () => For(each, key, render).

Returns

void

Example

ts
import { Group, signal, Show } from '@jsvision/ui';

const open = signal(false);
const group = new Group();
group.addDynamic(() => Show(() => open(), () => new Panel())); // Panel appears when `open` is true

Inherited from

Group.addDynamic


bind()

bind<T>(reader, apply?, opts?): void

Defined in: ui/src/view/view.ts:228

Bind a reactive value to a redraw. Creates an effect (owned by this view's scope) that reads reader() — subscribing to whatever signals it touches — runs the optional apply(value), then requests a frame: a repaint by default, or a reflow when { relayout: true }. It re-runs automatically whenever those signals change, and is disposed when the view unmounts.

Call it from onMount, not the constructor — the view's scope only exists once mounted, so a pre-mount bind throws rather than silently dropping the binding.

Type Parameters

T

T

Parameters

reader

() => T

Reads the reactive source; the signals it reads become dependencies.

apply?

(v) => void

Optional: apply the read value to the widget (e.g. store it in a field).

opts?

Pass { relayout: true } when the change affects layout, so it reflows instead of just repainting.

relayout?

boolean

Returns

void

Example

ts
import { signal } from '@jsvision/ui';

const count = signal(0);
// `status` is a View whose draw() reads count():
status.onMount(() => {
  status.bind(() => count()); // repaint the status line whenever `count` changes
});

Inherited from

Group.bind


bump()

protected bump(): void

Defined in: ui/src/tree/tree.ts:215

Bump the expand version so the flatten computed re-runs (the expand set is not itself reactive).

Returns

void


collapse()

collapse(node): void

Defined in: ui/src/tree/tree.ts:173

Collapse node (a no-op if already collapsed); re-flattens + repaints.

Parameters

node

TreeNode<T>

Returns

void


collapseAll()

collapseAll(): void

Defined in: ui/src/tree/tree.ts:190

Collapse every node; one repaint.

Returns

void


derived()

protected derived<T>(fn): () => T

Defined in: ui/src/view/view.ts:261

Create a stable derived accessor owned by this view's scope. The returned () => T keeps the same identity for the life of the view, so it is safe to build in the constructor and hand to child views before this view mounts. The backing computed is created lazily under the view's own scope, so it is always owned and disposed at unmount — unlike a bare computed() in the constructor, which would run before any scope exists, leak, and warn.

Reads behave sensibly across the lifecycle:

  • Before mount: evaluates fn() directly (correct current value, nothing persisted). Good for a pre-mount natural-size measure.
  • After mount: builds and memoizes a computed(fn) under the view's scope.
  • After an unmount→remount: the memo is keyed to the scope it was built under, so a remounted view (which gets a fresh scope) re-derives under the new scope instead of returning the previous mount's disposed, now-frozen computed — keeping a Show/For-remounted widget reactive.

Type Parameters

T

T

Parameters

fn

() => T

The derivation (pure; the signals it reads become the computed's dependencies).

Returns

A stable accessor; call it to read the derived value.

() => T

Inherited from

Group.derived


desiredCaret()

desiredCaret(): Point | null

Defined in: ui/src/view/view.ts:192

Where this view wants the hardware text cursor, in view-local cells, or null for no cursor (the default — most views never show one). A focused text input overrides this to place the caret at the edit position; the event loop reads it after each frame, converts it to an absolute cell, and moves the terminal cursor there.

Returns

Point | null

The view-local caret point (0-based, relative to this view's origin), or null.

Inherited from

Group.desiredCaret


draw()

draw(ctx): void

Defined in: ui/src/view/group.ts:75

Fill the background role (if set) across the group rect; children are composed by the render root.

Parameters

ctx

DrawContext

Returns

void

Inherited from

Group.draw


expand()

expand(node): void

Defined in: ui/src/tree/tree.ts:165

Expand node (a no-op if already expanded); re-flattens + repaints.

Parameters

node

TreeNode<T>

Returns

void


expandAll()

expandAll(): void

Defined in: ui/src/tree/tree.ts:184

Expand every node in the whole forest; one repaint.

Returns

void


expandSubtree()

expandSubtree(node): void

Defined in: ui/src/tree/tree.ts:196

Expand node and its entire subtree (the * key); one repaint.

Parameters

node

TreeNode<T>

Returns

void


focusSignal()

focusSignal(): Signal<void>

Defined in: ui/src/view/view.ts:136

Subscribe to this view's focus changes. Reading the returned signal inside a bind/effect re-runs that effect whenever this view gains or loses focus — including from another view (e.g. a Label repainting when the control it labels is focused). The signal notifies on every poke even without a value change. Lazy: the backing signal is created on first call.

Returns

Signal<void>

A signal that ticks whenever this view gains or loses focus.

Example

ts
// Inside a widget's onMount, repaint whenever `other` view's focus changes:
this.onMount(() => this.bind(() => other.focusSignal()()));

Inherited from

Group.focusSignal


invalidate()

invalidate(): void

Defined in: ui/src/view/view.ts:197

Request a repaint of this view. A no-op before the view is mounted (the first frame paints everything).

Returns

void

Inherited from

Group.invalidate


invalidateLayout()

invalidateLayout(): void

Defined in: ui/src/view/view.ts:202

Request a reflow (re-run layout, then repaint). Use this when a change affects size/position, not just pixels.

Returns

void

Inherited from

Group.invalidateLayout


isExpanded()

isExpanded(node): boolean

Defined in: ui/src/tree/tree.ts:160

Whether node is currently expanded (matched by object identity).

Parameters

node

TreeNode<T>

Returns

boolean


measure()?

optional measure(available): Size2D

Defined in: ui/src/view/view.ts:71

Optional intrinsic-size hook for auto sizing — return the size this view wants for available.

Parameters

available

Size2D

Returns

Size2D

Inherited from

Group.measure


onCleanup()

onCleanup(fn): void

Defined in: ui/src/view/view.ts:298

Register a teardown callback that runs once when this view unmounts. Requires a mounted view — so call it from within onMount. Use it to release anything the view acquired (a timer, an external subscription).

Parameters

fn

() => void

The teardown callback.

Returns

void

Inherited from

Group.onCleanup


onEvent()

onEvent(_ev): void

Defined in: ui/src/view/view.ts:172

Handle an input event — a no-op by default. The event loop wraps each event in a DispatchEvent envelope and routes it to the views; override this to react to keys/mouse and set ev.handled = true to consume the event so it does not propagate further.

Parameters

_ev

DispatchEvent

The dispatch envelope (the wrapped event plus the mutable handled flag).

Returns

void

Inherited from

Group.onEvent


onMount()

onMount(fn): void

Defined in: ui/src/view/view.ts:283

Register a callback to run once when the view becomes live (after its first layout gives it bounds). This is where to call bind, since the view's reactive scope exists by then. Registering after the view is already live runs the callback immediately.

Parameters

fn

() => void

Post-mount setup.

Returns

void

Inherited from

Group.onMount


remove()

remove(child): void

Defined in: ui/src/view/group.ts:104

Remove a child: dispose its scope (recursively disposing its descendants and running their onCleanup), detach it, and schedule a reflow. Removing a non-child (or removing twice) is a safe no-op.

Parameters

child

View

The view to remove.

Returns

void

Inherited from

Group.remove


seedExpanded()

protected seedExpanded(nodes): void

Defined in: ui/src/tree/tree.ts:202

Add every node with children (reachable from nodes) to the expanded set. Iterative.

Parameters

nodes

TreeNode<T>[]

Returns

void


selectByClick()?

optional selectByClick(): void

Defined in: ui/src/view/view.ts:182

Optional "select + raise on click" hook. Left undefined on the base, so a plain view is not a select/raise target. A container that owns z-order (a Window) overrides it to select and raise itself. The hit-test invokes the first ancestor that defines this — before delivering the mouse-down — so a click always raises the window even if the interior also consumes the click.

Returns

void

Inherited from

Group.selectByClick


toggle()

toggle(node): void

Defined in: ui/src/tree/tree.ts:178

Toggle node's expand state; re-flattens + repaints.

Parameters

node

TreeNode<T>

Returns

void