Skip to content

useTreeFocus

@astryxdesign/core v0.7.1 · useTreeFocus

Parameters ​

NameTypeDefaultDescription
optionsUseTreeFocusOptions—Configuration object for tree focus behavior. Required; every field inside it is optional.
options.itemSelectorstring'[role="treeitem"]'Selector for the visible treeitems within the tree, in DOM order.
options.isItemDisabled(item: HTMLElement) => boolean—Predicate for whether a treeitem is disabled and must be skipped during navigation. Defaults to reading data-tree-disabled and aria-disabled.
options.getLevel(item: HTMLElement) => number—Reads the 1-based nesting level of a treeitem. Defaults to the aria-level attribute.
options.onToggleExpand(id: string) => void—Called to expand or collapse the treeitem with the given id: ArrowRight on a collapsed parent, ArrowLeft on an expanded parent, and Enter or Space on a parent without its own action. The id is the item's data-tree-id, or its id attribute when that is absent.
options.onActivate(item: HTMLElement, id: string | undefined) => boolean | void—Called when Enter or Space activates a treeitem. Return true when handled; return false or nothing to let the hook fall back to toggling expansion.
options.onActiveChange(id: string | undefined) => void—Notified when the hook moves focus to a treeitem. Consumers use this to move a single roving tab stop when the hook does not own it, and to keep their own active state in step.
options.hasRovingTabIndexbooleanfalseWhen true, the hook owns a single roving tab stop across the visible treeitems: it stamps tabindex 0/-1, repairs the stop on mount, and moves it with navigation. An existing tabindex="0" seed is preserved on mount. Attach the returned handleFocus to keep the stop in sync after clicks.
options.typeaheadbooleantrueWhether typeahead is enabled: a printable character jumps to the next item whose text starts with the typed characters.

Returns ​

NameTypeDescription
treeRefRef<HTMLElement | null>Ref to attach to the tree container element (role="tree").
handleKeyDown(event: KeyboardEvent) => voidKey down handler to attach to the tree container.
handleFocus(event?: FocusEvent) => voidFocus handler to attach to the container's @focus. Keeps the roving tab stop in sync when hasRovingTabIndex is on, and does nothing otherwise, so it is always safe to attach.
focusFirst() => voidFocus the first enabled visible treeitem.
focusLast() => voidFocus the last enabled visible treeitem.