1. Data Grid docs
  2. Developers

API reference

Every export, option, event and method of @8sheets/data-grid, with its type, default and a one-line example.

@8sheets/data-grid exports three things. Its TypeScript declarations ship with the package (table-view/index.d.ts); this page follows them. Everything a user can do in the grid, your code can do through the mounted grid's methods, and the interface takes the same paths, so the same events fire either way.

import { mountTable, remoteTableSource, VERSION } from '@8sheets/data-grid';
ExportTypeExample
mountTable(element, options?)Promise<MountedTable>const grid = await mountTable(el, { data, rowSelection: 'multiple' })
remoteTableSource(options)TableDataSourcedataSource: remoteTableSource({ queryUrl: '/q' })
VERSIONstringconsole.log(VERSION)

mountTable replaces the element's content with the grid and resolves once the first records are drawn. The element needs a height.

Options

Options marked live can change after mount with grid.setOptions({ … }). The others set the records: change them with setData(), setDataSource(), openFile() or enableEditing().

OptionTypeDefaultLiveExample
dataobjects, rows or columnsnonedata: [{ Region: 'East', Units: 2 }]
fieldsTableField[]inferred from data; required with dataSourcefields: [{ name: 'Units', type: 'number' }]
fileFilenonefile: input.files[0]
dataSourceTableDataSourcenonedataSource: remoteTableSource({ queryUrl: '/q' })
editablebooleanfalseeditable: true
transferColumnsbooleanfalsetransferColumns: true
titlestring'Table'yestitle: 'Orders'
storageKeystringnone: no saved views for data and remote recordsyesstorageKey: 'orders-v1'
language'en' | 'pl' | 'de' | 'fr' | 'es' | 'ja'the browser's, when the grid has it; else 'en'yeslanguage: 'de'
chromeTableChrome'auto'yeschrome: 'dark'
allowEditbooleanfalseyesallowEdit: true (adds Edit copy)
scrolling'continuous' | 'pages''continuous'yesscrolling: 'pages' (50 rows a page)
rowSelection'multiple' | 'single'none: no checkboxesyesrowSelection: 'multiple'
renderers{ [field]: (cell) => Node | string }noneyesrenderers: { Email: ({ text }) => text.toLowerCase() }
detailRenderer(record) => Node | stringnone: no detail arrowsyesdetailRenderer: (r) => 'Order ' + r.values.Order
detailMode'single' | 'multiple''single': one panel open at a timeyesdetailMode: 'multiple'
density'compact' | 'normal' | 'comfortable''normal' (34 px rows)yesdensity: 'compact' (28 px)
columnGroups{ caption, fields }[]none; fields' groupyescolumnGroups: [{ caption: 'Person', fields: ['Name', 'Role'] }]
contextMenuboolean | (items, context) => itemstrue: the grid's menuyescontextMenu: (items) => items.filter((i) => i.id !== 'export')
rowNumbersbooleanfalseyesrowNumbers: true
rowDragbooleanfalseyesrowDrag: true (a grip in each row)
rowDropbooleanfalseyesrowDrop: true (takes rows from other grids)
flashChangesbooleanfalseyesflashChanges: true
assistant(request) => Promise<{ state?, message? }>none: no Askyesassistant: (r) => askMyServer(r)
sharing{ create(file), revoke(id) }noneyessnapshot links through your own service
on…event handlersnoneyesonStateChange: (e) => save(e.state)

Give one of data, file or dataSource, or none for an empty grid that opens a file later. data takes an array of objects, an array of rows (the first row holds the field names when fields is left out) or an object of columns. sharing adds revocable snapshot links to Share and createShareLink(); the source download has a reference service in src/table-view/shares.js. These options have their own pages: master/detail (detailMode), themes (density), columns (columnGroups), context menu, pinned rows, moving and numbers (rowNumbers, rowDrag, rowDrop), live data (flashChanges) and assistant.

Events

Each event has an option of the same name with on in front (stateChange → onStateChange), and grid.on(name, handler) adds a handler and returns a function that removes it. The option's handler runs first. A cancellable event stops the grid's own action when a handler calls e.preventDefault() or returns false.

