Skip to content

Data Table

A sortable, filterable table. It is a Filtered List whose items are rows, framed by a header whose sortable columns sort ascending, descending, then not at all. The Filtered List brings the search, the filter selects, the data view, the selection (selectable: true or 'single' for one row, 'multiple' for a checkbox column with a select all and bulkActions), onOpen, actions, and limit, and the List under it owns the rows' height, scrolling, and empty and loading states. It works on local rows or on a server that searches, filters, sorts, and pages.

Decision

When Use
Rows with columns a reader sorts and filters, such as activity, bans, or counts by country Data Table
A table paired with a World Map linkWorldMap
The Jellyfin item tables with thumbnails, status buttons, and bulk selection Paginated Table
A few fixed rows with no sorting Static Table

Usage

import { createDataTable } from './configurationpage?name=myplugin_stolon.js';

var table = createDataTable({
    columns: [
        { key: 'name', label: 'Country' },
        { key: 'people', label: 'People', align: 'end' },
        { key: 'last', label: 'Last', value: function (row) { return new Date(row.last); }, render: function (row) { return shared.formatRelativeTime(new Date(row.last)); } }
    ],
    rows: rows,
    rowKey: 'country',
    sort: { key: 'people', dir: 'desc' },
    search: { keys: ['name'], placeholder: 'Search countries' },
    filters: [{ name: 'type', label: 'Types', options: [{ value: 'failed', label: 'Failed' }] }],
    selectable: true,
    onSelect: function (row, key) { showDetail(row); }
});
view.querySelector('#tableHost').appendChild(table.element);

For server data, pass fetch(query) instead of rows. It gets { search, filters, sort, page, pageSize } and returns { Items, TotalCount } or an array. An answer that is no longer the latest is dropped.

The handle is { element, setRows, setSearch, setFilter, setFilterOptions, setSort, select, getSelected, getSelectedKeys, getSelectedRows, setSelectedKeys, clearSelection, onSelect, setHeight, getState, reload, edit, cancelEdit, getEditing, setColumnHidden, setColumnWidth, getColumnWidths, destroy }. onSelect(listener) adds a listener beside the option and returns a function that removes it. Under 'multiple', getSelectedKeys, getSelectedRows, and setSelectedKeys read and set the checked rows.

Rows can open into fields:

var table = createDataTable({
    columns: columns, rows: rows, rowKey: 'id',
    editable: {
        fields: [{ key: 'name', label: 'Name', required: true }, { key: 'limit', label: 'Limit', type: 'number', min: 0 }],
        onSave: function (row, values) { return shared.apiRequest('Rules/' + row.id, 'POST', values); }
    }
});

States and Modifiers

  • A column is sortable unless sortable: false. A click on its heading sorts ascending, again descending, and a third time not at all. The heading carries aria-sort and an arrow that shows only while it is sorted.
  • value(row) gives the value the column sorts and shows. render(row) draws the cell instead, as text or a node. Numbers sort as numbers and text in the reader's language, with blanks last.
  • align: 'end' right-aligns a column with even-width digits in a fixed track that the heading shares, so headings and values line up. width sets a column's grid track instead, a share of the width by default.
  • width: 'auto' sizes a column to its widest value, up to maxWidth (default six large sizes), and the other columns share what is left. Every column counts toward the table's least width, so columns wider than the table scroll sideways inside its frame instead of spilling out.
  • Each heading has a handle on its right edge that drags the column wider or narrower. A double-click or Enter on the handle fits the column to its widest value, and Alt with the left or right arrow resizes it from the keyboard. widthKey remembers each reader's widths in localStorage, and resizable: false leaves the handles out. setColumnWidth(key, width) sets pixels, 'fit', or null for the column's own width.
  • A cell too narrow for its text shows the full text on hover.
  • hidden: true starts a column hidden, and setColumnHidden(key, hidden) hides or shows its heading and its cells, which carry data-column with the column's key. The other columns share its width, and the compact layout counts only the shown columns.
  • When the table is too narrow for its number columns, it turns stolon-compact: number columns narrow, and a column with icon shows that icon in its heading in place of the label, which stays its tooltip and accessible name. A number column with its own width counts toward this too, so a column widened for a long heading still turns into its icon on a phone.
  • Each filter is a select whose first choice is "All {label}", with the label in sentence case, such as "All runs" for Runs. setFilter(name, values) sets it from code, such as from a map.
  • With selectable, a click, Enter, or Space on a row selects it, and again clears it. The row takes the accent wash with a leading bar. select(key) highlights a row picked elsewhere without reporting it.
  • pageSize shows that many rows and loads more as the list scrolls to its end. height and maxHeight work as a List's do.
  • With nothing matching it shows emptyText, "Nothing matches." by default.
  • editable adds an edit button at the end of each row, "Edit {value}" by editLabel, where the value is the first column. It opens the row into Repeater fields under its cells, with Save and Cancel. Save checks every field through the validation core, then calls onSave(row, values). A promise that fails keeps the row open with "Could not save." (failedText). Cancel and Escape close it and return focus to the edit button.
  • An open row stays open, with what was typed, while setRows or a fetch refreshes the rows. edit(key) opens a row from code, and getEditing() names the open one.

