Web Component Implementation (<vn-grid>)
This document describes how the Vanilla-Grid Web Component is implemented in vanilla-grid-element.js, including lifecycle, markup generation, DataManager wiring, API forwarding, and event dispatch.
1. Overview
VanillaGridElement is a light-DOM wrapper around VanillaGrid (no Shadow DOM). It provides:
- Declarative usage via HTML attributes and optional
<vn-grid-column>children - Imperative control via methods (
initializeGrid,setDataManager,reload, etc.) - Direct callback-based routing of grid data events (
vn-grid-selection-changed,vn-grid-row-dblclick,vn-grid-command) to the host element
Because it is light-DOM, host app CSS and theme files apply directly.
2. Registration and Class Structure
The component class extends HTMLElement and is registered once:
if (!window.customElements.get('vn-grid')) {
window.customElements.define('vn-grid', VanillaGridElement);
}
The constructor initialises internal references:
_grid: activeVanillaGridinstance_dataManager: current data manager instance_gridOptions: merged options used when creating_grid_pendingRows,_pendingColumns: buffers used when data/columns are set before grid init, or while an async persistence load is pending_awaitingPersistence: true frominitializeGrid()until an async (storage-mode="remote") persistence load settles; keeps the buffers parked (§11)_domRefs: cached DOM references created by_ensureMarkup()_rowKeyGetter: optional custom selection key resolver
The element exposes a get _logger() accessor that returns this._grid.logger when a grid is initialised, or falls back to a module-level _elementDefaultLogger (a thin console.* wrapper) before initializeGrid() has run. All warnings emitted by the element (unknown storage-mode attribute, failed DataManager reloads, etc.) route through this accessor so that options.logger: false or a custom logger passed to initializeGrid() controls element-level output too.
3. Observed Attributes
observedAttributes returns:
['environment', 'infinite-scroll', 'max-rows', 'locale', 'theme', 'theme-css-path', 'selection-mode', 'row-key-field', 'storage-mode', 'stretch-to-fit', 'highlight-search-matches', 'row-height', 'header-height', 'group-by', 'sort-by', 'tree-parent-field', 'tree-column']
Notable attributes:
row-height— explicit per-grid row height in pixels (positive finite number). When set, it takes precedence over the active theme's--vn-grid-row-heightand is forwarded aslayout.rowHeightto the underlyingVanillaGridatinitializeGrid()time. When absent, the grid adopts the theme's row-height (see Themes Implementation §4.3). The corresponding JS property mirrors the attribute (getterreturnsnullwhen missing/invalid,setterwrites a normalized positive number).header-height— explicit per-grid column-header height in pixels (positive finite number). Same resolution semantics asrow-height: when set it overrides the active theme's--vn-grid-header-heightand is forwarded aslayout.headerHeightto the underlyingVanillaGridatinitializeGrid()time. When absent, the grid adopts the theme's header height (see Themes Implementation §4.4). The JSheaderHeightproperty mirrors the attribute (getterreturnsnullwhen missing/invalid,setterwrites a normalized positive number).tree-parent-field/tree-column— tree mode'stree.parentFieldandtree.column(Tree Rows § 1). Hyphenated, so React and Vue pass them through as attributes, as they dogroup-by. Resolved into thetreeoption atinitializeGrid()(an option wins over the attribute,_resolveTreeOptions()). Unlike the other configuration attributes they are also live: a change afterinitializeGrid()calls the grid's_setTreeOptions(), which turns tree mode on, off or onto another column, and hands the attached StaticDataManager the new parent rule (setTreeOptions()), reloading when a filter or search is active.
attributeChangedCallback(name, oldValue, newValue) behavior:
- Returns immediately when value is unchanged.
- Special-cases
theme: mirrors todataset.theme. - Special-cases
tree-parent-fieldandtree-columnonce the grid exists (above). - Emits
vn-grid-attribute-changedwith{ name, oldValue, newValue }.
This callback does not rebuild the grid by itself; it emits state changes and leaves reloading decisions to host code.
4. Lifecycle
4.1 connectedCallback()
Calls _ensureMarkup() to guarantee required table/viewport nodes exist.
When the element is re-inserted after a removal tore its grid down (§4.2),
it also rebuilds itself: it calls initializeGrid() with the options the
host passed before (kept by setGridOptions()), which replaces the stale
body, and, when a DataManager is attached, calls reloadDataManager(). A
failed reload is logged as a warning and emits vn-grid-error as any load
does. This is what Vue <KeepAlive>, Angular route reuse and hand-built tab
code need: they detach a view and re-attach it in a later task, and expect
the custom element to survive that with no host code.
What survives the rebuild: the options, the column declaration (the
setColumns() columns, or the declarative <vn-grid-column> children
re-parsed as on any initializeGrid()), the DataManager with its own query
state (filter model, search term), the rows the grid holds when its
DataManager was detached with setDataManager(null), and everything the storage
provider persists (widths, order, visibility, freezing, sort, grouping).
Everything else starts fresh: selection, scroll position, expanded groups,
and sort or column state that storage-mode="none" never persisted.
The rebuild runs only for an element whose grid was torn down by a removal. An element never initialized, one moved within a single task, and one the host re-initialized while it was detached are unchanged.
4.2 disconnectedCallback()
Teardown is deferred by one microtask and skipped when the element is
already re-connected: reparenting — appendChild into a new
container, drag-and-drop layouts, some framework re-renders — fires
disconnect + connect synchronously, and destroying the grid there would
silently kill a populated grid with no signal to the host. Moving a
<vn-grid> in the DOM therefore keeps it alive; no re-initialization is
needed.
On a genuine removal (still disconnected when the microtask runs): the
current full load's signal is aborted (§8.2); _grid.destroy() is called to
clean up event listeners/timers and abort the in-flight load-more page's
signal; then _grid is nulled and the theme stylesheet link is released. Before
the grid is destroyed, its column declaration (and, with no DataManager, its
rows) is kept so a later re-insertion can rebuild (§4.1). The body is idempotent,
so rapid repeated disconnects are harmless.
<vn-grid-toolbar>'s disconnectedCallback applies the same
microtask-deferred pattern so its grid listeners survive a reparent (its
handler references are stable, making the reconnect re-attach a no-op).
5. Internal Markup Generation
_ensureMarkup() is idempotent (no-op if _domRefs already exists).
If a root node ([data-vn-grid-root]) does not exist, it builds this structure:
<div class="vn-table-container" data-vn-grid-root>
<div class="vn-group-bar" data-vn-grid-ref="group-bar" hidden></div>
<div class="vn-header-spacer">
<table class="vn-header-table" data-vn-grid-ref="header-table">
<colgroup data-vn-grid-ref="header-colgroup"></colgroup>
<thead data-vn-grid-ref="header"></thead>
</table>
</div>
<div class="vn-virtual-list-viewport" data-vn-grid-ref="viewport">
<table class="vn-body-table">
<colgroup></colgroup>
<tbody class="vn-virtual-tbody" data-vn-grid-ref="body">…</tbody>
</table>
</div>
</div>
If <vn-grid-column> children are present, the generated container is appended as a sibling so declarative column nodes remain in place.
The group-bar strip is created unconditionally, exactly like the header spacer and viewport — it is the mount point for the row-grouping group bar. Row grouping removes an applied group level's column from the grid, and the bar's chip is the only interactive way to bring it back once that column's header menu leaves with it, so this element must never be host-supplied markup that can go missing. It stays empty and hidden (occupying no space) until a group state exists. See Row Grouping Implementation § 18.
After creation, _domRefs caches:
root,headerSpacer,headerColGroup,header,viewport,body,groupBar
6. Declarative Columns
_parseDeclarativeColumns() reads all <vn-grid-column> child elements and maps attributes into grid column objects in two steps: the attribute mapping, the public static VanillaGridElement.parseColumnElements(elements, logger?), then the key, header and label fallbacks <vn-grid> applies. <vn-gantt> calls the static on its own <vn-grid-column> children and applies its own defaults instead (Gantt Web Component § 4.1). The static warns through logger (default console; <vn-grid> passes its own) about the misplaced attributes of Grouping, and returns [] for no elements, where _parseDeclarativeColumns() returns null.
Mapping details (parseColumnElements(), except where marked):
- Copies all element attributes into a plain object
- Maps
column-keytokey. The attribute is not calledkeybecause React and Vue reservekeyin templates and never render it as an attribute. Akeyattribute is not read: it is kept as an internal marker that_validateColumns()reports (<vn-grid-column> takes 'column-key', not 'key') - Copies
kindandtypeverbatim; nothing is defaulted. A missingkind, a data column without atype, atypeon a command column and a leftoverfieldattribute are reported by_validateColumns()with the same messages as a JS column (thrown understrict, warned otherwise) headerdefaults to element text content (never for akind="command"column, whose text content is its<template>'s)<vn-grid>only: enforceskeyandheaderfallbacks ('', then the key)<vn-grid>only: setslabel = header || label || keyso VanillaGrid header rendering works- For
kind="command": mapscommand-text/command-icon/command-tooltiptocommandText/commandIcon/commandTooltip, and, when nocommand-iconattribute is set, takes the icon markup from a<template>child (itsinnerHTML). The template is inert, so the icon never renders inside<vn-grid-column>itself. See Command Columns.
Supported <vn-grid-column> attributes
| HTML attribute | Column property | Type | Default | Description |
|---|---|---|---|---|
kind |
kind |
string | — (required) | data for a data column, command for a per-row action button |
column-key |
key |
string | — (required) | Unique column identifier; on a data column also the dot-path read from each row (e.g. Customer.City) |
header |
header / label |
string | the key | Column header text |
type |
type |
string | — (required on kind="data") |
Data type (string, number, boolean, date, datetime, time, uuid, uid, checkbox). Not allowed on kind="command" |
width |
width |
number | — | Initial width in pixels |
min-width |
minWidth |
number | — | Minimum width in pixels (default floor: 60; explicit values below 60 are honoured) |
max-width |
maxWidth |
number | — | Maximum width in pixels |
is-key-column |
isKeyColumn |
boolean | false |
Marks column as the row identity key |
hidden |
hidden |
boolean | false |
Column starts hidden; user can show via context menu, persistence overrides |
sortable |
sortable |
boolean | true |
Whether the column can be sorted |
resizable |
resizable |
boolean | true |
Whether the column can be resized by dragging |
frozen |
frozen |
boolean | false |
Column starts frozen; user can unfreeze via context menu, persistence overrides |
sort-fields |
sortFields |
string | — | Comma-separated dot-notation field paths used for sorting instead of the key path. Enables template columns (whose renderCell assembles a composite display) to sort by underlying data properties — e.g. "Employee.FirstName,Employee.LastName". Multiple fields are compared in priority order (tiebreaker chain). See Sorting §7.4. |
command |
command |
string | key |
kind="command" only: the identifier reported in vn-grid-command |
command-text |
commandText |
string | — | kind="command" only: visible button text (requires width) |
command-icon |
commandIcon |
string | — | kind="command" only: SVG markup for an icon-only button; a <template> child holding the <svg> is the usual declarative form |
command-tooltip |
commandTooltip |
string | text | kind="command" only: tooltip and accessible name (required with an icon) |
sort-field-types |
sortFieldTypes |
string | — | Comma-separated type hints parallel to sort-fields entries (e.g. "string,string"). Accepts the same values as column.type. Defaults to 'string' for any omitted entry. Only meaningful when sort-fields is also set. |
Numeric attributes (width, min-width, max-width) are parsed as positive finite numbers; invalid values are ignored. Boolean attributes use standard HTML truthy conventions: bare attribute, "true", or "1" are truthy; "false" or "0" are falsy. For sortable and resizable, the default is true — only explicit "false" disables the feature.
The parsed result is applied at initializeGrid() time.
7. Grid Initialization Pipeline
initializeGrid(options) does the following in order:
- Ensures markup exists (
_ensureMarkup()). - Throws if
window.VanillaGridis missing. - Merges provided options into
_gridOptionsviasetGridOptions. - Destroys previous
_gridinstance if present. - Re-parses declarative columns and stages them (
setColumns). - Builds merged options for
new VanillaGrid(...).
7.1 Options Merging Rules
Merged options include DOM refs; selection, sorting, and infinite-scroll settings are grouped into sub-objects:
{
..._gridOptions,
header, body, headerColGroup, viewport, headerSpacer, groupBar,
sorting: { ..._gridOptions.sorting, onSort },
infiniteScroll: { ..._gridOptions.infiniteScroll },
onTotalRowCountChanged: resolvedOnTotalRowCountChanged,
getActiveSearchTerm: () => this.getSearchTerm(),
getDataManager: () => this._dataManager,
selection: {
mode: _gridOptions.selection?.mode || this.selectionMode,
rowKeyField: _gridOptions.selection?.rowKeyField || this.rowKeyField,
rowKeyGetter: _gridOptions.selection?.rowKeyGetter || this.rowKeyGetter
}
}
formatting is _gridOptions.formatting, plus noMatchesMessage from the
no-matches-message attribute when the attribute is set and neither
formatting.noMatchesMessage nor formatting.messages.noMatchesMessage is.
The attribute is read once here, not observed. It is the text the grid shows
when a load ends with no rows while a search term or a column filter is
active (see 16 § 8).
Unlike empty-message, which only seeds the placeholder row rendered before
the grid initializes, it reaches the grid's messages.
getDataManager is pull-based, like getActiveSearchTerm: the grid asks for
whatever manager is attached when it needs one. A select-all reads the query
it is scoped to from it (filter model + search term), getSelectionDescriptor()
builds its query from it, and an export of every matching row drains it
(fetchAllRows()). The export: { maxMaterializedRows, drainPageSize } option group passes
through _gridOptions unchanged.
onSort resolution priority:
_gridOptions.sorting.onSort- a bridge to the attached manager's
handleSort, read when the sort changes (a no-op while no manager is attached, or the attached one has nohandleSort)
onTotalRowCountChanged is a top-level grid constructor option (not
nested under infiniteScroll) — total-row-count state applies to any grid a
DataManager is attached to, not just infinite-scroll ones. The element wraps
_gridOptions.onTotalRowCountChanged (if any) so every change also dispatches
the public vn-grid-total-row-count-changed CustomEvent. There is no
default/fallback resolver — the grid never pulls for the total; see §8.1.
7.2 DataManager Auto-Wiring
The auto-wired callbacks are late-bound: they read this._dataManager
when they run, never the manager attached at init, so a manager swapped in by
setDataManager() after initializeGrid() (§8.1) receives every load-more
page and every sort. Capabilities are detected via duck-type checks at call
time (only sophisticated managers like ODataDataManager have these methods):
- If
infiniteScroll.enabledistrueandonLoadMoreis not explicitly provided:onLoadMoreis auto-wired to(skip, pageSize, { signal }) => dm.fetchMoreRows(skip, pageSize, { signal })against the attached manager — the grid-owned load-more signal is forwarded, no context parameter. It resolves to no rows while no manager is attached, or the attached one has nofetchMoreRows. - If
pageSizewas not explicitly provided in_gridOptions.infiniteScrolland the manager attached at init hasgetPageSize():pageSizeis set fromdm.getPageSize()(re-read on a later swap, §8.1). - The
dataLoading.useWorker/workerThresholdoptions are forwarded to the manager'ssetWorkerOptions()when it has one (re-applied on a later swap, §8.1).
A host-supplied infiniteScroll.onLoadMore or sorting.onSort is never replaced.
7.3 Post-Construction Steps
After new VanillaGrid(mergedOptions):
- Applies pending columns/rows (
_pendingColumns,_pendingRows) if any. For an async storage provider (storage-mode="remote") it holds them instead and applies them onceready()resolves, then firesvn-grid-persistence-ready(§11). - Returns the created
VanillaGridinstance.
No viewport event listeners are added by the element itself. Selection and row double-click events are routed directly via the callbacks described in §7.1 and §12 below.
8. Data Loading and DataManager Integration
8.1 setDataManager(dataManager)
Stores an object reference (or clears with null). Returns void.
Also unconditionally wires dataManager.onTotalRowCountChanged = (count) => this._grid.setTotalRowCount(count) (detached from the previous manager on
swap, mirroring the existing onConfigChanged detach-on-swap logic) — this is
passive state sync, not a reload trigger, so it is not gated behind
setAutoReloadOnConfigChange(). Any manager that calls
this._fireTotalRowCountChanged(count) therefore automatically updates the
grid's total, which in turn dispatches vn-grid-total-row-count-changed (see
§7.1).
Requests made to the previous manager are superseded: the current full load's
signal and the in-flight load-more page's signal (VanillaGrid._abortLoadMore())
are both aborted before the swap.
Calling it again with the attached manager (e.g. a framework wrapper's effect re-running) is a no-op: nothing is aborted, detached or copied.
After initializeGrid(), a swap behaves like a fresh attach. Before the new
manager's onConfigChanged hook is wired (so none of this schedules an
auto-reload), the element:
- re-applies the manager-scoped init options:
setWorkerOptions()with the storeddataLoading.useWorker/workerThreshold, and, unless the host setinfiniteScroll.pageSize, the grid's page size fromgetPageSize(); - carries the query state over from the previous manager (skipped on a first
attach, when there is none):
- the filter model:
previous.getColumnFilters()intosetColumnFilters(), plus anyfilterValueGetters, then the header filter icons are re-synced; - the search term:
previous.getSearchTerm()intosetSearchTerm(); - the sort: the grid's
getSortState()intohandleSort(column, direction, sortState), withnulls when no sort is active. Skipped when the host suppliedsorting.onSort, which owns the sort.
- the filter model:
Grouping is grid-local: it stays across the swap and re-resolves on the next load, as on any reload. So nothing visible changes on a swap: the sort indicator, filter icons, toolbar search box and group bar agree with the query the new manager will run.
Capability mismatch. State the new manager cannot take is cleared from the
grid's display, with one logger.warn per dropped piece: a filter model when it
has no setColumnFilters() (the icons read the new manager, so they clear), a
search term when it has no setSearchTerm() (the toolbar search box reads
getSearchTerm() from it), and an active server-side sort when it does not
override handleSort() (clearSort(), so the indicator does not claim a sort
the manager never runs). A client-side sort is kept: the grid sorts the rows itself.
Sort support is read from an override, not from the method's presence: every
manager inherits the base DataManager's empty handleSort(), so the grid
treats a manager as sort-capable only when its handleSort is not
DataManager.prototype.handleSort. ODataDataManager and GraphQLDataManager
override it; StaticDataManager does not, so a swap to it from a server-sorting
manager clears the sort and warns. A duck-typed manager that defines its own
handleSort counts as capable.
No reload. The swap never reloads, with or without
setAutoReloadOnConfigChange(true): the grid keeps showing the previous
manager's rows until the host calls reloadDataManager(), which lets it adjust
the new manager first and load once. hasMoreRows() is unchanged until then.
setDataManager(null) after init keeps the rows on screen; load-more
resolves to no rows and sorting reaches no manager. A host wanting an empty
grid calls setRows([]).
Persisted state. The one-shot restore of the persisted search term and filter model runs on the first successful load, against whichever manager is attached then: a swap before that load hands the parked state to the new manager.
Clean start. A host that wants the new manager to start from an unrefined query clears it with existing calls, in this order:
el.setDataManager(newManager);
el.clearGrouping(); // grid-local, no load
el.search(''); // reloads (manual mode)
await el.clearColumnFiltersAndSorting(); // reloads (manual mode)
clearColumnFiltersAndSorting() alone keeps the search term and the grouping.
The recipe replaces the reloadDataManager() call: in manual-reload mode it
loads twice (search('') and clearColumnFiltersAndSorting() each reload);
with setAutoReloadOnConfigChange(true), calling the three back to back,
without awaiting in between, coalesces into a single load. Clearing grouping
first keeps the loads from re-grouping rows that are about to be ungrouped.
8.2 loadRowsAsync(options = {})
Requires a DataManager; otherwise throws:
throw new Error('No DataManager set. Call setDataManager() before loadRowsAsync().');
Awaits grid.ready() before fetching, ensuring persisted column settings are applied first (important for storageMode: 'remote').
Execution flow:
await this.ready()— wait for persisted settings to be applied- Abort the previous load's signal and create this load's
AbortController(_loadController); stamp the call with_loadGeneration(last-wins) - Create context via
_createContext(options)(used for lifecycle events) - Emit
vn-grid-loading(phase: 'rows') rows = await dm.fetchRows({ signal })— the grid-owned signal is the only argument and the only cancellation mechanism (the grid never calls a managercancel()); all other config is internal to the DataManager- Optional transform:
rows = await dm.transformRows(rows)if provided _deliverRows(rows)to grid (private; parks the rows while_awaitingPersistenceis set)- Optional post-hook:
await dm.onRowsLoaded(rows) - Emit
vn-grid-loadedwith rows - On error: an
AbortErroror a superseded generation returns[]silently; otherwise clear the loading state and replace the skeleton body (setLoading(false)leaves the skeletons for asetRows()that never comes): when the grid holds rows from an earlier load it renders them again, otherwise it shows its error row (showError(error.message || messages.loadError)). Then emitvn-grid-errorand rethrow
The signal is aborted by the next loadRowsAsync(), by setDataManager(), and when the element is removed (§4.2). It is kept after the load settles, so manager work tied to it (a count request) is torn down by the next load. A result that arrives after a newer load started is discarded by the generation check even when the manager ignored the signal. See 03-data-manager-implementation.md §5.1.
vn-grid-loaded does not mean the grid is idle. Step 7 clears the loading flag and then
hands the rows to _deliverRows(), and on a grid at or above sortShimmerThreshold with a sort or
an applied grouping to produce, that call raises the shimmer again and defers the reorder — so
by step 9 the grid is busy once more, for a window that ends with no lifecycle event of its
own. Anything tracking "is the grid working" must listen to vn-grid-busy-changed (§ 12.1)
rather than bracketing vn-grid-loading / vn-grid-loaded, which bracket the fetch. A
toolbar that greyed itself out on the pair stayed greyed out indefinitely after every large
load.
8.3 reload()
reload() delegates to loadRowsAsync() (rows only).
8.4 refresh(options?)
Rebinds every visible cell against the grid's current in-memory rows — re-running column formatters / renderCell — without calling the DataManager. Delegates to VanillaGrid.refresh(), a no-op when _grid isn't initialized. Resets scroll position to the top-left by default; pass { preserveScroll: true } to keep it. Useful after a live theme swap or any other cosmetic change where cell output may depend on external state but the underlying rows haven't changed. _updateThemeStylesheet()'s theme-link-load handler already calls refresh({ preserveScroll: true }) once a runtime theme swap's stylesheet finishes loading, to rebind cells against the new theme without disturbing scroll position; a host-triggered refresh() (no options) after setTheme() is what resets scroll to the top for a deliberate theme switch.
9. Context Object Contract
_createContext(overrides = {}) returns a merged context object containing:
- Grid-owned fields:
element,grid,dataManager,locale,infiniteScroll,theme host: a sub-bag for host pass-through metadata that the grid does not interpret:host.environment— value of theenvironmentattribute (host application concern)host.maxRows— value of themax-rowsattribute (host page-size concern)
- Any caller overrides
The infinite-scroll attribute is parsed via the same tolerant parser used for declarative columns: '', 'true', '1', or the literal boolean true all map to true.
This context is passed to DataManager methods and lifecycle events. Hosts that need to add their own metadata can populate additional keys under host via overrides.
10. API Forwarding Layer
The element exposes a thin forwarding API over _grid.
10.1 Selection API
getSelectedKeys()— under a select-all, the loaded rows' keys onlygetSelectedRows()— under a select-all, the loaded rows onlygetSelectedCount()— the number of selected rows, O(1); under a select-all, the query's total minus the unticked rows (loaded or not), or the loaded rows minus the unticked ones while no total is known;0when the grid is not yet initializedisSelectedCountExact()— whethergetSelectedCount()is exact or a lower bound;truewhen the grid is not yet initializedgetSelectionDescriptor()— the selection as a serialisable object for a backend bulk command;nullwhen the grid is not yet initializedmaterializeSelectedRows(opts)—Promiseof every selected row, fetching the rest of the query under a select-all; resolves[]when the grid is not yet initializedsetSelectedKeys(keys)clearSelection()isRowSelected(row)— returnstrueif the row is currently selected;falsewhen the grid is not yet initialized
Fallback behavior when _grid is not initialised:
get...methods return empty arraysisRowSelected()returnsfalse- mutating methods no-op
10.2 Column Visibility API
hideColumn(key)showColumn(key)showAllColumns()getHiddenColumns()canHideColumn(key)
10.3 Column Freeze API
freezeColumn(key)unfreezeColumn(key)unfreezeAll()isFrozenColumn(key)getFrozenColumns()
10.4 Column Auto-Fit API
autoFitColumn(columnKey, options?)— sizes a single column to fit its content (header + visible body cells). Skipped ifcolumn.resizable === false. Options:persist(boolean, defaulttrue),mode('missingOnly'|'overwriteAll'),minWidth,maxWidth. Returnstrueif the column was resized.autoFitAllColumns(options?)— iterates left-to-right through all columns and auto-fits each visible, resizable column. Skips: the selection column, hidden columns, columns withresizable === false. Persists in a single batch at the end. Accepts the same options asautoFitColumn. Returnstrueif at least one column was resized.
See Column Resizing Implementation §14 for full details.
10.5 Export API
exportToExcel(options?)— exports grid data to an Excel (.xlsx) file and returns a Promise, rejected with a codedVanillaGridExportError(EXPORT_FAILED,EXPORT_TOO_LARGE,EXPORT_OVER_CAP,EXPORT_UNSUPPORTED,EXPORT_CANCELLED,EXPORT_IN_PROGRESS).scope: 'all'(the default) exports every row matching the query and'selected'every selected row, draining the DataManager when rows are outstanding;'loaded'exports the rows fetched so far. Throws if the grid is not initialized.
Key options: fileName, sheetName, scope ('all' | 'selected'), includeHeaders, columns (array of keys), formatCell callback, useGridColumnWidths (default true — mirrors grid pixel widths in Excel), useColumnTypeFormatting (default true — applies Excel numFmt and right-alignment based on col.type). See Export to Excel for the full list, progress and Cancel.
Column header text is always resolved as col.label || col.header || col.key. If the column has secondary header text (col.secondaryLabel), it is automatically appended: "Height [m]". Internal columns (__vgSelection__, __rowNumber__) are always excluded. Cell values are read via column._getValue(row) — the precompiled per-column accessor installed by setColumns() — so dotted column keys (address.city) and host-supplied column.valueGetter(row) are honored uniformly across rendering, sorting, and export.
10.6 Persistence Reset API
clearPersistedSettings()— wipes every grid-owned settings key from the active storage provider, resets the in-memory width/order/hidden/frozen caches, and re-applies the declarative columns so the grid returns to its initial layout. Always returnsPromise<void>(regardless of whether the underlying provider is sync or async). On completion the element dispatchesvn-grid-persistence-cleared; on failure it dispatchesvn-grid-errorwithphase: 'persistence-clear'. See Local Storage Settings Implementation §6.5 for the full contract.
10.7 Grid Attachment / Introspection
attachGridInstance(gridInstance)getGridElements()setTheme(theme)
setTheme(theme) normalizes input and updates/removes the theme attribute.
10.8 Viewport API for Followers
getViewportState()—undefinedwhen the grid is not yet initializedaddViewportListener(listener)— returns the function that removes itgetScrollTop()—0when the grid is not yet initializedsetScrollTop(scrollTop),scrollTopBy(delta),forwardWheel(event),forwardKeydown(event)— no-op when the grid is not yet initializedscrollToRow(key, options?)—falsewhen the grid is not yet initializedgetRenderEntry(index)—undefinedwhen the grid is not yet initializedgetRenderIndexByKey(key)—-1when the grid is not yet initialized
The logical scroll-by-delta method is scrollTopBy(), not scrollBy(): an element method of that name would hide the native Element.scrollBy() and could not be declared on a class extending HTMLElement (TypeScript rejects the override).
The element owns the listeners. addViewportListener() stores each listener in the element's own set, attaches it to the grid when one exists, and _attachViewportListeners() attaches the whole set to every grid the element gets afterwards: the one initializeGrid() creates (right after new VanillaGrid(), before any columns or rows reach it, so the first pass is reported) and one handed to attachGridInstance(). A listener added before initializeGrid() therefore starts firing once the grid exists, and one added to a live element keeps firing after the element is removed and re-inserted (§ 4): the old grid is destroyed with its registrations, and the rebuilt one receives the set again. The removal function drops the listener from the set and from the current grid.
The state, the listener rules and the scroll units are in Row Virtualization § 1.18.
10.9 Tree Rows API
isTreeMode(), expandRow(), collapseRow(), toggleRow(), expandAllRows(), collapseAllRows(), isRowExpanded(), isRowVisible(), getNearestVisibleAncestorKey(), revealRow(), getTreeRowInfo() and getTreeRowPositions() forward to the grid (Tree Rows § 1). Before the grid exists the boolean ones return false, getNearestVisibleAncestorKey(), getTreeRowInfo() and getTreeRowPositions() return undefined, and the two *AllRows() are no-ops.
11. Pending Data/Columns Buffering
setColumns(columns) is safe to call before initializeGrid(). Rows have no
public entry point: they reach the grid only through a DataManager, and every
load hands them to the private _deliverRows(rows), which buffers the same way.
Static rows go through StaticDataManager.
- If
_gridis ready,_deliverRows()/setColumns()call_grid.setRows(...)/_grid.setColumns(...)immediately. - If not, inputs are stored in
_pendingRows/_pendingColumns. - During
initializeGrid(), pending values are applied once and then cleared.
This lets host code stage data/columns without coordinating initialisation order.
Hold during an async persistence load. With an async storage provider
(storage-mode="remote"), initializeGrid() sets _awaitingPersistence and
leaves the buffers parked: the stored settings have not arrived yet, and laying
the grid out from the declaration would apply the declared defaults (sort,
hidden and frozen sets) and persist them over the stored values. While the flag
is set, _deliverRows() and setColumns() park their argument as they do before
initializeGrid(), and _getColumnDefs() returns the parked columns. When
grid.ready() resolves (on success or failure), the element clears the flag,
calls the grid's setColumns() once and then setRows(), re-applies the saved
widths and refreshes the header, and fires vn-grid-persistence-ready. The
grid therefore shows no columns and no rows until the settings arrive. A removal
during the load (§4.2) keeps the parked buffers for the rebuild, and the
superseded grid's ready() handler does nothing. See
Local Storage Settings §1.3.
12. Event Model
All app-facing events fire on the <vn-grid> host element with
bubbles: true, composed: true. This is the single well-known target that
hosts listen on — no matter which internal node originally triggered the
action. (Internal camelCase events such as selectionChanged and
rowDblClick may still be dispatched on the viewport for backward
compatibility, but are not part of the public API.)
12.1 Component Lifecycle Events
Emitted by _emitLifecycleEvent(name, detail) with bubbles: true, composed: true:
vn-grid-loadingvn-grid-loadedvn-grid-errorvn-grid-attribute-changedvn-grid-persistence-cleared— emitted afterclearPersistedSettings()finishes successfully
vn-grid-busy-changed is dispatched the same way but is not a fetch event, so it is listed
apart: it fires whenever isBusy() changes value, and only when it actually changes. Its detail
is { busy }.
The busy window is wider than the fetch window. The grid is also busy while a large sort, group
change or freshly-set dataset reorders behind the shimmer, and while an infinite-scroll page is
in flight — windows that open and close without a fetch, and that used to close in silence. The
routing is the callback pattern § 12.2 describes for selection: VanillaGrid#_notifyBusyChanged()
compares isBusy() against the last value it announced and calls the injected onBusyChanged,
which VanillaGridElement re-dispatches. Both writers of the two flags isBusy() reads —
setLoading() and _setLoadingMore() — go through it, so a nested window (a load-more raised
while a full load already holds the flag) stays one window rather than announcing two.
Use it for anything that tracks whether the grid is working: spinners, busy-gated controls,
"please wait" affordances. <vn-grid-toolbar> recomputes its own state on it, which is what
keeps state.busy from latching (see
vanilla-grid-toolbar/02-implementation.md
§ "State assembly").
vn-grid-export-state-changed is the export's counterpart, kept apart from the busy signal
because an export is not a load. isExporting() (on VanillaGrid, delegated by the element) is
true from the moment exportToExcel() accepts a call until its promise settles, whatever the
outcome. excel-export.feature.js dispatches the event from the grid container (bubbles: true, composed: true, detail { exporting }) each time that value changes, and never twice in a row
with the same value. <vn-grid-toolbar> recomputes on it and disables its interactive items for
the whole export (see
17-export-to-excel-implementation.md § "Progress, Cancel
and failures").
12.2 Selection Event
vn-grid-selection-changed is dispatched on <vn-grid> with bubbles: true, composed: true.
Routing (callback-based, no intermediate listener):
VanillaGridSelectionFeature.emitSelectionChanged()calls theonSelectionChanged(detail)function it received in its config.- That callback was provided by
VanillaGridElement.initializeGrid()and dispatchesvn-grid-selection-changeddirectly onthis.
Detail shape:
{ mode, selectionState, selectAllActive, selectedKeys, selectedCount, selectedCountExact, selectedRows }
12.3 Row Double-Click Event
vn-grid-row-dblclick is dispatched on <vn-grid> with bubbles: true, composed: true.
Routing (callback-based, no intermediate listener):
VanillaGrid.handlePointerDown()detects the double-click and callsthis._onRowDblClick(detail)if the callback is set.- That callback was provided by
VanillaGridElement.initializeGrid()and dispatchesvn-grid-row-dblclickdirectly onthis.
Detail shape: { row, rowIndex }
12.3a Command Event
vn-grid-command (VanillaGridEvents.COMMAND) is dispatched on <vn-grid> with bubbles: true, composed: true when a command column's button is activated (click, or Enter/Space on the focused button).
Routing is the same as the double-click's: handleClick() resolves the button by delegation and calls this._onCommand(detail), a callback initializeGrid() provides, which dispatches the event on this.
Detail shape: { command, columnKey, row, rowIndex, rowKey }. See Command Columns.
12.4 Load-More Failure Event
vn-grid-load-more-failed is dispatched on <vn-grid> with bubbles: true, composed: true.
Routing (callback-based, mirrors 12.2/12.3): initializeGrid() wraps the
host-supplied infiniteScroll.onLoadMoreError (if any) with a dispatcher, so
the event always fires and the host callback still runs. The grid keeps
retrying with an exponential backoff (1 s → 30 s cap) and never flips
hasMoreRows() off on failures — see
docs/vanilla-grid/05-infinite-scroll-implementation.md §5.4.
Detail shape: { error, failureCount, retryDelayMs }
12.5 Load-More Success Event
vn-grid-load-more-succeeded is dispatched on <vn-grid> with bubbles: true, composed: true, every time an infinite-scroll page fetch resolves and its rows are appended (even when the page is empty). appendRows() itself dispatches no event, and LOADED only covers the initial load / reload path, so this is the only signal for incremental, scroll-triggered pagination — consumers that need to reflect the running row count (e.g. <vn-grid-toolbar-status>) must listen here in addition to LOADED.
Routing (callback-based, mirrors 12.4): initializeGrid() wraps the
host-supplied infiniteScroll.onLoadMoreSuccess (if any) with a dispatcher, so
the event always fires and the host callback still runs.
Detail shape: { rows, loadedRowCount, hasMoreRows }
Double-click detection uses pointerdown timing (not native dblclick) so
it works reliably even when renderCell replaces cell DOM between clicks.
13. Practical Usage Pattern
const el = document.querySelector('vn-grid');
el.setDataManager(new ODataDataManager({
baseUrl: '/api/items',
countUrl: '/api/items/$count',
pageSize: 500
}));
// Key column is declared via is-key-column="true" on a <vn-grid-column> in the HTML.
// rowKeyField is only needed as an explicit override when no declarative key column exists.
el.initializeGrid({
infiniteScroll: { enabled: true },
selection: { mode: 'multiple' }
});
await el.reload();
el.addEventListener('vn-grid-selection-changed', (e) => {
console.log('Selected keys:', e.detail.selectedKeys);
});
14. Design Notes and Constraints
- No Shadow DOM by design: easier styling and theme integration with existing app CSS.
- Wrapper role only: rendering/virtualization/sorting logic remains in
VanillaGrid; the element composes and forwards. - DataManager-first loading model:
loadRowsAsync()requires a DataManager, ensuring a consistent async contract. - Idempotent markup creation:
_ensureMarkup()can be called repeatedly without duplicating DOM. - Safe pre-init API calls: pending buffers reduce ordering hazards in host code.