EventPayloadCancellableWhen
stateChange{ state, changed }The view state changed: search, filters, sort, groups, columns, totals
changeTableChangeA data change: an edit, paste, fill down, added or removed records, undo, redo, a calculated field, moved records or a transaction
selectionChangeTableSelection & { count? }The row selection changed
rangeChangeTableRange | nullThe selected cell range changed or was cleared
cellClick{ id, field, text, value, event }A data cell was clicked
cellDoubleClickthe sameyes: no editing or detailsA data cell was double-clicked
rowClick{ id, field, event }A record's row was clicked
rowDoubleClickthe sameyes, as cellDoubleClickA record's row was double-clicked
editStart{ id, field, value, text }yes: the editor stays closedThe cell editor is about to open
editEnd{ id, field, cancelled, value }The cell editor closed
beforeEdit{ cells, revision?, source }yes; a handler may change cells[i].valueValues are about to be stored
beforeAdd{ records, source }yesRecords are about to be added
beforeRemove{ ids, source }yesRecords are about to be removed
beforePaste{ id, field, lines, repeat, source }yesA paste is about to be applied
sourceLoad{ kind, title, fields }Records loaded: at mount, openFile, setData, setDataSource, setSource, openPivot, closePivot
viewportChange{ firstRow, lastRow, rowCount, exact, scrollTop, scrollLeft }The rows in view or the scroll position changed
loadStart{ task, label }A slow load began; the loading panel shows after 150 ms
loadProgress{ task, records, loaded, total, fraction }Progress of the load, at most ten times a second
loadEnd{ task, label, status, error?, records, duration }The load is done, cancelled or failed
rowMove{ ids, before, source }yes: nothing movesRecords are about to move: a drag of their grips, the menu, Alt+Up or Alt+Down, or moveRecords(). A server source moves them itself
rowDrop{ records, source }yes: nothing is addedRecords were dropped on this grid (rowDrop: true) from another one; source is that grid. An editable local grid then adds them
errorErrorAn action of the interface or a remote block request failed

TableChange is one of { action: 'edit', cells, revision? }, { action: 'paste', id, field, lines, repeat } (local) or { action: 'paste', cells, revision? } (remote), { action: 'add', records, ids }, { action: 'remove', ids }, { action: 'undo' }, { action: 'redo' }, { action: 'formula', name, formula }, { action: 'move', ids, before } or { action: 'transaction', add?, update?, remove?, ids } (ids are the IDs of the added records), and every change carries source: 'user' | 'api'. cells are { id, field, value }.

In the framework wrappers: React takes each event as a prop (onStateChange), Vue as a kebab-case listener (@state-change), Angular as an output of the event's name ((stateChange)), except change and error, which are gridChange and gridError in Angular. Through Vue's emit, only e.preventDefault() cancels; returning false doesn't.

JavaScript

const grid = await mountTable(el, { data, editable: true, onChange: (c) => console.log(c.action, c.source) });

// Refuse negative units, wherever the edit comes from.
const stop = grid.on('beforeEdit', (e) => {
  if (e.cells.some((c) => c.field === 'Units' && Number(c.value) < 0)) e.preventDefault();
});
// Later: stop();

React

<DataGrid
  options={options}
  onChange={(c) => console.log(c.action, c.source)}
  onBeforeEdit={(e) => {
    if (e.cells.some((c) => c.field === 'Units' && Number(c.value) < 0)) e.preventDefault();
  }}
/>

Vue

<DataGrid
  :options="options"
  @change="(c) => console.log(c.action, c.source)"
  @before-edit="(e) => { if (e.cells.some((c) => c.field === 'Units' && Number(c.value) < 0)) e.preventDefault(); }"
/>

Angular

// template: <eight-data-grid [options]="options" (gridChange)="changed($event)" (beforeEdit)="check($event)" />
changed(c: DataGridChange) {
  console.log(c.action, c.source);
}
check(e: { cells: { field: string; value: unknown }[]; preventDefault(): void }) {
  if (e.cells.some((c) => c.field === 'Units' && Number(c.value) < 0)) e.preventDefault();
}

Methods

The object mountTable resolves with has the 123 methods below; the wrappers' refs and the Angular component have 120 of them, all except destroy, on and off. Methods that change the view resolve once it is drawn again. Methods that need records throw "No table loaded." before any are, and every method throws after destroy().

Event handlers

MethodReturnsWhat it doesExample
on(type: K, handler: (event: TableEventMap[K]) => void | boolean)() => voidAdds an event handler; returns a function that removes it. The on… option of the event runs first.const stop = grid.on('stateChange', (e) => save(e.state));
off(type: K, handler: (event: TableEventMap[K]) => void | boolean)voidRemoves a handler added with on().grid.off('change', onChange);

Lifecycle and sources

