@borealjs/react-grid 0.0.0-stage → 0.1.0
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/LICENSE +21 -0
- package/README.md +514 -2
- package/index.d.ts +136 -0
- package/package.json +51 -4
- package/src/index.js +367 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 BorealJS
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,515 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @borealjs/react-grid
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A React data grid that stays fast at any size: hand it an array, or connect a backend with a hook, and
|
|
4
|
+
scroll through millions of rows and thousands of columns (billions with a server). Cells, headers,
|
|
5
|
+
filters and the empty state are plain React components.
|
|
6
|
+
|
|
7
|
+
```jsx
|
|
8
|
+
<VirtualGrid rows={customers} style={{ height: 600 }}>
|
|
9
|
+
<Column field="name" title="Customer" />
|
|
10
|
+
<Column field="status" title="Status" filter="values" renderCell={({ value }) => <Badge status={value} />} />
|
|
11
|
+
<Column field="amount" title="Amount" type="number" format={(v) => money.format(v)} />
|
|
12
|
+
</VirtualGrid>
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
- **Data your way**: `rows` for in-memory data (sorted, filtered and searched in the browser), or
|
|
16
|
+
`useDataSource` for any backend (REST, GraphQL, SQL, a worker), with caching, batching and cancellation done for you
|
|
17
|
+
- **React all the way**: JSX columns, components in cells / headers / filters, your context providers apply,
|
|
18
|
+
inline functions are fine (no memoizing needed)
|
|
19
|
+
- **Controlled or uncontrolled** sort, filter, column filter and selection
|
|
20
|
+
- Sorting (multi-column), filters (ranges, value lists with search, text, your own), column chooser,
|
|
21
|
+
pivots with subtotals and expand/collapse, merged cells, range selection, keyboard navigation, copy
|
|
22
|
+
- TypeScript types inferred from your row type, SSR / Next.js ready (`'use client'`), no dependencies besides React
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
## Contents
|
|
26
|
+
|
|
27
|
+
[Install](#install) · [Quick start](#quick-start) · [Columns](#columns) · [Custom cells](#custom-cells) ·
|
|
28
|
+
[Data](#data) · [Server data](#server-data-usedatasource) · [Sorting & filtering](#sorting-and-filtering) ·
|
|
29
|
+
[Controlled state](#controlled-state) · [Custom filters](#custom-filters) · [Selection & copy](#selection-and-copy) ·
|
|
30
|
+
[Grid API (ref)](#grid-api-ref) · [Events](#events) · [Styling](#styling-and-theming) · [Empty state](#empty-state) ·
|
|
31
|
+
[Translations](#translations) · [TypeScript](#typescript) · [Next.js & SSR](#nextjs-and-ssr) · [Pivots](#pivots) ·
|
|
32
|
+
[Performance](#performance) · [Accessibility](#accessibility-and-keyboard) · [Recipes](#recipes) · [All props](#all-props) · [FAQ](#faq)
|
|
33
|
+
|
|
34
|
+
## Install
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
npm install @borealjs/react-grid @borealjs/grid-core
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
```js
|
|
41
|
+
import '@borealjs/grid-core/style.css'; // once, e.g. in your root layout
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
React 18 or 19.
|
|
45
|
+
|
|
46
|
+
## Quick start
|
|
47
|
+
|
|
48
|
+
```jsx
|
|
49
|
+
import { VirtualGrid, Column } from '@borealjs/react-grid';
|
|
50
|
+
import '@borealjs/grid-core/style.css';
|
|
51
|
+
|
|
52
|
+
export function Customers({ customers }) {
|
|
53
|
+
return (
|
|
54
|
+
<VirtualGrid rows={customers} style={{ height: 600 }} aria-label="Customers">
|
|
55
|
+
<Column field="id" title="ID" type="number" width={80} />
|
|
56
|
+
<Column field="name" title="Customer" width={220} />
|
|
57
|
+
<Column field="status" title="Status" filter="values" />
|
|
58
|
+
<Column field="amount" title="Amount" type="number" format={(v) => `$${v.toFixed(2)}`} />
|
|
59
|
+
<Column field="signedAt" title="Signed" type="date" />
|
|
60
|
+
</VirtualGrid>
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
That grid already sorts (click a header; Shift+click adds a column), filters (the funnel in each header),
|
|
66
|
+
resizes columns, selects ranges, copies with ⌘C / Ctrl+C and is fully keyboard accessible.
|
|
67
|
+
|
|
68
|
+
**Give it a height.** The grid fills its container: set `style={{ height }}`, a CSS class, or make it a flex
|
|
69
|
+
child with `flex: 1; min-height: 0`.
|
|
70
|
+
|
|
71
|
+
## Columns
|
|
72
|
+
|
|
73
|
+
Columns can be JSX children or an array; both take the same props.
|
|
74
|
+
|
|
75
|
+
```jsx
|
|
76
|
+
const columns = [
|
|
77
|
+
{ field: 'name', title: 'Customer', width: 220 },
|
|
78
|
+
{ field: 'amount', title: 'Amount', type: 'number' },
|
|
79
|
+
];
|
|
80
|
+
<VirtualGrid rows={rows} columns={columns} />
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
| Prop | | |
|
|
84
|
+
|---|---|---|
|
|
85
|
+
| `field` | `string` | property of the row; also the column's id in sort / filter / events (alias: `key`) |
|
|
86
|
+
| `title` | `string` | header text |
|
|
87
|
+
| `type` | `'text' \| 'number' \| 'date'` | `number` aligns right and filters by range; `date` filters by date range |
|
|
88
|
+
| `width` | `number` | px (users can resize; see `onColumnResize`) |
|
|
89
|
+
| `align` | `'start' \| 'end' \| 'center'` | |
|
|
90
|
+
| `format` | `(value, ctx) => string` | text shown in the cell (fastest path) |
|
|
91
|
+
| `cellClass` | `(value, ctx) => string` | extra class per cell, e.g. negative numbers |
|
|
92
|
+
| `renderCell` | `(ctx) => ReactNode` | any React content |
|
|
93
|
+
| `renderHeader` | `(ctx) => ReactNode` | custom header content |
|
|
94
|
+
| `value` | `(row) => any` | computed column (in-memory rows) |
|
|
95
|
+
| `compare` | `(a, b) => number` | custom sort order (in-memory rows) |
|
|
96
|
+
| `filter` | `'text' \| 'number' \| 'date' \| 'values' \| { type: 'values', values } \| { op, render } \| false` | see [filters](#sorting-and-filtering) |
|
|
97
|
+
| `sortable`, `resizable`, `hidden` | `boolean` | |
|
|
98
|
+
| `group` | `string` | group name for the column chooser |
|
|
99
|
+
| `className`, `headerClass` | `string` | static classes |
|
|
100
|
+
|
|
101
|
+
**No memoizing needed.** Inline arrays and inline functions are fine: the grid rebuilds only when the
|
|
102
|
+
*structure* changes (fields, titles, types, widths, filters). New functions just redraw the visible cells,
|
|
103
|
+
so closures always see your latest state:
|
|
104
|
+
|
|
105
|
+
```jsx
|
|
106
|
+
const [highlight, setHighlight] = useState('');
|
|
107
|
+
<Column field="name" renderCell={({ value }) => <Highlight text={value} term={highlight} />} />
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
## Custom cells
|
|
111
|
+
|
|
112
|
+
`renderCell` gets a context object:
|
|
113
|
+
|
|
114
|
+
| | |
|
|
115
|
+
|---|---|
|
|
116
|
+
| `value` | the cell's value |
|
|
117
|
+
| `row` | the whole record (in-memory `rows`; `undefined` for server data) |
|
|
118
|
+
| `text` | the value after `format` |
|
|
119
|
+
| `rowIndex`, `colIndex` | position on screen (after sorting / filtering) |
|
|
120
|
+
| `rowSource`, `colSource` | position in the data source |
|
|
121
|
+
| `column` | the column definition |
|
|
122
|
+
| `grid` | the [Grid API](#grid-api-ref) |
|
|
123
|
+
|
|
124
|
+
```jsx
|
|
125
|
+
<Column field="status" renderCell={({ value }) => <span className={`badge badge-${value}`}>{value}</span>} />
|
|
126
|
+
<Column field="progress" type="number" renderCell={({ value }) => <ProgressBar value={value} />} />
|
|
127
|
+
<Column field="actions" title="" sortable={false} filter={false}
|
|
128
|
+
renderCell={({ row }) => <button onClick={() => openCustomer(row.id)}>Open</button>} />
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
- Components in cells can use hooks and context (they render through portals inside your tree).
|
|
132
|
+
- Links, buttons and inputs in cells work as usual: clicks on them don't move the selection, and keys typed
|
|
133
|
+
into an input stay in the input. Mark other interactive elements with `data-vg-interactive`.
|
|
134
|
+
- Keep cells light: they are mounted as rows scroll into view. Prefer `format` / `cellClass` for plain text.
|
|
135
|
+
|
|
136
|
+
Grid-wide `renderCell`, `format`, `cellClass` and `renderHeader` props apply to columns without their own
|
|
137
|
+
(and to pivots, which have no column definitions).
|
|
138
|
+
|
|
139
|
+
## Data
|
|
140
|
+
|
|
141
|
+
### In-memory: `rows`
|
|
142
|
+
|
|
143
|
+
```jsx
|
|
144
|
+
const [rows, setRows] = useState(initialRows);
|
|
145
|
+
<VirtualGrid rows={rows} columns={columns} />
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
Sorting (natural order: "Item 2" before "Item 10", empty values last), filtering and value lists run in the
|
|
149
|
+
browser; a million rows is fine. Passing a new array updates the grid in place: scroll position, sort,
|
|
150
|
+
filter and selection stay. Rows can be objects (`field` names a property) or arrays (columns map by position).
|
|
151
|
+
|
|
152
|
+
### Server data: `useDataSource`
|
|
153
|
+
|
|
154
|
+
Give the grid callbacks; it decides what to load, caches it, batches scattered requests, prioritizes what is
|
|
155
|
+
on screen and aborts what scrolled away (every call gets an `AbortSignal`).
|
|
156
|
+
|
|
157
|
+
```jsx
|
|
158
|
+
import { VirtualGrid, Column, useDataSource } from '@borealjs/react-grid';
|
|
159
|
+
|
|
160
|
+
function Orders({ customerId }) {
|
|
161
|
+
const source = useDataSource({
|
|
162
|
+
// How many rows match the current filter.
|
|
163
|
+
async getLayout({ query, signal }) {
|
|
164
|
+
const res = await fetch(`/api/orders/count?${params(customerId, query)}`, { signal });
|
|
165
|
+
return { rowCount: (await res.json()).count };
|
|
166
|
+
},
|
|
167
|
+
// Rectangles of cells: rows row … row + rowCount - 1 of the sorted / filtered result,
|
|
168
|
+
// columns col … col + colCount - 1. Return the rows of values for each rect.
|
|
169
|
+
async getCells({ rects, query, signal }) {
|
|
170
|
+
const res = await fetch('/api/orders/cells', {
|
|
171
|
+
method: 'POST',
|
|
172
|
+
body: JSON.stringify({ customerId, rects, query }),
|
|
173
|
+
signal,
|
|
174
|
+
});
|
|
175
|
+
return (await res.json()).cells; // [ [[…row], [ …row]], … ] one entry per rect
|
|
176
|
+
},
|
|
177
|
+
// Optional: values for 'values' filters (first `limit` matching `search`).
|
|
178
|
+
async getFilterValues({ key, search, limit, signal }) {
|
|
179
|
+
const res = await fetch(`/api/orders/values?field=${key}&q=${encodeURIComponent(search)}&limit=${limit}`, { signal });
|
|
180
|
+
return res.json(); // { values: string[], total, matches }
|
|
181
|
+
},
|
|
182
|
+
}, [customerId]); // when these change, the grid reloads in place
|
|
183
|
+
|
|
184
|
+
return (
|
|
185
|
+
<VirtualGrid dataSource={source} style={{ height: 600 }}>
|
|
186
|
+
<Column field="id" title="Order" type="number" />
|
|
187
|
+
<Column field="product" title="Product" filter="values" />
|
|
188
|
+
<Column field="total" title="Total" type="number" />
|
|
189
|
+
</VirtualGrid>
|
|
190
|
+
);
|
|
191
|
+
}
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
The callbacks may use props and state freely; the source object stays the same, so the grid isn't rebuilt
|
|
195
|
+
when your component re-renders. Only `getCells` is required (without `getLayout`, pass `rowCount` and
|
|
196
|
+
filtering is off).
|
|
197
|
+
|
|
198
|
+
`query` looks like this (map it to SQL `WHERE` / `ORDER BY`, a search engine, …):
|
|
199
|
+
|
|
200
|
+
```js
|
|
201
|
+
{
|
|
202
|
+
sort: [{ key: 'total', column: 2, direction: 'desc' }],
|
|
203
|
+
filter: [
|
|
204
|
+
{ key: 'total', column: 2, op: 'range', min: 100, max: 500 }, // numbers or 'YYYY-MM-DD'
|
|
205
|
+
{ key: 'product', column: 1, op: 'in', values: ['Lamp'] }, // also 'notin'
|
|
206
|
+
{ key: 'note', column: 4, op: 'contains', text: 'urgent' },
|
|
207
|
+
{ key: 'score', column: 5, op: 'atLeast', value: 90 }, // custom filters
|
|
208
|
+
],
|
|
209
|
+
columnFilter: [],
|
|
210
|
+
}
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
Use `key` (your field names) and keep an allow-list on the server; never put client text into SQL. For the
|
|
214
|
+
reference HTTP protocol there is a ready-made `createHttpSource({ baseUrl, params, headers })`.
|
|
215
|
+
|
|
216
|
+
## Sorting and filtering
|
|
217
|
+
|
|
218
|
+
Sorting is on by default: click a header (▲ ▼ off), Shift+click to add columns. `sortable={false}` turns it
|
|
219
|
+
off for the grid or a column; `multiSort={false}` allows one column only.
|
|
220
|
+
|
|
221
|
+
Each column gets a filter from its `filter` prop, else from its `type`:
|
|
222
|
+
|
|
223
|
+
| | dialog |
|
|
224
|
+
|---|---|
|
|
225
|
+
| `filter="values"` | checkbox list with search: values from `filter={{ type: 'values', values: [...] }}`, or from the data source (`rows`: distinct values; servers: `getFilterValues`). At most 1,000 are listed; the dialog asks to refine the search beyond that |
|
|
226
|
+
| `filter="text"` (default for text) | "contains" |
|
|
227
|
+
| `type="number"` / `filter="number"` | min / max |
|
|
228
|
+
| `type="date"` / `filter="date"` | from / to |
|
|
229
|
+
| `filter={{ op, render }}` | your component ([custom filters](#custom-filters)) |
|
|
230
|
+
| `filter={false}` | none |
|
|
231
|
+
|
|
232
|
+
Use value lists for columns with a modest set of repeated values (status, city, owner), text search for
|
|
233
|
+
near-unique ones (names, codes). If your server reports limits (`maxFilterRows` in `getLayout`), the dialog
|
|
234
|
+
explains why filtering is unavailable instead of failing.
|
|
235
|
+
|
|
236
|
+
## Controlled state
|
|
237
|
+
|
|
238
|
+
Pass a value to control it; leave it out (or pass `defaultSort` etc.) to let the grid keep it.
|
|
239
|
+
|
|
240
|
+
```jsx
|
|
241
|
+
const [sort, setSort] = useState([{ key: 'amount', direction: 'desc' }]);
|
|
242
|
+
const [filter, setFilter] = useState([]);
|
|
243
|
+
|
|
244
|
+
<VirtualGrid rows={rows} columns={columns}
|
|
245
|
+
sort={sort} onSortChange={setSort}
|
|
246
|
+
filter={filter} onFilterChange={setFilter} />
|
|
247
|
+
|
|
248
|
+
<button onClick={() => setFilter([])}>Clear filters</button>
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
| Value | Change event | Uncontrolled initial value |
|
|
252
|
+
|---|---|---|
|
|
253
|
+
| `sort` | `onSortChange` | `defaultSort` |
|
|
254
|
+
| `filter` | `onFilterChange` | `defaultFilter` |
|
|
255
|
+
| `columnFilter` | `onColumnFilterChange` | `defaultColumnFilter` |
|
|
256
|
+
| `selectedCells` | `onSelectionChange` | — |
|
|
257
|
+
|
|
258
|
+
Controlled values are compared by content, so passing a new array with the same items does nothing. Sort and
|
|
259
|
+
filter items can name columns by `key` (field) or `column` (index).
|
|
260
|
+
|
|
261
|
+
## Custom filters
|
|
262
|
+
|
|
263
|
+
A filter is a component; it gets `{ value, setValue, apply, clear, close, column, title, condition }`. The
|
|
264
|
+
dialog's Apply button sends the staged `value` as `{ op, value }` to the data source.
|
|
265
|
+
|
|
266
|
+
```jsx
|
|
267
|
+
function MinScore({ value, setValue }) {
|
|
268
|
+
const [min, setMin] = useState(value ?? 50);
|
|
269
|
+
useEffect(() => setValue(min), [min, setValue]);
|
|
270
|
+
return <input type="range" min={0} max={100} value={min} onChange={(e) => setMin(+e.target.value)} />;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
<VirtualGrid rows={rows} filterFns={{ atLeast: (cellValue, min) => cellValue >= min }}>
|
|
274
|
+
<Column field="score" type="number" filter={{ op: 'atLeast', render: (api) => <MinScore {...api} /> }} />
|
|
275
|
+
</VirtualGrid>
|
|
276
|
+
```
|
|
277
|
+
|
|
278
|
+
With `rows`, `filterFns[op](cellValue, value, row)` decides; with a server, your backend receives
|
|
279
|
+
`{ key: 'score', op: 'atLeast', value: 72 }`.
|
|
280
|
+
|
|
281
|
+
## Selection and copy
|
|
282
|
+
|
|
283
|
+
Click, Shift+click, drag, ⌘/Ctrl+click to add ranges, ⌘/Ctrl+A. ⌘C / Ctrl+C copies as tab-separated text
|
|
284
|
+
(pastes into spreadsheets) plus an HTML table, loading any cells not on screen first.
|
|
285
|
+
|
|
286
|
+
```jsx
|
|
287
|
+
<VirtualGrid selection="single" onSelectionChange={(s) => setActive(s.active)} /> // 'multi' | 'single' | 'none'
|
|
288
|
+
<VirtualGrid copy={false} onCopy={(info) => toast(`Copied ${info.cells} cells`)} />
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
`onSelectionChange` receives `{ active: { r, c }, ranges, text, rows, cols, cells }`. Control it with
|
|
292
|
+
`selectedCells={{ active, ranges }}`.
|
|
293
|
+
|
|
294
|
+
## Grid API (ref)
|
|
295
|
+
|
|
296
|
+
```jsx
|
|
297
|
+
const grid = useRef(null);
|
|
298
|
+
<VirtualGrid ref={grid} … />
|
|
299
|
+
|
|
300
|
+
grid.current.scrollToCell(5000, 0);
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
| Method | |
|
|
304
|
+
|---|---|
|
|
305
|
+
| `scrollToCell(row, col)` | bring a cell into view |
|
|
306
|
+
| `refresh()` | reload what is visible (data changed on the server) |
|
|
307
|
+
| `setSort(sort)`, `setFilter(filter)`, `setColumnFilter(list)`, `getQuery()` | uncontrolled state from code |
|
|
308
|
+
| `toggleSort(field)`, `openFilter(field)`, `closeFilter()` | what the header buttons do |
|
|
309
|
+
| `getSelection()`, `setSelection(sel)`, `selectAll()`, `copySelection()`, `selectionInfo()` | |
|
|
310
|
+
| `cellValue(row, col)`, `cellText(row, col)` | loaded values |
|
|
311
|
+
| `setColumnWidth(col, px)`, `setMerges(list)` | |
|
|
312
|
+
| `rowCount`, `columnCount`, `visibleRange` | |
|
|
313
|
+
| `levels`, `showLevel(axis, level)`, `expandAll(axis)`, `toggleGroup(…)` | pivots |
|
|
314
|
+
| `focus()` | |
|
|
315
|
+
|
|
316
|
+
## Events
|
|
317
|
+
|
|
318
|
+
| Prop | Payload |
|
|
319
|
+
|---|---|
|
|
320
|
+
| `onSortChange` | `SortItem[]` |
|
|
321
|
+
| `onFilterChange` | `FilterItem[]` |
|
|
322
|
+
| `onColumnFilterChange` | `ColumnFilterItem[]` |
|
|
323
|
+
| `onSelectionChange` | `{ active, ranges, text, rows, cols, cells }` |
|
|
324
|
+
| `onCopy` | `{ ok, cells, rows, cols, fetched, ms, reason? }` |
|
|
325
|
+
| `onColumnResize` | `{ column, key, width }` (on release) |
|
|
326
|
+
| `onViewChange` | sort / filter progress: `{ pending }`, then `{ ok, rows, … }` or `{ ok: false, reason }` |
|
|
327
|
+
| `onError` | `(error, { kind: 'layout' \| 'cells' \| 'labels' })` (otherwise logged) |
|
|
328
|
+
| `onReady` | `(grid)` once drawn |
|
|
329
|
+
|
|
330
|
+
## Styling and theming
|
|
331
|
+
|
|
332
|
+
```jsx
|
|
333
|
+
<VirtualGrid className="my-grid" style={{ height: '70vh' }} theme="dark" /> // 'auto' (default) | 'light' | 'dark'
|
|
334
|
+
```
|
|
335
|
+
|
|
336
|
+
Everything is themed with CSS variables on `.vg`, so it fits any design system (or Tailwind via arbitrary
|
|
337
|
+
properties):
|
|
338
|
+
|
|
339
|
+
```css
|
|
340
|
+
.my-grid .vg {
|
|
341
|
+
--vg-bg: #fff; --vg-fg: #111827; --vg-muted: #6b7280; --vg-line: #e5e7eb;
|
|
342
|
+
--vg-head: #f9fafb; --vg-zebra: #fcfcfd; --vg-accent: #7c3aed; --vg-sel-fill: rgb(124 58 237 / 0.1);
|
|
343
|
+
--vg-font: 14px/1.4 Inter, sans-serif;
|
|
344
|
+
}
|
|
345
|
+
```
|
|
346
|
+
|
|
347
|
+
`rowHeight`, `headerHeight`, `columnWidth`, `rowClass(rowIndex)`, `cellClass(value, ctx)` and per-column
|
|
348
|
+
`className` / `headerClass` cover the rest. The row-number column is `rowHeader={{ width, title, label }}` or
|
|
349
|
+
`rowHeader={false}`.
|
|
350
|
+
|
|
351
|
+
## Empty state
|
|
352
|
+
|
|
353
|
+
```jsx
|
|
354
|
+
<VirtualGrid rows={rows} emptyState={({ filtered }) => filtered
|
|
355
|
+
? <p>No matches. <button onClick={() => setFilter([])}>Clear filters</button></p>
|
|
356
|
+
: <EmptyIllustration />} />
|
|
357
|
+
```
|
|
358
|
+
|
|
359
|
+
## Translations
|
|
360
|
+
|
|
361
|
+
Every text the grid shows is in `messages`:
|
|
362
|
+
|
|
363
|
+
```jsx
|
|
364
|
+
<VirtualGrid messages={{ noRows: 'Keine Treffer', apply: 'Anwenden', clear: 'Zurücksetzen',
|
|
365
|
+
searchValues: (n) => `${n ?? ''} Werte durchsuchen`, refineSearch: (shown, total) => `${shown} von ${total} …` }} />
|
|
366
|
+
```
|
|
367
|
+
|
|
368
|
+
## TypeScript
|
|
369
|
+
|
|
370
|
+
Types come from your row type:
|
|
371
|
+
|
|
372
|
+
```tsx
|
|
373
|
+
type Customer = { id: number; name: string; amount: number; status: 'Active' | 'Closed' };
|
|
374
|
+
|
|
375
|
+
<VirtualGrid<Customer> rows={customers} onSortChange={(sort) => …}>
|
|
376
|
+
<Column<Customer, 'amount'> field="amount" format={(v) => v.toFixed(2)} /> {/* v: number */}
|
|
377
|
+
</VirtualGrid>
|
|
378
|
+
```
|
|
379
|
+
|
|
380
|
+
For column arrays, `createColumnHelper` types each value exactly:
|
|
381
|
+
|
|
382
|
+
```tsx
|
|
383
|
+
import { createColumnHelper, type ColumnDef } from '@borealjs/react-grid';
|
|
384
|
+
const col = createColumnHelper<Customer>();
|
|
385
|
+
|
|
386
|
+
const columns: ColumnDef<Customer>[] = [
|
|
387
|
+
col.field('name', { title: 'Customer' }),
|
|
388
|
+
col.field('amount', { type: 'number', format: (v) => v.toFixed(2) }), // v: number
|
|
389
|
+
col.field('status', { renderCell: ({ value, row }) => <Badge s={value} /> }), // value: 'Active' | 'Closed'
|
|
390
|
+
col.computed('label', (r) => `${r.name} #${r.id}`, { title: 'Label' }), // value: string
|
|
391
|
+
];
|
|
392
|
+
```
|
|
393
|
+
|
|
394
|
+
The ref is typed as `GridApi`: `useRef<GridApi>(null)`.
|
|
395
|
+
|
|
396
|
+
## Next.js and SSR
|
|
397
|
+
|
|
398
|
+
The package is marked `'use client'`, so you can render `<VirtualGrid>` from a Server Component page and pass
|
|
399
|
+
it serializable props (`rows`, column props without functions), or wrap it in your own client component when
|
|
400
|
+
you pass functions. Nothing touches the DOM until it mounts in the browser; server rendering outputs the
|
|
401
|
+
container only.
|
|
402
|
+
|
|
403
|
+
```tsx
|
|
404
|
+
// app/customers/page.tsx (Server Component)
|
|
405
|
+
import { CustomersGrid } from './customers-grid'; // 'use client' component with your renderCell etc.
|
|
406
|
+
export default async function Page() {
|
|
407
|
+
return <CustomersGrid rows={await db.customers.findMany()} />;
|
|
408
|
+
}
|
|
409
|
+
```
|
|
410
|
+
|
|
411
|
+
## Pivots
|
|
412
|
+
|
|
413
|
+
Point the grid at a data source whose `getLayout` returns `{ type: 'pivot', rows, cols }` trees (see the core
|
|
414
|
+
docs) and it draws grouped headers, subtotals and expand/collapse; `ref.current.showLevel('rows', 1)` collapses
|
|
415
|
+
to a level. The reference server's pivot works out of the box:
|
|
416
|
+
|
|
417
|
+
```jsx
|
|
418
|
+
const pivot = useMemo(() => createHttpSource({ baseUrl: '/api', params: { mode: 'pivot' } }), []);
|
|
419
|
+
<VirtualGrid dataSource={pivot} onReady={(g) => setLevels(g.levels)} />
|
|
420
|
+
```
|
|
421
|
+
|
|
422
|
+
## Performance
|
|
423
|
+
|
|
424
|
+
- Only visible rows and columns exist in the DOM (plus a small margin); scrolling reuses the same elements.
|
|
425
|
+
- `format` / `cellClass` keep a cell a plain text node; `renderCell` mounts React content per visible cell.
|
|
426
|
+
Both are fine for typical grids; for very dense grids prefer `format`.
|
|
427
|
+
- A cell renderer runs again only when the cell shows a different value, or when the functions you pass
|
|
428
|
+
change (then the visible cells redraw).
|
|
429
|
+
- Changing a column's *structure* rebuilds the grid (scroll and query are kept). With `getColumn` (very wide
|
|
430
|
+
tables), wrap the function in `useCallback`.
|
|
431
|
+
- Server data: return what is asked (rects), quickly; the grid caches about two million cells and keeps four
|
|
432
|
+
sort/filter combinations.
|
|
433
|
+
|
|
434
|
+
## Accessibility and keyboard
|
|
435
|
+
|
|
436
|
+
The grid follows the WAI-ARIA grid pattern: one tab stop, `aria-rowcount` / `aria-colcount` for the whole
|
|
437
|
+
table, `aria-selected`, `aria-sort`, `aria-expanded`. Give it an `aria-label`.
|
|
438
|
+
|
|
439
|
+
| Keys | |
|
|
440
|
+
|---|---|
|
|
441
|
+
| Arrows, Home / End, PageUp / PageDown | move (⌘ / Ctrl jumps to the edge) |
|
|
442
|
+
| Shift + movement | extend the selection |
|
|
443
|
+
| Enter / Shift+Enter | next / previous cell (inside a selection: cycles through it) |
|
|
444
|
+
| ⌘/Ctrl+A, ⌘/Ctrl+C, Escape | select all, copy, reduce to one cell |
|
|
445
|
+
| Alt+S / Alt+Shift+S | sort by the active column / add it as another sort key |
|
|
446
|
+
| Alt+F | filter the active column |
|
|
447
|
+
| Alt+Shift+arrows | collapse / expand pivot groups |
|
|
448
|
+
|
|
449
|
+
## Recipes
|
|
450
|
+
|
|
451
|
+
**Debounced server search**
|
|
452
|
+
|
|
453
|
+
```jsx
|
|
454
|
+
const [search, setSearch] = useState('');
|
|
455
|
+
const debounced = useDeferredValue(search); // or your own debounce hook
|
|
456
|
+
const source = useDataSource({ getLayout: …, getCells: … /* use debounced */ }, [debounced]);
|
|
457
|
+
```
|
|
458
|
+
|
|
459
|
+
**TanStack Query cache**
|
|
460
|
+
|
|
461
|
+
```jsx
|
|
462
|
+
const queryClient = useQueryClient();
|
|
463
|
+
const source = useDataSource({
|
|
464
|
+
getCells: ({ rects, query, signal }) =>
|
|
465
|
+
queryClient.fetchQuery({ queryKey: ['cells', rects, query], queryFn: () => api.cells(rects, query, signal), staleTime: 60_000 }),
|
|
466
|
+
getLayout: ({ query, signal }) =>
|
|
467
|
+
queryClient.fetchQuery({ queryKey: ['count', query], queryFn: () => api.count(query, signal) }),
|
|
468
|
+
});
|
|
469
|
+
```
|
|
470
|
+
|
|
471
|
+
**Refresh after a mutation**
|
|
472
|
+
|
|
473
|
+
```jsx
|
|
474
|
+
await api.updateOrder(id, patch);
|
|
475
|
+
grid.current.refresh(); // server data (or bump a useDataSource dependency)
|
|
476
|
+
setRows((rows) => [...rows]); // in-memory rows
|
|
477
|
+
```
|
|
478
|
+
|
|
479
|
+
**Row actions with the row record**
|
|
480
|
+
|
|
481
|
+
```jsx
|
|
482
|
+
<Column field="actions" title="" width={120} sortable={false} filter={false}
|
|
483
|
+
renderCell={({ row }) => <Menu onEdit={() => edit(row)} onDelete={() => remove(row.id)} />} />
|
|
484
|
+
```
|
|
485
|
+
|
|
486
|
+
## All props
|
|
487
|
+
|
|
488
|
+
Data: `rows`, `dataSource`, `columns` / `<Column>`, `columnCount` + `getColumn`, `rowCount`, `filterFns`, `layout`.
|
|
489
|
+
Look: `theme`, `className`, `style`, `rowHeight`, `headerHeight`, `columnWidth`, `minColumnWidth`, `rowHeader`,
|
|
490
|
+
`rowClass`, `messages`, `emptyState`, `notices`.
|
|
491
|
+
Features: `sortable`, `multiSort`, `filterable`, `resizable`, `expandable`, `selection`, `copy`, `keyboard`,
|
|
492
|
+
`columnChooser`, `columnGroups`.
|
|
493
|
+
State: `sort`, `filter`, `columnFilter`, `selectedCells`, `defaultSort`, `defaultFilter`, `defaultColumnFilter`.
|
|
494
|
+
Hooks: `format`, `cellClass`, `renderCell`, `renderHeader`.
|
|
495
|
+
Events: `onSortChange`, `onFilterChange`, `onColumnFilterChange`, `onSelectionChange`, `onCopy`, `onColumnResize`,
|
|
496
|
+
`onViewChange`, `onError`, `onReady`.
|
|
497
|
+
Other: `ref`, `id`, `aria-label`.
|
|
498
|
+
|
|
499
|
+
## FAQ
|
|
500
|
+
|
|
501
|
+
**Nothing shows up.** The grid needs a height (see [Quick start](#quick-start)).
|
|
502
|
+
|
|
503
|
+
**My column changes rebuild the grid.** Only structural changes do (field, title, type, width, filter kind).
|
|
504
|
+
Functions can change freely.
|
|
505
|
+
|
|
506
|
+
**Clicks on a button in a cell select the cell.** Links, buttons and form fields are excluded automatically;
|
|
507
|
+
add `data-vg-interactive` to other clickable elements.
|
|
508
|
+
|
|
509
|
+
**How do I show 10,000+ columns?** Use `columnCount` + `getColumn(index)` instead of an array; titles you leave
|
|
510
|
+
out can be loaded from the data source (`getLabels`).
|
|
511
|
+
|
|
512
|
+
**Can I edit cells?** Not built in yet; render an input in `renderCell` and save on change, then
|
|
513
|
+
`refresh()` / update `rows`.
|
|
514
|
+
|
|
515
|
+
**Does it work without React?** Yes: `@borealjs/grid-core` has the same features with a plain JS API.
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
// Type definitions for @borealjs/react-grid
|
|
2
|
+
import type { CSSProperties, ReactElement, ReactNode, Ref } from 'react';
|
|
3
|
+
import type {
|
|
4
|
+
ArraySource,
|
|
5
|
+
CellContext as CoreCellContext,
|
|
6
|
+
ColumnDef as CoreColumnDef,
|
|
7
|
+
CustomFilterApi,
|
|
8
|
+
DataSource,
|
|
9
|
+
Grid,
|
|
10
|
+
GridOptions,
|
|
11
|
+
HeaderContext,
|
|
12
|
+
} from '@borealjs/grid-core';
|
|
13
|
+
|
|
14
|
+
export { createArraySource, createHttpSource } from '@borealjs/grid-core';
|
|
15
|
+
export type {
|
|
16
|
+
Grid,
|
|
17
|
+
Grid as GridApi,
|
|
18
|
+
DataSource,
|
|
19
|
+
Query,
|
|
20
|
+
SortItem,
|
|
21
|
+
FilterItem,
|
|
22
|
+
ColumnFilterItem,
|
|
23
|
+
HeaderContext,
|
|
24
|
+
CustomFilterApi,
|
|
25
|
+
SelectionInfo,
|
|
26
|
+
Selection,
|
|
27
|
+
SelectionRange,
|
|
28
|
+
CopyInfo,
|
|
29
|
+
ViewChangeInfo,
|
|
30
|
+
Layout,
|
|
31
|
+
TableLayout,
|
|
32
|
+
PivotLayout,
|
|
33
|
+
CellRect,
|
|
34
|
+
Messages,
|
|
35
|
+
} from '@borealjs/grid-core';
|
|
36
|
+
|
|
37
|
+
/** What renderCell / format / cellClass receive. `row` is the record for in-memory rows (undefined for servers). */
|
|
38
|
+
export interface CellContext<Row = any, V = unknown> extends Omit<CoreCellContext<V>, 'column'> {
|
|
39
|
+
row: Row | undefined;
|
|
40
|
+
column?: ColumnDef<Row>;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** A custom filter rendered by React inside the grid's filter dialog; Apply sends { op, value }. */
|
|
44
|
+
export interface ReactCustomFilter {
|
|
45
|
+
/** Operator the data source receives (for in-memory rows, a key of `filterFns`). Default 'custom'. */
|
|
46
|
+
op?: string;
|
|
47
|
+
render(api: CustomFilterApi): ReactNode;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The value type of a field: exact for a known field, `any` when the column is not tied to one. */
|
|
51
|
+
type FieldValue<Row, F> = string extends F ? any : F extends keyof Row ? Row[F] : any;
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* A column. With in-memory `rows`, `field` names the property to show (or use `value(row)`).
|
|
55
|
+
* Functions may be inline: only structural changes (fields, titles, types, widths, filters) rebuild the grid.
|
|
56
|
+
*/
|
|
57
|
+
export interface ColumnDef<Row = any, F extends string = string, V = FieldValue<Row, F>>
|
|
58
|
+
extends Omit<CoreColumnDef, 'key' | 'renderCell' | 'renderHeader' | 'filter' | 'format' | 'cellClass' | 'value' | 'compare'> {
|
|
59
|
+
/** Field of the row (alias: `key`). Also the id used in sort / filter items and events. */
|
|
60
|
+
field?: F;
|
|
61
|
+
key?: F;
|
|
62
|
+
format?(value: V, ctx: CellContext<Row, V> | null): string;
|
|
63
|
+
cellClass?(value: V, ctx: CellContext<Row, V> | null): string | undefined | null | false;
|
|
64
|
+
renderCell?(ctx: CellContext<Row, V>): ReactNode;
|
|
65
|
+
renderHeader?(ctx: HeaderContext): ReactNode;
|
|
66
|
+
filter?: Exclude<CoreColumnDef['filter'], { render: unknown }> | ReactCustomFilter;
|
|
67
|
+
/** In-memory rows: computed value (default row[field]). */
|
|
68
|
+
value?(row: Row): V;
|
|
69
|
+
/** In-memory rows: sort comparator. */
|
|
70
|
+
compare?(a: V, b: V): number;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Typed columns (values typed from the row type):
|
|
75
|
+
* const col = createColumnHelper<Customer>();
|
|
76
|
+
* const columns = [col.field('amount', { format: (v) => v.toFixed(2) }), col.computed('total', (r) => r.a + r.b)];
|
|
77
|
+
*/
|
|
78
|
+
export function createColumnHelper<Row>(): {
|
|
79
|
+
field<F extends Extract<keyof Row, string>>(field: F, def?: Omit<ColumnDef<Row, F, Row[F]>, 'field' | 'key' | 'value'>): ColumnDef<Row>;
|
|
80
|
+
computed<V>(id: string, value: (row: Row) => V, def?: Omit<ColumnDef<Row, string, V>, 'field' | 'key' | 'value'>): ColumnDef<Row>;
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
export interface VirtualGridProps<Row = any>
|
|
84
|
+
extends Omit<GridOptions, 'dataSource' | 'columns' | 'getColumn' | 'renderCell' | 'renderHeader' | 'renderEmpty' | 'format' | 'cellClass' | 'controlled'> {
|
|
85
|
+
/** In-memory data (sorted, filtered and searched in the browser). New arrays update the grid in place. */
|
|
86
|
+
rows?: readonly Row[];
|
|
87
|
+
/** Or any data source (your backend: see useDataSource). */
|
|
88
|
+
dataSource?: DataSource;
|
|
89
|
+
columns?: ColumnDef<Row>[];
|
|
90
|
+
/** Or declare columns as <Column> children. */
|
|
91
|
+
children?: ReactNode;
|
|
92
|
+
/** Very wide tables: describe column i (wrap in useCallback; a new function rebuilds the grid). */
|
|
93
|
+
getColumn?(index: number): ColumnDef<Row>;
|
|
94
|
+
/** In-memory rows: custom filter operators, { op: (cellValue, conditionValue, row) => boolean }. */
|
|
95
|
+
filterFns?: Record<string, (value: any, conditionValue: any, row: Row) => boolean>;
|
|
96
|
+
/** Grid-wide cell hooks (pivots and columns without their own). */
|
|
97
|
+
format?(value: unknown, ctx: CellContext<Row> | null): string;
|
|
98
|
+
cellClass?(value: unknown, ctx: CellContext<Row> | null): string | undefined | null | false;
|
|
99
|
+
renderCell?(ctx: CellContext<Row>): ReactNode;
|
|
100
|
+
renderHeader?(ctx: HeaderContext): ReactNode;
|
|
101
|
+
/** Shown when there are no rows (`filtered`: because of a filter). */
|
|
102
|
+
emptyState?: ReactNode | ((ctx: { filtered: boolean }) => ReactNode);
|
|
103
|
+
/** Controlled selection (pair with onSelectionChange). */
|
|
104
|
+
selectedCells?: { active?: { r: number; c: number }; ranges?: { r0: number; c0: number; r1: number; c1: number }[] };
|
|
105
|
+
className?: string;
|
|
106
|
+
style?: CSSProperties;
|
|
107
|
+
id?: string;
|
|
108
|
+
'aria-label'?: string;
|
|
109
|
+
ref?: Ref<Grid>;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* The grid. Give it a size (CSS height, or a flex child with min-height: 0).
|
|
114
|
+
* `sort` / `filter` / `columnFilter` / `selectedCells` are controlled when passed (update them from the
|
|
115
|
+
* on…Change callbacks); use defaultSort etc. for uncontrolled state. The ref is the Grid API.
|
|
116
|
+
*/
|
|
117
|
+
export declare function VirtualGrid<Row = any>(props: VirtualGridProps<Row>): ReactElement | null;
|
|
118
|
+
|
|
119
|
+
/** Declares a column as JSX inside <VirtualGrid>; takes the same props as a column object. */
|
|
120
|
+
export declare function Column<Row = any, F extends Extract<keyof Row, string> | (string & {}) = string>(props: ColumnDef<Row, F>): null;
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* A data source from callbacks that may close over props and state. Stays the same object; when `deps`
|
|
124
|
+
* change the grid reloads what is visible (keeping scroll, sort and filter).
|
|
125
|
+
*/
|
|
126
|
+
export function useDataSource(spec: DataSource, deps?: readonly unknown[]): DataSource & { version: number };
|
|
127
|
+
|
|
128
|
+
/** An in-memory data source object that stays the same while rows and options do. */
|
|
129
|
+
export function useArraySource<Row = any>(
|
|
130
|
+
rows: Row[],
|
|
131
|
+
options?: {
|
|
132
|
+
columns?: (ColumnDef<Row> | string | number)[];
|
|
133
|
+
filterFns?: Record<string, (value: any, conditionValue: any, row: Row) => boolean>;
|
|
134
|
+
compare?(a: unknown, b: unknown): number;
|
|
135
|
+
},
|
|
136
|
+
): ArraySource<Row>;
|
package/package.json
CHANGED
|
@@ -1,6 +1,53 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@borealjs/react-grid",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "React wrapper for @borealjs/grid-core: a virtual data grid for billions of rows, fed by async callbacks, with React cells, headers and filters.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/borealjs/grid.git",
|
|
10
|
+
"directory": "packages/react-grid"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/borealjs/grid/tree/main/packages/react-grid#readme",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/borealjs/grid/issues"
|
|
15
|
+
},
|
|
16
|
+
"main": "./src/index.js",
|
|
17
|
+
"module": "./src/index.js",
|
|
18
|
+
"types": "./index.d.ts",
|
|
19
|
+
"exports": {
|
|
20
|
+
".": {
|
|
21
|
+
"types": "./index.d.ts",
|
|
22
|
+
"default": "./src/index.js"
|
|
23
|
+
},
|
|
24
|
+
"./package.json": "./package.json"
|
|
25
|
+
},
|
|
26
|
+
"files": [
|
|
27
|
+
"src",
|
|
28
|
+
"index.d.ts",
|
|
29
|
+
"README.md",
|
|
30
|
+
"LICENSE"
|
|
31
|
+
],
|
|
32
|
+
"sideEffects": false,
|
|
33
|
+
"dependencies": {
|
|
34
|
+
"@borealjs/grid-core": "0.1.0"
|
|
35
|
+
},
|
|
36
|
+
"peerDependencies": {
|
|
37
|
+
"react": ">=18",
|
|
38
|
+
"react-dom": ">=18"
|
|
39
|
+
},
|
|
40
|
+
"keywords": [
|
|
41
|
+
"react",
|
|
42
|
+
"grid",
|
|
43
|
+
"datagrid",
|
|
44
|
+
"data-grid",
|
|
45
|
+
"table",
|
|
46
|
+
"virtual",
|
|
47
|
+
"pivot",
|
|
48
|
+
"server-side"
|
|
49
|
+
],
|
|
50
|
+
"engines": {
|
|
51
|
+
"node": ">=18"
|
|
52
|
+
}
|
|
53
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
// @borealjs/react-grid — React bindings for @borealjs/grid-core.
|
|
3
|
+
//
|
|
4
|
+
// <VirtualGrid rows={data} columns={columns} /> in-memory rows
|
|
5
|
+
// <VirtualGrid dataSource={useDataSource({ getCells, … }, deps)} /> your backend
|
|
6
|
+
// <VirtualGrid rows={data}><Column field="name" title="Name" /></VirtualGrid>
|
|
7
|
+
//
|
|
8
|
+
// React content (cells, headers, filters, the empty state) is rendered with portals into the grid's own
|
|
9
|
+
// elements, so it shares your context. Inline functions are fine: only structural column changes rebuild
|
|
10
|
+
// the grid; new functions just redraw the visible cells. Sort / filter / columnFilter / selectedCells are
|
|
11
|
+
// controlled when passed, uncontrolled otherwise. The ref is the core Grid API.
|
|
12
|
+
//
|
|
13
|
+
// Written without JSX so the package ships as plain ES modules with no build step.
|
|
14
|
+
|
|
15
|
+
import {
|
|
16
|
+
Children, createElement, forwardRef, Fragment, isValidElement, useEffect, useImperativeHandle, useLayoutEffect,
|
|
17
|
+
useMemo, useRef, useState, useSyncExternalStore,
|
|
18
|
+
} from 'react';
|
|
19
|
+
import { createPortal } from 'react-dom';
|
|
20
|
+
import { createGrid, createArraySource, createHttpSource } from '@borealjs/grid-core';
|
|
21
|
+
|
|
22
|
+
export { createArraySource, createHttpSource };
|
|
23
|
+
|
|
24
|
+
const useIsoLayoutEffect = typeof document !== 'undefined' ? useLayoutEffect : useEffect;
|
|
25
|
+
|
|
26
|
+
// ------------------------------------------------------------------ portal store
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Elements the grid asked React to fill: element -> React node. The grid calls set() when a cell or
|
|
30
|
+
* header changes and the returned cleanup when it goes back to text or is reused; updates are batched
|
|
31
|
+
* into one React render per frame (a microtask after the grid's own frame, before paint).
|
|
32
|
+
*/
|
|
33
|
+
function createPortalStore() {
|
|
34
|
+
const nodes = new Map();
|
|
35
|
+
const ids = new WeakMap();
|
|
36
|
+
const listeners = new Set();
|
|
37
|
+
let seq = 0;
|
|
38
|
+
let snapshot = [];
|
|
39
|
+
let queued = false;
|
|
40
|
+
const flush = () => {
|
|
41
|
+
queued = false;
|
|
42
|
+
snapshot = Array.from(nodes, ([el, node]) => [el, node, ids.get(el)]);
|
|
43
|
+
for (const l of listeners) l();
|
|
44
|
+
};
|
|
45
|
+
const schedule = () => {
|
|
46
|
+
if (queued) return;
|
|
47
|
+
queued = true;
|
|
48
|
+
queueMicrotask(flush);
|
|
49
|
+
};
|
|
50
|
+
return {
|
|
51
|
+
set(el, node) {
|
|
52
|
+
if (!ids.has(el)) ids.set(el, `p${seq++}`);
|
|
53
|
+
nodes.set(el, node);
|
|
54
|
+
schedule();
|
|
55
|
+
return () => {
|
|
56
|
+
if (nodes.get(el) === node) {
|
|
57
|
+
nodes.delete(el);
|
|
58
|
+
schedule();
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
},
|
|
62
|
+
subscribe(listener) {
|
|
63
|
+
listeners.add(listener);
|
|
64
|
+
return () => listeners.delete(listener);
|
|
65
|
+
},
|
|
66
|
+
getSnapshot: () => snapshot,
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const EMPTY = [];
|
|
71
|
+
const emptySnapshot = () => EMPTY;
|
|
72
|
+
|
|
73
|
+
function Portals({ store }) {
|
|
74
|
+
const entries = useSyncExternalStore(store.subscribe, store.getSnapshot, emptySnapshot);
|
|
75
|
+
return entries.map(([el, node, key]) => createPortal(node, el, key));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// ------------------------------------------------------------------ columns
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Declares a column as JSX: <Column field="amount" title="Amount" type="number" renderCell={…} />.
|
|
82
|
+
* Takes the same props as a column object. Renders nothing itself.
|
|
83
|
+
*/
|
|
84
|
+
export function Column() {
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
Column.displayName = 'Column';
|
|
88
|
+
|
|
89
|
+
const withKey = (d) => (d && d.field !== undefined && d.key === undefined ? { ...d, key: d.field } : d);
|
|
90
|
+
|
|
91
|
+
/** Column objects from <Column> children, else the `columns` prop (`field` is an alias of `key`). */
|
|
92
|
+
function collectColumns(columns, children) {
|
|
93
|
+
const fromChildren = [];
|
|
94
|
+
Children.forEach(children, (child) => {
|
|
95
|
+
if (isValidElement(child) && child.type === Column) fromChildren.push(child.props);
|
|
96
|
+
});
|
|
97
|
+
const list = fromChildren.length ? fromChildren : columns;
|
|
98
|
+
return list?.map(withKey);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const FN_PROPS = ['format', 'cellClass', 'renderCell', 'renderHeader', 'value', 'compare'];
|
|
102
|
+
|
|
103
|
+
/** What decides the grid's structure: everything except function identities (their presence counts). */
|
|
104
|
+
function columnSignature(list) {
|
|
105
|
+
if (!list) return '';
|
|
106
|
+
return JSON.stringify(list, (k, v) => (typeof v === 'function' ? 'ƒ' : k === 'children' ? undefined : v));
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Stable core columns, rebuilt only when the structure changes. Their functions call the latest ones,
|
|
111
|
+
* so inline functions are fine; when any function identity changes, `fnVersion` moves (redraw cells).
|
|
112
|
+
*/
|
|
113
|
+
function useCoreColumns(list, store) {
|
|
114
|
+
const latest = useRef(list);
|
|
115
|
+
latest.current = list;
|
|
116
|
+
const sig = columnSignature(list);
|
|
117
|
+
const core = useMemo(() => list?.map((d, i) => {
|
|
118
|
+
const out = { ...d };
|
|
119
|
+
for (const p of FN_PROPS) {
|
|
120
|
+
if (typeof d[p] !== 'function') continue;
|
|
121
|
+
if (p === 'renderCell' || p === 'renderHeader') out[p] = (el, ctx) => store.set(el, latest.current[i][p](ctx));
|
|
122
|
+
else out[p] = (...args) => latest.current[i][p](...args);
|
|
123
|
+
}
|
|
124
|
+
if (d.filter && typeof d.filter === 'object' && typeof d.filter.render === 'function') {
|
|
125
|
+
out.filter = { ...d.filter, render: (el, api) => store.set(el, latest.current[i].filter.render(api)) };
|
|
126
|
+
}
|
|
127
|
+
return out;
|
|
128
|
+
}), [sig, store]); // eslint-disable-line react-hooks/exhaustive-deps
|
|
129
|
+
const fns = list ? list.flatMap((d) => [...FN_PROPS.map((p) => d[p]), d.filter?.render]) : EMPTY;
|
|
130
|
+
const prevFns = useRef(fns);
|
|
131
|
+
const version = useRef(0);
|
|
132
|
+
if (fns.length !== prevFns.current.length || fns.some((f, i) => f !== prevFns.current[i])) {
|
|
133
|
+
prevFns.current = fns;
|
|
134
|
+
version.current++;
|
|
135
|
+
}
|
|
136
|
+
return { core, fnVersion: version.current };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** A React column -> core column, for getColumn (very wide tables). */
|
|
140
|
+
function toCoreColumn(d, store) {
|
|
141
|
+
if (!d) return d;
|
|
142
|
+
const out = { ...withKey(d) };
|
|
143
|
+
if (typeof d.renderCell === 'function') out.renderCell = (el, ctx) => store.set(el, d.renderCell(ctx));
|
|
144
|
+
if (typeof d.renderHeader === 'function') out.renderHeader = (el, ctx) => store.set(el, d.renderHeader(ctx));
|
|
145
|
+
if (d.filter && typeof d.filter === 'object' && typeof d.filter.render === 'function') {
|
|
146
|
+
out.filter = { ...d.filter, render: (el, api) => store.set(el, d.filter.render(api)) };
|
|
147
|
+
}
|
|
148
|
+
return out;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Column helpers (typed in TypeScript from the row type):
|
|
153
|
+
* const col = createColumnHelper();
|
|
154
|
+
* col.field('amount', { format: (v) => v.toFixed(2) }); col.computed('total', (row) => row.a + row.b);
|
|
155
|
+
*/
|
|
156
|
+
export function createColumnHelper() {
|
|
157
|
+
return {
|
|
158
|
+
field: (field, def = {}) => ({ ...def, field }),
|
|
159
|
+
computed: (field, value, def = {}) => ({ ...def, field, value }),
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// ------------------------------------------------------------------ props -> core options
|
|
164
|
+
|
|
165
|
+
const CALLBACKS = ['onSortChange', 'onFilterChange', 'onColumnFilterChange', 'onSelectionChange', 'onCopy', 'onError', 'onViewChange', 'onColumnResize', 'onReady'];
|
|
166
|
+
const PASS = [
|
|
167
|
+
'layout', 'rowCount', 'columnCount', 'rowHeight', 'headerHeight', 'columnWidth', 'minColumnWidth',
|
|
168
|
+
'columnChooser', 'columnGroups', 'theme', 'sortable', 'filterable', 'resizable', 'multiSort', 'expandable',
|
|
169
|
+
'selection', 'copy', 'keyboard', 'notices', 'defaultSort', 'defaultFilter', 'defaultColumnFilter', 'blockRows', 'blockCols',
|
|
170
|
+
'rowHeaderWidths', 'model',
|
|
171
|
+
];
|
|
172
|
+
const OBJECTS = ['rowHeader', 'messages'];
|
|
173
|
+
const QUERY = ['sort', 'filter', 'columnFilter'];
|
|
174
|
+
|
|
175
|
+
const shallowEqual = (a, b) => {
|
|
176
|
+
if (a === b) return true;
|
|
177
|
+
if (!a || !b || typeof a !== 'object' || typeof b !== 'object') return false;
|
|
178
|
+
const ka = Object.keys(a);
|
|
179
|
+
return ka.length === Object.keys(b).length && ka.every((k) => a[k] === b[k]);
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
const sameJson = (a, b) => a === b || JSON.stringify(a) === JSON.stringify(b);
|
|
183
|
+
|
|
184
|
+
/** Keeps the previous object while it is shallowly equal, so inline objects do not rebuild the grid. */
|
|
185
|
+
function useShallowStable(value) {
|
|
186
|
+
const ref = useRef(value);
|
|
187
|
+
if (!shallowEqual(ref.current, value)) ref.current = value;
|
|
188
|
+
return ref.current;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// ------------------------------------------------------------------ component
|
|
192
|
+
|
|
193
|
+
export const VirtualGrid = forwardRef(function VirtualGrid(props, ref) {
|
|
194
|
+
const hostRef = useRef(null);
|
|
195
|
+
const gridRef = useRef(null);
|
|
196
|
+
const propsRef = useRef(props);
|
|
197
|
+
propsRef.current = props;
|
|
198
|
+
const [store] = useState(createPortalStore);
|
|
199
|
+
|
|
200
|
+
const list = collectColumns(props.columns, props.children);
|
|
201
|
+
const { core: columns, fnVersion } = useCoreColumns(list, store);
|
|
202
|
+
const getColumn = useMemo(() => (props.getColumn ? (i) => toCoreColumn(props.getColumn(i), store) : undefined), [props.getColumn, store]);
|
|
203
|
+
const stableObjects = useShallowStable(Object.fromEntries(OBJECTS.map((k) => [k, props[k]])));
|
|
204
|
+
|
|
205
|
+
// In-memory rows: one source per column structure; new `rows` arrays go in with setRows + refresh.
|
|
206
|
+
const filterFnsRef = useRef(props.filterFns);
|
|
207
|
+
filterFnsRef.current = props.filterFns;
|
|
208
|
+
const useRows = !props.dataSource && !!props.rows;
|
|
209
|
+
const rowsSource = useMemo(() => {
|
|
210
|
+
if (!useRows) return undefined;
|
|
211
|
+
const filterFns = new Proxy({}, { get: (_, op) => filterFnsRef.current?.[op] });
|
|
212
|
+
return createArraySource(propsRef.current.rows, { columns, filterFns });
|
|
213
|
+
}, [useRows, columns]);
|
|
214
|
+
const dataSource = props.dataSource ?? rowsSource ?? null;
|
|
215
|
+
|
|
216
|
+
// Grid-wide hooks: stable functions reading the latest props (presence changes rebuild the grid).
|
|
217
|
+
const has = (k) => props[k] !== undefined && props[k] !== null && props[k] !== false;
|
|
218
|
+
const hooks = useMemo(() => ({
|
|
219
|
+
format: has('format') ? (v, ctx) => propsRef.current.format?.(v, ctx) : undefined,
|
|
220
|
+
cellClass: has('cellClass') ? (v, ctx) => propsRef.current.cellClass?.(v, ctx) : undefined,
|
|
221
|
+
rowClass: has('rowClass') ? (r) => propsRef.current.rowClass?.(r) : undefined,
|
|
222
|
+
renderCell: has('renderCell') ? (el, ctx) => store.set(el, propsRef.current.renderCell?.(ctx)) : undefined,
|
|
223
|
+
renderHeader: has('renderHeader') ? (el, ctx) => store.set(el, propsRef.current.renderHeader?.(ctx)) : undefined,
|
|
224
|
+
renderEmpty: has('emptyState')
|
|
225
|
+
? (el, ctx) => {
|
|
226
|
+
const e = propsRef.current.emptyState;
|
|
227
|
+
return store.set(el, typeof e === 'function' ? e(ctx) : e);
|
|
228
|
+
}
|
|
229
|
+
: undefined,
|
|
230
|
+
}), [has('format'), has('cellClass'), has('rowClass'), has('renderCell'), has('renderHeader'), has('emptyState'), store]); // eslint-disable-line react-hooks/exhaustive-deps
|
|
231
|
+
const callbacks = useMemo(() => Object.fromEntries(CALLBACKS.map((k) => [k, (...args) => propsRef.current[k]?.(...args)])), []);
|
|
232
|
+
|
|
233
|
+
const options = {
|
|
234
|
+
...Object.fromEntries(PASS.map((k) => [k, props[k]])),
|
|
235
|
+
...stableObjects,
|
|
236
|
+
dataSource,
|
|
237
|
+
columns,
|
|
238
|
+
getColumn,
|
|
239
|
+
...hooks,
|
|
240
|
+
...callbacks,
|
|
241
|
+
// Controlled when the prop is given: the grid reports changes and waits for the new prop.
|
|
242
|
+
sort: props.sort,
|
|
243
|
+
filter: props.filter,
|
|
244
|
+
columnFilter: props.columnFilter,
|
|
245
|
+
controlled: { sort: props.sort !== undefined, filter: props.filter !== undefined, columnFilter: props.columnFilter !== undefined },
|
|
246
|
+
};
|
|
247
|
+
const optionsRef = useRef(options);
|
|
248
|
+
optionsRef.current = options;
|
|
249
|
+
|
|
250
|
+
const ready = !!(dataSource || props.model);
|
|
251
|
+
useIsoLayoutEffect(() => {
|
|
252
|
+
if (!ready) return undefined;
|
|
253
|
+
const grid = createGrid(hostRef.current, optionsRef.current);
|
|
254
|
+
gridRef.current = grid;
|
|
255
|
+
grid.ready.catch(() => {}); // reported through onError
|
|
256
|
+
return () => {
|
|
257
|
+
grid.destroy();
|
|
258
|
+
gridRef.current = null;
|
|
259
|
+
};
|
|
260
|
+
}, [ready]);
|
|
261
|
+
|
|
262
|
+
useImperativeHandle(ref, () => gridRef.current, [ready]);
|
|
263
|
+
|
|
264
|
+
// Later renders: hand the grid what changed (it decides between redraw, query change and rebuild).
|
|
265
|
+
const mounted = useRef(false);
|
|
266
|
+
useEffect(() => {
|
|
267
|
+
if (!mounted.current) {
|
|
268
|
+
mounted.current = true;
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
const grid = gridRef.current;
|
|
272
|
+
if (!grid) return;
|
|
273
|
+
const prev = grid.options;
|
|
274
|
+
const next = { ...optionsRef.current };
|
|
275
|
+
// Controlled queries compare by content (a new array with the same items is no change).
|
|
276
|
+
for (const k of QUERY) if (next[k] !== undefined && sameJson(next[k], grid.getQuery()[k])) next[k] = prev[k];
|
|
277
|
+
if (shallowEqual(next.controlled, prev.controlled)) next.controlled = prev.controlled;
|
|
278
|
+
grid.setOptions(next).catch(() => {});
|
|
279
|
+
});
|
|
280
|
+
|
|
281
|
+
// New functions in columns (same structure): redraw what is visible.
|
|
282
|
+
const lastFnVersion = useRef(fnVersion);
|
|
283
|
+
useEffect(() => {
|
|
284
|
+
if (lastFnVersion.current === fnVersion) return;
|
|
285
|
+
lastFnVersion.current = fnVersion;
|
|
286
|
+
gridRef.current?.repaint();
|
|
287
|
+
}, [fnVersion]);
|
|
288
|
+
|
|
289
|
+
// New rows for the in-memory source: keep scroll, sort and filter, reload what is visible.
|
|
290
|
+
useEffect(() => {
|
|
291
|
+
if (!rowsSource || rowsSource.rows === props.rows) return;
|
|
292
|
+
rowsSource.setRows(props.rows);
|
|
293
|
+
gridRef.current?.refresh();
|
|
294
|
+
}, [props.rows, rowsSource]);
|
|
295
|
+
|
|
296
|
+
// useDataSource: its dependencies changed -> reload (same source object, new version).
|
|
297
|
+
const version = props.dataSource?.version;
|
|
298
|
+
const lastVersion = useRef(version);
|
|
299
|
+
useEffect(() => {
|
|
300
|
+
if (lastVersion.current === version) return;
|
|
301
|
+
lastVersion.current = version;
|
|
302
|
+
gridRef.current?.refresh();
|
|
303
|
+
}, [version]);
|
|
304
|
+
|
|
305
|
+
// Controlled selection: apply when it differs from the grid's.
|
|
306
|
+
const selected = props.selectedCells;
|
|
307
|
+
useEffect(() => {
|
|
308
|
+
const grid = gridRef.current;
|
|
309
|
+
if (!grid || !selected) return;
|
|
310
|
+
const apply = () => {
|
|
311
|
+
const cur = grid.getSelection();
|
|
312
|
+
const want = { active: selected.active ?? cur?.active, ranges: selected.ranges ?? cur?.ranges };
|
|
313
|
+
if (!cur || !sameJson({ active: cur.active, ranges: cur.ranges }, want)) grid.setSelection(selected);
|
|
314
|
+
};
|
|
315
|
+
if (grid.engine) apply();
|
|
316
|
+
else grid.ready.then(apply, () => {});
|
|
317
|
+
}, [selected]);
|
|
318
|
+
|
|
319
|
+
const { className, style, id } = props;
|
|
320
|
+
return createElement(
|
|
321
|
+
Fragment,
|
|
322
|
+
null,
|
|
323
|
+
createElement(
|
|
324
|
+
'div',
|
|
325
|
+
{ className, style: { position: 'relative', minHeight: 0, ...style }, id, 'aria-label': props['aria-label'] },
|
|
326
|
+
createElement('div', { ref: hostRef, style: { position: 'absolute', inset: 0 } }),
|
|
327
|
+
),
|
|
328
|
+
createElement(Portals, { store }),
|
|
329
|
+
);
|
|
330
|
+
});
|
|
331
|
+
VirtualGrid.displayName = 'VirtualGrid';
|
|
332
|
+
|
|
333
|
+
// ------------------------------------------------------------------ hooks
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* A data source from callbacks that may close over props and state. It stays the same object (the grid
|
|
337
|
+
* is not rebuilt); when `deps` change, the grid reloads what is visible, keeping scroll, sort and filter.
|
|
338
|
+
*
|
|
339
|
+
* const source = useDataSource({
|
|
340
|
+
* getLayout: async ({ query, signal }) => ({ rowCount: await api.count(search, query, signal) }),
|
|
341
|
+
* getCells: ({ rects, query, signal }) => api.cells(search, rects, query, signal),
|
|
342
|
+
* }, [search]);
|
|
343
|
+
*/
|
|
344
|
+
export function useDataSource(spec, deps = []) {
|
|
345
|
+
const ref = useRef(spec);
|
|
346
|
+
ref.current = spec;
|
|
347
|
+
const [source] = useState(() => {
|
|
348
|
+
const s = { version: 0 };
|
|
349
|
+
for (const name of ['getCells', 'getLayout', 'getLabels', 'getFilterValues', 'rowAt']) {
|
|
350
|
+
if (typeof spec[name] === 'function') s[name] = (...args) => ref.current[name](...args);
|
|
351
|
+
}
|
|
352
|
+
for (const name of ['maxRectsPerRequest', 'maxCellsPerRequest']) if (spec[name] !== undefined) s[name] = spec[name];
|
|
353
|
+
return s;
|
|
354
|
+
});
|
|
355
|
+
const prevDeps = useRef(deps);
|
|
356
|
+
if (deps.length !== prevDeps.current.length || deps.some((d, i) => !Object.is(d, prevDeps.current[i]))) {
|
|
357
|
+
prevDeps.current = deps;
|
|
358
|
+
source.version++;
|
|
359
|
+
}
|
|
360
|
+
return source;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** An in-memory data source that stays the same object while `rows` and the options do. */
|
|
364
|
+
export function useArraySource(rows, options) {
|
|
365
|
+
const { columns, filterFns, compare } = options ?? {};
|
|
366
|
+
return useMemo(() => createArraySource(rows, { columns, filterFns, compare }), [rows, columns, filterFns, compare]);
|
|
367
|
+
}
|