Documentation
API: core (@fragiola/tree)

Model

Create a tree model from a document, read it with get and is, and find every key they take. The state only commands change.

A model holds one tree: its items, what is expanded, checked, focused and being renamed, its settings, and the state of its opt-in features (what is selected, with selection()). It runs in plain Node (no DOM), and every member is one verb:

memberdoes
statethe current state (TreeState<T>): immutable, a new object after every change
run(command, payload, options?)changes the tree: runs a command through the middleware chain, returns a CommandResult
dispatch(input, options?)run for untrusted JSON { command, payload, transient? }, validated
can(command, payload, options?)answers whether run would succeed now: a boolean
check(command, payload, options?)returns what run would return, without changing anything
get(key, payload?)reads: an item, its parent, the visible items, the document (Reading)
is(key, payload)asks a yes/no question (Asking)
use(middleware)adds a middleware around every command; returns its remover
subscribe(listener)listens to every committed command; returns its remover

Every method is bound: const { run, get } = model works. The commands are on Commands, run, dispatch, middleware and events on The command bus, and the document on The JSON model.

Creating a model

function createTreeModel<T extends TreeTypes = AnyTypes, const F extends TreeFeatures = readonly []>(
    json?: TreeJson<T>,
    options?: TreeModelOptions<T, F>,
): TreeModel<T, F>;

createTreeModel validates the document and normalizes it; without one it creates an empty tree. An invalid document throws a TreeValidationError whose issues (ValidationIssue[]: a JSON path and a message each) list every problem; validateTree(json) returns the same issues without throwing. The document's JSON Schema is exported as treeSchema (a JsonSchema).

T is your registry (Typed data): pass it explicitly. F is the list of features (options.features): inferred when T is, else pass it too (createTreeModel<Types, typeof features>(json, { features })). A document field of a feature that is not installed (selectedItemIds without selection()) is a validation issue.

The type registry

A registry extends TreeTypes ({ items: object }): each item kind, and the type of its data. KindOf<T> is the union of its kinds, DataOf<T, K> the data type of kind K, and ItemOf<T> an item, discriminated by kind. With no registry, AnyTypes accepts any kind with unknown data. FromSchema<S> derives a data type from a JSON Schema written as const, as in the example below.

TreeModelOptions

optiontypedescription
featuresF (TreeFeatures)the opt-in features, each from its own entry (selection() from @fragiola/tree/selection, virtualization(options) from @fragiola/tree/virtualization), fixed for the model's life (Features)
createIdCreateId: (kind: "item") => stringgenerates the id of an item created without one (item.add, item.set-children); default `item-${n}`, skipping ids in use
dataSchemas{ [K in KindOf<T>]?: JsonSchema }a JSON Schema per item kind: the document, item.add, item.set-data and item.set-children validate that kind's data with it
freezebooleanfreeze every state object (default true); with false, the state must still never be mutated
import { createTreeModel, type FromSchema } from "@fragiola/tree";

const fileSchema = {
    type: "object",
    properties: { size: { type: "number", minimum: 0 } },
    required: ["size"],
    additionalProperties: false,
} as const;

type Types = { items: { folder: undefined; file: FromSchema<typeof fileSchema> } };

const model = createTreeModel<Types>(json, {
    createId: () => `item-${crypto.randomUUID()}`,
    dataSchemas: { file: fileSchema },
});

The state

TreeState<T> is plain, frozen, JSON-shaped data; model.state is a TreeStateOf<T, F>, the core's fields and the installed features' (the two marked selection() below):

fieldtypedescription
settingsTreeSettingsthe modes and the flags' defaults (The JSON model)
rootItemIdsreadonly string[]the root items, in order
items{ readonly [id: string]: ItemOf<T> }every item, by id
expandedItemIdsreadonly string[]the expanded items
selectedItemIdsreadonly string[]selection(): the selection, in the order it was made
checkedItemIdsreadonly string[]the checked items (in cascade mode, a parent with children exactly when all are)
selectionAnchorItemIdstring | nullselection(): where a range selection starts
focusedItemIdstring | nullthe roving tab stop, always visible
renamingItemIdstring | nullthe item whose label is being edited

An item (TreeItem<K, D>, typed as ItemOf<T>) has id, kind, label, data, and optionally childItemIds, childrenStatus (ChildrenStatus) and the flags (ItemFlags: disabled, movable, renamable, droppable). DEFAULT_SETTINGS are the settings of a document that gives none. The mode types are SelectionMode ("none" | "single" | "multiple") and CheckMode ("cascade" | "independent"); a checkbox's state is CheckState.

Reading: get

model.get(key, payload) reads through a named key (ModelGetKey, typed by ModelGetMap: ModelGetPayload and ModelGetResult). A key that takes an id ends in -by; a key that takes nothing needs no payload (QueryArgs).

