Skip to content

Latest commit

 

History

History

README.md

@vates/data-table-vanilla

npm node bundle size License: MIT

Vanilla JS adapter for data-table — a flexible, fully-typed data table with sorting, filtering, column visibility/reordering, and row grouping. No framework required.

Internally built on @vates/data-table-solid, bundled so you never need to install Solid yourself. Already using Solid in your own project? Depend on @vates/data-table-solid directly instead — it shares your app's own solid-js instance rather than a second, separately-bundled copy.

Install

npm install @vates/data-table-vanilla

Usage

import { createDataTable, type ColumnDef } from '@vates/data-table-vanilla'

interface Employee {
  id: number
  name: string
  department: string
  salary: number
}

const COLUMNS: ColumnDef<Employee>[] = [
  { key: 'name', label: 'Name', type: 'string' },
  { key: 'department', label: 'Department', type: 'string', groupable: true },
  {
    key: 'salary',
    label: 'Salary',
    type: 'number',
    format: (v) => Number(v).toLocaleString() + ' €',
  },
]

const table = createDataTable(document.getElementById('table')!, {
  data: employees,
  columns: COLUMNS,
  rowKey: 'id',
})

// Update data or columns later
table.setData(newEmployees)
table.setColumns(newColumns)

// Remove the table and all event listeners
table.destroy()

CSS is injected automatically into <head> on the first createDataTable call. This includes all color tokens and dark-mode overrides that activate automatically via prefers-color-scheme: dark. The injected <style> tag is placed before any existing <head> children, so a stylesheet you define yourself (see Theming) always wins the cascade regardless of import order.

Theming

▶ Try it in the demo

All colors are CSS custom properties. Dark mode activates automatically when the OS preference is dark. You can force a theme by setting data-theme on any ancestor element (typically <html>):

document.documentElement.dataset.theme = 'dark' // force dark
document.documentElement.dataset.theme = 'light' // force light
delete document.documentElement.dataset.theme // follow OS (default)

To override individual tokens, define the custom property in your own stylesheet:

:root {
  --color-background-primary: #0f0f0f;
  --color-text-primary: #f5f5f5;
}
Token Light Dark
--color-background-primary #ffffff #141413
--color-background-secondary #f7f6f3 #2b2a26
--color-background-tertiary #eae9e5 #3a3830
--color-background-info #e6f1fb #0d2640
--color-background-warning #faeeda #2a1900
--color-text-primary #1a1916 #e8e7e4
--color-text-secondary #666561 #a6a5a1
--color-text-tertiary #9b9a96 #86847e
--color-text-info #185fa5 #5b9fe0
--color-text-warning #854f0b #e8a040
--color-border-secondary #dddcd8 #504d46
--color-border-tertiary #eeedea #333029
--color-border-info #b8d6f5 #1a4070
--color-border-warning #f0d4a8 #4a2c00

Cell customization

▶ Try it in the demo

Use col.format(value, row) to control the plain-text string rendered for a cell — the second argument gives access to the rest of the row for cross-field conditional formatting:

{ key: 'status', label: 'Status', format: (v) => v === 1 ? 'Active' : 'Inactive' }
{ key: 'playtime', label: 'Played (h)', format: (v, row) => row.score > 90 ? `⭐ ${v}` : String(v) }

format's return value is always HTML-escaped, so it can't be used to render markup. For richer cells — images, links, colored badges — use col.render(value, row) instead: it returns a DOM node that's mounted directly into the cell, taking priority over format when both are set. It also applies to group header values and aggregate cells for the same column.

{
  key: 'name',
  label: 'Name',
  render: (v, row) => {
    const a = document.createElement('a')
    a.href = `/games/${row.id}`
    a.textContent = String(v)
    return a
  },
}

Use col.renderFilterLabel(value) to render the same kind of custom node for a value's row in the filter dropdown's checklist — it doesn't get row (a checklist row represents a raw value, not a specific row) and isn't applied to type: 'date' columns, whose filter is a Year/Month/Day tree rather than a flat checklist:

{
  key: 'status',
  label: 'Status',
  render: (v) => badge(String(v)),
  renderFilterLabel: (v) => badge(v), // same badge in the filter checklist
}

Multi-value (array) columns

▶ Try it in the demo

A column whose cell value is an array — tags, genres, categories — is detected automatically, no flag required:

interface Game {
  id: number
  name: string
  tags: string[]
}

const COLUMNS: ColumnDef<Game>[] = [
  { key: 'name', label: 'Name' },
  { key: 'tags', label: 'Tags', groupable: true }, // no extra config needed
]