MethodReturnsWhat it doesExample
destroy()voidRemoves the grid and ends its Worker and requests.grid.destroy();
openFile(file: File, options?: { delimiter?: string; textColumns?: (string | number)[]; chooseSource?: boolean })Promise<void>Opens a CSV or Excel file in place of the records. textColumns reads CSV columns as text ('A' or 0). With chooseSource (default true) a file with several sheets or tables shows the source chooser.await grid.openFile(file, { delimiter: ';', chooseSource: false });
setData(data: NonNullable<TableOptions['data']>, options?: { fields?: TableField[]; title?: string; editable?: boolean; storageKey?: string })Promise<void>Shows other local records. Options left out keep their mount values. The view starts over.await grid.setData(rows, { fields, title: 'Orders', editable: true });
setDataSource(dataSource: TableDataSource, options?: { fields?: TableField[]; title?: string; editable?: boolean; storageKey?: string })Promise<void>Shows records from another data source. fields is required unless given at mount.await grid.setDataSource(remoteTableSource({ queryUrl: '/api/orders' }), { fields });
getSources()TableFileSource[]The sheets and tables of the open file; empty for other sources.grid.getSources()[1].name
setSource(index: number, options?: { range?: string; header?: boolean })Promise<void>Shows another sheet or table of the open file. For a sheet, range (inside its used range) and header (default true: the first row holds the field names) choose the records.await grid.setSource(0, { range: 'A1:D40', header: true });
getSource()TableSourceInfoWhat the grid shows.if (grid.getSource().dirty) warn();
refresh(options?: { purge?: boolean })Promise<void>Draws the records again. For a remote source it fetches them again; purge (default false) also forgets the known total, as for a new query.await grid.refresh();

View state

MethodReturnsWhat it doesExample
getState()TableStateA copy of the view state.localStorage.view = JSON.stringify(grid.getState());
setState(state: Partial<TableState>)Promise<void>Replaces the whole view state; keys left out take their defaults. Scrolls to the top.await grid.setState(saved);
updateState(patch: Partial<TableState>)Promise<void>Changes some keys of the view state. Scrolls to the top.await grid.updateState({ search: 'east', sort: [] });
resetState()Promise<void>The view of a fresh source: every field in order, nothing filtered, sorted or grouped.await grid.resetState();
setSearch(text: string)Promise<void>Searches every visible field. '' clears it.await grid.setSearch('east');
setFilters(filters: TableFilterEntry[])Promise<void>Replaces the filters. Entries combine with AND; a group { any: [...] } meets one of its parts.await grid.setFilters([{ any: [{ field: 'Region', op: 'equal', value: 'East' }, { field: 'Units', op: 'gt', value: 10 }] }]);
addFilter(filter: TableFilterEntry)Promise<void>Adds a filter; filters combine with AND.await grid.addFilter({ field: 'Region', op: 'in', values: ['East', 'West'] });
clearFilters(field?: string)Promise<void>Removes every filter, or those of one field. The search stays.await grid.clearFilters('Region');
setQuickFilter(field: string, text: string)Promise<void>Sets a field's filter-row filter from typed text: '>100', '<=5', '10..20', '=42' for numbers and dates, words or '=word' for text. '' removes it. Works with the filter row shown or hidden.await grid.setQuickFilter('Units', '>30');
getDistinctValues(field: string, options?: { limit?: number })Promise<{ value: unknown; text: string; count: number }[]>A field's values among the records the other filters let through, with counts (as Pick values lists). Local records only. limit default 500.const regions = await grid.getDistinctValues('Region');
setSort(sort: TableSortKey[])Promise<void>Replaces the sort keys.await grid.setSort([{ field: 'Region' }, { field: 'Units', desc: true }]);
sortBy(field: string, options?: { desc?: boolean; add?: boolean })Promise<void>Sorts by a field alone (as clicking its heading), or with add: true keeps the other keys (as Shift-click). desc default false.await grid.sortBy('Revenue', { desc: true, add: true });
clearSort(field?: string)Promise<void>Removes every sort key, or one field's.await grid.clearSort();
setGroups(groups: TableGroup[])Promise<void>Replaces the groups, outermost first.await grid.setGroups([{ field: 'Region' }, { field: 'Product' }]);
groupBy(field: string, options?: { desc?: boolean })Promise<void>Adds a group level under the others.await grid.groupBy('Region');
clearGroups(field?: string)Promise<void>Removes every group level, or one field's.await grid.clearGroups('Region');
expandGroup(group: TableGroupRef)Promise<void>Expands a group.await grid.expandGroup(['East', 'Widget']);
collapseGroup(group: TableGroupRef)Promise<void>Collapses a group.await grid.collapseGroup(['East']);
expandAll()Promise<void>Expands every group, or every branch of a tree.await grid.expandAll();
collapseAll()Promise<void>Collapses every group at every level, or every branch of a tree.await grid.collapseAll();
setSummary(summary: TableSummary | null)Promise<void>Sets the summary under the records and in each group row, or null for none.await grid.setSummary({ field: 'Revenue', agg: 'sum' });
setTotalsRow(on: boolean)Promise<void>Shows or hides the totals row. Turning it on sums each number column that has no total yet.await grid.setTotalsRow(true);
setFilterRow(on: boolean)Promise<void>Shows or hides the filter row under the headings. Its filters stay either way.await grid.setFilterRow(true);

Tree

