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:

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:

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:

attributeChangedCallback(name, oldValue, newValue) behavior:

  1. Returns immediately when value is unchanged.
  2. Special-cases theme: mirrors to dataset.theme.
  3. Special-cases tree-parent-field and tree-column once the grid exists (above).
  4. Emits vn-grid-attribute-changed with { 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:


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

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:

  1. Ensures markup exists (_ensureMarkup()).
  2. Throws if window.VanillaGrid is missing.
  3. Merges provided options into _gridOptions via setGridOptions.
  4. Destroys previous _grid instance if present.
  5. Re-parses declarative columns and stages them (setColumns).
  6. 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:

  1. _gridOptions.sorting.onSort
  2. 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 no handleSort)

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

A host-supplied infiniteScroll.onLoadMore or sorting.onSort is never replaced.

7.3 Post-Construction Steps

After new VanillaGrid(mergedOptions):

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:

  1. re-applies the manager-scoped init options: setWorkerOptions() with the stored dataLoading.useWorker / workerThreshold, and, unless the host set infiniteScroll.pageSize, the grid's page size from getPageSize();
  2. carries the query state over from the previous manager (skipped on a first attach, when there is none):
    • the filter model: previous.getColumnFilters() into setColumnFilters(), plus any filterValueGetters, then the header filter icons are re-synced;
    • the search term: previous.getSearchTerm() into setSearchTerm();
    • the sort: the grid's getSortState() into handleSort(column, direction, sortState), with nulls when no sort is active. Skipped when the host supplied sorting.onSort, which owns the sort.

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:

  1. await this.ready() — wait for persisted settings to be applied
  2. Abort the previous load's signal and create this load's AbortController (_loadController); stamp the call with _loadGeneration (last-wins)
  3. Create context via _createContext(options) (used for lifecycle events)
  4. Emit vn-grid-loading (phase: 'rows')
  5. rows = await dm.fetchRows({ signal }) — the grid-owned signal is the only argument and the only cancellation mechanism (the grid never calls a manager cancel()); all other config is internal to the DataManager
  6. Optional transform: rows = await dm.transformRows(rows) if provided
  7. _deliverRows(rows) to grid (private; parks the rows while _awaitingPersistence is set)
  8. Optional post-hook: await dm.onRowsLoaded(rows)
  9. Emit vn-grid-loaded with rows
  10. On error: an AbortError or a superseded generation returns [] silently; otherwise clear the loading state and replace the skeleton body (setLoading(false) leaves the skeletons for a setRows() 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 emit vn-grid-error and 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:

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

Fallback behavior when _grid is not initialised:

10.2 Column Visibility API

10.3 Column Freeze API

10.4 Column Auto-Fit API

See Column Resizing Implementation §14 for full details.

10.5 Export API

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

10.7 Grid Attachment / Introspection

setTheme(theme) normalizes input and updates/removes the theme attribute.

10.8 Viewport API for Followers

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.

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

  1. VanillaGridSelectionFeature.emitSelectionChanged() calls the onSelectionChanged(detail) function it received in its config.
  2. That callback was provided by VanillaGridElement.initializeGrid() and dispatches vn-grid-selection-changed directly on this.

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

  1. VanillaGrid.handlePointerDown() detects the double-click and calls this._onRowDblClick(detail) if the callback is set.
  2. That callback was provided by VanillaGridElement.initializeGrid() and dispatches vn-grid-row-dblclick directly on this.

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