const data = [
  { id: 1, name: 'Game A', tags: ['Action', 'RPG'] },
  { id: 2, name: 'Game B', tags: ['Action', 'Adventure'] },
]

createDataTable(container, { data, columns: COLUMNS, rowKey: 'id' })
// Filter dropdown shows individual items: "Action" | "Adventure" | "RPG"
// Selecting "Action" matches both games
  • The filter checklist lists each individual item instead of the stringified whole array, and a row matches if it contains any selected item (multiMode: 'or', the default) or all of them (multiMode: 'and'). The checklist also gets a runtime "Any"/"All" segmented control the user can switch at any time, overriding multiMode's own default for that session.
  • Grouping by an array column fans a row out into one group per item — a row tagged ['Action', 'RPG'] appears under both the "Action" and "RPG" groups.
  • A row with an empty array (tags: []) is bucketed under a labeled placeholder — (none) by default, customizable via the emptyValue label — instead of a blank checklist entry or an unlabeled group.
  • Cells without a custom format display the array joined with , .
  • Every checklist item (array-valued columns and plain string columns alike) shows how many rows currently match it — helpful for scanning a high-cardinality column like tags before picking a value. The count is faceted: it reflects every other active filter, but not the checklist's own column, so selecting a value elsewhere narrows the counts shown here without a value's own selection state affecting its neighbors. A value with a count of 0 is dropped from the checklist entirely — unless it's already selected, in which case it stays listed so it can still be unticked.
  • A sort-order button next to the search input cycles the checklist between alphabetical (A→Z / Z→A) and by-count (high→low / low→high) order — default is alphabetical ascending.

Date filter tree

▶ Try it in the demo

type: 'date' columns get a Year › Month › Day checkbox tree in the filter dropdown instead of a checklist, plus a range filter (2 date inputs + a slider) above it that narrows the tree itself — dates outside the range drop out of the tree, not just the final row set. Check a year or month to select every date under it in one click, or drill into individual days; the search box and per-value row counts work the same as for string columns. The same sort-order button toggles the tree's chronological order (ascending/descending) instead — there's no by-count order for a tree of grouped branches. Values that don't parse as dates are grouped under the emptyValue label rather than dropped.

{ key: 'joined', label: 'Joined', type: 'date' }

Computed columns

▶ Try it in the demo

A column doesn't need a matching property on TRow — set value to a function to compute the cell value from the whole row. Sorting, filtering, grouping, and aggregation all work off the computed value, same as a regular column.

const COLUMNS: ColumnDef<Employee>[] = [
  { key: 'salary', label: 'Salary', type: 'number' },
  { key: 'bonus', label: 'Bonus', type: 'number' },
  {
    key: 'total',
    label: 'Total Comp',
    type: 'number',
    value: (row) => row.salary + row.bonus,
    aggregate: 'sum',
  },
]

value also covers simple aliasing, reading a different property than key:

{ key: 'employeeName', label: 'Name', value: (row) => row.name }

Custom sort order

▶ Try it in the demo

compare overrides the default numeric-or-alphabetical comparison for a column whose natural order is neither, e.g. an enum/tier column:

const TIER_ORDER = ['Bronze', 'Silver', 'Gold', 'Platinum']

{
  key: 'tier',
  label: 'Tier',
  compare: (a, b) => TIER_ORDER.indexOf(String(a)) - TIER_ORDER.indexOf(String(b)),
}

It applies everywhere the column's values are ordered: row sort, group order (for a groupBy column), and the filter checklist's default and explicit ordering.

compare also receives a 3rd dir argument (the active ascending/descending direction) — ignore it for an ordinary comparator like the one above, since every call site already flips the return value's sign for a descending sort, the same way the default comparison does. It's there for the rarer case of a value that has to stay pinned to one end regardless of which direction is active, e.g. a missing value that should sort last whether ascending or descending — impossible to express as a plain (a, b) => number return, since that gets sign-flipped right along with everything else. compareMissingLast is a ready-made comparator for exactly this:

import { compareMissingLast } from '@vates/data-table-vanilla'

{ key: 'score', label: 'Score', type: 'number', compare: compareMissingLast() } // null/undefined/'' always last, in both directions

Its default isMissing check is (v) => v == null || v === ''; pass your own compare/isMissing to compareMissingLast(compare?, isMissing?) to combine it with a custom order — e.g. compareMissingLast((a, b) => TIER_ORDER.indexOf(String(a)) - TIER_ORDER.indexOf(String(b))) sorts by tier rank with an empty tier always last.

Grouped columns

▶ Try it in the demo

Set groupable: true on a column to make it available in the toolbar's Group dropdown; a grouped column disappears from the table header/cells and its rows are bucketed under a header row instead.