MethodReturnsWhat it doesExample
setTree(tree: TableTree | null)Promise<void>Shows the records as a tree, or with null as a list again.await grid.setTree({ parent: 'ManagerId', key: 'Id' });
expandTreeNode(id: TableRecordId)Promise<void>Expands a tree parent.await grid.expandTreeNode(7);
collapseTreeNode(id: TableRecordId)Promise<void>Collapses a tree parent.await grid.collapseTreeNode(7);

Pinned rows and moving records

MethodReturnsWhat it doesExample
getPinnedRows(){ top: TableRecordId[]; bottom: TableRecordId[] }The pinned records.grid.getPinnedRows().top
pinRows(ids: TableRecordId[], where?: 'top' | 'bottom')Promise<void>Pins records above (default) or below the scrolling ones. A server source needs pinnedRows.await grid.pinRows([42], 'bottom');
unpinRows(ids?: TableRecordId[])Promise<void>Unpins records, or every pinned record.await grid.unpinRows();
moveRecords(ids: TableRecordId[], before?: TableRecordId | null)Promise<boolean>Moves records before another record, or to the end with null; needs no sort, groups or tree. Fires rowMove; a server source only fires it. Resolves with false when a handler cancelled.await grid.moveRecords([42], 7);

Live data

MethodReturnsWhat it doesExample
applyTransaction(tx: TableTransaction)Promise<{ added: TableRecordId[]; updated: number; removed: number }>Applies the application's own changes to local records: updates, added and removed records. It works on read-only records and fields, skips undo, and flashes the changed cells with flashChanges.await grid.applyTransaction({ update: [{ id: 3, values: { Price: 101.5 } }] });
applyTransactionAsync(tx: TableTransaction)Promise<{ added: TableRecordId[]; updated: number; removed: number }>Collects transactions for 50 ms and applies them as one; each call resolves with the combined result.grid.applyTransactionAsync({ update });
flashCells(cells: { id: TableRecordId; field: string }[])voidFlashes cells, as a changed value does with flashChanges; for remote data the host changed.grid.flashCells([{ id: 'A-1', field: 'Price' }]);

Columns

MethodReturnsWhat it doesExample
getFields()TableFieldInfo[]The fields of the records.grid.getFields().map((f) => f.name)
getColumn(field: string)TableColumnState | nullA copy of one column's settings, or null.grid.getColumn('Units')?.width
setColumns(columns: TableColumnState[])Promise<void>Replaces the columns: order, visibility, pins, widths, formats, totals and rules.await grid.setColumns(grid.getState().columns.reverse());
setColumn(field: string, patch: Partial<Omit<TableColumnState, 'field'>>)Promise<void>Changes some settings of a column: hide or show, pin, width (48 to 800 px, null for automatic), number format, totals-row aggregate (null for none) and conditional rules. The scroll position stays.await grid.setColumn('Revenue', { pinned: true, width: 140, format: '#,##0.00', total: 'sum' });
moveColumn(field: string, before?: string | null)Promise<void>Moves a column before another one, or to the end.await grid.moveColumn('Revenue', 'Units');
autosizeColumn(field: string)Promise<number | null>Fits a column to its heading and loaded values; resolves with the width, or null.await grid.autosizeColumn('Customer');
addCalculatedField(name: string, formula: string)Promise<void>Adds a field computed from each record to an editable local copy, and shows it.await grid.addCalculatedField('Total', '=[@Units]*[@Price]');

Saved views (need a storageKey for data and remote sources; files have one)

MethodReturnsWhat it doesExample
getSavedViews(){ name: string; state: TableState }[]The saved views, in the order saved.grid.getSavedViews().map((v) => v.name)
saveView(name: string, state?: TableState)voidSaves the current view (or state) under a name, replacing one of that name.grid.saveView('East only');
restoreView(name: string)Promise<void>Shows a saved view.await grid.restoreView('East only');
deleteView(name: string)booleanDeletes a saved view; false when there was none.grid.deleteView('East only');

Pivot and chart

MethodReturnsWhat it doesExample
openPivot(pivot: TablePivot)Promise<void>Replaces the records with a pivot of the matching ones. closePivot() returns to them and their view.await grid.openPivot({ rowField: 'Region', columnField: 'Product', valueField: 'Revenue' });
chartRange()Promise<void>Charts the selected cells in a dialog (column, bar, line or pie): categories from the first text column, a series per number column.await grid.chartRange();
closePivot()Promise<void>Leaves a pivot for the records. Nothing happens outside a pivot.await grid.closePivot();
getChartData(field: string)Promise<{ label: string; value: number; text: string }[]>The pivot's top 20 values of a field by absolute value, as the Chart dialog draws them.await grid.getChartData('Total');

Paging, scrolling and focus

