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.
| Option | Type / default | Purpose |
|---|---|---|
| items | DataItem[] / [] | Mutable source objects shown as rows. |
| columns | ColumnOptions[] / inferred | Ordered column definitions. |
| rowHeight | number / 32 | Default row height in pixels. |
| columnWidth | number / 120 | Default column width in pixels. |
| rowHeaderWidth | number / 48 | Width of the row header panel. |
| columnHeaderHeight | number / 32 | Height of the column header panel. |
| overscanRows | number / 5 | Extra rendered rows around the viewport. |
| overscanColumns | number / 2 | Extra rendered columns around the viewport. |
| fastScrollThreshold | number / 1500 | Pixels per second at which scrolling is treated as fast. |
| allowMerging | AllowMerging / None | Enable body and/or header merging. |
| allowDragging | AllowDragging / None | Enable row and/or column reordering. |
| selectionMode | SelectionMode / CellRange | Choose single-cell, rectangular, row, or multi-range selection. |
| autoSizeRows | boolean / false | Measure visible cell content outside fast scrolling. |
| locale | string / browser locale | Locale 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.
| Field | Type | Meaning |
|---|---|---|
| binding | string (required) | Object key read and written for this column. |
| header | string | Header label; defaults to binding. |
| width | number | Initial pixel width. |
| dataType | DataType | Parser, formatter, and built-in editor choice; defaults to String. |
| format | string | String, number, or date format; see Formatting. |
| allowMerging | boolean | Merge identical neighboring body values vertically in this column. |
| readOnly | boolean | Prevent editing and skip this column during paste. |
| editor | (value, item, column) => HTMLElement | Custom 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
| Member | Description |
|---|---|
| new RapidGrid(host, options?) | host is an HTMLElement or CSS selector string. Throws if the host cannot be found. |
| hostElement | Original host HTMLElement. |
| collectionView | Data collection and mutation API. |
| rows / columns | RowCollection and ColumnCollection with indexed sizes. |
| cells / columnHeaders / rowHeaders / topLeftCells | The four GridPanel instances. |
| allowMerging | Mutable AllowMerging setting. |
| allowDragging | Mutable AllowDragging setting. |
| selectionMode | Mutable SelectionMode setting. |
| autoSizeRows | Mutable Boolean setting, off by default. |
| selection | Read-only copy of selected CellRange objects. |
Lookup and layout
| Method | Result |
|---|---|
| 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
| Method | Result |
|---|---|
| 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.
| Hook | Arguments / timing |
|---|---|
| onFormatItem | FormatItemEventArgs when a body or header element is bound. Use panel to distinguish panels. |
| onCellRecycling | FormatItemEventArgs before a body cell is released; unmount custom framework content here. |
| onBeginningEdit | CellEditEventArgs before an editor is allocated; cancelable. |
| onCellEditEnding | CellEditEventArgs before a value is written; cancelable and also used during paste. |
| onCellEditEnded | CellEditEventArgs after a value is written. |
| onSelectionChanging | CellRangeEventArgs before selection changes; cancelable. |
| onSelectionChanged | CellRangeEventArgs after selection changes. |
| onDraggedRow | DragEventArgs { from, to } after the source row moves. |
| onDraggedColumn | DragEventArgs { 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.
| Member | Description |
|---|---|
| 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
| Export | Values / meaning |
|---|---|
| DataType | String, Number, Date, Time, DateTime, DateRange, Boolean. |
| AllowMerging | None, 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. |
| AllowDragging | None, Columns, Rows, Both. |
| SelectionMode | None, Cell, CellRange, Row, RowRange, MultiRange. |
| DataItem | Record<string, unknown>. |
| DateRangeValue | { start: Date; end: Date }. |
| PanelKind | cells | 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.
| Type | Built-in behavior |
|---|---|
| String | Raw text, upper, or a mask:###-## pattern. |
| Number | Locale-aware input and output. Formats include n2 decimal, c0 USD currency, and p1 percent. |
| Date | Native date input. Tokens include yyyy, MM, dd. |
| Time | Native time input. Tokens include HH, hh, mm, ss, a. |
| DateTime | Native date-time input; date and time tokens may be combined. |
| DateRange | Two date inputs; stores { start: Date, end: Date } and requires start ≤ end. |
| Boolean | Checkmark 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']]