Tree Rows Implementation in Vanilla-Grid
A <vn-grid> can show its rows as a tree: each row names its parent row's
key, and the grid shows the rows depth-first, indented in a tree column, with
an expand/collapse toggle on every parent row. Collapsing a row hides its whole
subtree.
flat rows (data) tree mode, "Phase 2" collapsed
id parentId name v Phase 1
1 - Phase 1 Design
2 1 Design v Build
3 1 Build Backend
4 3 Backend Frontend
5 3 Frontend > Phase 2
6 - Phase 2
7 6 Review
Tree mode reuses grouping's projection contract (renderEntries and
_renderEntryDataIndex, see Row Grouping
§ 4 and § 9), but it is a feature of its own: features/tree.feature.js, a
standalone VanillaGridTreeFeature class constructed next to the grouping
feature. Grouping and tree mode are mutually exclusive.
The file-system-js sample (its README)
shows tree mode on a generated file system of 1,000 to 1,000,000 folders and
files.
1. Options and API
grid = el.initializeGrid({
tree: {
parentField: 'parentId', // or parentKeyGetter: (row) => key
column: 'name', // default: the first visible data column
expandMode: 'collapsed', // default 'expanded'
toggleTabStop: false, // default true
},
});
tree.parentFieldnames the row field holding the parent row's key;null,undefinedor''makes the row a root.tree.parentKeyGettercomputes it instead. Either one turns tree mode on.- A parent key names a row by the grid's own row key
(Row Key Management):
rowKeyGetter, the key column, thenrowKeyField. tree.columnis the tree column's key. Without it, the tree column is the first visible non-internal data column, by the group caption toggle's rule, so hiding the tree column moves the tree to the next eligible column.tree.expandModeis the state a parent starts in, untilexpandAllRows()orcollapseAllRows()sets a baseline that replaces it.tree.toggleTabStop(defaulttrue) keeps the toggles in the tab order.falsegives themtabindex="-1": they stay clickable and keep their ARIA, and the host provides the keyboard path (§ 10).- Attributes:
tree-parent-fieldandtree-columnon<vn-grid>(Web Component § 3). An option wins over the attribute. Changing or removing either attribute afterinitializeGrid()turns tree mode on, off, or onto another column.
Methods (on VanillaGrid and <vn-grid>):
| Method | Returns |
|---|---|
isTreeMode() |
Whether the grid shows a tree |
expandRow(key, { descendants }), collapseRow(key, { descendants }) |
false when the key is unknown or names a leaf; true when the state changed or already held. descendants: 'expanded' | 'collapsed' also sets every row below |
toggleRow(key) |
Same contract |
expandAllRows(), collapseAllRows() |
Nothing; rows that appear later follow the new baseline |
isRowExpanded(key) |
false for a leaf |
isRowVisible(key) |
In the query and every ancestor expanded |
getNearestVisibleAncestorKey(key) |
The key itself when visible, else its highest collapsed ancestor; undefined when unknown |
revealRow(key) |
Expands every collapsed ancestor; false when unknown |
getTreeRowInfo(key) |
{ depth, parentKey, childCount, expanded, isContext, position, subtreeSize }, or undefined |
getTreeRowPositions(keys) |
An Int32Array of each key's position, -1 for a key the tree doesn't hold (unknown, or left out by a filter or search); undefined outside tree mode |
position is the row's index in the depth-first displayRows, visible or not,
and subtreeSize counts the row and everything below it, so the subtree is
[position, position + subtreeSize). Both are stable across expand and
collapse and change only when the tree is rebuilt (§ 6).
Outside tree mode isRowVisible(), getNearestVisibleAncestorKey() and
revealRow() answer from the flat projection (in the query or not), and
getTreeRowInfo() and getTreeRowPositions() return undefined.
2. Availability
A tree needs every row, so tree mode is not offered, with one warning, when
the grid loads progressively (infiniteScroll) or the DataManager caps the
row count (getMaxRows()). These are the two conditions
getGroupingRefusal() checks, but the tree feature checks them itself
(getRefusal()): a server grouping strategy could let grouping through on
such grids, and a tree still could not be shown there.
Mutual exclusion with grouping is enforced where each side is requested:
- Tree options while grouping is applied (or a
grouping.columnsdeclaration at construction) are dropped with one warning. - Grouping while tree mode is on is refused with the reason
'tree-mode':getGroupingRefusal()returns it first, so every grouping API answers it and the header menu renders no grouping items (Row Grouping § 10).
The tree's own refusal never consults grouping: grouping asks whether tree mode is on while it resolves its own request, with its new state already assigned, and the two answers would depend on each other.
3. Building the tree
Every full rebuild of displayRows (a load, a sort, a filter or search
result, a column change that re-orders, an appendRows() a host makes, which
re-derives the flat order rather than pushing onto the tree order) ends in
grouping's "no projection" alias, because grouping is never applied in tree mode. The grid routes that
alias to the tree feature (_syncTreeProjection()), which rebuilds its index
when displayRows holds new rows and otherwise only re-commits its
projection. displayRows is then the array the last build wrote, which is how
the feature tells the two apart.
The build works on typed arrays indexed by a row's position in the incoming, already sorted, flat array:
- Keys. Every row's key and parent key, into one key-to-index
Map. - Cycle cut. A parent chain that closes on itself is cut at the row whose parent closes it, which becomes a root. Every row is walked once overall.
- Children. Bucketed by parent in incoming order, in CSR form
(
childStart,childList). - Depth-first order. An iterative walk from the roots (no recursion, so
any depth) writes the tree-ordered
displayRowsplusdepth,parentPos,subtreeEnd,childCountandsiblingIndexper position. The subtree of the row at positionpis[p, subtreeEnd[p]). - Projection. A walk that jumps from a collapsed row at
pstraight tosubtreeEnd[p], writingrenderEntries, the data-index map (anInt32Array) andrenderIndexOf(a position's render index,-1when hidden).
R1 in tree mode. With nothing collapsed the projection is displayRows
itself: the alias is kept, the map stays null and renderIndexOf is not
materialised, so an untouched tree renders at flat-grid cost.
Bad data, warned once per build with a count and the first key:
- an unknown parent key, or a row that is its own parent: the row is a root;
- a parent cycle: cut as above;
- duplicate keys: the first row with a key wins every lookup by that key (as
a parent, and for
setSelectedKeys()); the warning counts the rows that repeat a key. The selection feature builds no key map in tree mode, so this is the only duplicate-key warning a tree grid logs (Selection § 4).
Collapse state is a Set of keys toggled away from the effective default
(the baseline when set, else expandMode), as grouping keeps
_collapsedGroupKeys. A key that leaves the data leaves the set at the next
build (not while a filter is active: a filtered-out row is still in the data).
It is not persisted.
Behind the shimmer. In tree mode setRows() always runs the sorting
feature's reorder pipeline (_reapplyClientOrdering()), even with no sort:
the build is the ordering. Until it lands the projection is flat
(commitFlat()), and above sortShimmerThreshold the build runs behind the
shimmer, exactly where a sort's ordering would.
4. Sorting
Siblings are sorted; children stay under their parent (Sorting):
- The grid's existing pipeline sorts every row (comparator, Worker, shimmer), unchanged.
- The build buckets children in that sorted order, so every sibling list comes out sorted.
- The depth-first walk lays them out.
Cost: the sort plus O(n). With no sort, siblings keep the order the rows arrived in.
5. Filtering, search and context rows
A match's ancestors are always kept, so a match is shown in context, never as an orphan.
StaticDataManager, givensetTreeOptions({ keyOf, parentKeyOf })(<vn-grid>calls it in tree mode, withnulloutside it), adds every match's ancestors after its filter pipeline, so it covers the in-thread and the Worker paths alike. The walk is O(matches x depth) over a key index built once per dataset version, and the result keeps the original row order (DataManager § 5).- Context rows. The ancestors added only for context are kept in a
WeakSet, read throughisTreeContextRow(row). They get the classvn-grid-row-tree-context(dimmed by--vn-grid-tree-context-fg),isContext: trueingetTreeRowInfo(), and thetreeContextRowmessage appended to their accessible name. - Everything expanded while filtered. While a column filter or a search term is active, a separate collapse session with an expanded baseline replaces the user's, so every match is visible. The user's state is put aside and comes back when the filter and the search clear.
- Other managers (OData, GraphQL with every row loaded) filter on the server and return no ancestors: a match whose parent did not come back shows as a root (§ 3).
6. Events
All bubble and are composed, on the grid container, like every grid event
(grid-events.js):
| Event | Detail | When |
|---|---|---|
vn-grid-tree-row-expanded / vn-grid-tree-row-collapsed |
{ key, all, descendants } |
One per gesture: a toggle, expandRow() / collapseRow() / toggleRow(), revealRow() (keyed by the revealed row), or expandAllRows() / collapseAllRows() (key: null, all: true). None for a call that changed nothing |
vn-grid-tree-rebuilt |
{ reason, rowCount } |
After every rebuild of the depth-first order, once it has rendered |
vn-grid-tree-mode-changed |
{ treeMode } |
Tree mode turned on or off: options or attributes set or removed, or a change of availability noticed by the next load |
vn-grid-tree-rebuilt carries why the order changed:
'rows':setRows(), a reload, or tree mode turning on;'sort': a sort change, including clearing it;'filter': a load whose filter model or search term changed.
A load notes its reason before its ordering runs, and a sort's write of
displayRows notes 'sort' only when no reason is pending, so a load whose
rows the pipeline sorts still reports 'rows'. The event waits for a
microtask: every build happens inside an ordering whose finish renders in the
same synchronous run, so the order it reports is already on screen. A rebuild
that another one overtook never ran its build, so it fires nothing of its own.
Expand, collapse, expand-all, collapse-all and revealRow() never fire it:
they change what is shown, not the order. A follower that indexes rows by
position (the Gantt's link index) rebuilds its index on this event.
vn-grid-tree-mode-changed fires before the first vn-grid-tree-rebuilt
of a tree; turning tree mode off rebuilds displayRows flat through the
normal pipeline and fires no rebuild event. A tree option change that keeps
tree mode on fires nothing of its own. <vn-grid-toolbar> recomputes its
isTreeMode state on it (§ 10).
7. Toggles and the projection version
A toggle splices one contiguous block, as a group toggle does:
- Collapse removes the visible entries after row
pup to the first one whose position is at or pastsubtreeEnd[p], found by a binary search of the (ascending) data-index map. - Expand projects
[p + 1, subtreeEnd[p]), skipping collapsed descendants, and inserts the block afterp. - The new arrays are built with
slice/concatandInt32Array#set,renderIndexOfis refreshed for the moved part, and the grid re-renders in place with the scrollbar thumb re-sized (_rerenderTreeInPlace()). - A toggle of a hidden row (under a collapsed ancestor) changes the state only. An expand that leaves nothing hidden goes back to the R1 alias.
descendantssets every descendant's state (O(subtree)), then re-projects once; expand-all / collapse-all set the baseline, clear the set and re-project: O(n), with no key resolution.
tests/node/tree-feature.test.js checks that a splice leaves exactly the
projection a fresh one would, after every step of random toggle sequences, in
both expand modes and under both baselines.
The projection version. The pool's change detection and the viewport
API's key map read one grid helper, _getProjectionVersion(): grouping's
_projectionVersion plus the tree feature's own counter. Each counter only
grows, so the sum moves whenever either projection changes. Without it a
collapse would leave every pool row below the toggle with the same entry index
and the same version, still showing its old row
(Row Virtualization
§ 1.18, Row Grouping § 8).
8. Lookups for followers
O(1) or O(depth) once built, so a follower can call them per drawn row:
| Method | How |
|---|---|
getTreeRowInfo(key) |
key to position, then the per-position arrays |
getTreeRowPositions(keys) |
key to position for each key, in one call: O(keys) |
isRowVisible(key) |
renderIndexOf[position] !== -1 |
getNearestVisibleAncestorKey(key) |
walk parentPos up, keep the highest collapsed ancestor |
revealRow(key) |
expand every collapsed ancestor, then one projection |
setSelectedKeys(keys) |
key to position, then displayRows[position], for each key, instead of the selection feature's key map, which costs a pass over every row on the first call after each load (Selection § 4) |
getRenderIndexByKey(key) (the viewport API) |
in tree mode, key to position (stable across toggles), then renderIndexOf[position], instead of the viewport API's lazy map, which every toggle would invalidate |
A follower that indexes many rows at once (the Gantt's link index, on every
vn-grid-tree-rebuilt) calls getTreeRowPositions() once instead of
getTreeRowInfo() per key. Each getTreeRowInfo() call goes through the
element's and the grid's forwarders, which an obfuscated build keeps on the
heavy profile (§ 12), and builds an object the follower drops.
scrollToRow(key) keeps returning false for a hidden row; a follower calls
revealRow(key) first. getRenderEntry() reports every tree entry as
'row'. The scroll indicator counts a collapsed row's whole subtree as passed
(rowsThroughPosition()), as it does for a collapsed group caption.
9. Rendering
<td class="vn-grid-tree-cell" style="--vn-grid-tree-depth: N">
<span class="vn-grid-tree-inner"> the toggle's containing block
<button class="vn-grid-tree-toggle" aria-expanded="..." aria-label="..."> parents, out of flow
<span class="vn-grid-tree-a11y">level 2, 1 of 3</span> leaves, visually hidden
<span class="vn-grid-tree-content"> the value, or renderCell's output </span>
- One hoisted check. The render pass resolves the tree column once per
pass (
_resolveTreeColumnIndex()), or-1outside tree mode, and every tree branch keys off it. A cell that was a tree cell under another column order or mode is cleared before it renders (_clearTreeCell()). renderCellon the tree column receives the content span as itscell, so the toggle and the indent survive whatever it writes. Every other column is unchanged.- Truncation. The content span is a block box (
overflow: hidden,text-overflow: ellipsis,nowrap), so its width is what the indent leaves of the cell: the value ellipsizes at the cell's edge at every depth, and arenderCellbox bounded bymax-width: 100%(an icon beside the text, say) resolves against that space, not the whole cell. The truncation tooltip measures the span too, or avn-grid-truncate-ellipsiselement inside it, so it counts the indent and leaves out a leaf's visually hidden level text (Performance § 2.5). The span clips vertically too, and the cell'sline-height: 1.1leaves a font's glyph box (ascent plus descent) taller than the line, so a span as tall as its line cut the descenders of g, p and y. A0.25emblock padding moves its clip edge past the glyph box and an equal negative block margin cancels it, so the row height and the text's position don't change. ArenderCelltext element inside the span that carriesvn-grid-truncate-ellipsisgets the same from the class (Row Virtualization § 1.14), as thefile-system-jssample's name text does. - A narrow column caps the indent. The indent stops growing where it
would leave the content narrower than
--vn-grid-tree-content-min-width(4em): every deeper row lines up at the deepest whole level that still leaves that much, its toggle with it. So a deep row in a narrow column still shows its toggle and the start of its value ("Fol…"), where an indent wider than the cell left it empty and its toggle cut off or gone. The rows past the cap look like siblings of the capped level: the toggle's accessible name and a leaf's level text still give screen readers the real level, and the truncation tooltip gives the whole value. Pure CSS: amin()of the depth's indent and around(down, ...)to whole levels of100%less the toggle's space and the minimum, so it follows every width change (a drag, auto-fit, stretch-to-fit, a theme) with nothing to recompute. The100%is the inner box's width for the content span (in flow in it) and the toggle (positioned in it) alike; positioned in the cell, the toggle would resolve it against the cell's padding box and drift from the content by the theme's padding.tests/playwright/tree-cell-truncation.spec.jspins the truncation, the tooltip and the cap, in Chromium and (thefirefox-layoutproject) Firefox. - Row height. A tree row, parent or leaf, is exactly
rowHeighttall, as a caption is (D2'sindex * rowHeightplacement). The toggle copies the caption toggle's mechanics: absolutely positioned at its static inline position, plus the row's indent, and centred vertically. The content span startsdepth * --vn-grid-tree-indent + --vn-grid-tree-toggle-sizein on every row (up to the cap above), so parents and leaves line up with no spacer element.tests/playwright/tree-rows-row-height.spec.jspins it in every built-in theme, in Chromium and (thefirefox-layoutproject) Firefox. - The toggle is reused in place, so focus survives a toggle.
- Freezing. The inner box, not the cell, is the toggle's containing block,
so a frozen cell stays
sticky. - RTL. The indent is an inline-start margin, and the collapsed glyph mirrors, as the caption glyph does.
- Forced colors. The toggle paints
ButtonText. - Auto-fit measures a tree cell by its content span, plus that row's
whole indent: its depth times one indent step, plus the toggle space, both
measured by probes in a tree cell (
vn-grid-tree-step-probe,vn-grid-tree-lead-probe). The span's own margin would be the capped one, short of what the row needs. So the widest row's depth is counted (Column Resizing).
Tokens (every one optional, with a neutral fallback; Themes § 4):
| Token | Falls back to |
|---|---|
--vn-grid-tree-indent |
16px |
--vn-grid-tree-toggle-size |
1.25em (the space before the content on every row) |
--vn-grid-tree-content-min-width |
4em (the narrowest the indent leaves the content; deeper rows stop indenting there) |
--vn-grid-tree-toggle-icon-expanded / -collapsed |
--vn-grid-group-toggle-icon-expanded / -collapsed, then the caption's chevrons |
--vn-grid-tree-toggle-icon-size / -color |
--vn-grid-group-toggle-icon-size / -color |
--vn-grid-tree-context-fg |
the text colour at 55% (color-mix()) |
10. Keyboard, ARIA and the toolbar
The group caption toggle's contract, unchanged (Row Grouping § 12, Keyboard Navigation):
- The toggles are Tab stops, one per rendered parent row, unless
tree.toggleTabStopisfalse; the grid has no other keyboard path to expand and collapse, so a host that turns it off gives one.<vn-gantt>does, for its task grid: ArrowRight / ArrowLeft on the selected task expand, collapse and move to a child or parent (Task Moving § 4). - Space and Enter activate the focused toggle natively through the delegated
viewport click:
shouldHandleKeyboardEventleaves Space to a focused button, and Enter is never a grid key. The arrow, Page, Home and End keys on a focused toggle go to the grid and scroll by its row step (Keyboard Navigation § 4). - Shift+Enter, handled on keydown (Firefox drops modifiers from a keyboard
activation's click), and Shift-click toggle the row with
descendantsset to its new state. Parents that have parent children carryaria-keyshortcuts="Shift+Enter". handleClickreturns before its viewportfocus()for a tree toggle, so a keyboard toggle keeps focus; a press on a toggle never counts toward a row double-click.
ARIA. The native table stays: no treegrid role, which would promise a
cell focus model the grid does not have. The toggle carries aria-expanded
and an aria-label from the treeToggleLabel message
('{label}, level {level}, {position} of {size}', for example "Design, level
2, 1 of 3"). A leaf has no toggle, so the same level and position go before its
content as visually hidden text, without the label its content already shows
(Localization).
Toolbar. <vn-grid-toolbar> offers expandAllRows and collapseAllRows
as standard commands, and an isTreeMode state predicate to show them only in
tree mode (show-when="isTreeMode"), recomputed on
vn-grid-tree-mode-changed
(Toolbar implementation).
11. Behaviour with other features
| Feature | Behaviour |
|---|---|
| Grouping | Mutually exclusive (§ 2) |
| Scaled mode (1M rows) | Unchanged: the tree only changes renderEntries |
| Server-side DataManagers | Offered when every row loads; server filters show orphans as roots (§ 5) |
| Selection | Rows are data rows; select-all covers collapsed rows too (Selection) |
| Row numbers | The position in displayRows, so collapsed rows are counted |
| Excel export | Flat, in tree order: every scope reads displayRows, collapsed and context rows included, with no indent or outline (Export to Excel) |
| Column hide, reorder, freeze | The tree follows its column; hiding it moves the tree to the next eligible column |
12. Performance
| Work | Runs | Cost at 1M rows |
|---|---|---|
| Keys, cycle cut, children, depth-first walk | per full rebuild | O(n) over typed arrays, one key resolution per row; behind the shimmer above sortShimmerThreshold. About 1.1 s in Node for the build plus two toggles plus 1M getTreeRowInfo() calls (tree-feature.test.js) |
| Sort | per sort | the existing sort, plus the O(n) build |
| Projection | per full rebuild, expand-all, collapse-all | O(visible rows) |
| One toggle | per click or key | O(block) plus O(n) pointer copies; 3 to 26 ms in file-system-js at 1M |
| Filter ancestors | per filter or search | O(matches x depth), plus one O(n) key index per dataset version |
| Lookups | per call | O(1) or O(depth) |
| Render pass | per frame | one hoisted check outside tree mode; the tree cell on repopulated rows inside it |
features/tree.feature.js runs per-row passes, so it is on build.js's
BUNDLE_FAST_PATH: on the heavy obfuscator profile a 1M-row build would
hang. What the build calls per row is fast-profile code too: its key hook is
the selection feature's resolveRowKey(), bound, and a parentKeyGetter
the Gantt passes comes from its task model (parentKeyGetterOf()). The
key and parent-key hooks the grid hands a StaticDataManager's tree index
are the same bound feature methods. An arrow in vanilla-grid.js or the
element would instead go through the obfuscator's string decoder on every
row: 3.3x slower for a 1M-row build
(Performance § 7.3). The index holds about six Int32Arrays plus a key Map per row.