PUBLIC API / VERSION 0.1.0

API reference.

Every exported class, option, method, event, enum, and helper in the package. Indices are zero-based unless stated otherwise.

Quick start

Give the host a width and height, then construct the grid after the element mounts. The core uses browser DOM APIs and has no runtime framework dependency.

import { RapidGrid, DataType } from 'rapid-grid';
import 'rapid-grid/style.css';

const grid = new RapidGrid('#grid', {
  items: [{ name: 'Northstar', revenue: 12400 }],
  columns: [
    { binding: 'name', header: 'Account', width: 180 },
    { binding: 'revenue', header: 'Revenue', dataType: DataType.Number, format: 'c0' }
  ]
});

// On component cleanup:
grid.destroy();

The host must have a height. Importing style.css adds the supplied visual styling; layout positioning is handled by the core.

GridOptions

Pass this object as the optional second argument to new RapidGrid(host, options). Columns default to the keys of the first item when omitted.

OptionType / defaultPurpose
itemsDataItem[] / []Mutable source objects shown as rows.
columnsColumnOptions[] / inferredOrdered column definitions.
rowHeightnumber / 32Default row height in pixels.
columnWidthnumber / 120Default column width in pixels.
rowHeaderWidthnumber / 48Width of the row header panel.
columnHeaderHeightnumber / 32Height of the column header panel.
overscanRowsnumber / 5Extra rendered rows around the viewport.
overscanColumnsnumber / 2Extra rendered columns around the viewport.
fastScrollThresholdnumber / 1500Pixels per second at which scrolling is treated as fast.
allowMergingAllowMerging / NoneEnable body and/or header merging.
allowDraggingAllowDragging / NoneEnable row and/or column reordering.
selectionModeSelectionMode / CellRangeChoose single-cell, rectangular, row, or multi-range selection.
autoSizeRowsboolean / falseMeasure visible cell content outside fast scrolling.
localestring / browser localeLocale used for number formatting and parsing.

ColumnOptions

Each column binds to a key in a data item. Custom editors are DOM factories and should return an input, select, textarea, or a container holding one.

FieldTypeMeaning
bindingstring (required)Object key read and written for this column.
headerstringHeader label; defaults to binding.
widthnumberInitial pixel width.
dataTypeDataTypeParser, formatter, and built-in editor choice; defaults to String.
formatstringString, number, or date format; see Formatting.
allowMergingbooleanMerge identical neighboring body values vertically in this column.
readOnlybooleanPrevent editing and skip this column during paste.
editor(value, item, column) => HTMLElementCustom editor created when a cell begins editing.
const statusEditor = value => {
  const select = document.createElement('select');
  for (const label of ['New', 'Review', 'Done']) select.add(new Option(label, label));
  select.value = String(value ?? '');
  return select;
};

{ binding: 'status', header: 'Status', editor: statusEditor }

RapidGrid

Constructor and properties

MemberDescription
new RapidGrid(host, options?)host is an HTMLElement or CSS selector string. Throws if the host cannot be found.
hostElementOriginal host HTMLElement.
collectionViewData collection and mutation API.
rows / columnsRowCollection and ColumnCollection with indexed sizes.
cells / columnHeaders / rowHeaders / topLeftCellsThe four GridPanel instances.
allowMergingMutable AllowMerging setting.
allowDraggingMutable AllowDragging setting.
selectionModeMutable SelectionMode setting.
autoSizeRowsMutable Boolean setting, off by default.
selectionRead-only copy of selected CellRange objects.

Lookup and layout

MethodResult
getRow(index)Return a Row; throws for an unknown index.
getColumn(indexOrBinding)Return a Column by index or binding; throws if missing.
getCell(row, col)Return the cell's CellRange, including its merged span.
getCellElement(row, col)Return a mounted HTMLElement, or null for an offscreen cell.
hitTest(clientX, clientY)Return HitTestInfo for browser viewport coordinates.
scrollIntoView(row, col)Scroll until the indexed cell is visible.
refresh(full?)Rebuild the currently rendered panels and sizes; full is accepted for API compatibility.
invalidate()Request a full refresh.
autoSizeRow(index)Measure a currently rendered row and update its height.
autoSizeColumn(index)Measure a currently rendered column and update its width.
destroy()Detach listeners, observers, panels, and editor state.

Editing, selection, and clipboard

MethodResult
beginEdit(row, col)Start an inline editor; returns true if editing began.
commitEdit()Commit the active editor; returns false on failed validation.
cancelEdit()Discard the active editor.
select(range, add?, preserveAnchor?)Select a CellRange; returns false when cancelled or out of bounds. add adds a range in MultiRange mode.
copySelection()Return the latest selected rectangle as TSV text.
paste(text)Parse TSV into the selected top-left cell and return updated cell count. One value fills the selected rectangle. Invalid values throw before any updates.

Pointer drag, Shift-click, and Shift+Arrow extend a cell range. Ctrl/Cmd+C and Ctrl/Cmd+V use the browser clipboard when the grid has focus. Read-only columns are skipped during paste. The clipboard operations limit a request to one million cells.

Events

Each on… registration accepts (grid, args) and returns an unsubscribe function. A changing event can be cancelled by returning false or setting args.cancel = true.

HookArguments / timing
onFormatItemFormatItemEventArgs when a body or header element is bound. Use panel to distinguish panels.
onCellRecyclingFormatItemEventArgs before a body cell is released; unmount custom framework content here.
onBeginningEditCellEditEventArgs before an editor is allocated; cancelable.
onCellEditEndingCellEditEventArgs before a value is written; cancelable and also used during paste.
onCellEditEndedCellEditEventArgs after a value is written.
onSelectionChangingCellRangeEventArgs before selection changes; cancelable.
onSelectionChangedCellRangeEventArgs after selection changes.
onDraggedRowDragEventArgs { from, to } after the source row moves.
onDraggedColumnDragEventArgs { from, to } after a column moves.