{ key: 'department', label: 'Department', groupable: true }

Grouping a column also adds a matching sort for it (ascending by default), so groups have a defined order right away instead of an arbitrary one — the same sort entry shown as a chip in the active bar and a row in the Sort dropdown, reversible or removable like any other sort. Removing that sort later doesn't ungroup the column; it just goes back to an arbitrary group order.

Grouping buckets rows by exact value by default — fine for low-cardinality columns (department, status), but a continuous or near-unique column (a percentage, a raw timestamp) would create one group per row. Set groupValue to bucket into coarser groups instead — it only affects grouping; sort/filter/aggregate/cell rendering keep reading the column's real value, untouched:

import { bucketNumericRange, formatNumericRange, bucketDatePart, formatDatePart } from '@vates/data-table-vanilla'

{
  key: 'salary',
  label: 'Salary',
  type: 'number',
  groupable: true,
  groupValue: bucketNumericRange(20000), // 47000 -> 40000 (the range's lower bound)
  groupFormat: formatNumericRange(20000, ' USD'), // "40000–60000 USD" in the group header
}

{
  key: 'joined',
  label: 'Joined',
  type: 'date',
  groupable: true,
  groupValue: bucketDatePart('year'), // any date -> "2019-01-01"
  groupFormat: formatDatePart('year'), // "2019" in the group header
}

groupValue(value, row) returns the bucket key — return a value whose type matches col.type (a number for type: 'number', a parseDate-parseable string for type: 'date') so groups still sort correctly, the same type-aware comparison a plain groupBy column already gets. groupFormat(keyPart) renders that bucket key for the group header (bucketNumericRange's lower bound alone, e.g. 40000, usually isn't fit to display on its own); omit it to show the raw bucket key. bucketDatePart/formatDatePart accept 'year' | 'month' | 'day' granularity. Both bucketers return null for a missing (null/undefined) value rather than miscounting it (e.g. Number(null) === 0 would otherwise merge "no value" into the real 0 bucket) — groupFormat renders that group as '(none)' by default, overridable via a 3rd missingLabel argument.

For a right-skewed column spanning several orders of magnitude (review counts, hours played, file sizes), where a single linear step is either too coarse for the long tail or too fine for the low end, bucketLogRange/formatLogRange bucket on a log scale instead:

import { bucketLogRange, formatLogRange } from '@vates/data-table-vanilla'

{
  key: 'hoursPlayed',
  label: 'Hours played',
  type: 'number',
  groupable: true,
  groupValue: bucketLogRange({ divisions: [1, 3] }), // 47 -> 30 (a half-decade "1-3-10" grid)
  groupFormat: formatLogRange({ divisions: [1, 3] }, 'h'), // "30–100h" in the group header
}

divisions (default [1], plain order-of-magnitude) lists the bucket starts within one power of base (default 10) — [1, 3] above gives a half-decade grid, [1, 2, 5] the classic "1-2-5" grid; base: 2 with the default [1] buckets by octave/binary doubling instead of decades. min (default 1) collapses everything below it into one low bucket instead of extending the grid toward zero (log is undefined at/below 0 regardless) — pass min: 0 to keep bucketing all the way down to (but not including) zero.

Since groupValue/groupFormat need the same arguments (step/unit, part, or options/unit) passed twice, a typo or later edit to just one side silently produces a group header that disagrees with its own bucket's real boundaries. numericRangeGroup/datePartGroup/logRangeGroup remove that risk by bundling both from one call, spreadable directly into a column def:

import { numericRangeGroup, logRangeGroup } from '@vates/data-table-vanilla'

{ key: 'salary', label: 'Salary', type: 'number', groupable: true, ...numericRangeGroup(20000, ' USD') }
{ key: 'hoursPlayed', label: 'Hours played', type: 'number', groupable: true, ...logRangeGroup({ divisions: [1, 3] }, 'h') }

A grouped column normally disappears from the row cells too, since its value is already shown in the group header — but that's a loss for a bucketed column (the header only shows "40000–60000 USD", not the row's exact 47000) or a multi-value column (a ["Roguelike", "Deckbuilder"] row shows up in both groups, and hiding the column removes the only way to see its other tags from within one group). Set keepVisibleWhenGrouped: true on such a column to keep it in the row cells even while grouped:

{ key: 'salary', label: 'Salary', type: 'number', groupable: true, groupValue: bucketNumericRange(20000), keepVisibleWhenGrouped: true }

Aggregation

▶ Try it in the demo

Set aggregate on a column to show a computed value in a row below each group header — try grouping by Department in the demo. Built-in types: 'sum' | 'count' | 'avg' | 'min' | 'max'; or supply a function for anything else:

{ key: 'salary', label: 'Salary', type: 'number', aggregate: 'sum' }
{ key: 'score', label: 'Score', type: 'number', aggregate: (rows) => Math.max(...rows.map((r) => r.score)) }

The aggregate row only appears once grouping is active and only shows values for columns that define aggregate; it's always visible regardless of a group's collapsed state.

Row selection

▶ Try it in the demo

Pass selectable to show a checkbox column. The header checkbox selects/deselects the full filtered dataset (all pages at once). Group header checkboxes select/deselect all rows in that group. Both support indeterminate state.

const table = createDataTable(container, {
  data: employees,
  columns: COLUMNS,
  rowKey: 'id',
  selectable: true,
  onSelectionChange: (rows) => console.log(rows.length, 'selected'),
})

Selection uses object identity, so it persists across sort/filter changes as long as row references are stable.

Refetching or re-mapping data breaks that assumption — even identical content in a new array of new objects silently drops selection, since a Set can only ever match by reference. Pass getRowId to opt into id-based matching instead, so selection survives a setData call with fresh row objects:

const table = createDataTable(container, {
  data: employees,
  columns: COLUMNS,
  rowKey: 'id',
  selectable: true,
  onSelectionChange: (rows) => console.log(rows.length, 'selected'),
  getRowId: (employee) => employee.id,
})

With getRowId set, a selected id is remapped to its fresh object reference whenever setData is called, and dropped if the id no longer exists. Omit it to keep the default object-identity behavior exactly as above.

Row click

▶ Try it in the demo

Pass onRowClick to react to a data row being clicked — it receives the full row object and the native click event, no key lookup needed. Group header rows, the aggregate row, and the selection checkbox cell never trigger it. Pressing Enter while a row has keyboard focus fires it too, with the native KeyboardEvent in place of the click event.

const table = createDataTable(container, {
  data: employees,
  columns: COLUMNS,
  rowKey: 'id',
  onRowClick: (row, event) => console.log('clicked', row.name),
})

Column reordering

▶ Try it in the demo

Drag a column header to reorder it, or drag a row (or press Alt+ArrowUp/Alt+ArrowDown on it) in the Columns panel — both work out of the box, no extra options required. Order is tracked independently of visibility, so hiding and re-showing a column keeps its place. It's included in getViewState()/setViewState() (as columnOrder) for persistence and sharing.

Options

Option Type Default Description
data TRow[] — Row data
columns ColumnDef<TRow>[] — Column definitions
rowKey keyof TRow & string — DOM key only — not selection identity
labels Partial<DataTableLabels> English UI string overrides
defaultGroupsCollapsed boolean true Whether newly-grouped groups start collapsed
initialViewState TableViewState {} Construction-time defaults for columns/sort/filters/grouping/page/search — also what resetView restores
getRowId (row: TRow) => string | number — Opt-in id-based selection identity (see "Row selection" above)
selectable boolean false Show checkbox column for row selection
onSelectionChange (rows: TRow[]) => void — Called when selection changes
onRowClick (row: TRow, event: MouseEvent | KeyboardEvent) => void — Called when a data row is clicked
currentRow TRow | null — Row to mark as current (e.g. open in a side panel): aria-current="true" and the dt-tr--current class, unstyled. Matched by object identity
showSearch boolean true Shows/hides the toolbar's search box (Sort/Group/Filter already auto-hide when no column qualifies)
showColumns boolean true Shows/hides the Columns toolbar button; also auto-hides when columns.length < 2
toolbarEnd Node | null — Content at the right end of the toolbar's action row, in a .dt-toolbar-end wrapper (e.g. "Share view"/"Reset view" buttons); no wrapper when omitted

Column definition

interface ColumnDef<TRow extends object> {
  key: string // unique column id; used for row[key] lookup unless `value` is set
  label: string
  type?: 'string' | 'number' | 'date' // controls filter UI: checklist / range / year-month-day tree; default: 'string'
  width?: number
  value?: (row: TRow) => unknown // compute the cell value from the whole row (also covers aliasing)
  format?: (value: unknown, row: TRow) => string
  render?: (value: unknown, row: TRow) => Node // custom cell DOM node; takes priority over format; see Cell customization
  renderFilterLabel?: (value: string) => Node // custom filter-checklist label; not applied to type: 'date' columns
  compare?: (a: unknown, b: unknown, dir: SortDir) => number // custom ordering for row sort, group order, and the filter checklist; see Custom sort order
  sortable?: boolean // default: true
  filterable?: boolean // default: true
  rangePresets?: { label: string; min?: number; max?: number }[] // number column: named ranges shown as buttons above its range filter
  groupable?: boolean // default: false
  groupValue?: (value: unknown, row: TRow) => unknown // bucket a groupBy value into a coarser group key; see Grouped columns
  groupFormat?: (keyPart: string) => string // render a groupValue bucket key in the group header
  keepVisibleWhenGrouped?: boolean // default: false; keep this column's cells visible even while it's grouped
  multiMode?: 'and' | 'or' // match mode for array-valued columns; default: 'or'
  aggregate?: 'sum' | 'count' | 'avg' | 'min' | 'max' | ((rows: TRow[]) => unknown) // see Aggregation
}