Gotchas

  • A cell's text is clipped with an ellipsis. Put long text in a column with more width.
  • rowClass(row, index) marks a row from its first draw, such as stolon-selected for a row picked elsewhere, which takes the table's selected look. It is the Filtered List's itemClass, so it follows every setRows and refresh. With selectable on, the selection owns stolon-selected, so give a picked row another name.

Reference

Generated from the code by scripts/build-docs.mjs. Edit the code, not this section.

createDataTable

function createDataTable<T = any>(options: DataTableOptions<T>): DataTableHandle<T>

A sortable, filterable table: a Filtered List whose items are rows, framed by a header whose sortable columns sort ascending, descending, then not at all. The Filtered List brings the search, the filter selects, the data view over local rows or a server fetch, and the List the rows sit in. With selectable a click or Enter on a row selects it, and again clears it, and onSelect reports it, so a map or a detail pane can follow. select(key) highlights a row picked elsewhere.

Option Type What it does
columns (required) DataTableColumn<T>[] array of { key, label, icon (a Material icon the heading shows in place of the label when the table is narrow), sortable (default true), align ('start', 'end', or 'center' for a narrow column such as a checkbox), width (a grid track, or 'auto' to size it to its widest value up to maxWidth while the other columns share what is left; default a share, or a fixed number column for end and center), maxWidth (the most an 'auto' column takes; default six large sizes), hidden (true starts it hidden; default false), value(row), render(row) } [required]
rows T[] | null local rows [optional]
fetch (query: DataQuery): Promise<PagedResult<T> | T[]> | PagedResult<T> | T[] function(query) returning a page { Items, TotalCount } or an array, for server data [optional]
rowKey string | ((row: T) => unknown); rowClass?(row: T, index: number): unknown; search?: { keys?: string[] the field or function that names a row (default 'id')
placeholder string
label string aria-label of the table (default 'Table')
Handle member Type
setRows (rows: T[] | null | undefined): void
setSearch (text: string): void
setFilter (name: string, values: string[] | null | undefined): void
setSort (key: string | null, dir?: 'asc' | 'desc'): void
select (key: unknown): void
getSelected (): string | null
getSelectedKeys (): string[]
getSelectedRows (): T[]
setSelectedKeys (keys: unknown[] | null | undefined): void
clearSelection (): void
setFilterOptions (name: string, options: FilteredListOption[] | null | undefined): void
Type What it is
DataTableColumn One column. value gives the sort and display value, and render draws the cell, else the value is shown as text. hidden starts it hidden. width 'auto' sizes it to its widest value, up to maxWidth.
DataTableFilter A filter shown as a select above the table. field is the row field it matches, and options its choices.
DataTableEditing Inline row editing. fields are Repeater fields read from the row by key, and onSave gets the row and the edited values, and may return a promise.
DataTableWidth A column width set by a drag, the keyboard, or a double-click: pixels, or 'fit' for the column's widest value.
Class What it looks like
stolon-data-table A sortable, filterable table, a Filtered List whose rows sit in a grid under a header of column headings
stolon-filtered-list.stolon-data-table A table spans its toolbar and its grid across its frame, where the Filtered List alone would center them
stolon-data-grid The header row and each body row share the column tracks, so headings and cells line up
stolon-data-heading.stolon-center A narrow centered column, such as a checkbox, its heading centered over its cells
stolon-data-sort A sortable heading, a button whose arrow shows only while the column is sorted, and turns over when descending
stolon-data-glyph A narrow table: number columns shrink, and a heading with an icon shows the icon in place of its label
stolon-data-heading.stolon-resizable A resizable heading, with a handle on its right edge that drags the column wider or narrower
stolon-data-row A body row at least a field tall, with a hover wash, and the accent wash with a leading bar while selected
stolon-data-cell.stolon-data-edit-cell The edit button's column, one row button wide
stolon-data-row.stolon-editing An open row's editor under its cells, spanning every column: its fields in a grid, a message, and Save and Cancel

Example

Example Code

<!-- title: Data Table -->
<div id="table"></div>
<script type="module">
const base = await window.__baseReady;
const rows = [
    { id: 1, time: '10:04', user: 'ada', type: 'Sign in', country: 'United States', result: 'OK' },
    { id: 2, time: '10:06', user: 'bob', type: 'Failed sign in', country: 'Germany', result: 'Wrong password' },
    { id: 3, time: '10:07', user: 'cy', type: 'Blocked', country: 'China', result: 'Banned address' },
    { id: 4, time: '10:12', user: 'dee', type: 'Sign in', country: 'United Kingdom', result: 'OK' }
];
const table = base.createDataTable({
    columns: [{ key: 'time', label: 'Time' }, { key: 'user', label: 'User' }, { key: 'type', label: 'Type' }, { key: 'country', label: 'Country' }, { key: 'result', label: 'Result', sortable: false }],
    rows,
    search: { placeholder: 'Search activity' },
    filters: [{ name: 'type', label: 'Types', options: [{ value: 'Sign in', label: 'Sign in' }, { value: 'Failed sign in', label: 'Failed sign in' }, { value: 'Blocked', label: 'Blocked' }] }],
    selectable: true
});
document.getElementById('table').appendChild(table.element);
</script>