MethodReturnsWhat it doesExample
getPage(){ mode: 'continuous' | 'pages'; index: number; count: number | null; size: number | null }The page shown in 'pages' mode. count is null while a remote total is unknown.grid.getPage().index
setPage(index: number)Promise<void>Shows a page, from 0, in 'pages' mode.await grid.setPage(2);
setScrolling(mode: 'continuous' | 'pages')Promise<void>Switches between continuous scrolling and pages.await grid.setScrolling('pages');
getViewport()TableViewportThe view rows in the scroll area.const { firstRow, lastRow } = grid.getViewport();
scrollToRow(index: number)Promise<void>Scrolls a view row (a record or group row, from 0) into view. A remote row may still be loading.await grid.scrollToRow(5000);
scrollToRecord(id: TableRecordId)Promise<boolean>Scrolls a record into view; false when it doesn't match or sits in a collapsed group. A remote source scrolls to loaded records only and rejects others.await grid.scrollToRecord(42);
scrollToColumn(field: string)Promise<void>Scrolls a visible column into view.await grid.scrollToColumn('Revenue');
focusCell(id: TableRecordId, field: string)Promise<boolean>Scrolls to a cell and gives it keyboard focus; false as scrollToRecord.await grid.focusCell(42, 'Units');
getFocusedCell(){ id: TableRecordId; field: string } | nullThe cell with keyboard focus, or null.grid.getFocusedCell()?.field

Cell range (over drawn records)

MethodReturnsWhat it doesExample
getRange()TableRange | nullThe selected cells, or null.grid.getRange()?.values
setRange(range: { anchor: { id: TableRecordId; field: string }; focus?: { id: TableRecordId; field: string } })Promise<void>Selects cells from anchor to focus (default the anchor). It scrolls to the anchor when needed; both ends must then be drawn, which a range of up to a screenful of records is.await grid.setRange({ anchor: { id: 0, field: 'Units' }, focus: { id: 4, field: 'Price' } });
copyRange(options?: { headers?: boolean })Promise<string>Copies the range as tab-separated text (as Ctrl+C), with the headings first with headers, and resolves with it. Needs clipboard permission.await grid.copyRange({ headers: true });

Find and the context menu

MethodReturnsWhat it doesExample
openFind(text?: string)Promise<void>Opens the Find bar, with text in it. Local records.await grid.openFind('Acme');
closeFind()voidCloses the Find bar.grid.closeFind();
findNext(text?: string, options?: { back?: boolean })Promise<{ id: TableRecordId; field: string } | null>Moves to the next cell holding text (the previous one with back), across every matching record, and focuses it. Resolves with its record and field, or null when no cell holds it.const hit = await grid.findNext('Acme');
openContextMenu(id: TableRecordId, field: string)Promise<boolean>Opens a cell's context menu; false when it is turned off.await grid.openContextMenu(42, 'Units');

Row selection (needs rowSelection)

MethodReturnsWhat it doesExample
getSelection()TableSelectionThe selected records.const sel = grid.getSelection();
setSelection(selection: TableSelection)Promise<void>Replaces the selection.await grid.setSelection({ all: false, ids: [1, 2] });
selectRecords(ids: TableRecordId[], selected?: boolean)Promise<void>Selects (or with selected: false clears) some records, keeping the others.await grid.selectRecords([7, 9]);
selectAll()Promise<void>Selects every matching record.await grid.selectAll();
clearSelection()Promise<void>Clears the selection.await grid.clearSelection();
getSelectedIds()Promise<TableRecordId[]>IDs of the selected records that match the current view, in display order. A remote source can't list "all matching records"; this rejects then, and the host resolves getSelection() on its server.const ids = await grid.getSelectedIds();

Record details and master/detail

MethodReturnsWhat it doesExample
openRecordDetails(id: TableRecordId)Promise<void>Opens a record's details dialog (where an editable record can be changed or removed).await grid.openRecordDetails(42);
openDialog(name: TableDialog, options?: { field?: string })Promise<void>Opens one of the grid's dialogs, as its toolbar does. field preselects the field of 'filter' and is required for 'conditionalFormatting'. Rejects when the dialog doesn't apply (e.g. 'chart' outside a pivot).await grid.openDialog('filter', { field: 'Region' });
closeDialog()booleanCloses the open dialog or menu; false when none was open.grid.closeDialog();
expandRecord(id: TableRecordId)Promise<boolean>Expands a record's detail panel (needs detailRenderer), closing any other unless detailMode is 'multiple'; false as scrollToRecord.await grid.expandRecord(42);
collapseRecord(id?: TableRecordId)booleanCloses a record's detail panel, or every panel; false when none was open.grid.collapseRecord();
getExpandedRecord()TableRecordId | nullThe record whose detail panel opened last, or null.grid.getExpandedRecord()
getExpandedRecords()TableRecordId[]The records whose detail panels are open, in the order they opened.grid.getExpandedRecords()

Editing

