Documentation
API: core (@fragiola/tree)

Engine

One tree on screen - DOM focus, keys, drags, the async loader and announcements - behind the model's verbs, with every key it takes.

The engine is the half of the core that needs a screen: DOM focus, the keyboard, the Pointer Events drag and the keyboard drag, scrolling, calling your loader, and the live region's text. Tree.Root creates one per model for you; read it with useTree() or a tree ref. It has the model's verbs with its own keys, and changes the tree only by running the model's commands, so your middleware sees what a key or a drop does.

const { engine } = useTree<Types>();

engine.run("focus", { itemId: "app" });
engine.run("start-keyboard-drag", { itemIds: ["app"] });
engine.get("drop-target");
engine.is("item-dragging", { itemId: "app" });

Creating an engine

createTreeEngine(model, options) creates one. Adapters call it; you need it only for another framework, or a page with no framework:

function createTreeEngine<T extends TreeTypes = AnyTypes>(
    model: TreeModel<T>,
    options?: TreeEngineOptions<T>,
): TreeEngine<T>;
import { createTreeEngine, createTreeModel } from "@fragiola/tree";

const model = createTreeModel<Types>(json);
const engine = createTreeEngine(model, { root: document.querySelector<HTMLElement>("#files") ?? undefined });
// …
engine.destroy();

The engine reaches the DOM only through the root's ownerDocument and defaultView, so it works in an iframe or a popup window.

TreeEngineOptions

optiontypedefaultdescription
rootHTMLElementnonethe role="tree" element; an adapter may attach it later
loadChildrenLoadChildren<T>noneyour loader: (item, { signal }) => Promise<readonly TreeItemJson<T>[]>, called with asyncChildren() in the model's features (ignored without it)
announce(event: AnnounceEvent) => string | undefinednonethe live region's text for a drag step or a failed load
keyMapPartial<KeyMap>DEFAULT_KEY_MAPthe key bindings, over the defaults
expandOnClickbooleanfalsea click on a parent's content also expands or collapses it
resetLoadsOnDestroybooleanfalsewith asyncChildren(): destroy() puts the items it was loading back to unloaded, so the next engine loads them again (adapters set it)

Members

memberdoes
run(action, payload?)runs a screen action (below); returns a CommandResult
can(action, payload?)whether the action would run now
check(action, payload?)what run would return, without running it
get(key, payload?)reads a fact of the screen
is(key, payload?)asks a yes/no question about the screen
subscribe(listener)listens to the engine's own state (a drag step, an announcement); returns its remover
destroy()releases every listener, timer and pending load; no command runs afterwards
adapterwhat only an adapter calls (below)

Actions: run

An engine key never has a dot, so it never reads as a command (EngineActionKey, typed by EngineActionMap: EngineActionPayload, EngineActionResult).