keypayloadresult
"tree-json"noneTreeJson<T>: the document of the current state, every field written (a copy)
"commands"nonereadonly CommandInfo[]: every command of the core and of the installed features, with its description and JSON Schemas
"features"nonereadonly TreeFeatureInfo[]: the installed features (name), each with the controlled root props it ships (rootProps)
"item-attributes-by"{ itemId }Readonly<Record<string, string | undefined>>: the ARIA and data-* the installed features give an item (selection(): aria-selected, data-selected), from the state alone; an adapter puts them all on the item's element, the data-* on its other parts
"root-attributes"noneReadonly<Record<string, string | undefined>>: the ARIA and data-* the installed features give the root (aria-multiselectable)
"settings"noneTreeSettings
"item-by"{ id }ItemOf<T> | undefined
"item-parent-by"{ itemId }ItemOf<T> | undefined: undefined for a root item
"child-items-by"{ itemId }ItemOf<T>[]: in order; empty for a leaf or a parent not loaded
"root-items"noneItemOf<T>[]
"visible-items"nonereadonly VisibleItem[]: the render order (below)
"item-path-by"{ itemId }string | undefined: /0/2, its data-tree-path
"check-state-by"{ itemId }CheckState: "checked", "unchecked" or "mixed"
"selected-items"noneItemOf<T>[]: in the order they were selected (selection())
"children-status-by"{ itemId }ChildrenStatus | undefined: undefined when it holds its children itself
"type-ahead-match"{ text, fromItemId? }ItemOf<T> | undefined: the next visible item after fromItemId (wrapping) whose label starts with text, ignoring case
"tab-stop-item"noneItemOf<T> | undefined: the focused item, else the first visible selected one (selection()), else the first visible one

A VisibleItem is { itemId, parentItemId, level, posinset, setsize }: the items whose ancestors are all expanded, in render order. It is the base of the keyboard navigation, and the list a virtualizer will consume (Known limitations).

const parent = model.get("item-parent-by", { itemId: "app" });
const rows = model.get("visible-items").map((entry) => model.get("item-by", { id: entry.itemId }));

Asking: is

model.is(key, payload) answers a yes/no question (ModelIsKey, typed by ModelIsMap: ModelIsPayload). An unknown item answers false.

keypayloadtrue when
"item-expanded"{ itemId }its children are shown
"item-selected"{ itemId }it is selected (selection())
"item-focused"{ itemId }it is the focused item, as stored (see "item-tab-stop")
"item-checked"{ itemId }its checkbox is checked (not mixed)
"item-renaming"{ itemId }its label is being edited
"item-loading"{ itemId }its children are being loaded
"item-disabled"{ itemId }it is disabled
"item-movable"{ itemId }it can be moved now: movable (its flag or the default) and not disabled
"item-renamable"{ itemId }it can be renamed now: renamable and not disabled
"item-leaf"{ itemId }it has no children and no children status
"item-visible"{ itemId }its ancestors are all expanded
"item-tab-stop"{ itemId }it is the roving tab stop ("tab-stop-item")
"item-descendant-of"{ itemId, ancestorItemId }it is inside the other item's subtree (itself excluded)

Features

A feature is an opt-in part of the tree: its state, commands, keys and engine behaviour, in its own entry, so a bundle that never imports it does not ship it. The model takes them once, in options.features; a root's features prop does the same for the model it creates.

featureentryadds
selection(options?)@fragiola/tree/selectionselectedItemIds, selectionAnchorItemId, settings.selectionMode (options.mode, default "single"), the selection commands, "selected-items", "item-selected", the keys and clicks that select, aria-selected, and the selectedItemIds root prop
virtualization(options?)@fragiola/tree/virtualizationnothing in the model: each engine renders a window of the visible items (engine.get("virtual-window"), The engine)

A command of a feature that is not installed returns not_found (and does not compile); its get key reads undefined and its is key answers false. A feature is a TreeFeature<N, S> (AnyTreeFeature for any; FeatureName names them): a plain object whose optional parts the core composes once, at creation, and which only the core reads: its settings, document rules and fields (FeatureDocument, FeatureDocumentContext), its commands and keys on a FeatureState, its reactions to removed, disabled and reconfigured items, and its part of each engine (FeatureEngine, given a FeatureEngineHost with a FeatureModel, a key action's FeatureKeyContext, and a FeatureViewport for virtualization). TreeRootProp is a controlled root prop a feature ships, and TreeFeatureInfo what "features" lists of it. The core's own controlled lists (expandedItemIds, checkedItemIds) are TREE_ROOT_PROPS, so an adapter maps every list the same way; FEATURE_ROOT_PROPS names every feature's root prop with its feature, and FeatureRootPropsOf<F> types the root props of the features F. The concept is on Features.

The types follow the list: TreeFeatures is a list of features (AnyFeatures any of them), TreeStateOf<T, F> the state with their fields (FeatureStateOf<F> alone), and CommandNameOf<F>, ModelGetKeyOf<F>, ModelIsKeyOf<F>, EngineActionKeyOf<F>, EngineGetKeyOf<F> and EngineIsKeyOf<F> the commands and keys a model or engine with them takes. A model with more features is a model with fewer: code that takes any model takes TreeModel<T>.

import { createTreeModel } from "@fragiola/tree";
import { selection } from "@fragiola/tree/selection";

const features = [selection({ mode: "multiple" })] as const;
const model = createTreeModel<Types, typeof features>(json, { features });
model.run("tree.select-all", {});
model.state.selectedItemIds;

In React

useTreeState selects a value of the state and re-renders only when it changes; useTree and a tree ref give the model itself (Hooks).