Documentation
API: primitives (@fragiola/tree-react, @fragiola/tree-vue, @fragiola/tree-angular)

Tree.Root

The tree element (role tree) - it owns the engine of its model, forwards the keys to it and re-renders the tree when the model changes.

Tree.Root is the role="tree" element of the WAI-ARIA APG tree view pattern: one tab stop for the whole tree, the keys handled on it, and the ARIA of the installed features (aria-multiselectable with selection() in multiple mode). It takes a model, or a defaultTree it creates one from, creates the engine for it once mounted, and renders only its children. No provider is needed above it.

import { createTreeModel, Tree } from "@fragiola/tree-react";
import { useState } from "react";

export function Files() {
    const [model] = useState(() => createTreeModel<Types>(json));
    return (
        <Tree.Root<Types> model={model} aria-label="Project files" className="tree">
            <Tree.Items<Types>>{(item) => <FileItem item={item} />}</Tree.Items>
            <Tree.LiveRegion className="visually-hidden" />
        </Tree.Root>
    );
}

Root is generic over the model's registry (RootProps<T>): model: TreeModel<Types> types treeRef, and loadChildren with asyncChildren(). The parts that hand you items through a function (Tree.Items, Tree.Group) cannot infer it through context: pass it as their type argument (in Vue, take the parts from typedTree<Types>(): Vue primitives; in Angular, give the model to [treeItems]: Angular primitives).

The tree's policies live on the model, not on the root: a middleware (model.use) sees, rewrites or vetoes every command the tree runs, and a listener (model.subscribe) every change. See The command bus.

Props

RootProps<T, F> is RootBaseProps<T, F> (every tree's props, below, which extend the common primitive props on a div) and the props the features F ship (Feature props). F comes from the model (TreeModel<T, F>) or the features prop; with an explicit registry, pass both: <Tree.Root<Types, typeof features>>.

proptypedefaultdescription
modelTreeModel<T, F>nonethe tree model. Its middleware sees every command the tree runs, and its listeners every change. A new model identity creates a new engine. Give either model or defaultTree
defaultTreeTreeJson<T>an empty treethe document of a model the root creates and keeps, read once at mount
featuresF (TreeFeatures)nonethe opt-in features of the model the root creates from defaultTree ([selection()], from @fragiola/tree-react/selection), read once at mount: a later change is ignored, with a warning. A model has its own (Features)
expandedItemIdsreadonly string[]uncontrolledcontrolled expansion (Controlled state)
onExpandedItemIdsChange(itemIds: string[]) => voidnonecalled with the expanded items after every command that changes them
announce(event: AnnounceEvent) => string | undefinednonethe live region's text for a drag step or a failed load; no text is built in
keyMapPartial<KeyMap>DEFAULT_KEY_MAPkey bindings, over the defaults (Keyboard and type-ahead)
expandOnClickbooleanfalsea click on a parent's row also expands or collapses it
treeRefTreeRef<T, F>noneaccess to the model and the engine from outside the root (useTreeRef, createTreeRef)
childrenReactNodenonethe tree: Tree.Items, Tree.LiveRegion, a feature's parts (DropIndicator, VirtualItems), and anything else

The root names nothing: give it aria-label or aria-labelledby (Accessible names).

Feature props

A feature ships its root props: a controlled list and its change callback, or the loader of asyncChildren(). They compile only when the feature is installed, and the root maps a list as it maps expandedItemIds. Given without the feature, a prop is ignored with a warning. Space toggles the focused item's check with checkboxes() (checkboxes({ space })), the type-ahead's delay is typeAhead({ timeout }), and the drags are dragAndDrop({ dragThreshold, autoExpandDelay, indentation, indicatorInset, autoScroll }), dragGroup({ name, transfer }), foreignDrop({ accept, onDrop }) and dropOutside({ onDrop }): options of the features, not props (Drag and drop).

propfeaturedescription
selectedItemIdsselection()controlled selection: the selected items (Controlled state)
onSelectedItemIdsChangeselection()called with the selection after every command that changes it
checkedItemIdscheckboxes()controlled checks: the checked items (Checkboxes)
onCheckedItemIdsChangecheckboxes()called with the checked items after every command that changes them
loadChildrenasyncChildren()your loader of the children of an item with a childrenStatus: LoadChildren<T>, (item, { signal }) => Promise<readonly TreeItemJson<T>[]> (Async loading)

State

RootState, passed to render, className and style functions.

fieldtypedescription
multiselectablebooleanthe selection mode is multiple (aria-multiselectable, with selection())
draggingbooleana drag is under way (pointer or keyboard)
keyboardDraggingbooleana keyboard drag is under way
draggingFromOtherTreebooleana drag from another tree of the drag group is under way (dragGroup())
emptybooleanthe tree has no item

Attributes

attributewhen
role="tree"always
aria-multiselectableselection() in multiple mode (the features' ARIA and data-* are model state: model.get("root-attributes"), a server render has them)
data-tree-part="root"always
data-dragginga drag is under way (dragAndDrop()), or foreign content (foreignDrop()) is dragged over the tree
data-keyboard-dragginga keyboard drag is under way
data-dragging-from-other-treea drag from another tree of the drag group is under way
data-emptythe tree has no item

Structural style: position: relative, the containing block DropIndicator is positioned in.

Behaviour

  • Creates one engine per model identity once mounted (React's StrictMode remount creates a new one; a load the first engine had started starts again), and destroys it on unmount.
  • Forwards keydown to the engine (onKeyDown runs after it; a key it used has its default prevented).
  • Re-renders the tree on every commit and on every drag step or announcement.
  • Runs the commands that bring the model to the controlled props, before paint.
  • Attaches treeRef while mounted.

Common props

Every primitive except Tree.Items accepts these on top of its own props (PrimitiveProps<State> and its element's attributes: DivPrimitiveProps<State>, SpanPrimitiveProps<State> for Tree.Toggle):

proptypedescription
renderRenderProp<State>: ReactElement | ((props: RenderedProps, state: State) => ReactElement)replaces the rendered element (never asChild)
classNamestring | ((state: State) => string | undefined)a class name, or a function of the primitive's state returning one
styleCSSProperties | ((state: State) => CSSProperties | undefined)a style, or a function of the primitive's state returning one. Structural keys the primitive sets always win
refRef<HTMLElement>merged with the primitive's own ref
any attribute of the elementforwarded to the element; event handlers run after the primitive's own

RenderedProps<E extends Element = HTMLElement> is what a render function receives: the element's attributes, the primitive's data-* attributes and a callback ref. Spread them onto the element it returns; they fit any element's ref with no cast:

<Tree.Item item={item} render={(props, state) => <li {...props} data-kind={item.kind} />}>
    <Tree.ItemContent>{item.label}</Tree.ItemContent>
</Tree.Item>

See The primitive contract.