@borealjs/grid-core 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,195 +1,557 @@
1
1
  # @borealjs/grid-core
2
2
 
3
- A DOM data grid that stays fast at any size: billions of rows, millions of columns, rows of different
4
- heights, multi-level headers and pivots. You give it **callbacks**; it decides what to load, caches it,
5
- batches and cancels requests, and only touches the DOM nodes that changed.
6
-
7
- - Server-side or in-memory data through one small `DataSource` interface
8
- - Sorting (multi-column), filtering (ranges, value lists with search, text, custom), column filtering
9
- - Pivot layouts: row/column trees with subtotals, expand/collapse, spanning group headers
10
- - Merged cells, range selection, keyboard navigation (WAI-ARIA grid), copy as TSV + HTML
11
- - Customizable: `format`, `cellClass`, `renderCell`, `renderHeader`, custom filter dialogs, messages, theme tokens
12
- - No dependencies, plain ES modules, TypeScript types. React wrapper: [`@borealjs/react-grid`](../react-grid)
13
-
14
-
15
- ## Install
3
+ [![npm](https://img.shields.io/npm/v/@borealjs/grid-core)](https://www.npmjs.com/package/@borealjs/grid-core)
4
+ [![Bundle size](https://deno.bundlejs.com/badge?q=@borealjs/grid-core)](https://bundlejs.com/?q=@borealjs/grid-core)
5
+ [![Types](https://img.shields.io/npm/types/@borealjs/grid-core)](https://github.com/borealjs/grid/blob/main/packages/grid-core/index.d.ts)
6
+ [![License](https://img.shields.io/npm/l/@borealjs/grid-core)](https://github.com/borealjs/grid/blob/main/LICENSE)
7
+
8
+ A data grid for the web that stays smooth at any size: thousands to billions of rows and up to millions of
9
+ columns. Give it an array, or a few async callbacks that read from your backend. Works with plain JavaScript
10
+ and any framework; React users want [`@borealjs/react-grid`](https://www.npmjs.com/package/@borealjs/react-grid).
11
+
12
+ **[Live demo](https://borealjs.github.io/grid/)**: a billion-row table, a pivot and custom cells, right in your browser.
13
+
14
+ <picture>
15
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/borealjs/grid/main/media/grid-dark.png">
16
+ <img alt="A pivot table with one billion rows, grouped headers and quarterly subtotals" src="https://raw.githubusercontent.com/borealjs/grid/main/media/grid-light.png">
17
+ </picture>
18
+
19
+ - Multi-column sorting; filters for ranges, dates, text, searchable value lists and your own
20
+ - Pivots with grouped headers, subtotals, expand and collapse
21
+ - Range selection, copy into spreadsheets, merged cells, full keyboard support
22
+ - Custom cells, headers, filters and empty state; CSS-variable themes, dark mode, translations
23
+ - About 34 kB gzipped, no dependencies, TypeScript types included
24
+
25
+ ## Contents
26
+
27
+ - [Installation](#installation)
28
+ - [Quick start](#quick-start)
29
+ - [Without a bundler](#without-a-bundler)
30
+ - [Columns and cells](#columns-and-cells)
31
+ - [Sorting and filtering](#sorting-and-filtering)
32
+ - [Server data](#server-data)
33
+ - [Selection and copy](#selection-and-copy)
34
+ - [Controlled state](#controlled-state)
35
+ - [Styling and theming](#styling-and-theming)
36
+ - [Translations](#translations)
37
+ - [Pivots](#pivots)
38
+ - [Keyboard](#keyboard)
39
+ - [API reference](#api-reference)
40
+ - [FAQ](#faq)
41
+
42
+ ## Installation
16
43
 
17
44
  ```bash
18
45
  npm install @borealjs/grid-core
46
+ # or
47
+ pnpm add @borealjs/grid-core
48
+ yarn add @borealjs/grid-core
49
+ bun add @borealjs/grid-core
19
50
  ```
20
51
 
52
+ Import the styles once in your app:
53
+
21
54
  ```js
22
- import { createGrid, createArraySource } from '@borealjs/grid-core';
23
55
  import '@borealjs/grid-core/style.css';
24
56
  ```
25
57
 
26
- The grid fills its host element, so give the host a size (`height: 500px`, or a flex child with `min-height: 0`).
58
+ The package is published as ES modules and runs in all current browsers (Chrome, Edge, Firefox, Safari).
59
+
60
+ ## Quick start
27
61
 
28
- ## Quick start (in-memory)
62
+ **1. Add a container with a height.** The grid fills it.
63
+
64
+ ```html
65
+ <div id="grid" style="height: 500px"></div>
66
+ ```
67
+
68
+ **2. Describe your columns and create the grid.**
29
69
 
30
70
  ```js
71
+ import { createGrid, createArraySource } from '@borealjs/grid-core';
72
+ import '@borealjs/grid-core/style.css';
73
+
74
+ const rows = [
75
+ { id: 1, name: 'Ada Lovelace', status: 'Active', amount: 1200, signed: '2024-03-01' },
76
+ { id: 2, name: 'Grace Hopper', status: 'Pending', amount: 950, signed: '2024-05-17' },
77
+ { id: 3, name: 'Alan Turing', status: 'Active', amount: 1430, signed: '2023-11-30' },
78
+ ];
79
+
31
80
  const columns = [
32
- { key: 'id', title: 'ID', type: 'number' },
33
- { key: 'name', title: 'Name' },
81
+ { key: 'id', title: 'ID', type: 'number', width: 80 },
82
+ { key: 'name', title: 'Customer', width: 200 },
34
83
  { key: 'status', title: 'Status', filter: 'values' },
35
84
  { key: 'amount', title: 'Amount', type: 'number', format: (v) => `$${v.toFixed(2)}` },
85
+ { key: 'signed', title: 'Signed', type: 'date' },
36
86
  ];
87
+
37
88
  const grid = createGrid(document.getElementById('grid'), {
38
89
  dataSource: createArraySource(rows, { columns }),
39
90
  columns,
91
+ ariaLabel: 'Customers',
40
92
  onSortChange: (sort) => console.log(sort), // [{ column: 3, key: 'amount', direction: 'desc' }]
41
93
  });
42
94
  ```
43
95
 
44
- ## Your own data source
96
+ That grid already sorts (click a header; Shift+click adds a column), filters (the funnel in each header),
97
+ resizes columns, selects ranges, copies with ⌘C / Ctrl+C and works from the keyboard.
98
+
99
+ > **Important**
100
+ > The grid takes the size of its container. If nothing shows up, give the container a height, or make it a
101
+ > flex child with `flex: 1; min-height: 0`.
102
+
103
+ ## Without a bundler
104
+
105
+ Load the module and the stylesheet straight from a CDN:
106
+
107
+ ```html
108
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@borealjs/grid-core@0.1.1/src/grid.css" />
109
+ <div id="grid" style="height: 400px"></div>
110
+
111
+ <script type="module">
112
+ import { createGrid, createArraySource } from 'https://cdn.jsdelivr.net/npm/@borealjs/grid-core@0.1.1/+esm';
113
+
114
+ const columns = [{ key: 'name', title: 'Name' }, { key: 'city', title: 'City', filter: 'values' }];
115
+ const rows = [{ name: 'Ada', city: 'London' }, { name: 'Grace', city: 'New York' }];
116
+ createGrid(document.getElementById('grid'), { dataSource: createArraySource(rows, { columns }), columns });
117
+ </script>
118
+ ```
119
+
120
+ Pin the version in the URL so an update never changes your page unexpectedly.
121
+
122
+ ## Columns and cells
123
+
124
+ ```js
125
+ {
126
+ key: 'amount', // the row field, and the column's id in sort, filter and events
127
+ title: 'Amount',
128
+ type: 'number', // 'number' aligns right and filters by range; 'date' filters by date range
129
+ width: 120,
130
+ format: (value) => money.format(value),
131
+ cellClass: (value) => (value < 0 ? 'negative' : ''),
132
+ }
133
+ ```
134
+
135
+ There are three ways to customize a cell, from lightest to most flexible:
136
+
137
+ | | Use it for |
138
+ |---|---|
139
+ | `format(value, ctx)` | the text shown: currencies, dates, units |
140
+ | `cellClass(value, ctx)` | a CSS class: colors, weights, icons from CSS |
141
+ | `renderCell(el, ctx)` | your own elements: badges, links, buttons, progress bars |
142
+
143
+ ```js
144
+ renderCell(el, { value, row }) {
145
+ const link = document.createElement('a');
146
+ link.href = `/customers/${row.id}`;
147
+ link.textContent = value;
148
+ el.append(link);
149
+ }
150
+ ```
151
+
152
+ `renderCell` draws into `el`. If it returns a function, that function runs before the cell shows something
153
+ else, so you can clean up (unmount a component, remove a listener). Links, buttons and inputs inside cells
154
+ work as usual; mark other clickable elements with `data-vg-interactive`.
155
+
156
+ All three receive the same context:
45
157
 
46
- Only `getCells` is required. Every call gets an `AbortSignal`; the grid aborts requests that scrolled out of view.
158
+ | | |
159
+ |---|---|
160
+ | `value` | the cell's value |
161
+ | `row` | the whole record (with `createArraySource`; `undefined` for server data) |
162
+ | `text` | the value after `format` |
163
+ | `rowIndex`, `colIndex` | position on screen, after sorting and filtering |
164
+ | `rowSource`, `colSource` | position in the data source |
165
+ | `column` | the column definition |
166
+ | `grid` | the [grid API](#grid-methods) |
167
+
168
+ `renderHeader(el, ctx)` customizes a header the same way, and the `renderEmpty(el, { filtered })` option draws
169
+ the empty state. Options with the same names on the grid apply to every column that has none of its own.
170
+
171
+ For tables with thousands of columns, pass `columnCount` and `getColumn(index)` instead of `columns`. Titles
172
+ you leave out are loaded with the data source's `getLabels`.
173
+
174
+ ## Sorting and filtering
175
+
176
+ Click a header to sort (▲, ▼, off); Shift+click adds it to the sort. Each column gets a filter dialog, chosen
177
+ like this:
178
+
179
+ 1. The column's `filter` decides when it is set:
180
+
181
+ | `filter` | Dialog |
182
+ |---|---|
183
+ | `'values'` | checkbox list with search |
184
+ | `{ type: 'values', values: [...] }` | checkbox list of the values you give |
185
+ | `'text'` | "contains" |
186
+ | `'number'`, `'date'` | min and max, from and to |
187
+ | `{ op, render }` | your own ([custom filters](#custom-filters)) |
188
+ | `false` | no filter |
189
+
190
+ 2. Otherwise the column's `type` decides: `'number'` gets a number range, `'date'` a date range, anything else
191
+ a text search.
192
+ 3. A value list shows the values you pass, or asks the data source (`getFilterValues`). At most 1,000 are
193
+ listed; beyond that the dialog asks the user to refine the search. A data source without
194
+ `getFilterValues` gets a text search instead.
195
+
196
+ Value lists suit columns with a modest set of repeated values (status, city, owner); text search suits
197
+ near-unique ones (names, codes).
198
+
199
+ ### Custom filters
200
+
201
+ ```js
202
+ {
203
+ key: 'score',
204
+ type: 'number',
205
+ filter: {
206
+ op: 'atLeast',
207
+ render(el, api) {
208
+ const input = Object.assign(document.createElement('input'), { type: 'range', value: api.value ?? 50 });
209
+ input.oninput = () => api.setValue(Number(input.value)); // the dialog's Apply button sends it
210
+ el.append(input);
211
+ },
212
+ },
213
+ }
214
+
215
+ // With in-memory rows, say what the operator means:
216
+ createArraySource(rows, { columns, filterFns: { atLeast: (cellValue, min) => cellValue >= min } });
217
+ ```
218
+
219
+ `api` has `value`, `setValue(value)`, `apply(value?)`, `clear()`, `close()`, `column` and `title`. A server
220
+ receives `{ key: 'score', op: 'atLeast', value: 72 }` in the query's filter list.
221
+
222
+ ## Server data
223
+
224
+ A data source is an object with async callbacks. Only `getCells` is required. The grid asks only for what is
225
+ on screen, and every call gets an `AbortSignal`: pass it to `fetch` so requests the grid no longer needs are
226
+ cancelled.
47
227
 
48
228
  ```js
49
229
  const dataSource = {
50
- // Row count for the current filter (tables) or the row/column trees (pivots).
230
+ // How many rows match the current filter.
51
231
  async getLayout({ query, signal }) {
52
- const res = await fetch(`/api/count?${toParams(query)}`, { signal });
232
+ const res = await fetch(`/api/orders/count?q=${encodeURIComponent(JSON.stringify(query))}`, { signal });
53
233
  return { rowCount: (await res.json()).count };
54
234
  },
55
- // One or more rectangles of cells. Return rows of values per rect ([[a, b], [c, d]]) or row-major arrays.
235
+
236
+ // The cells of one or more rectangles.
56
237
  async getCells({ rects, query, signal }) {
57
- const res = await fetch('/api/cells', { method: 'POST', body: JSON.stringify({ rects, query }), signal });
58
- return (await res.json()).cells;
238
+ const res = await fetch('/api/orders/cells', {
239
+ method: 'POST',
240
+ headers: { 'Content-Type': 'application/json' },
241
+ body: JSON.stringify({ rects, query }),
242
+ signal,
243
+ });
244
+ return (await res.json()).cells; // one entry per rect: [[a, b], [c, d]]
245
+ },
246
+
247
+ // Optional: values for value-list filters.
248
+ async getFilterValues({ key, search, limit, signal }) {
249
+ const res = await fetch(`/api/orders/values?field=${key}&q=${encodeURIComponent(search)}&limit=${limit}`, { signal });
250
+ return res.json(); // { values: ['Lamp', 'Desk', …], total: 3120, matches: 41 }
59
251
  },
60
- // Optional: distinct values for 'values' filters. Send at most `limit` (1000); the dialog asks the user
61
- // to refine the search when `matches` is larger.
62
- async getFilterValues({ column, key, search, limit, signal }) { /* … */ },
63
- // Optional: header labels for axes too large to describe up front (pivot groups, untitled columns).
64
- async getLabels({ axis, level, start, count, query, signal }) { /* … */ },
65
- maxRectsPerRequest: 400, // 1 = one rect per call
66
- maxCellsPerRequest: 20000,
67
252
  };
253
+
254
+ createGrid(el, { dataSource, columns });
68
255
  ```
69
256
 
70
- Rects are in **source coordinates**: row = position in the sorted/filtered result, column = column index
71
- (for collapsed pivot groups, the grid asks for thin strips instead of whole blocks, all batched in one call).
257
+ A rect is `{ row, col, rowCount, colCount }`. Rows are positions in the sorted and filtered result; columns
258
+ are column indexes. Answer each rect with its rows of values (`[[a, b], [c, d]]`) or one flat row-major
259
+ array (`[a, b, c, d]`).
72
260
 
73
- ### The query
261
+ The query describes the current sort and filters:
74
262
 
75
- ```ts
76
- query = {
77
- sort: [{ column: 3, key: 'amount', direction: 'desc' }], // or { level } for pivot row dimensions
263
+ ```js
264
+ {
265
+ sort: [{ column: 3, key: 'amount', direction: 'desc' }],
78
266
  filter: [
79
- { column: 3, key: 'amount', op: 'range', min: 0, max: 100 }, // numbers or 'YYYY-MM-DD'
80
- { column: 2, key: 'status', op: 'in', values: ['Open'] }, // also 'notin'
267
+ { column: 3, key: 'amount', op: 'range', min: 0, max: 100 }, // numbers, or dates as 'YYYY-MM-DD'
268
+ { column: 2, key: 'status', op: 'in', values: ['Open'] }, // also 'notin'
81
269
  { column: 1, key: 'name', op: 'contains', text: 'ada' },
82
- { column: 7, key: 'score', op: 'atLeast', value: 90 }, // custom filters: your op, any JSON value
270
+ { column: 7, key: 'score', op: 'atLeast', value: 90 }, // custom filters
83
271
  ],
84
- columnFilter: [{ level: 0, op: 'in', values: ['Amount'] }], // which columns are shown
272
+ columnFilter: [], // which column groups are shown
85
273
  }
86
274
  ```
87
275
 
88
- Mapping it to SQL is direct: `filter` → a parameterized `WHERE`, `sort` → `ORDER BY … , id`, a rect → rows
89
- `row … row + rowCount - 1` of that order and the columns `col … col + colCount - 1` (map column indexes to an
90
- allow-list of column names; never put client text into SQL). For deep positions in big tables, number the
91
- rows of each sort/filter once (`row_number() OVER (…)`) or use a columnar engine instead of `OFFSET`.
276
+ With SQL, `filter` becomes a parameterized `WHERE`, `sort` becomes `ORDER BY` (add a unique column last so the
277
+ order is stable), and a rect becomes rows `row` to `row + rowCount - 1` of that order. Map `key` to column
278
+ names through an allow-list on the server; never put client text into SQL.
92
279
 
93
- ### Bundled sources
280
+ If your backend can't sort or filter very large tables, return `maxSortRows` / `maxFilterRows` from
281
+ `getLayout`. The grid then explains the limit to the user instead of sending requests that would fail.
94
282
 
95
- - `createArraySource(rows, { columns, filterFns, compare })`: rows in memory (objects or arrays). Natural
96
- text order, empty values last, stable multi-column sort, value lists with search. `source.setRows(next)`
97
- then `grid.refresh()` when the data changes.
98
- - `createHttpSource({ baseUrl, params, headers, fetch })`: the reference HTTP protocol implemented by
99
- `server.mjs` in the repository (useful as a template for your backend).
283
+ ### Ready-made sources
100
284
 
101
- ## Columns
285
+ - **`createArraySource(rows, options)`** sorts, filters and searches rows in memory (objects, or arrays
286
+ addressed by position). Text sorts naturally ("Item 2" before "Item 10") and empty values go last. After
287
+ `source.setRows(newRows)`, call `grid.refresh()`.
288
+ - **`createHttpSource({ baseUrl, params, headers, fetch })`** talks to a server that implements this HTTP
289
+ API. `params` are added to every request. The query is sent as `sort` (for example `3:d,L1:a`: a column
290
+ index, or `L` and a pivot row level, then `a` or `d`) and as `filter` / `colfilter` (JSON lists of
291
+ `{ c | dim, op, v | min | max }`).
292
+
293
+ | Request | Response |
294
+ |---|---|
295
+ | `GET {baseUrl}/meta` | `{ rows, totalRows, cols }` for a table, or `{ mode: 'pivot', rows, cols, rowMaps?, colMaps? }` |
296
+ | `GET {baseUrl}/block?r0&c0&nr&nc` | `{ cells }`, row-major |
297
+ | `POST {baseUrl}/gather` with `{ rects: [[r0, c0, nr, nc], …] }` | `{ cells: [one row-major array per rect] }` |
298
+ | `GET {baseUrl}/labels?axis&level&from&n` | `{ names }` |
299
+ | `GET {baseUrl}/values?axis&level&q&limit` | `{ values, total, matches }` |
300
+
301
+ ## Selection and copy
302
+
303
+ Click, Shift+click, drag, ⌘/Ctrl+click to add ranges, ⌘/Ctrl+A to select all. ⌘C / Ctrl+C copies the
304
+ selection as tab-separated text (it pastes into Excel and Google Sheets) and as an HTML table, loading cells
305
+ that are not on screen first.
102
306
 
103
307
  ```js
104
- {
105
- key: 'amount', // id used in queries/events, and the field name for the in-memory source
106
- title: 'Amount',
107
- type: 'number', // aligns to the end, range filter ('date': date range)
108
- width: 120,
109
- filter: 'values', // 'text' | 'number' | 'date' | 'values' | { type: 'values', values } | custom | false
110
- sortable: true, resizable: true, hidden: false,
111
- group: 'Money', // for the column chooser (column filter level 0)
112
- format: (value, ctx) => '…', // fast path: the cell stays a text node
113
- cellClass: (value, ctx) => 'negative',
114
- renderCell: (el, ctx) => { el.append(badge(ctx.value)); return () => el.replaceChildren(); },
115
- renderHeader: (el, ctx) => { el.textContent = ctx.label.toUpperCase(); },
116
- }
308
+ createGrid(el, {
309
+ dataSource,
310
+ columns,
311
+ selection: 'single', // 'multi' (default) | 'single' | 'none'
312
+ onSelectionChange: (info) => console.log(info.active, info.cells),
313
+ onCopy: (info) => console.log(`Copied ${info.cells} cells`),
314
+ });
117
315
  ```
118
316
 
119
- For very wide tables pass `columnCount` and `getColumn(index)` instead of `columns`; titles you leave out
120
- are loaded with `getLabels`.
317
+ ## Controlled state
121
318
 
122
- `format`, `cellClass` and `renderCell` receive a context: `value`, `row` (the record, for in-memory
123
- sources), `text`, `rowIndex` / `colIndex` (on screen), `rowSource` / `colSource` (in the data source),
124
- `column` and `grid`. Links, buttons and inputs drawn by renderers get their own clicks and keys (mark other
125
- interactive elements with `data-vg-interactive`). `renderEmpty(el, { filtered })` draws the empty state.
319
+ By default the grid keeps its own sort and filters. To own them yourself (to store them in the URL, say),
320
+ mark them controlled. The grid then only reports what the user asked for, and you apply it:
126
321
 
127
- `format` and `cellClass` keep the hot path cheap. Renderers run only when a cell's content changes (never on
128
- plain scrolling of an already filled cell), and may return a cleanup.
322
+ ```js
323
+ const grid = createGrid(el, {
324
+ dataSource,
325
+ columns,
326
+ sort: [{ key: 'amount', direction: 'desc' }],
327
+ controlled: { sort: true },
328
+ onSortChange(sort) {
329
+ saveToUrl(sort);
330
+ grid.setSort(sort);
331
+ },
332
+ });
333
+ ```
129
334
 
130
- ### Which filter a column gets
335
+ Sort and filter items may name a column by `key` or by `column` index.
131
336
 
132
- 1. `filter` on the column decides: `'values'` (checkbox list), `'text'` (contains), `'number'` / `'date'`
133
- (range), a custom filter, or `false` (none).
134
- 2. Without `filter`, the column `type` decides: `'number'` → number range, `'date'` → date range, anything
135
- else → text search.
136
- 3. A `'values'` list comes from `filter.values` when you give it, otherwise from `dataSource.getFilterValues`
137
- (first 1,000 matches, searchable). If the data source has neither, the column falls back to text search.
138
- 4. Pivot dimensions use `getFilterValues` too (the reference server lists regions, countries, cities, years,
139
- quarters, months); products have too many names to list, so they are searched by text.
337
+ ## Styling and theming
140
338
 
141
- Use value lists for columns with a modest set of repeated values (status, city, owner) and text search for
142
- near-unique ones (names, codes, IDs as text).
339
+ `theme: 'auto'` (the default) follows the system's light or dark mode; `'light'` and `'dark'` force one. Colors,
340
+ fonts and lines are CSS variables, so the grid fits any design system:
143
341
 
144
- Filtering needs `getLayout` (the grid asks how many rows match). If your layout reports `maxFilterRows` /
145
- `maxSortRows` and the table is bigger, the filter dialog says so up front and multi-column sorts are refused
146
- with a notice, instead of sending requests the backend would reject.
342
+ ```css
343
+ #grid .vg {
344
+ --vg-bg: #ffffff;
345
+ --vg-fg: #111827;
346
+ --vg-muted: #6b7280;
347
+ --vg-line: #e5e7eb;
348
+ --vg-head: #f9fafb;
349
+ --vg-zebra: #fcfcfd;
350
+ --vg-accent: #7c3aed;
351
+ --vg-sel-fill: rgb(124 58 237 / 0.1);
352
+ --vg-font: 14px/1.4 Inter, sans-serif;
353
+ }
354
+ ```
147
355
 
148
- ### Custom filters
356
+ Sizes are options (`rowHeight`, `headerHeight`, `columnWidth`), and `rowClass`, `cellClass`, `className` and
357
+ `headerClass` add your own classes.
358
+
359
+ ## Translations
360
+
361
+ Every text the grid shows is in `messages`. Pass the ones you want to change:
149
362
 
150
363
  ```js
151
- filter: {
152
- op: 'atLeast',
153
- render(el, api) { // api: value, setValue, apply, clear, close, column, title
154
- const input = Object.assign(document.createElement('input'), { type: 'range', value: api.value ?? 50 });
155
- input.oninput = () => api.setValue(Number(input.value)); // the dialog's Apply button sends it
156
- el.append(input);
364
+ createGrid(el, {
365
+ dataSource,
366
+ columns,
367
+ messages: {
368
+ noRows: 'Keine Zeilen',
369
+ apply: 'Anwenden',
370
+ clear: 'Zurücksetzen',
371
+ searchValues: (n) => `${n ?? ''} Werte durchsuchen`,
157
372
  },
373
+ });
374
+ ```
375
+
376
+ `DEFAULT_MESSAGES` has the full list with the English texts.
377
+
378
+ ## Pivots
379
+
380
+ Return a pivot layout from `getLayout` and the grid draws grouped row and column headers, subtotals and
381
+ expand/collapse:
382
+
383
+ ```js
384
+ async getLayout() {
385
+ return {
386
+ type: 'pivot',
387
+ rows: { levels: [{ name: 'Region' }, { name: 'Country' }], leafName: 'Product', leafSize: 28, roots: 4, fanout: [[3, 2, 4, 1], [/* … */]] },
388
+ cols: { levels: [{ name: 'Year' }], leafName: 'Month', leafSize: 96, roots: 10, fanout: [[12, 12, /* … */]] },
389
+ };
158
390
  }
159
- // in-memory: createArraySource(rows, { filterFns: { atLeast: (v, min) => v >= min } })
160
391
  ```
161
392
 
162
- ## Options
393
+ In `getCells`, rows and columns are positions in the fully expanded trees, so they stay the same when groups
394
+ collapse. `grid.showLevel('rows', 0)` collapses to a level and `grid.expandAll('rows')` opens everything again.
395
+ See the `TreeSpec` type for all fields.
396
+
397
+ ## Keyboard
163
398
 
164
- | Option | Default | |
399
+ The grid is one tab stop and follows the WAI-ARIA grid pattern. Give it an accessible name with the
400
+ `ariaLabel` option. <kbd>Ctrl</kbd> is <kbd>⌘</kbd> on macOS.
401
+
402
+ | Keys | Action |
403
+ |---|---|
404
+ | <kbd>←</kbd> <kbd>→</kbd> <kbd>↑</kbd> <kbd>↓</kbd> | Move to the next cell |
405
+ | <kbd>Ctrl</kbd>+arrow | Jump to the first or last row or column |
406
+ | <kbd>Home</kbd> / <kbd>End</kbd> | First or last cell of the row |
407
+ | <kbd>Ctrl</kbd>+<kbd>Home</kbd> / <kbd>Ctrl</kbd>+<kbd>End</kbd> | First or last cell of the grid |
408
+ | <kbd>Page Up</kbd> / <kbd>Page Down</kbd> | Move by one screen |
409
+ | <kbd>Shift</kbd>+any of the above | Extend the selection |
410
+ | <kbd>Enter</kbd> / <kbd>Shift</kbd>+<kbd>Enter</kbd> | Next or previous cell; inside a selection, cycle through it |
411
+ | <kbd>Ctrl</kbd>+<kbd>A</kbd> | Select all |
412
+ | <kbd>Ctrl</kbd>+<kbd>C</kbd> | Copy the selection |
413
+ | <kbd>Escape</kbd> | Reduce the selection to the active cell |
414
+ | <kbd>Alt</kbd>+<kbd>S</kbd> | Sort by the active column (<kbd>Shift</kbd> adds it to the sort) |
415
+ | <kbd>Alt</kbd>+<kbd>F</kbd> | Open the active column's filter |
416
+ | <kbd>Alt</kbd>+<kbd>Shift</kbd>+arrow | Collapse or expand a pivot group |
417
+
418
+ ## API reference
419
+
420
+ ### `createGrid(host, options)`
421
+
422
+ Creates a grid inside `host` and returns its [API](#grid-methods).
423
+
424
+ #### Data
425
+
426
+ | Option | Type | Default | |
427
+ |---|---|---|---|
428
+ | `dataSource` | `DataSource` | required | where the data comes from ([server data](#server-data), [ready-made sources](#ready-made-sources)) |
429
+ | `columns` | `ColumnDef[]` | | the columns ([column options](#column-options)) |
430
+ | `columnCount`, `getColumn` | `number`, `(index) => ColumnDef` | | instead of `columns`, for thousands of columns |
431
+ | `rowCount` | `number` | | row count when the data source has no `getLayout` (filtering is then off) |
432
+ | `layout` | `Layout` | | a layout you already have, to skip the first `getLayout` call |
433
+
434
+ #### Features
435
+
436
+ | Option | Type | Default | |
437
+ |---|---|---|---|
438
+ | `sortable` | `boolean` | `true` | sorting from headers and the keyboard |
439
+ | `multiSort` | `boolean` | `true` | Shift+click adds columns to the sort |
440
+ | `filterable` | `boolean` | `true` | filter buttons in headers |
441
+ | `resizable` | `boolean` | `true` | drag header edges to resize columns |
442
+ | `expandable` | `boolean` | `true` | expand and collapse pivot groups |
443
+ | `selection` | `'multi' \| 'single' \| 'none'` | `'multi'` | |
444
+ | `copy` | `boolean` | `true` | ⌘C / Ctrl+C copies the selection |
445
+ | `keyboard` | `boolean` | `true` | keyboard navigation |
446
+ | `notices` | `boolean` | `true` | a short message when a sort or filter is refused or fails; turn it off to show `onViewChange` yourself |
447
+ | `columnChooser` | `boolean` | on when columns have a `group` | a corner menu to show and hide column groups |
448
+
449
+ #### Look
450
+
451
+ | Option | Type | Default | |
452
+ |---|---|---|---|
453
+ | `theme` | `'auto' \| 'light' \| 'dark'` | `'auto'` | |
454
+ | `ariaLabel` | `string` | | the grid's name for screen readers |
455
+ | `rowHeight` | `number` | `28` | px |
456
+ | `headerHeight` | `number` | `34` | px |
457
+ | `columnWidth` | `number` | `132` | px, for columns without `width` |
458
+ | `minColumnWidth` | `number` | `48` | px, the smallest a user can resize to |
459
+ | `rowHeader` | `false \| { width, title, label(row) }` | row numbers, 72 px | the row-number column |
460
+ | `rowHeaderWidths` | `number[]` | | widths of the pivot row-header columns |
461
+ | `messages` | `Partial<Messages>` | English | [translations](#translations) |
462
+ | `format`, `cellClass`, `renderCell`, `renderHeader` | | | defaults for columns without their own |
463
+ | `rowClass` | `(rowIndex) => string` | | a class per row |
464
+ | `renderEmpty` | `(el, { filtered }) => void \| cleanup` | "No rows" | the empty state |
465
+
466
+ #### Sort and filter
467
+
468
+ | Option | Type | |
469
+ |---|---|---|
470
+ | `sort`, `filter`, `columnFilter` | `SortItem[]`, `FilterItem[]`, `ColumnFilterItem[]` | the starting sort and filters |
471
+ | `controlled` | `{ sort?, filter?, columnFilter? }` | make them [controlled](#controlled-state) |
472
+
473
+ #### Events
474
+
475
+ | Option | Receives |
476
+ |---|---|
477
+ | `onSortChange` | `SortItem[]` |
478
+ | `onFilterChange` | `FilterItem[]` |
479
+ | `onColumnFilterChange` | `ColumnFilterItem[]` |
480
+ | `onSelectionChange` | `{ active, text, ranges, rows, cols, cells }` |
481
+ | `onCopy` | `{ ok, cells, rows, cols, ms, reason? }` |
482
+ | `onColumnResize` | `{ column, key, width }`, when the user lets go |
483
+ | `onViewChange` | `{ what, pending }` while a sort or filter runs, then `{ what, ok, rows, reason? }` |
484
+ | `onError` | `(error, { kind: 'layout' \| 'cells' \| 'labels' })`; errors are logged when this is not set |
485
+ | `onReady` | `(grid)` once the grid is drawn |
486
+
487
+ ### Column options
488
+
489
+ | Option | Type | |
490
+ |---|---|---|
491
+ | `key` | `string` | the row field, and the column's id in sort, filter and events |
492
+ | `title` | `string` | header text |
493
+ | `type` | `'text' \| 'number' \| 'date'` | alignment and the default filter |
494
+ | `width` | `number` | px |
495
+ | `align` | `'start' \| 'end' \| 'center'` | |
496
+ | `filter` | see [sorting and filtering](#sorting-and-filtering) | |
497
+ | `sortable`, `resizable`, `hidden` | `boolean` | |
498
+ | `group` | `string` | group name for the column chooser |
499
+ | `format` | `(value, ctx) => string` | text shown in the cell |
500
+ | `cellClass` | `(value, ctx) => string` | a class per cell |
501
+ | `className`, `headerClass` | `string` | classes for every cell, or the header |
502
+ | `renderCell` | `(el, ctx) => void \| cleanup` | your own cell content |
503
+ | `renderHeader` | `(el, ctx) => void \| cleanup` | your own header content |
504
+ | `value` | `(row) => any` | a computed value (`createArraySource`) |
505
+ | `compare` | `(a, b) => number` | a custom sort order (`createArraySource`) |
506
+
507
+ ### Grid methods
508
+
509
+ | Method | |
510
+ |---|---|
511
+ | `ready` | a promise that resolves once the grid is drawn |
512
+ | `setOptions(partial)` | change any option; scroll position, sort and filters are kept |
513
+ | `refresh()` | reload the visible data (it changed on the server) |
514
+ | `repaint()` | redraw cells (your `format` or `renderCell` output changed) |
515
+ | `getQuery()`, `getSort()`, `getFilter()`, `getColumnFilter()` | the current sort and filters |
516
+ | `setSort(sort)`, `setFilter(filter)`, `setColumnFilter(list)` | change them; resolve to `false` if refused |
517
+ | `toggleSort(column, additive?)` | what a header click does |
518
+ | `openFilter(column)`, `closeFilter()` | the filter dialog |
519
+ | `scrollToCell(row, col?)` | bring a cell into view |
520
+ | `getSelection()`, `setSelection(sel)`, `selectAll()`, `selectionInfo()` | selection |
521
+ | `copySelection()` | copy, as with ⌘C / Ctrl+C |
522
+ | `cellValue(row, col)`, `cellText(row, col)` | a loaded cell's value or text |
523
+ | `setColumnWidth(col, px)` | |
524
+ | `setMerges(merges)` | merged cells: `[{ r0, c0, nr, nc, label? }]` |
525
+ | `rowCount`, `columnCount`, `visibleRange` | sizes and what is on screen |
526
+ | `levels`, `showLevel(axis, level)`, `expandAll(axis)`, `toggleGroup(axis, level, group)` | pivots |
527
+ | `focus()`, `destroy()` | |
528
+
529
+ ### Data source
530
+
531
+ | Member | | |
165
532
  |---|---|---|
166
- | `sortable`, `multiSort`, `filterable`, `resizable`, `expandable`, `copy`, `keyboard` | `true` | feature switches |
167
- | `selection` | `'multi'` | `'single'` or `'none'` |
168
- | `rowHeight`, `headerHeight`, `columnWidth`, `minColumnWidth` | 28, 34, 132, 48 | |
169
- | `rowHeader` | row numbers | `false`, or `{ width, title, label(row) }` |
170
- | `theme` | `'auto'` | `'light'`, `'dark'`; or set `--vg-*` CSS variables |
171
- | `messages` | English | every text in the grid, for translation |
172
- | `sort`, `filter`, `columnFilter` | | initial query; with `controlled: { sort: true }` the grid only reports changes |
173
- | `format`, `cellClass`, `rowClass`, `renderCell`, `renderHeader`, `renderEmpty` | | grid-wide hooks (pivots use these) |
174
- | `onSortChange`, `onFilterChange`, `onColumnFilterChange`, `onSelectionChange`, `onCopy`, `onColumnResize`, `onError`, `onReady` | | events |
175
-
176
- `grid.setOptions(partial)` changes options later: callbacks and hooks apply at once, query options are
177
- applied like `setSort`, structural options rebuild the grid keeping scroll position and query.
178
-
179
- ## API
180
-
181
- `grid.ready`, `setSort / setFilter / setColumnFilter / getQuery`, `toggleSort(column)`, `openFilter(column)`,
182
- `refresh()`, `repaint()`, `scrollToCell(row, col)`, `getSelection / setSelection / selectAll / copySelection`,
183
- `cellValue / cellText`, `setColumnWidth`, `setMerges`, pivots: `levels`, `showLevel(axis, level)`,
184
- `expandAll(axis)`, `toggleGroup(...)`, and `destroy()`.
533
+ | `getCells({ rects, query, signal })` | required | cells for each rect |
534
+ | `getLayout({ query, signal })` | needed for filtering and pivots | `{ rowCount, totalRowCount?, maxSortRows?, maxFilterRows? }` or a pivot layout |
535
+ | `getFilterValues({ column, key, search, limit, query, signal })` | optional | `{ values, total?, matches? }` |
536
+ | `getLabels({ axis, level, start, count, query, signal })` | optional | header titles you did not put in the columns |
537
+ | `maxRectsPerRequest`, `maxCellsPerRequest` | optional | at most this many rects (default 400) or cells (default 20,000) per `getCells` call |
185
538
 
186
- ## Pivots
539
+ ## FAQ
187
540
 
188
- Return a `PivotLayout` from `getLayout` (`{ type: 'pivot', rows: TreeSpec, cols: TreeSpec }`, see the types)
189
- and the grid draws grouped headers, subtotals and expand/collapse; cells are addressed by source index in the
190
- fully expanded trees, so collapsing never refetches.
541
+ **Nothing shows up.** Give the container a height (see [Quick start](#quick-start)).
191
542
 
192
- ## Keyboard
543
+ **Can users edit cells?** Not built in yet. Render an input with `renderCell`, save the change, then call
544
+ `grid.refresh()` (or `source.setRows()` and `grid.refresh()` for in-memory rows).
545
+
546
+ **Can I export to Excel?** Copying a selection pastes straight into Excel and Google Sheets. File export is not
547
+ built in.
548
+
549
+ **Can it show a row count without `getLayout`?** Pass `rowCount` instead. Sorting still works; filtering is
550
+ off, since the grid can't ask how many rows match.
551
+
552
+ **Does it work with Vue, Svelte or Angular?** Yes. Create the grid when your component mounts, call
553
+ `grid.setOptions()` when inputs change, and `grid.destroy()` when it unmounts.
554
+
555
+ ## License
193
556
 
194
- Arrows / Shift+arrows / ⌘ or Ctrl+arrows, Home/End, PageUp/PageDown, Enter, Esc, ⌘/Ctrl+A, ⌘/Ctrl+C,
195
- Alt+S (sort by the active column, Shift adds), Alt+F (filter it), Alt+Shift+arrows (collapse/expand).
557
+ [MIT](https://github.com/borealjs/grid/blob/main/LICENSE)
package/index.d.ts CHANGED
@@ -32,7 +32,7 @@ export const EMPTY_QUERY: Readonly<Query>;
32
32
 
33
33
  // ------------------------------------------------------------------ data source
34
34
 
35
- /** A rectangle of cells in source coordinates. */
35
+ /** A rectangle of cells: rows are positions in the sorted / filtered result, columns are column indexes. */
36
36
  export interface CellRect {
37
37
  row: number;
38
38
  col: number;
@@ -40,7 +40,7 @@ export interface CellRect {
40
40
  colCount: number;
41
41
  }
42
42
 
43
- /** Merged cell in source coordinates. */
43
+ /** A merged cell: rows and columns as in CellRect. */
44
44
  export interface Merge {
45
45
  r0: number;
46
46
  c0: number;
@@ -112,11 +112,11 @@ export interface FilterValuesResult {
112
112
  }
113
113
 
114
114
  /**
115
- * Where the data comes from. Only getCells is required. The grid caches, de-duplicates, batches,
116
- * prioritizes and aborts requests itself; every call gets an AbortSignal.
115
+ * Where the data comes from. Only getCells is required. The grid asks only for what is on screen; every
116
+ * call gets an AbortSignal (pass it to fetch so requests that are no longer needed are cancelled).
117
117
  */
118
118
  export interface DataSource<V = unknown> {
119
- /** Cells of one or more rects (scattered rows/columns are batched into one call). */
119
+ /** Cells of one or more rects. */
120
120
  getCells(request: { rects: CellRect[]; query: Query; signal?: AbortSignal }): Promise<CellsResult<V>> | CellsResult<V>;
121
121
  /** Row count (tables) or the row/column trees (pivots) for a query. Needed for filtering and pivots. */
122
122
  getLayout?(request: { query: Query; signal?: AbortSignal }): Promise<Layout> | Layout;
@@ -205,7 +205,7 @@ export interface ColumnDef<V = unknown> {
205
205
  /** Group name for the column chooser (column filter level 0). */
206
206
  group?: string;
207
207
  filter?: FilterKind;
208
- /** Value -> text (fast path: the cell stays a text node). */
208
+ /** Value -> text shown in the cell (fastest way to customize a cell). */
209
209
  format?(value: V, ctx: CellContext<V> | null): string;
210
210
  /** Extra CSS class for a cell from its value. */
211
211
  cellClass?(value: V, ctx: CellContext<V> | null): string | undefined | null | false;
@@ -319,6 +319,8 @@ export interface GridOptions<V = unknown> {
319
319
  columnChooser?: boolean;
320
320
  columnGroups?: string[];
321
321
  theme?: 'auto' | 'light' | 'dark';
322
+ /** Accessible name of the grid, read by screen readers. */
323
+ ariaLabel?: string;
322
324
  messages?: Partial<Messages>;
323
325
 
324
326
  // Features (all on by default)
@@ -363,7 +365,7 @@ export interface GridOptions<V = unknown> {
363
365
  onError?(error: unknown, context: { kind: 'layout' | 'cells' | 'labels' }): void;
364
366
  onReady?(grid: Grid): void;
365
367
 
366
- /** Advanced: a custom model instead of the table / pivot layouts. */
368
+ /** Low-level: a custom layout model. May change in any release. */
367
369
  model?: unknown;
368
370
  }
369
371
 
@@ -373,7 +375,7 @@ export declare class Grid {
373
375
  /** Resolves when the first layout is in and the grid is drawn. */
374
376
  ready: Promise<void>;
375
377
  readonly options: GridOptions;
376
- /** Advanced: the engine (models, axes, caches). */
378
+ /** Low-level access to the grid's internals. May change in any release. */
377
379
  readonly engine: VirtualGrid | undefined;
378
380
  readonly rowCount: number;
379
381
  readonly columnCount: number;
@@ -447,7 +449,7 @@ export function createHttpSource(options?: {
447
449
  export function compareValues(a: unknown, b: unknown): number;
448
450
  export function defaultFormat(value: unknown): string;
449
451
 
450
- // ------------------------------------------------------------------ advanced building blocks
452
+ // ------------------------------------------------------------------ low-level pieces (may change in any release)
451
453
 
452
454
  export declare class VirtualGrid {
453
455
  constructor(host: HTMLElement, options: Record<string, unknown>);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@borealjs/grid-core",
3
- "version": "0.1.0",
4
- "description": "DOM virtual grid for billions of rows and millions of columns, fed by async callbacks: sorting, filtering, pivots, merged cells, selection and copy.",
3
+ "version": "0.1.1",
4
+ "description": "Fast data grid for the web: billions of rows from memory or any backend, with sorting, filtering, pivots, selection and copy. No dependencies.",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "repository": {
package/src/api.js CHANGED
@@ -101,6 +101,7 @@ export class Grid {
101
101
  initial,
102
102
  api: this,
103
103
  theme: this.#theme,
104
+ ariaLabel: o.ariaLabel,
104
105
  messages: o.messages,
105
106
  sortable: o.sortable !== false,
106
107
  filterable: o.filterable !== false,
@@ -181,12 +182,17 @@ export class Grid {
181
182
  const changed = Object.keys(next).filter((k) => next[k] !== prev[k]);
182
183
  if (!changed.length) return Promise.resolve();
183
184
  this.#opts = { ...prev, ...next };
184
- const structural = changed.filter((k) => !CALLBACKS.includes(k) && !HOOKS.includes(k) && !QUERY_KEYS.includes(k) && k !== 'theme' && k !== 'controlled'
185
+ const structural = changed.filter((k) => !CALLBACKS.includes(k) && !HOOKS.includes(k) && !QUERY_KEYS.includes(k) && k !== 'theme' && k !== 'controlled' && k !== 'ariaLabel'
185
186
  && !['defaultSort', 'defaultFilter', 'defaultColumnFilter'].includes(k));
186
187
  const hookPresence = changed.some((k) => HOOKS.includes(k) && typeof prev[k] !== typeof next[k]);
187
188
  if (structural.length || hookPresence || !this.#engine) return this.rebuild();
188
189
  const e = this.#engine;
189
190
  if (changed.includes('controlled')) e.o.controlled = this.#opts.controlled;
191
+ if (changed.includes('ariaLabel')) {
192
+ e.o.ariaLabel = next.ariaLabel;
193
+ if (next.ariaLabel) e.scroller.setAttribute('aria-label', next.ariaLabel);
194
+ else e.scroller.removeAttribute('aria-label');
195
+ }
190
196
  if (changed.includes('theme')) {
191
197
  const theme = THEMES.includes(next.theme) ? next.theme : 'auto';
192
198
  this.#host.classList.replace(`vg-${this.#theme}`, `vg-${theme}`);
package/src/grid.js CHANGED
@@ -1559,6 +1559,7 @@ export class VirtualGrid {
1559
1559
  this.scroller = div('vg-scroller', host);
1560
1560
  this.scroller.tabIndex = 0;
1561
1561
  this.scroller.setAttribute('role', 'grid');
1562
+ if (this.o.ariaLabel) this.scroller.setAttribute('aria-label', this.o.ariaLabel);
1562
1563
  this.scroller.setAttribute('aria-rowcount', String(this.rows.count + model.colTiers.length));
1563
1564
  this.scroller.setAttribute('aria-colcount', String(this.cols.count + model.rowBands.length));
1564
1565
  this.content = div('vg-content', this.scroller);