turbogrid
// global
const TG = window.turbogrid;
const { Grid, Util } = window.turbogrid;
// cjs
const TG = require("turbogrid");
const { Grid, Util } = require("turbogrid");
// esm
import TG from "turbogrid";
import { Grid, Util } from "turbogrid";
Creates a new grid instance for the specified container.
The container argument can be a CSS selector, a DOM element, or an options object that includes a container property.
//selector
const grid = new Grid(".container");
//or element
const container = document.querySelector(".container");
const grid = new Grid(container);
//or options with container
const grid = Grid({
container,
... other options
});
Methods
Sets the grid data. See the data structure section for details.
The data object reads columns, rows, rowsLength, and options. rowsLength is useful when the total row count is known before all rows are loaded.
grid.setData({
columns: [],
rows: []
});
Returns the current grid data object.
const data = grid.getData();
Loads data from a plain snapshot by stripping private tg_* fields and rebuilding normalized tree state for rows and columns.
grid.setDataSnapshot(data);
Returns a sanitized snapshot of a row or column item.
When keysSettings is omitted, private fields are removed. When keysSettings is provided, keys set to true are included explicitly and keys set to false are excluded.
const rowSnapshot = grid.getItemSnapshot(rowItem);
const rowSnapshot2 = grid.getItemSnapshot(rowItem, {
id: true,
name: true
});
Sets one or more grid options. See options for available settings.
Supports both setOption(optionKey, optionValue) and setOption(optionsObject).
//set multiple options
grid.setOption({
optionKey1: optionValue1,
optionKey2: optionValue2
});
//set single option
grid.setOption(optionKey, optionValue);
Returns the current option value for name, or the full options object when no name is provided.
Returns undefined for unknown keys.
//get all options
const options = grid.getOption();
//get single option
const optionValue = grid.getOption(optionKey);
Registers or overrides grid formatters.
Supports both setFormatter(type, handler) and setFormatter(formatterMap). Registered handlers run with the grid instance as this.
//set multiple formatters
grid.setFormatter({
string: function(value, rowItem, columnItem, cellNode) {
return value;
}
});
//set single formatter
grid.setFormatter("string", formatterHandler);
Built-in cell formatters: string, number, date, icon, blank, checkbox, tree, null
Built-in header formatter: header
Formatter signature:
function(value, rowItem, columnItem, cellNode) {
// value is formatted by null formatter
// get original value:
const originalValue = rowItem[columnItem.id];
const rowIndex = rowItem.tg_index;
const columnIndex = columnItem.tg_index;
// using default formatter returns:
const defaultFormatter = this.getDefaultFormatter("[formatter-name]");
return defaultFormatter(value + " new text", rowItem, columnItem, cellNode)
}
Demo Formatter
Returns the formatter function registered for the specified type, bound to the current grid instance.
const stringFormatter = grid.getFormatter("string");
Returns the built-in formatter function for the specified type.
Falls back to the built-in string formatter when the requested type is missing.
const treeFormatter = grid.getDefaultFormatter("tree");
Binds an event handler to the grid. See events for supported event types.
eventType can be a single event name, multiple names separated by spaces, or an object map of event names to handlers. Namespaced events such as onUpdated.demo are supported.
Use options such as { once: true } to control listener behavior.
grid.bind("onUpdated", function(e, d){
//console.log(d);
});
Demo Events
Binds a handler that runs once and is removed after the first trigger.
Accepts the same eventType formats as bind.
grid.once("onUpdated", function(e, eventData){
//console.log(eventData);
});
Removes previously bound event handlers from the grid.
Call without arguments to remove all handlers, with an event name or namespace to remove matching handlers, or with both eventType and handler to remove a specific binding.
grid.unbind();
grid.unbind("onUpdated");
grid.unbind("onUpdated", handler);
Triggers an event and calls all bound handlers with the provided event data.
Handlers receive the event object first and eventData as the second argument.
this.trigger(eventType, eventData);
Returns all supported event types.
const allEventTypes = grid.getAllEvents();
Demo Events
Schedules a render pass using the current data, options, and formatters.
Repeated calls in the same tick are merged, so render is safe to call after batched updates.
grid.render();
Forces a full rebuild of the grid structure and renders it again.
grid.rerender();
Recalculates the layout and optionally applies a new size.
Supports resize(), resize(width, height), and resize(styleMap) where styleMap is applied to the grid holder.
grid.resize();
grid.resize(600, 400);
Demo Resize
Destroys the grid instance and removes generated DOM, observers, and event bindings.
grid.destroy();
The rowIndex and columnIndex parameters support several input forms:
- If the parameter is a Number, the grid looks up the row or column by index. Negative indexes are supported, so -1 resolves to the last item.
- If the parameter is a String, the grid searches all items for a matching row or column id.
- If the parameter is an Object, the grid inspects these properties:
- If the object has a tg_index property, the grid looks up the row or column by index first.
- If the object has an id property of type String, the grid searches all items for a matching id.
const columnItem = grid.getColumnItem(columnIndex);
const columnItemById = grid.getColumnItemById("id_123");
const rowItem = grid.getRowItem(rowIndex);
const rowItemById = grid.getRowItemById("id_123");
const rowItem = grid.getRowItem(123);
const rowItem = grid.getRowItem("id_123");
const rowItem = grid.getRowItemBy("id", "id_123");
const rowItem = grid.getRowItemBy("key", "value");
Shows, hides, or customizes the built-in loading overlay.
loading can be plain content, a DOM node, a factory function that receives the loading container, or a default-loading options object such as { size, color, fast }.
grid.showLoading();
grid.hideLoading();
grid.setLoading("Loading ...");
grid.setLoading(function(container) {
return document.createElement("div");
});
Demo Show/Hide Loading
Shows or hides the interaction-blocking mask overlay.
Pass styleMap to override mask styles such as opacity or background color.
grid.showMask();
grid.showMask({
opacity: 0.3
});
grid.hideMask();
Demo Show/Hide Loading
Expands, collapses, or toggles all tree rows.
grid.expandAllRows();
grid.collapseAllRows();
grid.toggleAllRows();
Demo Row Collapse/Expand
Expands, collapses, or toggles a specific row.
If the target row is a group with no loaded subs yet, expandRow may trigger onRowSubsRequest so child rows can be loaded lazily.
grid.expandRow(rowIndex);
grid.collapseRow(rowIndex);
grid.toggleRow(rowIndex);
Demo Row Collapse/Expand
Expands rows up to the specified tree level.
grid.expandRowLevel(level);
Demo Row Collapse/Expand
Returns export-ready columns and rows with private fields removed, optionally filtered by keysSettings.
In keysSettings, true forces a key to be included and false excludes it.
const exportedData = grid.exportData();
const exportedData = grid.exportData({
the_key_need: true,
key_key_no_need: false
});
Demo Export
Replaces the child rows for the specified parent row.
Passing an array of subs updates the row tree immediately and marks the parent row as expanded.
const subs = [{name:"row1"},{name:"row2"}];
grid.setRowSubs(rowIndex, subs);
Demo Dynamic Load Subs
Replaces the current top-level columns and triggers a full rerender.
const columns = [{id:"name", name:"Name"}];
grid.setColumns(columns);
Replaces the current top-level rows with a new row list.
Use setRows when only the row tree changes. Use setData when columns or options also need to be replaced.
const rows = [{name:"row1"},{name:"row2"}];
grid.setRows(rows);
Demo Dynamic Set Rows
getRows and getColumns return the source top-level data.
A view index is the current visible order after filtering, collapsing, sorting, and column visibility changes.
getViewColumns(true) also includes visible group columns in the returned list.
const rows = grid.getRows();
const columns = grid.getColumns();
const viewRows = grid.getViewRows();
const viewColumns = grid.getViewColumns();
const viewRowItem = grid.getViewRowItem(0);
const viewColumnItem = grid.getViewColumnItem(0);
Adds a row or deletes one or more rows.
parent can be a row reference, row index, or row id. position inserts at a specific child index, and scrollTo defaults to true so the new row is brought into view.
grid.addRow({
id: "id1",
name: "row item"
});
grid.addRow(["Row 1", "Row 2"]);
grid.addRow(["Row 1", "Row 2"], parentIndex);
grid.addRow("Row Before","level_0", 0);
grid.deleteRow(2);
grid.deleteRow([1, 2]);
Demo Row Add/Delete
offset: values less than 0 move rows up, and values greater than 0 move rows down.
rowList can be a single row or a list of rows. The move is ignored when offset is 0 or when all visible rows are included.
grid.moveRowsToTop(["row_id1", "row_id2"]);
grid.moveRowsUp(["row_id1", "row_id2"]);
grid.moveRowsDown(["row_id1", "row_id2"]);
grid.moveRowsToBottom(["row_id1", "row_id2"]);
grid.moveSelectedRowsToTop();
grid.moveSelectedRowsUp();
grid.moveSelectedRowsDown();
grid.moveSelectedRowsToBottom();
grid.moveRows(["row_id"], -1);
grid.moveRows(["row_id"], -2);
grid.moveRows("row_id", 1);
Demo Row Move
Selects or clears all selectable rows.
In single-select mode, selectAll(true) is ignored.
grid.selectAll();
grid.selectAll(false);
Demo Row Select
Updates the selected state of one or more rows.
In multi-select mode, pass false as the only argument to clear all, pass false as the second argument to unselect specific rows, or pass an event with Shift pressed to select a range from the previous selection.
grid.setRowSelected(rowIndex);
grid.setRowSelected(rowIndex, false);
grid.setRowSelected(false);
Demo Row Select
getSelectedRow returns the first selected row or null.
getSelectedRows always returns an array sorted by selection order.
const selectedRow = grid.getSelectedRow();
const selectedRows = grid.getSelectedRows();
Demo Row Select
Sets whether the specified row is hovered.
grid.setRowHover(rowIndex, true);
grid.setRowHover(rowIndex, false);
Demo Frozen Middle
Sets a custom row state and toggles the CSS class tg-[state] on rendered row nodes.
grid.setRowState(rowIndex, "selected", true);
grid.setRowState(rowIndex, "warning", true);
grid.setRowState(rowIndex, "warning", false);
setSortColumn accepts the same input forms as getColumnItem.
Calling setSortColumn repeatedly with the same column toggles sortAsc. removeSortColumn clears the current sort state.
grid.setSortColumn(sortColumn);
grid.removeSortColumn();
Demo Row Sort
Updates a column width at runtime.
width is rounded to an integer, clamped to 0 or greater, and updates the column width, minWidth, and maxWidth together.
grid.setColumnWidth(columnIndex, width);
Demo Column Width Resize
Shows or hides one or more columns.
Accepts the same input forms as getColumnItem, including lists.
grid.showColumn(columnIndex);
grid.hideColumn(columnIndex);
grid.showColumn([1, 3]);
grid.hideColumn([1, 3]);
Demo Show/Hide Column
Adds a column or deletes one or more columns.
parent can be a column reference, column index, or column id. position inserts at a specific child index, and scrollTo defaults to true so the new column is brought into view.
grid.addColumn({
id: "id1",
name: "column item"
});
grid.addColumn(["Column 1", "Column 2"]);
grid.addColumn(["Column 1", "Column 2"], parentIndex);
grid.addColumn("Column Before","level_0",0);
grid.deleteColumn(2);
grid.deleteColumn([1, 2]);
Demo Column Add/Delete
Scrolls directly to the specified row, column, or cell.
scrollToLastColumn(end) skips the trailing blank filler column unless end is true.
grid.scrollToRow(rowIndex);
grid.scrollToColumn(columnIndex);
grid.scrollToCell(rowIndex, columnIndex);
Demo Scroll
Scrolls just enough to bring the target row, column, or cell into view.
grid.scrollRowIntoView(rowIndex);
grid.scrollColumnIntoView(columnIndex);
grid.scrollCellIntoView(rowIndex, columnIndex);
Demo Scroll
Sets or returns the current scroll positions.
grid.setScrollTop(200);
grid.setScrollLeft(200);
const st = grid.getScrollTop();
const sl = grid.getScrollLeft();
Demo Scroll
updateRow merges partial rowData into the existing row.
updateCell reads rowIndex and columnIndex using the normal row and column lookup rules. Omitting rowData or cellValue rerenders the existing data.
flushBody clears all cached row renders. flushSort clears the row cache used after sorting.
flushRow, flushRowFrom, flushColumn, flushColumnFrom, and flushCell use view indexes (tg_view_index), not source indexes.
grid.update();
grid.flushBody();
grid.flushSort();
grid.flushRow(viewRowIndex);
grid.flushRowFrom(viewRowIndex);
grid.flushColumn(viewColumnIndex);
grid.flushColumnFrom(viewColumnIndex);
grid.flushCell(viewRowIndex, viewColumnIndex);
grid.updateRow(rowIndex);
grid.updateRow(rowIndex, rowData);
grid.updateCell(rowIndex, columnIndex);
grid.updateCell(rowIndex, columnIndex, cellValue);
Demo Flush
Returns 0 when no vertical scrollbar is present; otherwise returns scrollbarSize when hasVScroll is true.
getScrollbarHeight()
Returns 0 when no horizontal scrollbar is present; otherwise returns scrollbarSize when hasHScroll is true.
const sbw = grid.getScrollbarWidth();
const sbh = grid.getScrollbarHeight();
Scroll view size equals scroll pane size minus scrollbar size.
const svw = grid.getScrollViewWidth();
const svh = grid.getScrollViewHeight();
Scroll pane size equals scroll view size plus scrollbar size.
const spw = grid.getScrollPaneWidth();
const sph = grid.getScrollPaneHeight();
Returns the number of visible columns by default. Pass true to include hidden columns.
const len = grid.getColumnsLength();
const totalLen = grid.getColumnsLength(true);
Returns the number of visible rows by default. Pass true to include collapsed or filtered rows.
const len = grid.getRowsLength();
const totalLen = grid.getRowsLength(true);
Returns the total rendered height of all rows.
const totalHeight = grid.getRowsHeight();
Returns the computed height of the specified row.
const rowHeight = grid.getRowHeight(rowIndex);
Returns the current visible row and column index ranges.
const viewport = grid.getViewport();
// { rows, columns }
Finds nodes inside the grid root with a CSS selector.
Pass container to limit the query to a specific node inside the grid.
const nodes = grid.find(".selector-name");
Returns the rendered DOM nodes for the specified row.
The return value is a Query collection, which is useful when the same row is rendered in multiple panes.
const rowNodes = grid.getRowNodes(rowIndex);
Returns a rendered cell node or resolves the raw cell value.
getCellValue returns rowItem[columnItem.id] before any formatter is applied.
const cellNode = grid.getCellNode(rowIndex, columnIndex);
const cellValue = grid.getCellValue(rowItem, columnItem);
Returns the header item node for the specified column.
Accepts the same input forms as getColumnItem.
const headerItemNode = grid.getHeaderItemNode(columnIndex);
Returns the header container node for the specified column.
Accepts the same input forms as getColumnItem.
const columnHeaderNode = grid.getColumnHeaderNode(columnIndex);
Iterates over each column or row and calls the provided callback.
The callback receives (item, index, parent) for each node in the tree.
grid.forEachColumn(function(column, index, parent) {
//
});
grid.forEachRow(function(row, index, parent) {
//
});
Returns whether the row can be selected under the current rules.
const rowItem = grid.getRowItem(rowIndex);
if (grid.isRowSelectable(rowItem)) {
console.log("selectable");
}
Returns whether the row is a leaf node.
Helper used by rowFilter and highlightKeywords to match and mark keywords.
columns should be a list of column ids, and keywords is split on whitespace before matching.
grid.setOption({
rowFilter: function(rowItem) {
return this.highlightKeywordsFilter(rowItem, ["name", "type"], "foo bar");
}
});
Registers a one-time handler for the next onUpdated event.
This is equivalent to a one-shot listener for onUpdated.
grid.onNextUpdated(function(e, eventData){
//console.log(eventData);
});
Data
[{
name: "item 1",
subs: [{
name : "item 2",
subs: [{
name : "item 3",
subs: [{
...
}]
}, ...]
}, ...]
}, ...]
const data = {
columns : [...],
rows : [...]
};
grid.setData(data);
See columnProps for available column fields.
const columns = [{
id:"c1",
type : "string",
name:"Column Name 1"
}, {
id : "c2",
type : "number",
name : "Column Name 2"
}, {
id: "c3",
name: "Column Name 3",
subs: [{
id: "c3_s1",
name: "Column Name 3-1"
}, {
id: "c3_s2",
name: "Column Name 3-2"
}]
}];
See rowProps for available row fields.
const rows = [{
id : "r1",
name : "Row Name 1",
c1 : "string value 1",
c2 : 1,
c3_s1 : "value 3 - 1",
c3_s2 : "value 1 - 2"
}, {
id : "r2",
type : "group",
name : "Row Name 2",
c1 : "string value 2",
c2 : "value 2",
c3_s1 : "value 3 - 1",
c3_s2 : "value 1 - 2",
subs : [{
id : "r3",
type : "holding",
name : "Row Name 3",
c1 : "string value 3",
c2 : 3,
c3_s1 : "value 3 - 1",
c3_s2 : "value 1 - 2"
}]
}];
Applies options from the data payload. These values take precedence over setOption.
const data = {
options : {
sortField : "name"
},
columns : columns,
rows : rows
};
grid.setData(data);
Supports lazy row loading when rows are not provided but the total row count is known.
const data = {
columns: columns,
rowsLength: 50000
};
grid.setData(data);
Demo Dynamic Load Rows
Events
| Event Type | Event Data | Example |
|---|---|---|
|
|
|
Demo Events
|
|
|
|
Demo Events
|
|
|
|
Demo Sort
|
|
|
|
Demo Column Add/Delete
|
|
|
|
Demo Events
|
|
|
|
Demo Row Add/Delete
|
|
|
|
Demo Events
|
|
|
|
Demo Dynamic Load Subs
|
|
|
|
Demo Row Drag
|
|
|
|
Demo Row Drag
|
|
|
|
Demo Row Move
|
|
|
|
Demo Events
|
|
|
|
Demo Row Select
|
|
|
|
Demo Events
|
|
|
|
Demo Events
|
|
|
|
Demo Events
|
|
|
|
Demo Touch
|
|
|
|
Demo Scroll
|
|
|
|
Demo Events
|
|
|
|
Demo Scroll
|
|
|
|
Demo Resize
|
|
|
|
Demo Resize
|
|
|
|
Demo Events
|
|
|
N/A |
Demo Flush
|
Lifecycle
| Phases | Sub Phases | Payload | Capacity | ||
|---|---|---|---|---|---|
| create |
Create styles and DOM structure inside the container.
Apply initial data.
Apply initial options.
Register initial formatters.
Bind initial event handlers.
|
low | loading APIs |
|
|
| render | init options | low | all APIs |
|
|
| render header | middle | ||||
| render body | render rows | middle | |||
| render cells | high | ||||
| update |
Update the grid body.
Update one or more rows.
Update one or more cells.
|
|
|||
| destroy | remove all | low | none |
|
|
tg
"tg" is the grid prefix and internal namespace.
Common CSS class names:
.tg-pane {}
.tg-body{}
.tg-row{}
.tg-cell{}
Common private properties:
//rowItem.tg_index
//rowItem.tg_level
//rowItem.tg_group
These private properties are removed when calling exportData() or getItemSnapshot().
Row Item Properties (rowItem.tg_*)
| Property | Type | Description |
|---|---|---|
| tg_index | Number | Global index of the row in the full data tree (including invisible rows). |
| tg_view_index | Number | Index of the row in the visible (view) list. Only set for visible rows. |
| tg_sub_index | Number | Index within the parent's subs array (includes invisible rows). |
| tg_list_index | Number | Index within the visible sub-list of the same parent. |
| tg_parent | Object | undefined | Reference to the parent row item. undefined for root-level rows. |
| tg_level | Number | Nesting level in the tree hierarchy. 0 for root-level rows. |
| tg_group | Boolean | true if the row has a subs array (is a group/parent node). |
| tg_subs_length | Number | Number of direct children in the row's subs array. |
| tg_frozen | Boolean | true if the row is in the frozen section. |
| tg_invisible | Boolean | true if the row was hidden by user via hideRow() or the invisible property. |
| tg_filtered | Boolean | true if the row was hidden by the rowFilter function. |
| tg_row_number | String | Number | The display row number (empty string if row number is not applicable). |
| tg_selected_index | Number | Sequential index indicating the order in which the row was selected. |
| tg_top | Number | Top position offset in pixels for rendering. |
| tg_height | Number | Actual rendered height of the row in pixels. |
Column Item Properties (columnItem.tg_*)
| Property | Type | Description |
|---|---|---|
| tg_index | Number | Global index of the column in the full column tree. |
| tg_view_index | Number | Index of the column in the visible (view) list. Only set for visible columns. |
| tg_sub_index | Number | Index within the parent group's subs array. |
| tg_list_index | Number | Index within the visible sub-list of the same parent group. |
| tg_parent | Object | undefined | Reference to the parent column group. undefined for top-level columns. |
| tg_group | Boolean | true if the column has a subs array (is a header group). |
| tg_subs_length | Number | Number of direct sub-columns in the group. |
| tg_frozen | Boolean | true if the column is in the frozen section. |
| tg_invisible | Boolean | true if the column was hidden by user via hideColumn() or the invisible property. |
| tg_width | Number | Actual rendered width of the column in pixels. |
| tg_left | Number | Left position offset of the column in pixels. |
| tg_height | Number | Height of the column header cell in pixels. |
| tg_layer | Number | Reverse level index for header layout (0 = bottom level). Used for grouped headers. |
Usage example:
grid.setFormatter({
string: function(value, rowItem, columnItem, cellNode) {
// access row properties
const rowIndex = rowItem.tg_index;
const level = rowItem.tg_level;
const isFrozen = rowItem.tg_frozen;
const isGroup = rowItem.tg_group;
// access column properties
const columnIndex = columnItem.tg_index;
const columnWidth = columnItem.tg_width;
return value;
}
});
grid.setOption({
rowFilter: function(rowItem) {
// frozen rows are always visible
if (rowItem.tg_frozen) {
return true;
}
return rowItem.name.includes(keywords);
}
});