actionpayloaddoes
"focus"{ itemId }moves DOM focus to the item and makes it the focused item (item.focus)
"scroll-to"{ itemId, align? }scrolls the item into view: the nearest edge, or align (ScrollAlign: "nearest", "start", "center", "end"); a virtualized tree scrolls to a visible item that is not rendered, which renders it
"load-children"{ itemId }asyncChildren(): calls your loadChildren for an item with a childrenStatus (a retry, or a first load); refused while it loads
"start-keyboard-drag"{ itemIds }starts a keyboard drag: the arrows move the drop target (on into the other trees of a drag group), Enter drops (item.move, or a transfer), Escape cancels
"cancel-drag"nonecancels the drag under way, pointer or keyboard, here or from another tree of the group: nothing is committed
"commit-rename"{ itemId, label, focus? }rename(): commits an item's rename with your editor's value (item.rename), then focuses the item, unless focus: false (a blur: focus stays where it went); refused as item.rename is (an empty label, a middleware's veto), and the item keeps renaming
"cancel-rename"{ itemId, focus? }rename(): cancels an item's rename (item.cancel-rename), then focuses the item, unless focus: false

Reading: get

EngineGetKey, typed by EngineGetMap (EngineGetPayload, EngineGetResult):

keyresult
"drop-target"DropTarget | null: the drop target of the drag under way (only one model.can accepts)
"dragging-item-ids"readonly string[]: the items being dragged (empty when no drag)
"drop-indicator"DropIndicator | null: where the drop indicator goes
"announcement"string: the latest text your announce returned ("" before any)
"direction""ltr" | "rtl": the root's writing direction; Right and Left swap in rtl
"virtual-window"VirtualWindow: the rows a virtualized tree renders (the virtualization() feature; a type error and undefined without it)
"drop-outside-element"Element | null: the element under the pointer while this tree's pointer drag is outside every tree (dropOutside()), for your own targets to show it; null otherwise

A DropTarget is the item.move a drop would run and how it reads on screen; a DropIndicator is where DropIndicator goes, relative to the root's border box, in pixels and logical sides:

fieldofdescription
parentItemIdDropTargetthe parent the items go into (null: the root)
indexDropTargettheir index among its children, as item.move takes it
positionbothDropPosition: "before", "after" or "inside", relative to itemId
itemIdboththe item the position is relative to; null for a drop into an empty tree
levelboththe level the dropped items take (1 for the root)
blockOffsetDropIndicatorfrom the root's top to the line, or to the row's top for inside, scroll included
blockSizeDropIndicatorthe row's height for inside, 0 for a line
inlineOffsetDropIndicatorfrom the root's inline-start edge: (level - 1) * indentation, plus dragAndDrop()'s indicatorInset for a line

DropContext and HoverPosition are the inputs of the drop evaluation (what it reads of the tree, and where the pointer is over a row), exported for an adapter's tests.

Virtualization

The virtualization feature, virtualization(options) from @fragiola/tree/virtualization, makes every engine on its model render only the visible items in view, plus overscan rows on each side, so a tree of hundreds of thousands of visible items scrolls, moves the focus and drags like a small one. It is opt-in and costs nothing without it: a bundle that never imports it leaves it out. Each engine on the model gets its own virtualizer. The guide is Virtualization.

import { createTreeEngine, createTreeModel } from "@fragiola/tree";
import { virtualization } from "@fragiola/tree/virtualization";

const model = createTreeModel(json, { features: [virtualization({ rowSize: 28 })] });
const engine = createTreeEngine(model, { root });
engine.get("virtual-window"); // the rows to render

TreeVirtualizerOptions, the options of virtualization(options):

optiontypedefaultdescription
rowSizeRowSizenoneevery row's exact size (px), or a function of the VisibleItem for one per row; rows are never measured, and your CSS gives them these sizes
estimateRowSizeRowSize32the size a row is given until it is measured (without rowSize): rendered rows are measured through the root window's ResizeObserver and keep their size while they stay visible
overscannumber8how many rows are rendered past each edge of the view
scrollElement() => HTMLElement | null | undefinedthe nearest scrolling ancestor of the root (the root included), else the documentthe element that scrolls the rows
initialViewportSizenumber0the view's size (px) while the scroll element has none: a server render, a test without layout, a hidden tree

engine.get("virtual-window") returns a VirtualWindow, and each of its rows is a VirtualRow, a VisibleItem with where it goes:

fieldofdescription
rowsVirtualWindowthe rows to render, in order: the ones in view plus the overscan, and the pinned ones (the roving tab stop, the item being renamed, the item a pointer pressed) wherever the scroll is
start, endVirtualWindowthe rows in view plus the overscan, as indexes of the visible items (end excluded)
totalSizeVirtualWindowthe size (px) of every visible item together
spaceAfterVirtualWindowthe space (px) after the last rendered row: the last spacer
indexVirtualRowits index in model.get("visible-items")
offsetVirtualRowfrom the top of the rows to its top (px)
sizeVirtualRowits size (px): given, measured or estimated
spaceBeforeVirtualRowthe space (px) between the previous rendered row (or the top) and this one: the spacer before it

A virtualized tree is flat: render each row as an item with no group, between spacers of spaceBefore and, after the last one, spaceAfter (what VirtualItems does). The rows start at the top of the root's content box. With estimated sizes, the engine keeps the view in place when a row above it is measured, so it sets overflow-anchor: none on the scroll element while attached (the browser's own anchoring would move the view a second time). PageDown and PageUp move the focus by the rows in view ("focus-page-down", "focus-page-up"); a tree that is not virtualized leaves those keys to the browser.

