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>:
| field | type | description |
|---|---|---|
model | TreeModel<T> | the tree's data and its rules: model.run changes it, model.get / model.is read it (Model) |
engine | TreeEngine<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>:
| field | type | description |
|---|---|---|
model | TreeModel<T, F> | the model to read; default: the enclosing Tree.Root's (then the hook needs one) |
isEqual | (a: S, b: S) => boolean | whether 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:
| field | type | description |
|---|---|---|
state | TreeItemState | the item's place and state (below) |
props | RenderedProps | spread 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):
| field | type | description |
|---|---|---|
itemId | string | the item's id |
path | string | its position from the root, /0/2 (its data-tree-path) |
level | number | 1 for a root item (aria-level) |
posinset | number | its 1-based position among its siblings (aria-posinset) |
setsize | number | how many siblings it has, itself included (aria-setsize) |
expanded | boolean | its children are shown |
selected | boolean | it is part of the selection (selection()) |
focused | boolean | it is the focused item (model data: the roving tab stop as stored) |
tabStop | boolean | it is the roving tab stop: the one item with tabindex 0 |
checkState | CheckState: "checked" | "unchecked" | "mixed" | its check (checkboxes(); unchecked without it); your check control reads it |
checked | boolean | it is checked (not mixed) |
indeterminate | boolean | it is mixed: only some of its descendants are checked |
renaming | boolean | its label is being edited |
loading | boolean | its children are being loaded |
loadError | boolean | the last load of its children failed |
disabled | boolean | focusable, not actionable |
leaf | boolean | no children and no children status |
dragging | boolean | it is being dragged |
dropTarget | boolean | the drop target of the drag under way is relative to it |
dropPosition | DropPosition | undefined | while it is the drop target: before, after or inside |
attributes | Readonly<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:
| field | type | description |
|---|---|---|
onRenameError | (error: CommandError) => void | called when a commit is refused (an empty label, a middleware's veto) |
UseTreeItemRenameResult:
| field | type | description |
|---|---|---|
state | TreeItemRenameState | the rename's state (below) |
props | TreeItemRenameProps | spread onto your input: its ref (focus and selection), defaultValue, the key, blur and change handlers, aria-invalid, data-invalid |
TreeItemRenameState:
| field | type | description |
|---|---|---|
renaming | boolean | the item's label is being edited (item.start-rename, F2): render your input |
invalid | boolean | the last commit was refused (an empty label, a middleware's veto) |
error | CommandError | undefined | why 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()):
| field | type | description |
|---|---|---|
current | TreeHandle<T, F> | null | the root's model and engine while it is mounted, null otherwise |
TreeHandle<T, F>:
| field | type | description |
|---|---|---|
model | TreeModel<T, F> | the root's model |
engine | TreeEngine<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>;Tree.LiveRegion
The tree's polite live region. It shows the text your announce function returns for each drag step or failed load, and writes none of its own.
Vue primitives
The same primitives and hooks for Vue 3.5, from @fragiola/tree-vue, and how each React prop maps onto Vue props, slots, events and attributes.