MethodReturnsWhat it doesExample
isEditable()booleanWhether edits are accepted now.grid.isEditable()
enableEditing()Promise<void>Makes an editable copy of read-only local records, as the Edit copy button. Needs allowEdit (or editable); rejects for a remote source and in a pivot.await grid.enableEditing();
setCellValue(id: TableRecordId, field: string, value: unknown)Promise<boolean>Stores a value in a cell. Resolves with false when a beforeEdit handler cancelled it. Rejects for a read-only view, a read-only, computed or hidden field, or a value a field rule refuses.await grid.setCellValue(42, 'Units', 12);
updateRecords(updates: { id: TableRecordId; values: Record<string, unknown> }[])Promise<boolean>Stores values in several records as one change and one undo step.await grid.updateRecords([{ id: 1, values: { Units: 3, Price: 9.5 } }]);
addRecords(records: Record<string, unknown>[])Promise<TableRecordId[] | null>Adds records to an editable local copy as one undo step, and resolves with their IDs (null when a beforeAdd handler cancelled it). Field rules and required fields apply to each.const [id] = await grid.addRecords([{ Customer: 'Acme', Units: 5 }]);
removeRecords(ids: TableRecordId[])Promise<boolean>Removes records from an editable local copy as one undo step.await grid.removeRecords([42]);
paste(data: string | unknown[][], options?: { id?: TableRecordId; field?: string; repeat?: number })Promise<boolean>Pastes tab-separated text (or rows of values) from a cell rightwards and down, over matching records in view order; repeat (default 1) repeats the rows. The start defaults to the range's top-left cell.await grid.paste('3\t9.5\n4\t10', { id: 0, field: 'Units' });
fillDown()Promise<boolean>Copies the range's first record into the records below it, as Ctrl+D. Local records.await grid.fillDown();
undo()Promise<boolean>Undoes the last change of an editable local copy; false when there is none.await grid.undo();
redo()Promise<boolean>Redoes the last undone change; false when there is none.await grid.redo();
canUndo()booleanWhether undo() has a change to undo (always false for a remote source).undoButton.disabled = !grid.canUndo();
canRedo()booleanWhether redo() has a change to redo.redoButton.disabled = !grid.canRedo();
startEdit(id: TableRecordId, field: string, options?: { text?: string })Promise<boolean>Opens the cell editor on a cell, scrolling to it; text replaces the value, as typing does. False when the record isn't in the view or an editStart handler cancelled.await grid.startEdit(42, 'Units');
stopEdit(options?: { cancel?: boolean })Promise<boolean>Closes the cell editor: saves its value, or with cancel drops it. False when no editor was open or the value was refused (the editor then stays open with the reason).await grid.stopEdit({ cancel: true });
getEditingCell(){ id: TableRecordId; field: string } | nullThe cell being edited, or null.grid.getEditingCell()

Export and sharing

MethodReturnsWhat it doesExample
exportResults(format: TableFormat, options?: { selected?: boolean; layout?: boolean })Promise<Blob>The matching records and visible columns as a file, or with selected: true only the selected ones among them.const blob = await grid.exportResults('xlsx');
download(format: TableFormat, options?: { selected?: boolean; fileName?: string; layout?: boolean })Promise<void>Exports and saves the file through the browser. fileName default: the title and record count.await grid.download('csv', { fileName: 'orders.csv' });
createShareLink()Promise<{ id: string; url: string }>Publishes the matching records as an XLSX copy through the sharing option.const { url } = await grid.createShareLink();
revokeShareLink()Promise<boolean>Revokes the last link createShareLink() made; false when there was none.await grid.revokeShareLink();

Loading

MethodReturnsWhat it doesExample
isLoading()booleanWhether a load runs now (a file, source, records, a remote first block or a pivot).spinner.hidden = !grid.isLoading();
cancelLoad()booleanCancels the load in progress, as its Cancel button does; false when none runs or it can't be cancelled. The records shown before stay as they were, and the call that started the load rejects with an AbortError.grid.cancelLoad();

Appearance and options

MethodReturnsWhat it doesExample
setChrome(chrome: TableChrome)voidChanges the theme.grid.setChrome('dark');
getChrome()TableChromeThe theme in use.grid.getChrome() === 'dark'
setDensity(density: 'compact' | 'normal' | 'comfortable')Promise<void>Changes the row height: 'compact', 'normal' or 'comfortable'.await grid.setDensity('compact');
getDensity()'compact' | 'normal' | 'comfortable'The row height in use.grid.getDensity()
setLanguage(language: string)Promise<void>Changes the interface language: 'en', 'pl', 'de', 'fr', 'es' or 'ja'.await grid.setLanguage('de');
getLanguage()stringThe interface language in use.grid.getLanguage()
setOptions(options: TableLiveOptions)Promise<void>Changes live options and event handlers. Options that set the records (data, fields, file, dataSource, editable, transferColumns) reject: use setData(), setDataSource(), openFile() or enableEditing().await grid.setOptions({ rowSelection: 'multiple', onChange: save });

