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
    },
});

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:

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:

  1. Keys. Every row's key and parent key, into one key-to-index Map.
  2. 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.
  3. Children. Bucketed by parent in incoming order, in CSR form (childStart, childList).
  4. Depth-first order. An iterative walk from the roots (no recursion, so any depth) writes the tree-ordered displayRows plus depth, parentPos, subtreeEnd, childCount and siblingIndex per position. The subtree of the row at position p is [p, subtreeEnd[p]).
  5. Projection. A walk that jumps from a collapsed row at p straight to subtreeEnd[p], writing renderEntries, the data-index map (an Int32Array) and renderIndexOf (a position's render index, -1 when 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:

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):

  1. The grid's existing pipeline sorts every row (comparator, Worker, shimmer), unchanged.
  2. The build buckets children in that sorted order, so every sibling list comes out sorted.
  3. 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.

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:

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:

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>

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):

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.