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

Hooks

The hooks under the primitives - the root's model and engine, an item's state and props for your own markup, a selected value of the state, and tree refs.

The primitives are built on these hooks, and your components use them to read the tree, change it, or build an item on an element of their own. Inside a Tree.Root, they read its model and engine; a tree ref reaches them from outside.

useTree

function useTree<T extends TreeTypes = AnyTypes, F extends TreeFeatures = readonly []>(): UseTreeResult<T, F>;

The model and the engine of the enclosing Tree.Root. Pass the registry, and the features when you use theirs, as the type arguments (useTree<Types, typeof features>()): a child cannot infer them through context. Outside a root, it throws.

function CollapseAll() {
    const { model } = useTree<Types>();
    return (
        <button type="button" onClick={() => model.run("tree.collapse-all", {})}>
            Collapse all
        </button>
    );
}

UseTreeResult<T>:

fieldtypedescription
modelTreeModel<T>the tree's data and its rules: model.run changes it, model.get / model.is read it (Model)
engineTreeEngine<T>the tree on screen: screen actions (engine.run("focus", { itemId })) and screen facts (engine.get("drop-target")). It is there from the first render; before the root is mounted (and on the server) an action is refused and a read is empty (Engine)

useTreeState

function useTreeState<T extends TreeTypes = AnyTypes, S = unknown, F extends TreeFeatures = readonly []>(
    selector: (state: TreeStateOf<T, F>, model: TreeModel<T, F>) => S,
    options?: UseTreeStateOptions<T, S, F>,
): S;

A value selected from the model's state, re-rendering the component only when the selection changes (Object.is by default). The selector runs once per state; keep it pure. Inside a Tree.Root it reads the root's model; pass model to read one anywhere. The state has the features' fields: given a model, the hook infers them; inside a root, pass them (useTreeState<Types, number, typeof features>(…)).

// a model with `selection()`: the selector's state has `selectedItemIds`
const count = useTreeState((state) => state.selectedItemIds.length, { model });
const status = useTreeState<Types, string | undefined>((_state, model) =>
    model.get("children-status-by", { itemId: item.id }),
);
const visible = useTreeState((_state, model) => model.get("visible-items").length, { model });

UseTreeStateOptions<T, S, F>:

fieldtypedescription
modelTreeModel<T, F>the model to read; default: the enclosing Tree.Root's (then the hook needs one)
isEqual(a: S, b: S) => booleanwhether two selections are the same, so the component does not re-render (default Object.is)

useTreeItem

function useTreeItem<T extends TreeTypes = AnyTypes>(item: ItemOf<T>): UseTreeItemResult;

An item of the enclosing Tree.Root: its state, and the props of its element (role="treeitem" with its ARIA, the roving tabindex, the data-* state, data-tree-part="item", data-tree-path, its focus handler, --tree-depth and the ref that registers it with the engine). Tree.Item is this hook on a div. The parts inside need an item context, so use it for an item whose row is your own markup:

function OutlineItem({ item }: { item: ItemOf<Types> }) {
    const { state, props } = useTreeItem(item);
    return (
        <li {...props}>
            {state.expanded ? "▾" : "▸"} {item.label}
        </li>
    );
}

UseTreeItemResult:

fieldtypedescription
stateTreeItemStatethe item's place and state (below)
propsRenderedPropsspread onto the item's element: ARIA, data-*, the roving tabindex, focus and its ref

TreeItemState, what every part of an item renders with (render, className and style functions):

