Row Selection Implementation in Vanilla-Grid
This document explains how row selection is implemented in Vanilla-Grid, including key resolution, mode semantics, select-all as a predicate over the query, event payloads, and web component forwarding.
1. Feature Scope
Row selection supports:
- Three modes:
noselection,single,multiple - Programmatic selection APIs
- Header checkbox for select-all in multiple mode
- Stable key-based selection across sort/append/reload cycles
- Select-all as a predicate: every row matching the query, loaded or not, minus the rows unticked since (§ 9)
- A serialisable selection descriptor for backend bulk commands, and materialising every selected row (§ 5)
- Selection-change event dispatch
Relevant options:
selection.mode(defaultnoselection)selection.rowKeyField(defaultnull— no implicit field name assumed)selection.rowKeyGetter(optional function)selection.showCheckboxes(defaulttrue)
See also: Row Key Management for detailed key strategy guidance, compound keys, and OData considerations.
2. Internal State Model
The selection has two representations, told apart by _selectionScope:
| scope | meaning | state it uses |
|---|---|---|
'explicit' |
the enumerated keys | _selectedKeys, _selectedRowsCache |
'all-matching' |
every row matching the query captured at select-all, minus the unticked rows | _excludedKeys, _selectAllQueryFingerprint, _heldTotal |
Nothing is enumerated under 'all-matching': _selectedKeys and _selectedRowsCache stay empty. That is what makes a select-all O(1) in time and memory at any row count.
Core selection fields:
_selectionMode_selectionScope: 'explicit' | 'all-matching'_selectedKeys: Set<string>—'explicit'only_excludedKeys: Set<string>—'all-matching'only: the rows unticked since the select-all_selectAllQueryFingerprint: string | null— the query (filter model + search term) the select-all is scoped to (§ 9)_heldTotal: number | null— the last exact total of an'all-matching'selection, held across a reload (§ 9)_keyToRow: Map<string, row>— key → loaded row, built on first use bysetSelectedKeys()(see § 4)_keyToRowStale: boolean— true while_keyToRowdoes not describe the current rows_selectedRowsCache: Map<string, row>— row snapshot for every key currently in_selectedKeys, independent of whether that row is in the currently loaded/filtered set (see § 4)_selectAllActive— a getter,_selectionScope === 'all-matching'_headerCheckbox: HTMLInputElement | null_selectionKeyColumnField: string | null
The feature reads the grid through getters passed at construction: rows, isLoading, and for 'all-matching' the query's total (getTotalRowCount()), whether rows are outstanding (hasMoreRows()) and the query fingerprint (VanillaGrid#_computeQueryFingerprint(), built from the attached DataManager's getColumnFilters() / getSearchTerm(), reached through the getDataManager option <vn-grid> supplies).
Auxiliary key fallback fields:
_generatedKeySymbolfor generated per-row keys_didWarnFallbackKeysto log fallback warning only once
3. Column and Key Strategy
3.1 Selection column injection
In setColumns(...), if mode is not noselection and selection.showCheckboxes is true, grid injects an internal checkbox column:
- key:
__vgSelection__ - fixed narrow width
- non-sortable / non-resizable
3.2 Key-column detection
_resolveSelectionKeyColumnField(...) scans all columns (_allColumns) for key-column markers — not just the visible subset. This ensures a hidden key column (e.g. a Row ID column the user chose to hide) is still discovered.
Recognised markers on a column definition object:
isKeyColumnkeyColumnis-key-columnkey-column
Any truthy-like value (true, 'true', '1', '') is accepted.
If multiple columns are marked, the first is used and a warning is logged.
3.3 Row key precedence
resolveRowKey(row) resolves a stable key in this order:
rowKeyGetter(row)— highest priority, full control- key-column field from column definitions (resolved via
_selectionKeyColumnField) rowKeyField— explicit field name shortcut- generated fallback UUID-like key (cached on row via
Symbol)
All three named strategies are opt-in only. No implicit field name is assumed — if none of the strategies is configured, the fallback fires and a one-time console warning is emitted.
4. Key Map and Duplicate Handling
_keyToRow maps a key to the loaded row that carries it. Its only lookup reader is setSelectedKeys(), which needs the row objects for the keys it is given, so the map is built lazily, not on every load (and, in tree mode, not at all: see "Tree mode" below):
setRows()callsinvalidateKeyToRowMap(): the old map is dropped (released at once, not cleared entry by entry) and marked stale. At a million rows this saves the ~250 ms walk and the ~33 MB the map held on every reload, search, filter and clear.setSelectedKeys()calls_ensureKeyToRowMap(), which rebuilds a stale map from the current rows in one pass (rebuildKeyToRowMap(rows)), duplicate detection included.appendRows()(infinite scroll) extends the map withaddRowsToKeyMap(newRows)only while one is built — O(page) per append instead of O(total), still warning on keys duplicated across pages because it checks the existing map. While the map is stale it does nothing: the next build reads every row, the appended ones included.setColumns()invalidates the map when the change moves the row key (a different key column resolves), and leaves it alone when the same declaration is re-applied, asclearPersistedSettings()does.hasKeyToRowMap()reports whether a current map exists.
A grid in 'noselection' mode, or one that never calls setSelectedKeys(), therefore never builds a map at all. hasAnySelection() is a cheap O(1) probe used by the render hot path to skip per-row isRowSelected() key resolution when nothing is selected. Both it and isRowSelected() stay O(1) under either scope: isRowSelected(row) is !_excludedKeys.has(key) under 'all-matching' and _selectedKeys.has(key) under 'explicit'.
Duplicate keys:
- the last row for a duplicate key wins its map entry
- duplicates are logged in one warning with their counts, when the map is built: at the first
setSelectedKeys()after a load, not at load time. A duplicate only matters to a key lookup, so it is reported where it can pick the wrong row; a grid that never looks keys up never warns. This covers flat grids: in tree mode no map is built.
Tree mode. Every tree build already maps each row's key to its position in the tree-ordered displayRows (Tree Rows § 3 and § 8), and in tree mode displayRows holds every loaded row (the tree reorders them and drops none; tree mode refuses infinite scroll). So the grid hands the selection feature a treeRowLookup getter: while tree mode is active and the tree's index describes the current displayRows (hasIndex()), it returns a lookup, key to position (positionOfKey()), then displayRows[position]; otherwise null. setSelectedKeys() uses that lookup when it gets one and builds no map, so its first call after a load costs O(keys), not O(rows): about 6 ms instead of about half a second at 1,000,000 rows, measured on project-tasks-js (Chromium; Firefox 8 ms). While the build is pending (behind the shimmer), or outside tree mode, the map path runs as above. A duplicate key resolves to the first row in tree mode (the tree's rule) and to the last through the map; both rows render selected either way, since isRowSelected() reads the key. The tree build, not the selection feature, warns about duplicates in tree mode.
_keyToRow is scoped strictly to "currently loaded rows", so a row that has been filtered or scrolled out of the loaded set has no entry here. It is not the source of truth for selected-row data (see _selectedRowsCache below).
Refreshing selected rows on a load. syncSelectionToRows(rows) runs on every setRows() (with the whole new row set) and appendRows() (with the page), and does nothing while no key is enumerated, which includes every 'all-matching' selection: a predicate needs no extending onto new rows. Otherwise, in one pass over the arriving rows, for any row whose key is in _selectedKeys the _selectedRowsCache entry is pointed at the newly-loaded row object, so a selected-and-then-refiltered-back-in row's cached snapshot stays current rather than stale. The pass stops once every selected key has been seen.
5. Public Selection API
Methods:
getSelectedKeys()/getSelectedRows()— see § 5.3 for what they return under a select-all.getSelectedCount()— the number of selected rows, O(1) (§ 5.4). Use it wherever only the count is needed:getSelectedKeys().lengthcopies the selection into an array first, and under a select-all it counts only the loaded rows.isSelectedCountExact()— whethergetSelectedCount()is exact or a lower bound (§ 5.4).getSelectionDescriptor()— the selection as a serialisable object for a backend bulk command (§ 5.5).materializeSelectedRows(opts)— every selected row, loaded or not (§ 5.6).setSelectedKeys(keys)clearSelection()isRowSelected(row)
Getters:
selectionState→'none' | 'partial' | 'all'selectAllActive→truewhile the selection is'all-matching'
Under 'explicit', getSelectedRows() reads from _selectedRowsCache, not _keyToRow — this is what makes it filter/reload-tolerant: a row selected before a filter is applied stays retrievable even after that filter removes it from the currently-loaded set. Every path that adds a key to _selectedKeys (row click/checkbox toggle, setSelectedKeys) writes the corresponding row into _selectedRowsCache in the same step; every path that removes a key (manual deselect, clearSelection(), selectAll(), the single-mode "reselect clears" path) deletes the matching cache entry, so the cache never outlives the selection it backs and cannot grow unbounded. Because the cache only ever holds references to already-in-memory row objects (no copies) and is bounded by the number of rows the user picked, not by the dataset size, it costs nothing a select-all could make large.
5.1 setSelectedKeys(keys)
- requires array input (throws
TypeErrorotherwise) - clears existing selection and
_selectedRowsCache - returns the selection to
'explicit': an enumeration replaces a select-all and its exclusions - looks the rows up through the tree's key index in tree mode, else builds
_keyToRowfrom the current rows if a load has invalidated it (§ 4) - inserts normalized string keys, caching the row for any key that lookup resolves (a key with no currently-loaded row simply isn't cacheable yet — it becomes cacheable once a matching row is loaded, via
syncSelectionToRows) - emits event + updates header checkbox + rerenders visible rows
5.2 clearSelection()
- returns the selection to
'explicit', dropping the exclusions, the fingerprint and the held total - clears key set and
_selectedRowsCacheif needed - emits event when actual selection changed
- updates header checkbox and visible rows
5.3 getSelectedKeys() / getSelectedRows() under a select-all
The full 'all-matching' set is, by definition, not in memory. Both methods return the loaded rows (or their keys) that are not excluded, in loaded order — never a fabricated million, and they never throw. The cost is O(loaded), paid only on access; the event detail and the toolbar state read them through lazy getters.
That makes the common host idiom safe: a detail panel that opens on rows.length === 1, gated by the toolbar's hasSingleSelection (selectedCount === 1). Under a select-all a count of 1 means every other row was unticked, each untick needs a rendered row, and rendering needs loading, so the survivor is among the loaded rows.
It makes one idiom wrong: counting with getSelectedKeys().length reads "200" for a select-all over a million rows. So the first time either method returns fewer entries than getSelectedCount() under 'all-matching', the grid logs one warning per grid instance through its logger (silenced with logger: false), naming getSelectedCount() and materializeSelectedRows(). It cannot fire under 'explicit', nor when every row is loaded.
5.4 Counting: getSelectedCount() and isSelectedCountExact()
getSelectedCount() returns a number in every case. Whether that number is exact is a separate question:
| scope | what is known | getSelectedCount() |
isSelectedCountExact() |
|---|---|---|---|
'explicit' |
— | _selectedKeys.size |
true |
'all-matching' |
total known (pushed by the DataManager, or held across a reload) | total − excluded |
true |
'all-matching' |
no total, every row loaded (!hasMoreRows()) |
loaded − excluded |
true |
'all-matching' |
no total, rows outstanding | loaded − excluded |
false (a lower bound) |
The third row covers StaticDataManager and any non-infinite-scroll grid: with nothing left to load, the loaded rows are the result set.
Because the count depends on the total, setTotalRowCount() calls the feature's handleTotalRowCountChanged(), which emits selectionChanged under 'all-matching' when the count or its exactness changed from what listeners were last told. While no total is known, the count follows the loaded rows, so setRows() and appendRows() emit selectionChanged too (countTracksLoadedRows()).
5.5 getSelectionDescriptor()
The selection as a small, serialisable object a host sends to a backend for a bulk command:
{
"scope": "all-matching",
"includedKeys": null,
"excludedKeys": ["4821", "9013"],
"query": { "filterModel": { "country": { "operator": "equals", "value": "IT" } }, "searchTerm": null },
"totalCount": 1000000, "loadedCount": 200, "countExact": true
}
An 'explicit' selection carries includedKeys and excludedKeys: null. The backend re-runs the query it already knows how to run and applies the exclusions, so a million-row selection is a few hundred bytes, and the server stays the authority on what "all" resolves to. query is built from the attached DataManager's getColumnFilters() / getSearchTerm() (the same values <vn-grid> exposes), with null for an empty one.
5.6 materializeSelectedRows({ signal, onProgress, maxRows, drainPageSize })
Every selected row, as a Promise:
| situation | result |
|---|---|
'explicit' |
getSelectedRows() |
'all-matching', every row loaded |
displayRows minus the exclusions, in display order; no network, no sort |
'all-matching', rows outstanding, DataManager supportsFullFetch() |
fetchAllRows() from row 0, minus the exclusions, ordered by the current sort (sortRowsByState(); skipped under serverSort, where the rows arrive in order) |
'all-matching', rows outstanding, no full fetch |
rejects, code: 'MATERIALIZE_UNSUPPORTED' |
more rows than maxRows (default Infinity) |
rejects, code: 'MATERIALIZE_OVER_CAP', with { matched, cap, matchedExact } — before any request when the total is exact, otherwise the moment the drained rows pass the cap (matchedExact: false) |
signal aborted |
rejects with an AbortError, the request in flight included |
drainPageSize is the rows per request of that fetch, handed to fetchAllRows() as pageSize; without it the DataManager pages with its own pageSize. The grid's export.drainPageSize applies to exports only, not here.
The exclusions are copied when the call starts, and the drain works from a copy of the query (see DataManager Implementation), so a filter change meanwhile affects neither. The drained rows never enter the grid, and none of the grid's loaded row objects are mixed into them. exportToExcel({ scope: 'selected' }) resolves its rows through the same routine; see Export to Excel.
6. Row Interaction Flow
6.1 Row click
handleClick(e) toggles row selection when mode is enabled:
- finds clicked
trin body - ignores direct checkbox clicks (checkbox handler owns those)
- resolves row by
data-vn-grid-row-index - delays
_toggleRowSelection(rowData)by 300 ms so a double-click can cancel it - skips scheduling it when the click is the second of a double-click (
_dblClickSuppressNextClick, set by the detector in §6.2)
A row grouping caption row is never selectable and carries no data-vn-grid-row-index at all (omitted entirely, not a sentinel value) — the existing !isNaN(dataIndex) guard in this handler already rejects it with no caption-specific branch, since parseInt(undefined, 10) is NaN. The same omission-based rejection covers the checkbox-change handler (§6.3) and the double-click detector (§6.2).
A click on a command column's button is an action only: handleClick() resolves it before this branch and returns without scheduling a toggle, and handlePointerDown() never counts its press toward a double-click.
6.2 Row double-click
handlePointerDown(e) implements a manual double-click detector (two pointerdown events on the same row within 300 ms). The native browser dblclick event is not used because custom renderCell content (e.g. thermometer bars) can be torn down and recreated by the selection re-render of the first click, causing the second click to land on a new DOM node.
When a double-click is detected:
- The pending selection timer from the first click is cancelled, and
_dblClickSuppressNextClickis set so the click that follows this press does not schedule a new one. A browser double-click sends twoclickevents, one per press; without the flag the second one would toggle the row. The flag is cleared by that click, and by everypointerdown, so a press that never becomes a click (dragged off the row) cannot swallow a later one. The row's selection state stays unchanged. e.preventDefault()suppresses text selection.- A
CustomEvent('rowDblClick')is dispatched on the viewport withdetail: { row, rowIndex }.
6.3 Checkbox cell rendering
During renderVisibleRows(...), selection column cells render checkboxes:
- checked state is computed via
isRowSelected(rowData) - checkbox
changehandler calls_toggleRowSelection(rowData)
Selection class vn-grid-row-selected is applied to selected rows. It is how
a selected row shows without the checkbox column (showCheckboxes: false, as
in the Gantt's task grid): the theme's --vn-grid-frozen-bg-selected tint,
and the selection marker, a 3px bar in --vn-grid-selection-marker-color on
the inline-start edge of the row's first cell that stands in for the
checkbox. The hover tint covers the selected tint, so a row just clicked,
with the pointer still on it, shows the selection by the marker alone. Under
forced colors there is no marker, and the cells are Highlight with
HighlightText (Themes § 4.2). The grid
marks the viewport vn-grid-selection-marker when selection is on and
showCheckboxes is false (_initSelection()), and only rows under that
class get the marker, so grids that show the checkbox column look as before.
7. Mode Semantics
_toggleRowSelection(row) behavior:
noselection: no-opsingle:- selecting one key clears all others
- selecting already-selected row clears selection
multiple:'explicit': toggles the key in_selectedKeys'all-matching': toggles the key in_excludedKeys, and the scope stays — "all except these". Unticking a row after a select-all never collapses it back to an enumeration.
After mutation: emit event, update header checkbox, rerender visible rows.
8. Header Checkbox and Select-All
In renderHeader(), selection header cell includes a checkbox in multiple mode.
Header checkbox click:
- if current
selectionStateisall→clearSelection() - otherwise →
_selectAll()
_selectAll() (selectAll() on the feature), O(1):
- sets
_selectionScope = 'all-matching' - clears
_selectedKeys,_selectedRowsCacheand_excludedKeys - captures the query fingerprint and the current total (
_heldTotal) - emits event, updates checkbox, rerenders the visible rows (bounded by the viewport, as any selection change)
getSelectionState():
| scope | state |
|---|---|
'all-matching', no exclusions |
'all' |
'all-matching', exclusions, and an exact count of 0 |
'none' |
'all-matching', exclusions |
'partial' |
'explicit' |
'none' when empty, 'all' when every loaded row is selected, 'partial' otherwise |
_updateHeaderCheckbox() sets:
- disabled state (no rows or not
multiplemode) - checked/indeterminate based on
selectionState, so a select-all shows checked and a select-all with an untick shows indeterminate
_syncHeaderCheckboxSizeFromBody() aligns header checkbox dimensions to row checkbox dimensions (queried via input.vn-grid-selection-checkbox). The measured size is cached after the first successful sync: the method is still invoked from every renderVisibleRows() pass but skips the forced layout read until invalidated. Invalidation happens via invalidateHeaderCheckboxSizeSync() on virtual-pool rebuilds (row-height / theme changes funnel through initVirtualPool()) and via setHeaderCheckbox() on header rebuilds.
9. Select-All and the Query
A select-all means "every row matching the query the grid is showing". On an infinite-scroll grid showing 200 of 1,000,000 rows, that is 1,000,000 rows: pages that arrive later are selected because the predicate covers them, not because anything is added.
A filter or search change clears it. "All rows matching the query" means nothing once the query changes, and keeping the selection would silently broaden it (select all of "orders in 2024", widen the filter to "all orders", and a bulk-delete one click away now covers every order). setRows() calls clearIfQueryChanged(), which compares the current fingerprint (filter model + search term, by value) with the one captured at select-all; a mismatch clears the selection and emits selectionChanged. Comparing values at load time, rather than interpreting config-change events, is what keeps it independent of how the query changed.
A sort does not. Sort is not part of the fingerprint: membership is the same in any order, the exclusions are keyed by row key, an export is expected to follow the current sort, and an 'explicit' selection already survives a re-sort. After a re-sort the unticked rows may no longer be on screen; they are still excluded.
The count holds across a reload. A server-sort reload runs _resetInfiniteScrollState(), which sets the grid's total to null and empties the rows. The count would read "0 selected", then the loaded count, then the total again. Instead the last exact total is held (_heldTotal) while 'all-matching' is active, so getSelectedCount() keeps returning heldTotal − excluded and isSelectedCountExact() stays true. A new total for the same query replaces it through setTotalRowCount(); a total for a different query is ignored, since the setRows() that follows clears the selection.
Known caveat: on some OData providers, $orderby across a nullable navigation property drops rows with a null relation, so a sort can shrink the result set. That surfaces as a changed total, not a wrong selection.
'explicit' selections are unaffected and keep their filter tolerance (§ 5).
Tree mode. Tree rows are ordinary data rows, so a select-all covers the rows under a collapsed parent too: membership is the query, not what is expanded (Tree Rows § 11).
10. Selection Event Contract
_emitSelectionChanged() dispatches CustomEvent('selectionChanged') on viewport with:
modeselectionStateselectAllActiveselectedKeys— loaded keys only under a select-all (§ 5.3)selectedCount—getSelectedCount()(§ 5.4)selectedCountExact—isSelectedCountExact()selectedRows— loaded rows only under a select-all (§ 5.3)
Event bubbles, enabling host-level listeners without direct grid internals access.
Lazy fields: selectedKeys and selectedRows are compute-once-on-first-access getters (defined via Object.defineProperty) — the arrays are only materialized when a listener actually reads them. Consumers reading within the dispatch turn (the toolbar and all sample apps) see identical data to eager fields; a consumer that first reads the arrays after mutating the selection again would see the state at first access.
selectedRows calls getSelectedRows() under the hood, so under 'explicit' it inherits the filter/reload tolerance described in § 4/§ 5: selectedCount and selectedRows.length stay consistent with each other across a filter apply, even when the filtered result set excludes some or all of the selected rows. Under a select-all they differ whenever rows are not loaded; count with selectedCount.
Selection and Double-Click Interaction
Row selection via single click is intentionally delayed (300 ms timeout). If a second pointerdown arrives on the same row within the delay window, the pending selection toggle is cancelled, and the second click that follows it schedules none (§6.2). This guarantees that double-clicking a row never alters its selection state — only single clicks and checkboxes modify selection.
11. Web Component Forwarding
vanilla-grid-element.js forwards selection APIs:
getSelectedKeys()getSelectedRows()getSelectedCount()isSelectedCountExact()getSelectionDescriptor()materializeSelectedRows(opts)setSelectedKeys(keys)clearSelection()
<vn-grid> passes the inner grid a getDataManager accessor, which the select-all's query fingerprint, the descriptor's query and the drain all read.
Element attributes/properties for selection identity:
selection-moderow-key-fieldrowKeyGetterproperty
When grid dispatches selectionChanged, web component re-emits:
vn-grid-selection-changed(bubbles + composed)
When grid dispatches rowDblClick, web component re-emits:
vn-grid-row-dblclick(bubbles + composed),detail: { row, rowIndex }
This keeps selection and row events observable in both imperative and declarative usage styles.
12. Failure Safety and Guardrails
- invalid rows/keys short-circuit safely
- strict type check for
setSelectedKeys - duplicate-key warnings expose unstable identity input
- generated fallback keys keep UI functional when host omits stable keys
Recommended best practice: always provide stable keys (rowKeyGetter, key column, or rowKeyField) to avoid selection drift. See Row Key Management for compound key patterns and best practices.
13. Example Configuration
Using a declarative key column (recommended):
<vn-grid id="myGrid">
<vn-grid-column kind="data" column-key="Id" header="Row ID" type="number" is-key-column="true"></vn-grid-column>
<vn-grid-column kind="data" column-key="Name" header="Name" type="string"></vn-grid-column>
</vn-grid>
const grid = el.initializeGrid({
selection: {
mode: 'multiple',
showCheckboxes: true
}
});
grid.setSelectedKeys(['1', '42']);
console.log(grid.selectionState); // 'partial' | 'all' | 'none'
console.log(grid.selectAllActive); // true while a select-all is active
console.log(grid.getSelectedCount(), grid.isSelectedCountExact());
// A bulk command over whatever is selected, however large:
await fetch('/api/orders/bulk-archive', {
method: 'POST',
body: JSON.stringify(gridEl.getSelectionDescriptor()),
});
Using rowKeyField as an explicit field shortcut:
el.initializeGrid({
selection: {
mode: 'multiple',
rowKeyField: 'rowId'
}
});
Using rowKeyGetter for custom or compound keys:
el.initializeGrid({
selection: {
mode: 'multiple',
rowKeyGetter: (row) => `${row.CompanyId}::${row.OrderId}`
}
});
See Row Key Management for full guidance.