Event argument shapes

FormatItemEventArgs = { panel, row, col, cellElement, dataItem }
CellEditEventArgs = { row, col, dataItem, oldValue, value, cellElement, cancel }
CellRangeEventArgs = { oldRanges, ranges, cancel }
DragEventArgs = { from, to }

Collections

CollectionView

Owns the mutable item array. items is a read-only view of its reference; mutations through the methods notify the grid.

MemberDescription
new CollectionView(items?)Construct from DataItem[].
items / length / at(index)Read current items, count, or a single item.
setItems(items)Replace the source array and notify listeners.
setValue(index, binding, value)Write one cell and notify listeners.
setValues(updates)Write an array of { index, binding, value } and notify once.
move(from, to)Mutate row order in the source array.
sort(binding, direction?, type?)Sort in place. Direction is asc or desc; type defaults to String.
onChange(listener)Subscribe to mutations; returns an unsubscribe function.

Row and RowCollection

new RowCollection(count, defaultHeight, onLayout) builds the indexed row state; new Row(index, collection) is also exported. grid.rows exposes length, defaultHeight, sizes: PrefixSum, get(index), setHeight(index, px), reset(count), and move(from, to). A Row exposes index, mutable height, header, and allowMerging. Change the header or merging flag, then call grid.refresh().

Column and ColumnCollection

new ColumnCollection(options, defaultWidth, onLayout) builds the indexed column state; new Column(options, index, collection) is also exported. grid.columns exposes length, defaultWidth, sizes: PrefixSum, get(indexOrBinding), toArray(), setWidth(index, px), and move(from, to). A Column exposes index, mutable width, binding, header, dataType, format, allowMerging, readOnly, and editor. Refresh after changing formatting or merge flags.

Ranges & panels

CellRange

new CellRange(row, col, row2?, col2?) normalizes both corners. It exposes row, col, row2, col2, isValid, contains(row, col), and intersects(otherRange).

GridPanel

new GridPanel(kind, hostElement) stores the panel kind and DOM host. The kind is one of cells, columnHeaders, rowHeaders, or topLeftCells.

HitTestInfo

hitTest returns { panel, row, col, nearRightEdge, nearBottomEdge }. Row or column is -1 when that coordinate does not belong to the panel.

MergeManager

new MergeManager(view, rows, cols, format, mode) accepts a CollectionView, RowCollection, ColumnCollection, (row, col) => string formatter, and () => AllowMerging mode callback. It exposes getCellRange(row, col), getHeaderRange(kind, index), and clear(). Most applications use grid.getCell() instead.

Enums & data types

ExportValues / meaning
DataTypeString, Number, Date, Time, DateTime, DateRange, Boolean.
AllowMergingNone, Cells, RowHeaders, ColumnHeaders, All. For body cells, set row.allowMerging to join values across a row or column.allowMerging to join values down a column.
AllowDraggingNone, Columns, Rows, Both.
SelectionModeNone, Cell, CellRange, Row, RowRange, MultiRange.
DataItemRecord<string, unknown>.
DateRangeValue{ start: Date; end: Date }.
PanelKindcells | columnHeaders | rowHeaders | topLeftCells.
VirtualWindow{ rowStart, rowEnd, colStart, colEnd, fast }.

Formatting and parsing

formatValue(value, column, locale?) produces display text. parseValue(text, column, locale?) parses edited and pasted values; invalid typed values throw. Empty input becomes null for most typed columns, false for Boolean, and an empty string for String.

TypeBuilt-in behavior
StringRaw text, upper, or a mask:###-## pattern.
NumberLocale-aware input and output. Formats include n2 decimal, c0 USD currency, and p1 percent.
DateNative date input. Tokens include yyyy, MM, dd.
TimeNative time input. Tokens include HH, hh, mm, ss, a.
DateTimeNative date-time input; date and time tokens may be combined.
DateRangeTwo date inputs; stores { start: Date, end: Date } and requires start ≤ end.
BooleanCheckmark display and checkbox editor; accepted pasted values include true/false, yes/no, 1/0, and ✓.

Virtualization building blocks

These classes are exported for advanced integrations. The grid constructs and manages them automatically for ordinary use.

PrefixSum

new PrefixSum(count, size) tracks row heights or column widths. Members: count, total, get(index), set(index, size), resize(count, defaultSize), move(from, to), offset(index), range(start, end), and indexAt(pixel). Offset lookup is indexed, and pixel-to-index lookup uses binary search. Size changes rebuild affected offsets lazily.

VirtualScroller

new VirtualScroller(viewport, rowSizes, colSizes, overscanRows, overscanCols, threshold, render) observes passive scroll events and calls render(window) on animation frames. Members: schedule(), refresh(), destroy(), and isFast. VirtualWindow gives inclusive row and column bounds plus a fast-scroll flag.

DOMPool

new DOMPool(container, className, onRelease?) reuses elements for keyed cells. Members: reconcile(keys, bind), get(key), forEachActive(callback), and clear(). The optional release callback runs before an active element is reused or removed.

Clipboard helpers

serializeTsv(rows) converts a matrix of strings to tab-separated text, quoting cells that contain tabs, line breaks, or quotes. parseTsv(text) reads that text back into a string matrix. Grid clipboard operations use these helpers internally.

import { serializeTsv, parseTsv } from 'rapid-grid';

const text = serializeTsv([['North', '12'], ['South', '24']]);
const rows = parseTsv(text); // [['North', '12'], ['South', '24']]