@dojo-ng/tree
v0.4.0
Published
Dojo NG tree web component
Readme
@dojo-ng/tree
<dj-tree> — A hierarchical tree built from nodes.
Part of Dojo NG, a framework-agnostic web component library built on Lit. BSD-3-Clause.
The tree knows nothing about what it shows: a file tree, a mail folder list, and a MIME structure are all just nodes. Each node can carry an icon (a name registered with registerIcon or registerIcons from @dojo-ng/icon) and a count, shown as a trailing badge such as an unread count.
Install
npm install @dojo-ng/treeUsage
Import the package to register the custom element, then use the tag.
Folders with registered icons and unread counts. The tree reports selection with dj-select and opened folders with dj-expand-change.
<dj-tree id="folders" value="inbox"></dj-tree>
<script type="module">
import "@dojo-ng/tree";
import { registerIcons } from "@dojo-ng/icon";
registerIcons({
inbox: '<svg viewBox="0 0 24 24"><path d="M4 13h4l2 3h4l2-3h4M4 13V5h16v8M4 13v6h16v-6" fill="none" stroke="currentColor" stroke-width="2"/></svg>',
folder: '<svg viewBox="0 0 24 24"><path d="M3 7h6l2 2h10v10H3z" fill="none" stroke="currentColor" stroke-width="2"/></svg>',
});
const t = document.getElementById("folders");
t.expanded = ["archive"];
t.nodes = [
{ id: "inbox", label: "Inbox", icon: "inbox", count: 12 },
{ id: "archive", label: "Archive", icon: "folder", children: [
{ id: "y2025", label: "2025", icon: "folder" },
{ id: "y2024", label: "2024", icon: "folder" },
] },
{ id: "trash", label: "Trash", icon: "folder" },
];
t.addEventListener("dj-select", (e) => console.log("select", e.detail.id));
t.addEventListener("dj-expand-change", (e) => console.log("expanded", e.detail.expandedIds));
</script>Selection and expansion
- Both are controlled.
valueis the selected node id, and the tree emitsdj-select. expandedis the array of open node ids, and the tree emitsdj-expand-change.- Clicking a row selects it; clicking the chevron expands or collapses it.
- Set
expand-on-row-clickto make a click on a parent row also expand or collapse it. Use it when some rows exist only to hold others, so a click on them does something visible.
Keyboard
The tree follows the APG tree pattern. Only one row is a tab stop: the selected row if it is visible, otherwise the first visible row. The arrow keys move focus without selecting.
- Down and Up move through the visible rows.
- Right expands a closed parent, moves into an open one, and does nothing on a leaf.
- Left collapses an open parent, or moves to the parent row.
- Home and End jump to the first and last visible row.
- Enter or Space selects the focused row.
Right-to-left
- Indentation uses
margin-inline-start, so it flips in a right-to-left page, and the chevron points in the reading direction.
Dropping onto rows
- Set
canDropto make the tree a target for native HTML5 drag and drop. It is called during a drag with a row id and the drag'sdataTransfer.types(the only part of a payload the browser shows before the drop), and returns whether that row accepts it. Unset, the tree ignores drags. - The row under the pointer that accepts the drag is marked: the
row--drop-targetpart and a built-in outline. A refused row is not marked and the cursor shows the drop is not allowed. - Resting on a collapsed parent for
spring-delayms (default 800; 0 turns it off) during a drag expands it, through the same path as a chevron click, sodj-expand-changefires. It stays open after the drop. - A drop emits
dj-dropwith{ id, dataTransfer }. The tree does not select the row; the consumer reads its payload fromdataTransferand applies the change. - Dragging has no keyboard form. A consumer that offers drop must offer another way to do the same thing (WCAG 2.5.7), such as a Move command with a picker.
Tracking navigation
Set track and the tree and @dojo-ng/history follow each other, with no route table to write.
- Each node has a path: its own
pathif it sets one, otherwisebase-pathplus the ids from the root down to the node, joined with/(each id URI-encoded). A tree withbase-path="/explore"gives the nodehr>comp>paythe path/explore/hr/comp/pay. - Selecting a row (click, Enter, or Space) emits
dj-navigatewith{ path, label, trail }alongsidedj-select.trailis the nodes from the root to this one, each as{ path, label }, and ends up in the history entry, so it survives Back, Forward, and a reload in the same tab. - When the location changes, the tree selects the node whose path matches it (an exact match, else the node with the longest path that is a prefix of the location) and expands that node's ancestors, emitting
dj-expand-changefor each. This is what makes Back reselect the right row. It does not emitdj-navigate, because that would loop. It does not emitdj-selecteither. - If the location has no
trail(a deep link, or a pasted URL), the tree adds the matched node's trail to the history entry, so adj-back-buttoninupmode can name the parent. - Ctrl-click, Cmd-click, or middle-click on a row opens its path in a new tab. Rows stay
treeitems and not links, because a focusable link inside a treeitem would break the tree's roving focus. Two nodes with the same path: the first in tree order wins. trackneeds@dojo-ng/historyinstalled. Without it nothing is tracked and nothing throws.
Long trees
- Above
virtual-thresholdvisible rows (default 200) the tree is virtual: only the rows in view (plus the focused one) are in the DOM, and the tree scrolls inside--dj-tree-max-height(20rem by default while virtual). Every row carriesaria-level,aria-setsize, andaria-posinset, so assistive technology still knows its place among all of them. - Rows have one height, measured from the first row. Keyboard,
track, and Back all work on rows that are not rendered: the tree scrolls the active row into view first.
Lazy children
- A node with
hasChildren: trueand nochildrenshows a chevron. Opening it, by any route (the chevron, the keyboard, spring-open, anexpandedthe app sets, ortrack), emitsdj-load-childrenwith{ id }once, and the node shows a "Loading" row under it. - The app answers with
setChildren(id, nodes). The tree storesnodesas that node'schildrenand renders them. An empty array makes the node a leaf. Answers can arrive in any order and any time; one for a node that no longer exists is ignored (the method returns false). - On failure the app calls
setChildren(id, null, { error }). The row under the node becomes a retry row; Enter, Space, or a click on it emitsdj-load-childrenagain. - With
track, a location below an unloaded node opens that node and so asks for its children; when they arrive the tree matches again and goes one level deeper, so a deep link emits one load per level, in order, until the node is found.
Checkboxes
- Set
checkableto show a checkbox on every node. Checking is separate from selecting: Space toggles the check, Enter still selects, and clicking the box does not select the row. checkedis the array of checked ids (controlled). Toggling updates it and emitsdj-check-changewith{ id, checked, partial, pendingParents }.- Checking a parent checks every loaded node below it; unchecking clears them and the parent's own checked ancestors. A parent with loaded children shows what they show: all checked, some (
aria-checked="mixed"), or none. An id incheckedalso checks everything loaded below it. partiallists the parents showing the mixed state.pendingParentslists checked lazy nodes whose children are not loaded; the tree cannot know what is below them, so the app resolves those on the server. Children that load later under a checked parent arrive checked.
Dragging rows
- Set
draggable-rowsto make every row a drag source (native HTML5 drag and drop, so a row can land on this tree, another tree, a grid, or any page element that reads the drag). The drag carries a JSON array of node ids underdrag-type(defaultapplication/x-dojo-tree-rows) and the labels astext/plain. The preview chip shows the label, or the count for several. - A row that is not checked drags alone. With
checkable, a checked row drags every checked row, top-most only (a checked parent carries what is below it); that is the multi-row drag. - Within one tree the pointer picks where a drop lands: the top edge of a row is "before", the bottom edge "after", the middle "inside". The bottom edge of an open parent is "inside", since "after" would draw above its first child. A line marks before and after (parts
row--drop-before,row--drop-after); "inside" usesrow--drop-targetas a drop does. A row can go "inside" a row that has children, or any rowcanDropaccepts. A drop on a dragged row or anything below it is refused. - The tree emits
dj-movewith{ ids, target, position }and changes nothing; the app editsnodes. A drag from another tree or a grid is a plain drop:canDropanddj-dropas above. - Dragging has no keyboard form, as with drops. Offer a "Move…" command (WCAG 2.5.7).
Properties
↻ marks an attribute reflected to the DOM; a dash means the property is set in JavaScript only.
| Property | Attribute | Type | Default |
|---|---|---|---|
| nodes | nodes | TreeNode[] | [] |
| value | value | string | "" |
| expanded | expanded | string[] | [] |
| expandOnRowClick | expand-on-row-click ↻ | boolean | false |
| canDrop | — | (id: string, types: readonly string[]) => boolean | — |
| springDelay | spring-delay | number | 800 |
| track | track | boolean | false |
| checkable | checkable ↻ | boolean | false |
| checked | checked | string[] | [] |
| draggableRows | draggable-rows ↻ | boolean | false |
| dragType | drag-type | string | "application/x-dojo-tree-rows" |
| virtualThreshold | virtual-threshold | number | 200 |
| basePath | base-path | string | "" |
Slots
none: Content comes fromnodes.
CSS parts
row: A node's clickable line.checkbox: The box, withcheckable.loadingrow--drop-beforerow--drop-target: Added to the row a drag would drop on.chevronlabelcount
Events
dj-load-children: Detail{ id }.dj-check-change: Detail{ id, checked, partial, pendingParents }, only withcheckable.dj-expand-change: Detail{ id, expanded, expandedIds }.dj-move: Detail{ ids, target, position }, a drag within this tree.dj-drop: Detail{ id, dataTransfer }.dj-select: Detail{ id }.dj-navigate: Detail{ path, label, trail }, only withtrack.
Methods
setChildren(id: string, children: TreeNode[] | null, options: { error?: unknown }): boolean: Answer adj-load-children: storechildrenon the nodeidand render them. For a failed load passnulland{ error }; the node then shows a retry row. Returns false when no node has that id (the tree was replaced while the load ran), and then does nothing.
CSS custom properties
--dj-tree-indent: Indentation added per nesting level. Default1.1rem.--dj-tree-max-height: Height the tree scrolls at while virtual. Default20rem.--dj-tree-count-color: Color of the trailing count badge. Defaultvar(--dj-color-text-muted).
Examples
Large lazy tree with checkboxes and dragging
A tree windows its rows above 200, so 50,000 nodes stay cheap. Groups load when opened (dj-load-children, answered with setChildren), checkable adds tri-state checkboxes, and draggable-rows lets rows be moved: the tree reports a drop in the same tree as dj-move and the app edits nodes.
<dj-tree id="big" checkable draggable-rows></dj-tree>
<script type="module">
import "@dojo-ng/tree";
const t = document.getElementById("big");
t.nodes = Array.from({ length: 50 }, (_, g) => ({ id: `g${g}`, label: `Group ${g}`, hasChildren: true }));
t.addEventListener("dj-load-children", async (e) => {
try {
const rows = await fetchChildren(e.detail.id); // your server call
t.setChildren(e.detail.id, rows);
} catch (error) {
t.setChildren(e.detail.id, null, { error }); // shows a retry row
}
});
t.addEventListener("dj-check-change", (e) => {
// e.detail.pendingParents: checked groups whose children are not loaded; resolve them on the server
console.log(e.detail.checked, e.detail.partial, e.detail.pendingParents);
});
t.addEventListener("dj-move", (e) => {
const { ids, target, position } = e.detail; // "before" | "after" | "inside"
t.nodes = applyMove(t.nodes, ids, target, position); // your update of the data
});
</script>Theming
Styled with Dojo NG --dj-* design tokens and exposes ::part() hooks for targeted overrides.
Accessibility and i18n
Follows the project's WCAG 2.2 AA and localization conventions.
More
Live, interactive examples are at play.dojo-ng.com. For the full API reference, theming, accessibility, and localization guides, see the Dojo NG documentation.