Asking: is

EngineIsKey, typed by EngineIsMap (EngineIsPayload):

keypayloadtrue when
"dragging"nonea drag is under way (pointer, keyboard, or foreign content over the tree)
"keyboard-dragging"nonea keyboard drag is under way
"dragging-from-other-tree"nonea drag that started in another tree of the drag group is under way: this tree shows its target when it is here
"item-dragging"{ itemId }the item is being dragged
"item-drop-target"{ itemId }the drop target is relative to the item

Drag and drop

The drags are features of the model (Features), each from its own entry; their options are the features', not the engine's:

featureentryoptions
dragAndDrop(options?)@fragiola/tree/drag-and-dropdragThreshold (px, default 4), autoExpandDelay (ms, default 800), indentation (px, default 16: the pointer's inline offset at the end of a sublist picks the level), indicatorInset (px, default 0: how far a before / after line starts past its level; the inside box gets none), autoScroll ({ threshold, speed })
dragGroup({ name, transfer? })@fragiola/tree/drag-groupthe group name, and the app's transfer (below); needs dragAndDrop()
foreignDrop({ accept?, onDrop, dropEffect? })@fragiola/tree/foreign-dropbelow, with the same autoExpandDelay, indentation, indicatorInset and autoScroll (drag and drop's win)
dropOutside({ onDrop })@fragiola/tree/drop-outsidebelow; needs dragAndDrop()

Without dragAndDrop() a press never drags and start-keyboard-drag is not_found; without a drag feature, the drag keys read nothing (get → undefined, is → false).

Drag groups

The trees in the same document whose models have the same dragGroup({ name }) share their drags. The drag stays its source tree's (its pointer capture, its keys, its announce); the tree under the pointer finds its own target, shows its DropIndicator and data-drop-target, expands a hovered collapsed parent and scrolls near its edges. The keyboard drag's Down and Up go on through the group's trees in document order. While a drag from another tree is under way, a tree's is("dragging") and is("dragging-from-other-tree") are true and get("drop-target") is its own target; get("dragging-item-ids") lists the dragged items when it shows the same model, and is empty otherwise.

A drop in a tree of the same model is one item.move. In a tree of another model it is a transfer: by default the target model runs one batch of item.add (each dragged item and its descendants, ids kept, children not loaded yet left to its loader) and the source model runs item.remove, each through its own middleware. A target shows only when the target model accepts the batch and the source model the removal (model.can). dragGroup({ transfer }) (a TransferHandler) replaces it, called with a TreeTransfer:

fieldtypedescription
itemIdsreadonly string[]the dragged items in the source model: the outermost, in tree order
itemsreadonly TreeItem[]those items, as the source model has them
fromTreeModelthe source model
to{ model, parentItemId, index }the target model, and where the items go (as item.add's to)
commandsreadonly BatchEntry[]the default transfer's commands for the target: an item.add per item, parents first, then an item.expand per item expanded in the source; map them to copy with new ids or to convert kinds
modifiersDragModifiersaltKey, ctrlKey, metaKey, shiftKey of the drop (of the pointer's last move during a dry run)
dryRunbooleantrue while the drag asks whether a target takes the items: change nothing, return false to hide it, true to show it, nothing for the default answer; false for the drop: run your commands and return true, false when nothing happened, nothing for the default transfer

Announcements name the tree of a target in another tree of the group: drag-start, drag-over and drop carry targetTree (a DragTree: its root and model), absent when the target is in the source tree. The guide is Drag and drop: between trees.

Foreign drops

foreignDrop(options) (@fragiola/tree/foreign-drop) makes the tree take foreign content: files from the desktop, links and text from another window, with or without dragAndDrop(). It is the one case the package listens to native HTML5 drag events: the adapters forward the root's dragenter, dragover, dragleave and drop (handleDragEvent) when it is installed, and the engine finds the target under the pointer as for its own drags, shows it (get("drop-target"), get("drop-indicator"), is("dragging")), expands a hovered collapsed folder and scrolls near the edges. The root is then a drop zone: the browser opens nothing dropped on it, and shows no drop where nothing is taken. A drag that leaves the root, drops, is cancelled (run("cancel-drag")) or goes a second without a dragover ends. ForeignDropOptions:

optiontypedescription
accept(drag: ForeignDrag<T>) => booleanwhether the tree takes the drag at a target (default: every type), asked once per target and drag; a refused target does not show. A disabled or non-droppable parent never takes a drop
onDrop(drop: ForeignDrop<T>) => voidthe drop: read the data and run your commands (item.add, an upload of yours)
dropEffect"copy" | "move" | "link"the cursor the browser shows over a target (default "copy")

A ForeignDrag has the drag's types (its DataTransfer.types: the data is readable only at the drop), the target to (a DropTarget) and the model; a ForeignDrop has the dataTransfer, to and the model. The package reads no file and makes no network call.

Drops outside

dropOutside(options) (@fragiola/tree/drop-outside, with dragAndDrop()) hands a pointer drag of the tree's items released outside every tree of its group (outside its own tree without a group) to DropOutsideOptions.onDrop, a (drop: DropOutside<T>) => boolean that returns true when it took the items. A DropOutside has the dragged itemIds, the model, the element under the pointer (from the root's document), the client point x, y and the modifiers of the release. While the drag is outside every tree, get("drop-outside-element") is that element. The keyboard drag has no place outside the trees. The guide is Drag and drop: foreign content.

Keys

DEFAULT_KEY_MAP (a KeyMap: each KeyAction and its keys) is the WAI-ARIA tree view's, listed on Keyboard and type-ahead. A key handler reads a KeyEventLike (key and the four modifier flags).

Announcements

AnnounceEvent is what your announce receives: drag-start (with the keyboard drag's first target), drag-over, drop, drag-cancel, drop-outside (the itemIds and the element your dropOutside() took them on), foreign-drag-over (the types and the target, null where nothing is taken), foreign-drop (the types and the target) or load-error (Tree.LiveRegion). LoadChildren<T> is the loader's type.

Attributes it reads

constantvalue
PART_ATTRIBUTE"data-tree-part": every part's element
PATH_ATTRIBUTE"data-tree-path": every item's position from the root
NO_DRAG_ATTRIBUTE"data-tree-no-drag": a subtree of a row that never starts a drag
DRAG_EXEMPTthe selector of what never starts a drag or a selection when pressed in a row: native controls, links, editable text, the toggle and data-tree-no-drag (put it on a check control of yours that is not a native control)

The adapter surface

engine.adapter (TreeEngineAdapter<T>) is what only an adapter (React, Vue, Angular) calls: an app never needs it. The adapter forwards events; the core decides.

memberdoes
modelthe model this engine draws
attachRoot(element)attaches the root element; another element replaces it
detachRoot()detaches it, cancelling a drag under way
registerItem(itemId, element)registers (or, with null, unregisters) an item's element, the one DOM focus goes to
registerContent(itemId, element)registers an item's content element: the pointer target and the row a drag hit-tests
handleKeyDown(event)a key on the tree (KeyEventInput: a KeyEventLike with target and preventDefault); true when the engine used it
handlePointerDown(itemId, event)a pointer pressed an item's content: it may become a drag
handleClick(itemId, event)a click on an item's content (PressInput: its modifiers): focus, select, and expand with expandOnClick
handleToggleClick(itemId)a press on an item's toggle: expand or collapse
handleFocus(itemId)DOM focus entered an item's element: it becomes the focused item
handleDragEvent(event)a native drag event on the root (dragenter, dragover, dragleave, drop): foreign content with foreignDrop() (adapters forward them only then)
subscribe(listener)calls listener when adapters should re-render; returns its remover
getSnapshot()the render revision: a number that changes whenever adapters should re-render