fieldtypedescription
itemIdstringthe item's id
pathstringits position from the root, /0/2 (its data-tree-path)
levelnumber1 for a root item (aria-level)
posinsetnumberits 1-based position among its siblings (aria-posinset)
setsizenumberhow many siblings it has, itself included (aria-setsize)
expandedbooleanits children are shown
selectedbooleanit is part of the selection (selection())
focusedbooleanit is the focused item (model data: the roving tab stop as stored)
tabStopbooleanit is the roving tab stop: the one item with tabindex 0
checkStateCheckState: "checked" | "unchecked" | "mixed"its check (checkboxes(); unchecked without it); your check control reads it
checkedbooleanit is checked (not mixed)
indeterminatebooleanit is mixed: only some of its descendants are checked
renamingbooleanits label is being edited
loadingbooleanits children are being loaded
loadErrorbooleanthe last load of its children failed
disabledbooleanfocusable, not actionable
leafbooleanno children and no children status
draggingbooleanit is being dragged
dropTargetbooleanthe drop target of the drag under way is relative to it
dropPositionDropPosition | undefinedwhile it is the drop target: before, after or inside
attributesReadonly<Record<string, string | undefined>>the ARIA and data-* the installed features give it (selection(): aria-selected, data-selected): its element gets them all, every other part of it the data-* (model.get("item-attributes-by", { itemId }): model state, so the first render and a server's have them)

useTreeItemRename

function useTreeItemRename<T extends TreeTypes = AnyTypes>(
    item: ItemOf<T>,
    options?: UseTreeItemRenameOptions,
): UseTreeItemRenameResult;

From @fragiola/tree-react/rename (Vue: @fragiola/tree-vue/rename), with rename() in the model's features. An item's rename, wired onto an input of yours: the part hook of the label editor, with no element of its own. Render your input only while state.renaming, spread props on it and name it. It opens with the label, focused and selected. Enter commits (engine.run("commit-rename")) and Escape cancels (engine.run("cancel-rename")), and focus goes back to the item. Leaving it commits, or cancels when refused, and leaves focus where it went. A refused commit keeps it open with aria-invalid and data-invalid. See the rename guide.

function Label({ item }: { item: ItemOf<Types> }) {
    const { state, props } = useTreeItemRename(item);
    if (!state.renaming) return <span>{item.label}</span>;
    return <input {...props} aria-label={`Rename ${item.label}`} />;
}

To add a handler of your own on the input, call the hook's handler first (props.onChange?.(event)).

UseTreeItemRenameOptions:

fieldtypedescription
onRenameError(error: CommandError) => voidcalled when a commit is refused (an empty label, a middleware's veto)

UseTreeItemRenameResult:

fieldtypedescription
stateTreeItemRenameStatethe rename's state (below)
propsTreeItemRenamePropsspread onto your input: its ref (focus and selection), defaultValue, the key, blur and change handlers, aria-invalid, data-invalid

TreeItemRenameState:

fieldtypedescription
renamingbooleanthe item's label is being edited (item.start-rename, F2): render your input
invalidbooleanthe last commit was refused (an empty label, a middleware's veto)
errorCommandError | undefinedwhy the last commit was refused

useTreeRef

function useTreeRef<T extends TreeTypes = AnyTypes, F extends TreeFeatures = readonly []>(): TreeRef<T, F>;

A tree ref kept by the component, which re-renders when the Tree.Root it is given to mounts or unmounts: read tree.current in render (a toolbar next to the tree) or in handlers (in Vue, tree.value; in Angular, a template reference, below).

function Explorer() {
    const tree = useTreeRef<Types>();
    return (
        <>
            <button type="button" onClick={() => tree.current?.model.run("tree.expand-all", {})}>
                Expand all
            </button>
            <Tree.Root<Types> treeRef={tree} defaultTree={json} aria-label="Files">
                <Tree.Items<Types>>{(item) => <FileItem item={item} />}</Tree.Items>
            </Tree.Root>
        </>
    );
}

createTreeRef

function createTreeRef<T extends TreeTypes = AnyTypes, F extends TreeFeatures = readonly []>(): TreeRef<T, F>;

Creates a tree ref outside React: in a module, or in a test. It does not re-render anything when it attaches; in a component, useTreeRef does.

TreeRef<T, F> (F: the model's features, which type the engine's keys: "virtual-window" with virtualization()):

fieldtypedescription
currentTreeHandle<T, F> | nullthe root's model and engine while it is mounted, null otherwise

TreeHandle<T, F>:

fieldtypedescription
modelTreeModel<T, F>the root's model
engineTreeEngine<T, F>the root's engine

useTreeVirtualWindow

import { useTreeVirtualWindow } from "@fragiola/tree-react/virtualization";

function useTreeVirtualWindow(): VirtualWindow | null;

The rows the enclosing Tree.Root renders when its model has the virtualization feature (virtualization(options)): engine.get("virtual-window"), read again whenever it changes (a scroll, a measured row, a change of the tree). null before the root is mounted, and without the feature. It comes with the feature's entry (@fragiola/tree-react/virtualization), as VirtualItems, which renders it; read it to render the rows your own way, or to show how many are rendered. Each VirtualRow has its offset, size and the spaceBefore to keep empty above it; spaceAfter follows the last one (the engine's reference).

const window = useTreeVirtualWindow();
return <output>{window?.rows.length ?? 0} of {model.get("visible-items").length} rows rendered</output>;