Instance methods

Method Description
setData(rows: TRow[]) Replace the data and re-render
setColumns(cols: ColumnDef<TRow>[]) Replace the column definitions and re-render
getViewState() Returns a serializable snapshot of sort/filter/group/page/etc. (not selection)
setViewState(view: TableViewState) Applies a view snapshot; fields absent from it reset to default
onViewChange(cb) Subscribes to view changes (not selection-only); returns an unsubscribe function
getSelection() Current selection (by object identity), including rows hidden by a filter
setSelection(rows: TRow[]) Replaces the selection outright — e.g. to pre-select rows on load
clearSelection() Empties the selection — e.g. to wire an external "Clear selection" button
getProcessedData() Current rows after search/filters/sort, before grouping/pagination
clearAll() Resets search/filters/sort/group/page to true defaults, ignoring initialViewState
setRowKey(key: keyof TRow & string) Changes the row DOM-key property after construction
setSelectable(value: boolean) Toggles whether rows show selection checkboxes after construction
setShowSearch(value: boolean) Shows/hides the toolbar's search box after construction
setShowColumns(value: boolean) Shows/hides the Columns toolbar button after construction
setToolbarEnd(node: Node | null) Replaces (or removes, with null) the toolbar-end node after construction
setOnRowClick(cb | undefined) Changes (or clears) the row-click callback after construction
setCurrentRow(row | null) Changes (or clears) the current row after construction
setLabels(labels | undefined) Replaces the label overrides after construction
setDefaultGroupsCollapsed(value: boolean) Changes whether newly-grouped groups start collapsed after construction
setGetRowId(getRowId | undefined) Changes (or clears) the selection-identity function after construction
destroy() Remove all event listeners and clear the container

View persistence & sharing

▶ Try it in the demo

getViewState()/setViewState() capture and apply a serializable snapshot of sort, filters, groups, page, etc. — everything except selection, which is identity-based and not meaningful to persist or share. persistView wires this up to both localStorage and the URL from one options object:

import { createDataTable, persistView } from '@vates/data-table-vanilla'

const table = createDataTable(container, { data, columns })
const { reset, unsubscribe } = persistView(table, {
  storageKey: 'my-table-view',
  paramName: 'view',
})

// call this alongside table.destroy() if the table can be torn down before a full page unload
unsubscribe()

persistView combines persistViewToLocalStorage (loads immediately, saves on every change via onViewChange) and syncViewToUrl (loads from ?view=... immediately and on back/forward navigation, writes back via history.replaceState) — both only act when their source actually has a view to apply, so a plain reload with no view param keeps the localStorage-restored view instead of resetting it. Its returned reset() puts the table back to its construction-time defaults and clears whatever was persisted (equivalent to resetView(table, options)); unsubscribe() stops both.

Use persistViewToLocalStorage(table, storageKey)/syncViewToUrl(table, { paramName? })/resetView(table, { storageKey?, paramName? }) directly instead if you only want one of the two (e.g. URL sharing with no localStorage) — pass the same storageKey/paramName to each, since persistView is just these three sharing one options object under the hood:

import { createDataTable, syncViewToUrl, resetView } from '@vates/data-table-vanilla'

const table = createDataTable(container, { data, columns })
const unsync = syncViewToUrl(table) // reflected in ?view=... — reload the page or share the link

resetButton.addEventListener('click', () => resetView(table))

To persist a view somewhere else (e.g. a backend), call getViewState()/setViewState(view)/onViewChange(cb) directly — these helpers work with any object shaped like that, so table (or anything else with that shape) can be passed in.

i18n

▶ Try it in the demo

Use a built-in locale or supply any Partial<DataTableLabels> overrides (shallow-merged over English defaults):

import { LABELS_FR } from '@vates/data-table-vanilla'

createDataTable(container, { data, columns, labels: LABELS_FR })

Built-in locales: LABELS_EN (default), LABELS_FR, LABELS_ES, LABELS_DE, LABELS_PT.

License

MIT