@lilydesignsystem/svelte-data-grid
v0.11.2
Published
Lily Design System - Svelte 5 headless data grid (sort, filter, select, resize, paginate over DataTable)
Maintainers
Readme
DataGrid (Svelte helper)
A reusable Svelte 5 headless interactive data grid. It composes
@lilydesignsystem/svelte-headless's DataTable family — the same
role="grid" container the headless catalog ships, with zero
behaviour built in — and adds sort, client-side filter, row selection,
column resize/visibility, pagination, and full WAI-ARIA APG Grid
keyboard navigation on top of it. Ships no CSS: every visual detail is
the consumer's, via kebab-case class hooks.
Unlike theme-picker/locale-picker/text-size-picker/motion-picker,
this is not a page-header preference control — it is the first Lily
helper that depends on the headless layer rather than being
self-contained, composing DataTable the way picker-bar composes
its four wrapped pickers.
Usage
<script lang="ts">
import DataGrid from "@lilydesignsystem/svelte-data-grid";
import type { DataGridColumn } from "@lilydesignsystem/svelte-data-grid";
const columns: DataGridColumn[] = [
{ id: "name", header: "Name", sortable: true, resizable: true },
{ id: "email", header: "Email", sortable: true, cell: emailCell },
{ id: "role", header: "Role", sortable: true, hidable: true },
];
// $state.raw: the grid never mutates rows, so skip the deep proxy.
// Update by assigning a new array, e.g. rows = [...rows, newRow].
let rows = $state.raw([
{ id: "u1", name: "Alice", email: "[email protected]", role: "Admin" },
{ id: "u2", name: "Bob", email: "[email protected]", role: "Editor" },
]);
let selected = $state<string[]>([]);
</script>
{#snippet emailCell({ value, formatted })}
<a href={`mailto:${value}`}>{formatted}</a>
{/snippet}
<DataGrid
label="User accounts"
{columns}
{rows}
rowId={(row) => String(row.id)}
selectionMode="multiple"
bind:selected
pageSize={25}
storageKey="lily-user-grid"
labels={{
search: "Search accounts",
columnVisibility: "Columns",
columnVisibilityOption: (header) => `Show ${header}`,
resizeHandle: (header) => `Resize ${header} column`,
selectAll: "Select all rows",
selectionColumn: "Select",
selectRow: (label) => `Select ${label}`,
previousPage: "Previous page",
nextPage: "Next page",
pageStatus: (page, pageCount, rowCount) => `Page ${page} of ${pageCount} (${rowCount} rows)`,
pageAnnouncement: (page, pageCount) => `Page ${page} of ${pageCount}`,
sortAnnouncement: (header, direction) => `${header} sorted ${direction}`,
filterAnnouncement: (matches, total) => `${matches} of ${total} rows match`,
selectionAnnouncement: (count) => `${count} rows selected`,
}}
/>Props
See spec/index.md §5 for the full table.
Required: label, columns, rows. Every optional labels.* field
gates the control it names — omit a label and that control simply
doesn't render (no baked-in English fallback).
Behaviour
- Sort: single-column, tri-state (
ascending → descending → none). - Filter: client-side, case-insensitive substring match.
- Selection:
"none" | "single" | "multiple", two-way bindable. - Resize: pointer drag or arrow keys on the column's resize handle.
- Visibility: hiding a column removes its cells from the DOM.
- Pagination: client-side, via
pageSize. - Keyboard: WAI-ARIA APG Grid roving-tabindex — arrows move cell-to-cell and clamp, Home/End jump within the row, Ctrl+Home/Ctrl+End jump to the grid's ends, PageUp/PageDown page.
- Row ids:
rowId(row, index)withindexthe row's position inrows, so ids survive sorting, filtering and paging. Pass arowIdthat reads a real key if you replacerowswith reordered data. - Cells: a column's
cellsnippet receives{ value, formatted, row, column };formatstill drives the filter. - Interactive cells: a
cellsnippet may hold links, buttons, inputs and selects. Keys pressed on such a widget are left alone (Escapereturns focus to the cell); widgets are not tab stops until youEnterthe cell, so Tab still leaves the grid in one step.Enteron a cell with no widget, or a click outside any widget, callsonRowActivate(row, id). - Table mode:
mode="table"gives a plainrole="table"with ordinary tab stops and no grid keyboard model — for data that is read, not navigated. Sort, filter, selection and paging work the same. - Column options:
headerCell(header content),rowHeader(<th scope="row">),align,cellClass,cellAttrs; grid propsrowClass,rowAttrs,empty,footer(inside a<tfoot>),busy(aria-busy), andscroll(the nameddata-grid-scrollregion, on by default). - Sort order: pass a column
compare, e.g.new Intl.Collator(locale).compare, for locale-aware text; the grid picks no locale. - Large data: hold
rowsin$state.raw(see spec/index.md §6). Sorting reads each key once and filtering reuses one search index across keystrokes. - Persistence:
storageKeypersists column widths, hidden columns, and sort — never row data or selection.
Filtering and sorting (0.10.0)
rowFilter(row)hides rows it rejects, combining with the textfilter(both must pass).- Multi-column sort:
thenBy(bindable, withonThenByChange) holds further sort keys aftersort. Shift+click on another sortable header adds it (ascending → descending → off); a plain click setssortalone and clearsthenBy. Each sort is read once per row per key and ties fall to the next key; missing values still sort last. Headers carryaria-sortfor every key anddata-sort-order(1 = primary) while more than one key is set;labels.sortAnnouncementannounces the change.
Export: copy to clipboard (0.10.0)
- Copy to clipboard:
labels.copynames a button (data-…-export-format="copy"; for the kanban board, Gantt chart and calendar it also needslabels.exportHeaders, like the downloads) that puts exactly what a download would hold — the same rows, scope and order, header row first — on the clipboard as tab-separated text (toClipboardText: no byte-order mark, formula text defused), ready to paste into a spreadsheet.copyToClipboarduses the async Clipboard API and falls back to a hidden, selected<textarea>withexecCommand("copy"); it never throws.labels.copyAnnouncement(rowCount)is announced,labels.copyFailedwhen neither path worked, andonCopy({ text, rowCount })may returnfalseto take over (nothing is copied).
Keyboard: page keys and type-ahead (0.10.0)
- Type-ahead: letters typed in quick succession (within 700 ms) move the cursor to the next row whose cell text, in the column the cursor is in, starts with them (
findTypeaheadMatch; the text is what the cell shows, ignoring case and diacritics). The same letter pressed again steps through the rows that start with it; a Ctrl, Alt or Meta key, and a prefix that matches nothing, do nothing. PageUp / PageDown already moved a page.
In-place edit: validation, undo and redo (0.10.0)
validateandaria-invalidon a refused cell were already there; undo and redo are new.- Undo and redo: every accepted edit is remembered (the latest 100). Ctrl/Cmd+Z puts the earlier value back and Ctrl/Cmd+Shift+Z (or Ctrl+Y) re-applies one, both through
onCellEditwith the restored value and the one it replaced — the consumer owns the data, so an undo is reported like an edit, and an undo is not itself recorded. A new edit ends the redo chain. Inside a field editor the browser's own undo is left alone; nothing happens in areadonlycomponent or withoutonCellEdit.labels.undoAnnouncement(header, text)/labels.redoAnnouncement(header, text)are announced. The stacks are the pureedit-history.ts(recordEdit,undoEdit,redoEdit,historyKey).
Defaults, locale, fields, labels and direction (0.10.0)
- Empty values.
emptyValue(grid) and a column's ownemptyValuegive a missing value (null,undefinedor"") visible text such as"—"; Lily ships none. The cell always carriesdata-emptyfor CSS, and an export is unaffected.nulls("last"default, or"first") says where missing values sort, in both directions. - Locale-aware sorting. With a
locale(or a column's own), plain text sorts withIntl.Collator(locale, { numeric: true })— "Item 2" before "Item 10", an accented letter with its base letter. Without a locale text sorts by code point, as before. A column's owncomparealways wins; typed columns keep their type's comparison. - Field-specific search.
filterField(bindable,onFilterFieldChange) limits the text filter to one column;labels.searchField(the select's name) withlabels.searchAllFields(its first option) shows the select, listing the filterable columns. Without a field the whole row is searched. movableColumnsmakes every column movable (Alt+Arrow on the header, or drag), unless a column'smovableisfalse.- Right-to-left. The horizontal arrows are visual, so in a right-to-left layout (the nearest
dir, else the computed direction) ArrowLeft goes to the next cell and ArrowRight to the previous, and Alt+Arrow moves a column the way the arrow points. Vertical keys, Home, End and the page keys do not change. The pureisRtl/logicalKeyare exported. - Labels.
DataGridLabelsis the one bundle of every string. What each feature needs is listed inCONTROL_LABELS(labels that name a control) andANNOUNCEMENT_LABELS(live-region messages), andrequiredLabels(features)/missingLabels(features, labels)compute it, so an app can assert in a test that its bundle for a locale is complete. In development the grid logs once, naming the labels its features call for thatlabelsleaves out (warnMissingLabels={false}silences it; it never logs in production). Lily has no English fallback: a missing label is a control with no name or an announcement never made.sortAnnouncementreceives the ARIA token (ascending,descending,none), which the bundle turns into its own words. - Row attributes.
rowAttrs(row)returns attributes spread onto each body row — the way to put test ids (data-testid), data attributes and other hooks on rows (rowAttrs={(row) => ({ "data-testid":row-${row.id}})});rowClassdoes the same for classes, and a column'scellAttrs/cellClassfor cells.
Pager landmark (0.10.0)
labels.pagination names the pager: it then renders as a <nav> landmark (the headless PaginationNav, keeping the data-grid-pagination class) instead of a plain <div>, so a screen-reader user can jump to it. Optional — without it nothing changes.
Search (0.10.0)
search (bindable; the field renders when labels.search names it) narrows the rows: every word must appear, in any order, ignoring case and diacritics. Every word must appear somewhere in the row (any order, any filterable cells), ignoring case and diacritics; filterText still sets a column's text. No match highlighting: cells are rendered by their cell type, so the grid marks nothing inside them. See spec §18.
Export formulas and file columns
exportFormulas (.xlsx only): a formula column's cells keep the live expression with the result cached, so a spreadsheet user keeps the formula; CSV and TSV always carry the result. A file column calls onFilesSelected({ rowId, row, columnId, files }) with the File objects the person chose and onFileRemove({ rowId, row, columnId, fileId }) when a remove button is pressed. Lily uploads nothing: the consumer does, then updates rows.
Non-goals (v1)
Row grouping, server-side sort/filter/pagination, drag-to-reorder rows. (Virtualization, in-place editing, column reorder, pinning, aggregates and copy export, once listed here, have shipped.) See spec/index.md §9 for why each is out — mostly because it requires real layout/scroll ownership that conflicts with this package staying headless.
Lily™ and Lily Design System™ are trademarks.
