Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 | 11x 11x 11x 11x 11x 11x 480x 1490x 127x 573x 11x 198x 198x 338x 382x 382x 382x 140x 198x 198x 11x 78x 136x 136x 78x 26x 78x 5x 5x 4x 3x 3x 1x 23x 11x 78x 78x 78x 136x 136x 161x 11x 11x 11x 11x 11x 11x 67x 11x 10x 10x 9x 9x 9x 9x 11x 7x 7x 6x 6x 6x 6x 6x 6x 11x 11x 11x 20x 30x 17x 17x 11x 14x 14x 11x 11x 14x 14x 10x 10x 11x 11x 11x 8x 8x 1x 11x 11x 7x 7x 11x 42x 110x 110x 11x 14x 11x 11x 11x 11x 11x 11x 25x 24x 25x 25x 25x 25x 6x 3x 4x 3x 3x 2x 2x 3x 20x 19x 26x 19x 18x 17x 16x 15x 4x 4x 2x 2x 11x 3x 3x 1x 8x 2x 6x 5x 5x 5x 1x 18x 18x | import { findTypeaheadMatch, type CollectionItem } from '../collections/collection';
import { createControllerHost } from '../core/host';
import { createTimeoutManager } from '../core/timers';
import type { ChangeDetails, RuntimeController, RuntimeEventSource } from '../core/types';
import { createControllableValue } from '../state/controllable';
/** Causes of tree expansion, focus, and selection mutations. @public */
export type TreeChangeReason = 'programmatic' | 'pointer' | 'keyboard' | 'async-load';
/** Hierarchical Tree View node registration. @public */
export interface TreeNode extends CollectionItem {
/** Parent node ID, or `null` for a root node. */
readonly parentId?: string | null;
/** Whether the node can expose children, including asynchronously loaded children. */
readonly hasChildren?: boolean;
/** Whether child registration is currently pending. */
readonly loading?: boolean;
}
/** Immutable visible treeitem semantics. @public */
export interface TreeNodeSnapshot {
/** Stable node ID. */
readonly id: string;
/** Parent node ID. */
readonly parentId: string | null;
/** Visible hierarchy level, starting at one. */
readonly level: number;
/** Sibling count for `aria-setsize`. */
readonly setSize: number;
/** One-based sibling position for `aria-posinset`. */
readonly positionInSet: number;
/** Expansion state for branch nodes. */
readonly expanded: boolean;
/** Selection state. */
readonly selected: boolean;
/** Disabled state. */
readonly disabled: boolean;
/** Whether the branch is waiting for asynchronous children. */
readonly loading: boolean;
/** Roving tabindex value. */
readonly tabIndex: 0 | -1;
/** Treeitem role for consumer markup. */
readonly role: 'treeitem';
}
/** Immutable Tree View snapshot. @public */
export interface TreeSnapshot {
/** Keyboard-active node ID. */
readonly activeId: string | null;
/** Ordered expanded branch IDs. */
readonly expandedIds: readonly string[];
/** Ordered selected node IDs. */
readonly selectedIds: readonly string[];
/** Whether expansion state is consumer-owned. */
readonly expansionControlled: boolean;
/** Whether selection state is consumer-owned. */
readonly selectionControlled: boolean;
/** Visible preorder treeitem metadata. */
readonly visibleNodes: readonly TreeNodeSnapshot[];
/** Tree role for consumer markup. */
readonly role: 'tree';
/** Whether multiple selection is enabled. */
readonly ariaMultiselectable: boolean;
}
/** Tree lifecycle payload. @public */
export interface TreeChangeEvent {
/** Node that initiated the transition. */
readonly node: Readonly<TreeNode>;
/** Typed cause and optional native event. */
readonly details: ChangeDetails<TreeChangeReason>;
}
/** Tree expansion and selection event map. @public */
export interface TreeEvents {
/** Cancellable event emitted before a branch changes expansion. */
readonly beforeExpand: TreeChangeEvent;
/** Event emitted after expansion changes. */
readonly expand: TreeChangeEvent;
/** Cancellable event emitted before selection changes. */
readonly beforeSelect: TreeChangeEvent;
/** Event emitted after selection changes. */
readonly select: TreeChangeEvent;
/** Event emitted for accepted expansion or selection changes. */
readonly stateChange: TreeChangeEvent;
}
/** Tree View state ownership and selection options. @public */
export interface TreeOptions {
/** Enables selection of more than one node. @defaultValue `false` */
readonly multiple?: boolean;
/** Initial expanded IDs in uncontrolled mode. */
readonly defaultExpandedIds?: readonly string[];
/** Reads consumer-owned expanded IDs. */
readonly getExpandedIds?: () => readonly string[];
/** Receives accepted expansion requests. */
readonly onExpandedIdsChange?: (
ids: readonly string[],
details: ChangeDetails<TreeChangeReason>,
) => void;
/** Subscribes to external expansion changes. */
readonly subscribeExpandedIds?: (listener: () => void) => () => void;
/** Initial selected IDs in uncontrolled mode. */
readonly defaultSelectedIds?: readonly string[];
/** Reads consumer-owned selected IDs. */
readonly getSelectedIds?: () => readonly string[];
/** Receives accepted selection requests. */
readonly onSelectedIdsChange?: (
ids: readonly string[],
details: ChangeDetails<TreeChangeReason>,
) => void;
/** Subscribes to external selection changes. */
readonly subscribeSelectedIds?: (listener: () => void) => () => void;
}
/** Headless hierarchical Tree View controller. @public */
export interface TreeController
extends RuntimeController<TreeSnapshot>, RuntimeEventSource<TreeEvents> {
/** Registers or replaces a dynamic node and returns scoped cleanup. */
registerNode(node: TreeNode): () => void;
/** Expands or collapses a branch. */
toggle(id: string, details?: ChangeDetails<TreeChangeReason>): void;
/** Selects or toggles an enabled node. */
select(id: string, details?: ChangeDetails<TreeChangeReason>): void;
/** Moves the active node without changing selection. */
setActive(id: string | null): void;
/** Handles Up/Down/Left/Right, Home/End, typeahead, Enter, and Space. */
handleKeyDown(event: KeyboardEvent): void;
}
/** Creates a dynamic Tree View with preorder traversal and computed hierarchy metadata. @public */
export function createTreeView(options: TreeOptions = {}): TreeController {
const entries = new Map<string, { node: TreeNode; token: symbol; sequence: number }>();
let sequence = 0;
let activeId: string | null = null;
let typeahead = '';
const typeaheadTimer = createTimeoutManager();
const childrenOf = (parentId: string | null): readonly TreeNode[] =>
[...entries.values()]
.filter(({ node }) => (node.parentId ?? null) === parentId)
.sort((a, b) => a.sequence - b.sequence)
.map(({ node }) => node);
const flatten = (
expandedIds: readonly string[],
): readonly { node: TreeNode; level: number }[] => {
const result: { node: TreeNode; level: number }[] = [];
const visit = (
parentId: string | null,
level: number,
ancestors: ReadonlySet<string>,
): void => {
for (const node of childrenOf(parentId)) {
Iif (ancestors.has(node.id)) continue;
result.push({ node, level });
if (expandedIds.includes(node.id))
visit(node.id, level + 1, new Set([...ancestors, node.id]));
}
};
visit(null, 1, new Set());
return result;
};
const reconcileActive = (expandedIds: readonly string[]): void => {
const visible = flatten(expandedIds)
.map(({ node }) => node)
.filter((node) => !node.disabled);
if (activeId && visible.some((node) => node.id === activeId)) return;
let ancestorId = activeId ? (entries.get(activeId)?.node.parentId ?? null) : null;
while (ancestorId) {
const ancestor = entries.get(ancestorId)?.node;
if (!ancestor) break;
if (!ancestor.disabled && visible.some((node) => node.id === ancestor.id)) {
activeId = ancestor.id;
return;
}
ancestorId = ancestor.parentId ?? null;
}
activeId = visible[0]?.id ?? null;
};
const build = (
expandedIds: readonly string[],
selectedIds: readonly string[],
expansionControlled: boolean,
selectionControlled: boolean,
): TreeSnapshot => {
reconcileActive(expandedIds);
const visible = flatten(expandedIds);
return {
activeId,
expandedIds: Object.freeze([...expandedIds]),
selectedIds: Object.freeze([...selectedIds]),
expansionControlled,
selectionControlled,
visibleNodes: visible.map(({ node, level }) => {
const siblings = childrenOf(node.parentId ?? null);
return {
id: node.id,
parentId: node.parentId ?? null,
level,
setSize: siblings.length,
positionInSet: siblings.findIndex((sibling) => sibling.id === node.id) + 1,
expanded: expandedIds.includes(node.id),
selected: selectedIds.includes(node.id),
disabled: node.disabled ?? false,
loading: node.loading ?? false,
tabIndex: activeId === node.id ? 0 : -1,
role: 'treeitem',
};
}),
role: 'tree',
ariaMultiselectable: options.multiple ?? false,
};
};
const defaultExpanded = options.defaultExpandedIds ?? [];
const defaultSelected = options.defaultSelectedIds ?? [];
const initialExpanded = options.getExpandedIds?.() ?? defaultExpanded;
const initialSelected = options.getSelectedIds?.() ?? defaultSelected;
const host = createControllerHost<TreeSnapshot, TreeEvents>(
build(
initialExpanded,
initialSelected,
options.getExpandedIds !== undefined,
options.getSelectedIds !== undefined,
),
);
const sync = (): void => {
host.update(build(expanded.get(), selected.get(), expanded.controlled, selected.controlled));
};
let pendingExpansion: TreeChangeEvent | undefined;
let pendingSelection: TreeChangeEvent | undefined;
const commitExpansion = (
_expandedIds: readonly string[],
changeDetails?: ChangeDetails<TreeChangeReason>,
): void => {
sync();
if (!changeDetails || !pendingExpansion) return;
const payload = { ...pendingExpansion, details: changeDetails };
pendingExpansion = undefined;
host.emit('expand', payload);
host.emit('stateChange', payload);
};
const commitSelection = (
_selectedIds: readonly string[],
changeDetails?: ChangeDetails<TreeChangeReason>,
): void => {
sync();
if (!changeDetails || !pendingSelection) return;
activeId = pendingSelection.node.id;
const payload = { ...pendingSelection, details: changeDetails };
pendingSelection = undefined;
sync();
host.emit('select', payload);
host.emit('stateChange', payload);
};
const expanded = createControllableValue<readonly string[], TreeChangeReason>(
{
defaultValue: defaultExpanded,
...(options.getExpandedIds ? { getValue: options.getExpandedIds } : {}),
...(options.onExpandedIdsChange ? { onValueChange: options.onExpandedIdsChange } : {}),
...(options.subscribeExpandedIds ? { subscribeValue: options.subscribeExpandedIds } : {}),
},
commitExpansion,
);
const selected = createControllableValue<readonly string[], TreeChangeReason>(
{
defaultValue: defaultSelected,
...(options.getSelectedIds ? { getValue: options.getSelectedIds } : {}),
...(options.onSelectedIdsChange ? { onValueChange: options.onSelectedIdsChange } : {}),
...(options.subscribeSelectedIds ? { subscribeValue: options.subscribeSelectedIds } : {}),
},
commitSelection,
);
const setActive = (id: string | null): void => {
if (!host.alive()) return;
if (id && !visibleEnabled().some((node) => node.id === id)) return;
activeId = id;
sync();
};
const toggle = (
id: string,
changeDetails: ChangeDetails<TreeChangeReason> = { reason: 'programmatic' },
): void => {
const node = entries.get(id)?.node;
if (!node || node.disabled || (!node.hasChildren && childrenOf(id).length === 0)) return;
const current = [...expanded.get()];
const next = current.includes(id) ? current.filter((item) => item !== id) : [...current, id];
const payload = { node, details: changeDetails };
if (!host.emit('beforeExpand', payload)) return;
pendingExpansion = payload;
if (expanded.set(next, changeDetails)) commitExpansion(next, changeDetails);
};
const selectNode = (
id: string,
changeDetails: ChangeDetails<TreeChangeReason> = { reason: 'programmatic' },
): void => {
const node = entries.get(id)?.node;
if (!node || node.disabled) return;
const current = [...selected.get()];
const next = options.multiple
? current.includes(id)
? current.filter((item) => item !== id)
: [...current, id]
: [id];
const payload = { node, details: changeDetails };
if (!host.emit('beforeSelect', payload)) return;
pendingSelection = payload;
if (selected.set(next, changeDetails)) commitSelection(next, changeDetails);
};
const visibleEnabled = (): readonly TreeNode[] =>
flatten(expanded.get())
.map(({ node }) => node)
.filter((node) => !node.disabled);
const resetTypeahead = (): void => {
typeahead = '';
};
host.resources.add(resetTypeahead);
host.resources.add(typeaheadTimer.clear);
host.resources.add(() => expanded.destroy());
host.resources.add(() => selected.destroy());
host.resources.add(() => entries.clear());
return {
getSnapshot: host.getSnapshot,
subscribe: host.subscribe,
on: host.on,
off: host.off,
once: host.once,
registerNode(node) {
if (!host.alive()) return () => undefined;
const registeredSequence = entries.get(node.id)?.sequence ?? ++sequence;
const token = Symbol(node.id);
entries.set(node.id, {
node: Object.freeze({ ...node }),
token,
sequence: registeredSequence,
});
sync();
return () => {
if (entries.get(node.id)?.token !== token) return;
const visibleBefore = visibleEnabled();
const removedIndex = visibleBefore.findIndex((item) => item.id === node.id);
entries.delete(node.id);
if (activeId === node.id) {
const visibleAfter = visibleEnabled();
activeId =
visibleAfter[Math.min(Math.max(removedIndex, 0), visibleAfter.length - 1)]?.id ?? null;
}
sync();
};
},
toggle,
select: selectNode,
setActive,
handleKeyDown(event) {
if (!host.alive()) return;
const visible = visibleEnabled();
const index = visible.findIndex((node) => node.id === activeId);
let next: string | undefined;
if (event.key === 'ArrowDown') next = visible[Math.min(index + 1, visible.length - 1)]?.id;
else if (event.key === 'ArrowUp') next = visible[Math.max(index - 1, 0)]?.id;
else if (event.key === 'Home') next = visible[0]?.id;
else if (event.key === 'End') next = visible.at(-1)?.id;
else if (event.key === 'ArrowRight' && activeId) {
const node = entries.get(activeId)?.node;
if (
node &&
!expanded.get().includes(activeId) &&
(node.hasChildren || childrenOf(activeId).length)
)
toggle(activeId, { reason: 'keyboard', event });
else next = childrenOf(activeId).find((child) => !child.disabled)?.id;
} else if (event.key === 'ArrowLeft' && activeId) {
const node = entries.get(activeId)?.node;
if (expanded.get().includes(activeId)) toggle(activeId, { reason: 'keyboard', event });
else next = node?.parentId ?? undefined;
} else if ((event.key === 'Enter' || event.key === ' ') && activeId) {
selectNode(activeId, { reason: 'keyboard', event });
} else if (event.key.length === 1 && !event.altKey && !event.ctrlKey && !event.metaKey) {
typeahead += event.key;
next = findTypeaheadMatch(
visible as readonly CollectionItem[],
typeahead,
activeId ?? undefined,
);
typeaheadTimer.schedule(resetTypeahead, 500);
} else return;
event.preventDefault();
if (next) setActive(next);
},
destroy: host.destroy,
};
}
|