Assistant and state checks

MethodReturnsWhat it doesExample
askAssistant(prompt: string)Promise<{ state: Partial<TableState> | null; message: string }>Sends words to the assistant option and applies the state it answers with, once checked. Resolves with the state applied (or null) and the assistant's message.await grid.askAssistant('revenue by region, largest first');
getStateSchema()Record<string, unknown>A JSON Schema of the view state with this grid's field names, for a language model.grid.getStateSchema()
validateState(state: Partial<TableState>)string[]The problems of a state (or some keys of one) against the fields: unknown keys, fields and conditions. Empty when sound.grid.validateState(saved)

Reading records

MethodReturnsWhat it doesExample
getRecords(options?: { offset?: number; limit?: number })Promise<{ total: number | null; records: TableRecord[] }>Matching records in display order (groups don't count, collapsed ones included), from offset (default 0), at most limit (default 100, up to 10000). total is the number of matching records, or null while a remote source hasn't reported it. A remote source is queried through its query; grouped, it rejects.const { records } = await grid.getRecords({ offset: 0, limit: 500 });
getRecord(id: TableRecordId)Promise<TableRecord>One record with every field. A remote record comes from the loaded rows (the columns on screen) or the source's detail (display text only), and otherwise rejects.const order = await grid.getRecord(42);
getCell(id: TableRecordId, field: string)Promise<{ value: unknown; text: string }>A cell's value and display text.const { value, text } = await grid.getCell(42, 'Revenue');
getCounts()TableCountsRecord and row counts of the result.grid.getCounts().matches
getTotals()TableTotalsThe summary and totals-row values over every matching record, as display text.grid.getTotals().totals.Revenue

Types

TableField

PropertyTypeExample
namestringname: 'Units'
captionstringcaption: 'Units sold'
type'any' | 'number' | 'string' | 'date' | 'boolean'type: 'number'
formatExcel number formatformat: '#,##0.00'
formulastructured-reference formulaformula: '[@Units]*[@Price]'
readOnlybooleanreadOnly: true
editableboolean, for server sourceseditable: true
requiredbooleanrequired: true
validator{ type, operator, min, max, items, message, errorStyle }validator: { type: 'list', items: ['A', 'B'] }
editorTableEditor: 'text' | 'number' | 'date' | 'checkbox' | 'select' | 'multiselect' | 'textarea'editor: 'multiselect'
options(string | number)[]: the values a select suggests or a multiselect listsoptions: ['East', 'West']
groupstring: the band over the headinggroup: 'Person'

Without editor, a field with options edits with a select, a boolean with a check box, a date with a date picker and a number with a number input; see Editing.

getFields() and the sourceLoad event report fields as TableFieldInfo: { name, caption?, type?, format?, editable?, options?, required?, editor?, group? }, where editable says whether edits are accepted now and options holds the host's options or a list rule's items.

TableState

PropertyTypeExample
columnsTableColumnState[], display order[{ field: 'Units', width: 90 }]
searchstring'acme'
filtersTableFilterEntry[]: conditions and { any } or { all } groups[{ field: 'Units', op: 'gt', value: 5 }]
sort{ field, desc? }[][{ field: 'Date', desc: true }]
groups{ field, desc? }[][{ field: 'Region' }]
collapsedstring[], group paths toggled away from the default[]
collapseLevelnumber: groups at this level and deeper start collapsed1
total{ field, agg } | null: the summary{ field: 'Revenue', agg: 'sum' }
totalsRowbooleantrue
filterRowbooleantrue
treeTableTree | null{ parent: 'Manager', key: 'Id', rollups: [{ field: 'Salary', agg: 'sum' }] }
treeCollapsedTableRecordId[]: tree parents shown collapsed[7, 12]
pinnedRows{ top?, bottom? }: IDs kept above or below the scrolling records{ top: [42] }

Without collapseLevel, collapsed lists the collapsed groups; with it, collapsed lists the groups opened at that level and deeper.

TableColumnState

PropertyTypeExample
fieldstring'Revenue'
hiddenbooleantrue
pinnedbooleantrue
widthnumber, 48 to 800140
formatExcel number format'#,##0'
total'sum' | 'average' | 'min' | 'max' | 'count' | null'sum'
rulesTableColumnRule[][{ type: 'bar' }]
captionstring: the heading in this view'Qty'
sparkline{ type?: 'line' | 'column' | 'winloss', fields? }{ type: 'line', fields: ['Jan', 'Feb', 'Mar'] }

Other types

TypeShapeSee
TableColumnRule{ type: 'bar', color? }, { type: 'scale', colors? } or { type: 'value', op, value, value2?, style?, color?, background? }Conditional formatting
TableFilter{ field, op, value?, value2?, values?, percent?, quick?, text? }Search and filters
TableFilterEntrya TableFilter, { any: TableFilterEntry[] } or { all: TableFilterEntry[] }Search and filters
TableTree{ parent, key?, rollups? } or { level, rollups? }; rollups are { field, agg? }Tree data
TableTransaction{ add?, update?: { id, values }[], remove? }Live data
TableMenuItem{ id?, label, action, icon?, disabled?, checked?, shortcut? } or { separator: true }Context menu
TableMenuContext{ id, field, value, text, range }Context menu
TableAssistantRequest{ prompt, state, fields, schema, language }Assistant
TableRowMoveEvent{ ids, before, source }, cancellablePinned rows, moving and numbers
TableRowDropEvent{ records, source }, cancellablePinned rows, moving and numbers
TableEditor'text' | 'number' | 'date' | 'checkbox' | 'select' | 'multiselect' | 'textarea'Editing
TableSummary{ field, agg }, agg one of sum, average, min, max, count, distinctSorting and grouping
TableSelection{ all: false, ids } or { all: true, except }Row selection
TableRange{ anchor, focus, ids, fields, values }Row selection
TableRecord{ id, values, raw }: display text and value of each fieldRecipes
TableDetailRecord{ id, values, raw } of the columns on screenMaster/detail
TablePivot{ rows?, columns?, values? }, or the short form { rowField, columnField?, valueField, agg? }Pivot reports
TablePivotValue{ field, agg?, showAs? }; showAs one of normal, percentOfTotal, percentOfCol, percentOfRow, runTotal, rankDescending, rankAscending, indexPivot reports
TableCounts{ matches, sourceCount, count, exact }
TableTotals{ summary, totals } as display textTotals
TableSourceInfo{ kind, title, editable, dirty, fileName?, index?, range?, header? }Local data
TableFileSource{ index, name, range, whole, header }Local data
TableViewport{ firstRow, lastRow, rowCount, exact, scrollTop, scrollLeft }
TableDialog'filter', 'sort', 'group', 'summary', 'columns', 'views', 'pivot', 'chart', 'export', 'share', 'calculatedField', 'addRecord', 'source', 'conditionalFormatting', 'sparkline', 'tree', 'find', 'assistant'
TableChromea named skin or { base?, tokens? }Themes
TableFormat'xlsx' | 'csv' | 'pdf'Export

Data sources

TableDataSource

MemberTypeExample
query(request)(TableQuery) => Promise<TablePage>required
update(request)({ state, revision, cells }) => Promise<{ revision }>for editing
exportResults(request)({ state, format, signal?, selection? }) => Promise<Blob>for Export
detail(request)({ id, state, signal }) => Promise<{ field, value }[]>for the record dialog
formatsTableFormat[]['xlsx', 'csv']
selectionExportbooleantrue when exportResults honours selection
pinnedRowsbooleantrue when pages answer state.pinnedRows with pinned
pivot(request)({ state, spec, signal }) => Promise<{ fields, rows }>for Pivot on the server

TableQuery

{ state, offset, limit, columnOffset, columnLimit, signal }. The grid asks for blocks of 100 rows at offsets that are multiples of 100.

TablePage

PropertyTypeRequired
offsetnumberyes
rowsrecords { id, values, raw? } or group rows { group, path, level, collapsed, summary }yes
columnsstring[]yes
summarystringyes, may be empty
count, matches, sourceCountnumberno, while unknown
totalsRecord<field, string>for the totals row
statsRecord<field, { min, max }>for bars and colour scales
revisionstring | numberfor editing
columnOffset, columnCount, collapsednumber, number, string[]no
treeCollapsed(string | number)[]: the collapsed tree parentsfor a tree
pinned{ top, bottom }: the pinned records as rows { id, values, raw? }with pinnedRows

A record row may also carry level, hasChildren and collapsed (for a tree), number (its place among the matching records, for row numbers) and series (the values of sparkline columns that draw other fields, by column field).

See Remote data for a full request and answer.

remoteTableSource options

OptionTypeDefaultExample
queryUrlstringrequired'/api/orders/query'
exportUrlstringnone: no Export'/api/orders/export'
detailUrlstringnone'/api/orders/detail'
updateUrlstringnone: read-only'/api/orders/update'
headersHeadersInit | () => Promise<HeadersInit>noneasync () => ({ Authorization: token() })
credentialsRequestCredentials'same-origin''include'
formatsTableFormat[]['xlsx', 'csv']['csv']
selectionExportbooleanfalsetrue
pivotUrlstringnone: no server pivots'/api/orders/pivot'
pinnedRowsbooleanfalsetrue

Each request is a POST with a JSON body. HTTP 409 from the update endpoint means a stale revision; any other error status fails the request.