@borealjs/react-grid 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 +429 -240
- package/index.d.ts +4 -3
- package/package.json +3 -3
- package/src/index.js +2 -1
package/README.md
CHANGED
|
@@ -1,8 +1,20 @@
|
|
|
1
1
|
# @borealjs/react-grid
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/@borealjs/react-grid)
|
|
4
|
+
[](https://github.com/borealjs/grid/blob/main/packages/react-grid/index.d.ts)
|
|
5
|
+
[](https://react.dev)
|
|
6
|
+
[](https://github.com/borealjs/grid/blob/main/LICENSE)
|
|
7
|
+
|
|
8
|
+
A React data grid that stays smooth at any size. Hand it an array, or connect a backend with a hook, and scroll
|
|
9
|
+
through millions of rows (billions with a server). Cells, headers, filters and the empty state are plain React
|
|
10
|
+
components.
|
|
11
|
+
|
|
12
|
+
**[Live demo](https://borealjs.github.io/grid/)**: a billion-row table, a pivot and React 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>
|
|
6
18
|
|
|
7
19
|
```jsx
|
|
8
20
|
<VirtualGrid rows={customers} style={{ height: 600 }}>
|
|
@@ -12,36 +24,54 @@ filters and the empty state are plain React components.
|
|
|
12
24
|
</VirtualGrid>
|
|
13
25
|
```
|
|
14
26
|
|
|
15
|
-
- **
|
|
16
|
-
|
|
17
|
-
- **React all the way
|
|
18
|
-
inline functions are fine
|
|
19
|
-
- **Controlled or uncontrolled** sort,
|
|
20
|
-
-
|
|
21
|
-
pivots with subtotals
|
|
22
|
-
- TypeScript types inferred from your row type
|
|
23
|
-
|
|
27
|
+
- **Your data, your way.** `rows` for data in memory, or `useDataSource` for any backend (REST, GraphQL, SQL,
|
|
28
|
+
a worker). Only what is on screen is requested.
|
|
29
|
+
- **React all the way.** JSX columns; components in cells, headers and filters; your context providers apply;
|
|
30
|
+
inline functions are fine.
|
|
31
|
+
- **Controlled or uncontrolled** sort, filters and selection.
|
|
32
|
+
- **Everything a grid needs.** Multi-column sorting, filters (ranges, dates, text, searchable value lists, your
|
|
33
|
+
own), column chooser, pivots with subtotals, merged cells, range selection, copy, full keyboard support.
|
|
34
|
+
- **Fits your stack.** TypeScript types inferred from your row type; works with Next.js, Remix and Vite; no
|
|
35
|
+
dependencies besides React.
|
|
24
36
|
|
|
25
37
|
## Contents
|
|
26
38
|
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
[
|
|
32
|
-
[
|
|
33
|
-
|
|
34
|
-
|
|
39
|
+
- [Installation](#installation)
|
|
40
|
+
- [Quick start](#quick-start)
|
|
41
|
+
- [Columns](#columns)
|
|
42
|
+
- [Custom cells](#custom-cells)
|
|
43
|
+
- [Data](#data): [in memory](#in-memory-rows), [from a server](#server-data-usedatasource)
|
|
44
|
+
- [Sorting and filtering](#sorting-and-filtering), [custom filters](#custom-filters)
|
|
45
|
+
- [Controlled state](#controlled-state)
|
|
46
|
+
- [Selection and copy](#selection-and-copy)
|
|
47
|
+
- [Grid API (ref)](#grid-api-ref)
|
|
48
|
+
- [Styling and theming](#styling-and-theming), [empty state](#empty-state), [translations](#translations)
|
|
49
|
+
- [TypeScript](#typescript)
|
|
50
|
+
- [Next.js and server rendering](#nextjs-and-server-rendering)
|
|
51
|
+
- [Pivots](#pivots)
|
|
52
|
+
- [Accessibility and keyboard](#accessibility-and-keyboard)
|
|
53
|
+
- [Performance](#performance)
|
|
54
|
+
- [Recipes](#recipes)
|
|
55
|
+
- [API reference](#api-reference)
|
|
56
|
+
- [FAQ](#faq)
|
|
57
|
+
|
|
58
|
+
## Installation
|
|
35
59
|
|
|
36
60
|
```bash
|
|
37
61
|
npm install @borealjs/react-grid @borealjs/grid-core
|
|
62
|
+
# or
|
|
63
|
+
pnpm add @borealjs/react-grid @borealjs/grid-core
|
|
64
|
+
yarn add @borealjs/react-grid @borealjs/grid-core
|
|
65
|
+
bun add @borealjs/react-grid @borealjs/grid-core
|
|
38
66
|
```
|
|
39
67
|
|
|
68
|
+
Import the styles once, for example in your root layout or `main.jsx`:
|
|
69
|
+
|
|
40
70
|
```js
|
|
41
|
-
import '@borealjs/grid-core/style.css';
|
|
71
|
+
import '@borealjs/grid-core/style.css';
|
|
42
72
|
```
|
|
43
73
|
|
|
44
|
-
React 18
|
|
74
|
+
Works with React 18 and 19 in all current browsers.
|
|
45
75
|
|
|
46
76
|
## Quick start
|
|
47
77
|
|
|
@@ -49,77 +79,66 @@ React 18 or 19.
|
|
|
49
79
|
import { VirtualGrid, Column } from '@borealjs/react-grid';
|
|
50
80
|
import '@borealjs/grid-core/style.css';
|
|
51
81
|
|
|
52
|
-
|
|
82
|
+
const customers = [
|
|
83
|
+
{ id: 1, name: 'Ada Lovelace', status: 'Active', amount: 1200, signed: '2024-03-01' },
|
|
84
|
+
{ id: 2, name: 'Grace Hopper', status: 'Pending', amount: 950, signed: '2024-05-17' },
|
|
85
|
+
{ id: 3, name: 'Alan Turing', status: 'Active', amount: 1430, signed: '2023-11-30' },
|
|
86
|
+
];
|
|
87
|
+
|
|
88
|
+
export default function Customers() {
|
|
53
89
|
return (
|
|
54
90
|
<VirtualGrid rows={customers} style={{ height: 600 }} aria-label="Customers">
|
|
55
91
|
<Column field="id" title="ID" type="number" width={80} />
|
|
56
92
|
<Column field="name" title="Customer" width={220} />
|
|
57
93
|
<Column field="status" title="Status" filter="values" />
|
|
58
94
|
<Column field="amount" title="Amount" type="number" format={(v) => `$${v.toFixed(2)}`} />
|
|
59
|
-
<Column field="
|
|
95
|
+
<Column field="signed" title="Signed" type="date" />
|
|
60
96
|
</VirtualGrid>
|
|
61
97
|
);
|
|
62
98
|
}
|
|
63
99
|
```
|
|
64
100
|
|
|
65
101
|
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
|
|
102
|
+
resizes columns, selects ranges, copies with ⌘C / Ctrl+C and works from the keyboard.
|
|
67
103
|
|
|
68
|
-
**
|
|
69
|
-
|
|
104
|
+
> **Important**
|
|
105
|
+
> The grid takes the size of its container. Give it a height with `style`, a CSS class, or make it a flex child
|
|
106
|
+
> with `flex: 1; min-height: 0`. If nothing shows up, this is almost always why.
|
|
70
107
|
|
|
71
108
|
## Columns
|
|
72
109
|
|
|
73
|
-
Columns can be JSX children or an array
|
|
110
|
+
Columns can be JSX children or an array. Both take the same props.
|
|
74
111
|
|
|
75
112
|
```jsx
|
|
76
113
|
const columns = [
|
|
77
114
|
{ field: 'name', title: 'Customer', width: 220 },
|
|
78
115
|
{ field: 'amount', title: 'Amount', type: 'number' },
|
|
79
116
|
];
|
|
117
|
+
|
|
80
118
|
<VirtualGrid rows={rows} columns={columns} />
|
|
81
119
|
```
|
|
82
120
|
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
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 |
|
|
121
|
+
`field` names the row property to show. It is also the column's id in sort, filter and events. `type="number"`
|
|
122
|
+
aligns right and filters by range, `type="date"` filters by date range. All column props are in the
|
|
123
|
+
[API reference](#column).
|
|
100
124
|
|
|
101
|
-
|
|
102
|
-
*structure* changes (fields, titles, types, widths, filters). New functions just redraw the visible cells,
|
|
103
|
-
so closures always see your latest state:
|
|
125
|
+
No memoizing needed: inline arrays and functions are fine, and they always see your latest state.
|
|
104
126
|
|
|
105
127
|
```jsx
|
|
106
|
-
const [
|
|
107
|
-
|
|
128
|
+
const [term, setTerm] = useState('');
|
|
129
|
+
|
|
130
|
+
<Column field="name" renderCell={({ value }) => <Highlight text={value} term={term} />} />
|
|
108
131
|
```
|
|
109
132
|
|
|
110
133
|
## Custom cells
|
|
111
134
|
|
|
112
|
-
|
|
135
|
+
There are three ways to customize a cell, from lightest to most flexible:
|
|
113
136
|
|
|
114
|
-
| | |
|
|
137
|
+
| Prop | Use it for |
|
|
115
138
|
|---|---|
|
|
116
|
-
| `value` | the
|
|
117
|
-
| `
|
|
118
|
-
| `
|
|
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) |
|
|
139
|
+
| `format={(value, ctx) => string}` | the text shown: currencies, dates, units |
|
|
140
|
+
| `cellClass={(value, ctx) => string}` | a CSS class: colors, weights |
|
|
141
|
+
| `renderCell={(ctx) => ReactNode}` | any React content: badges, links, buttons, charts |
|
|
123
142
|
|
|
124
143
|
```jsx
|
|
125
144
|
<Column field="status" renderCell={({ value }) => <span className={`badge badge-${value}`}>{value}</span>} />
|
|
@@ -128,31 +147,45 @@ const [highlight, setHighlight] = useState('');
|
|
|
128
147
|
renderCell={({ row }) => <button onClick={() => openCustomer(row.id)}>Open</button>} />
|
|
129
148
|
```
|
|
130
149
|
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
150
|
+
`renderCell` receives:
|
|
151
|
+
|
|
152
|
+
| | |
|
|
153
|
+
|---|---|
|
|
154
|
+
| `value` | the cell's value |
|
|
155
|
+
| `row` | the whole record (with `rows`; `undefined` for server data) |
|
|
156
|
+
| `text` | the value after `format` |
|
|
157
|
+
| `rowIndex`, `colIndex` | position on screen, after sorting and filtering |
|
|
158
|
+
| `rowSource`, `colSource` | position in the data source |
|
|
159
|
+
| `column` | the column definition |
|
|
160
|
+
| `grid` | the [grid API](#grid-api-ref) |
|
|
161
|
+
|
|
162
|
+
- Components in cells can use hooks and your context providers.
|
|
163
|
+
- Links, buttons and inputs in cells work as usual: clicking them doesn't move the selection, and typing into
|
|
164
|
+
an input stays in the input. Mark other clickable elements with `data-vg-interactive`.
|
|
165
|
+
- `renderHeader={(ctx) => ReactNode}` customizes a header the same way.
|
|
135
166
|
|
|
136
|
-
|
|
137
|
-
|
|
167
|
+
`format`, `cellClass`, `renderCell` and `renderHeader` on `<VirtualGrid>` apply to every column that has none of
|
|
168
|
+
its own, and to pivots.
|
|
138
169
|
|
|
139
170
|
## Data
|
|
140
171
|
|
|
141
|
-
### In
|
|
172
|
+
### In memory: `rows`
|
|
142
173
|
|
|
143
174
|
```jsx
|
|
144
175
|
const [rows, setRows] = useState(initialRows);
|
|
176
|
+
|
|
145
177
|
<VirtualGrid rows={rows} columns={columns} />
|
|
146
178
|
```
|
|
147
179
|
|
|
148
|
-
Sorting
|
|
149
|
-
|
|
150
|
-
|
|
180
|
+
Sorting, filtering and value lists run in the browser; a million rows is fine. Text sorts naturally ("Item 2"
|
|
181
|
+
before "Item 10") and empty values go last. Passing a new array updates the grid in place: scroll position,
|
|
182
|
+
sort, filters and selection stay. Rows can be objects (`field` names a property) or arrays (columns map by
|
|
183
|
+
position).
|
|
151
184
|
|
|
152
185
|
### Server data: `useDataSource`
|
|
153
186
|
|
|
154
|
-
Give the grid callbacks
|
|
155
|
-
|
|
187
|
+
Give the grid a few async callbacks and it asks them only for what is on screen. Every call gets an
|
|
188
|
+
`AbortSignal`: pass it to `fetch` so requests the grid no longer needs are cancelled.
|
|
156
189
|
|
|
157
190
|
```jsx
|
|
158
191
|
import { VirtualGrid, Column, useDataSource } from '@borealjs/react-grid';
|
|
@@ -161,28 +194,30 @@ function Orders({ customerId }) {
|
|
|
161
194
|
const source = useDataSource({
|
|
162
195
|
// How many rows match the current filter.
|
|
163
196
|
async getLayout({ query, signal }) {
|
|
164
|
-
const res = await fetch(`/api/orders/count?${
|
|
197
|
+
const res = await fetch(`/api/orders/count?${toParams(customerId, query)}`, { signal });
|
|
165
198
|
return { rowCount: (await res.json()).count };
|
|
166
199
|
},
|
|
167
|
-
|
|
168
|
-
//
|
|
200
|
+
|
|
201
|
+
// The cells of one or more rectangles.
|
|
169
202
|
async getCells({ rects, query, signal }) {
|
|
170
203
|
const res = await fetch('/api/orders/cells', {
|
|
171
204
|
method: 'POST',
|
|
205
|
+
headers: { 'Content-Type': 'application/json' },
|
|
172
206
|
body: JSON.stringify({ customerId, rects, query }),
|
|
173
207
|
signal,
|
|
174
208
|
});
|
|
175
|
-
return (await res.json()).cells; //
|
|
209
|
+
return (await res.json()).cells; // one entry per rect: [[a, b], [c, d]]
|
|
176
210
|
},
|
|
177
|
-
|
|
211
|
+
|
|
212
|
+
// Optional: values for value-list filters.
|
|
178
213
|
async getFilterValues({ key, search, limit, signal }) {
|
|
179
214
|
const res = await fetch(`/api/orders/values?field=${key}&q=${encodeURIComponent(search)}&limit=${limit}`, { signal });
|
|
180
|
-
return res.json(); // { values:
|
|
215
|
+
return res.json(); // { values: ['Lamp', 'Desk', …], total: 3120, matches: 41 }
|
|
181
216
|
},
|
|
182
217
|
}, [customerId]); // when these change, the grid reloads in place
|
|
183
218
|
|
|
184
219
|
return (
|
|
185
|
-
<VirtualGrid dataSource={source} style={{ height: 600 }}>
|
|
220
|
+
<VirtualGrid dataSource={source} style={{ height: 600 }} aria-label="Orders">
|
|
186
221
|
<Column field="id" title="Order" type="number" />
|
|
187
222
|
<Column field="product" title="Product" filter="values" />
|
|
188
223
|
<Column field="total" title="Total" type="number" />
|
|
@@ -191,51 +226,83 @@ function Orders({ customerId }) {
|
|
|
191
226
|
}
|
|
192
227
|
```
|
|
193
228
|
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
229
|
+
A rect is `{ row, col, rowCount, colCount }`. Rows are positions in the sorted and filtered result; columns
|
|
230
|
+
are column indexes. Answer each rect with its rows of values (`[[a, b], [c, d]]`) or one flat array
|
|
231
|
+
(`[a, b, c, d]`).
|
|
232
|
+
|
|
233
|
+
The callbacks can use props and state freely, and re-rendering your component doesn't reset the grid. Only
|
|
234
|
+
`getCells` is required; without `getLayout`, pass `rowCount` (filtering is then off).
|
|
197
235
|
|
|
198
|
-
|
|
236
|
+
The query describes the current sort and filters:
|
|
199
237
|
|
|
200
238
|
```js
|
|
201
239
|
{
|
|
202
240
|
sort: [{ key: 'total', column: 2, direction: 'desc' }],
|
|
203
241
|
filter: [
|
|
204
|
-
{ key: 'total', column: 2, op: 'range', min: 100, max: 500 },
|
|
205
|
-
{ key: 'product', column: 1, op: 'in', values: ['Lamp'] },
|
|
242
|
+
{ key: 'total', column: 2, op: 'range', min: 100, max: 500 }, // numbers, or dates as 'YYYY-MM-DD'
|
|
243
|
+
{ key: 'product', column: 1, op: 'in', values: ['Lamp'] }, // also 'notin'
|
|
206
244
|
{ key: 'note', column: 4, op: 'contains', text: 'urgent' },
|
|
207
|
-
{ key: 'score', column: 5, op: 'atLeast', value: 90 },
|
|
245
|
+
{ key: 'score', column: 5, op: 'atLeast', value: 90 }, // custom filters
|
|
208
246
|
],
|
|
209
247
|
columnFilter: [],
|
|
210
248
|
}
|
|
211
249
|
```
|
|
212
250
|
|
|
213
|
-
|
|
214
|
-
|
|
251
|
+
With SQL, `filter` becomes a parameterized `WHERE` and `sort` becomes `ORDER BY` (add a unique column last so
|
|
252
|
+
the order is stable). Map `key` to column names through an allow-list on the server; never put client text
|
|
253
|
+
into SQL.
|
|
254
|
+
|
|
255
|
+
If your server implements the [HTTP API in the core guide](https://github.com/borealjs/grid/tree/main/packages/grid-core#ready-made-sources),
|
|
256
|
+
`createHttpSource({ baseUrl, params, headers })` is a ready-made data source for it.
|
|
215
257
|
|
|
216
258
|
## Sorting and filtering
|
|
217
259
|
|
|
218
|
-
|
|
219
|
-
|
|
260
|
+
Click a header to sort (▲, ▼, off); Shift+click adds it to the sort. `sortable={false}` turns sorting off for
|
|
261
|
+
the grid or a column, and `multiSort={false}` allows one sorted column at a time.
|
|
220
262
|
|
|
221
|
-
Each column gets a filter from its `filter` prop, else from its `type`:
|
|
263
|
+
Each column gets a filter dialog from its `filter` prop, or else from its `type`:
|
|
222
264
|
|
|
223
|
-
| |
|
|
265
|
+
| Column | Dialog |
|
|
224
266
|
|---|---|
|
|
225
|
-
| `filter="values"` | checkbox list with search: values from `
|
|
226
|
-
| `filter=
|
|
227
|
-
| `
|
|
228
|
-
| `type="
|
|
267
|
+
| `filter="values"` | checkbox list with search: the values from `rows`, or from your server's `getFilterValues` |
|
|
268
|
+
| `filter={{ type: 'values', values: [...] }}` | checkbox list of the values you give |
|
|
269
|
+
| `filter="text"`, or no `type` | "contains" |
|
|
270
|
+
| `type="number"` or `filter="number"` | min and max |
|
|
271
|
+
| `type="date"` or `filter="date"` | from and to |
|
|
229
272
|
| `filter={{ op, render }}` | your component ([custom filters](#custom-filters)) |
|
|
230
|
-
| `filter={false}` |
|
|
273
|
+
| `filter={false}` | no filter |
|
|
274
|
+
|
|
275
|
+
Value lists show at most 1,000 values; beyond that the dialog asks the user to refine the search. They suit
|
|
276
|
+
columns with a modest set of repeated values (status, city, owner); text search suits near-unique ones (names,
|
|
277
|
+
codes).
|
|
278
|
+
|
|
279
|
+
If your backend can't sort or filter very large tables, return `maxSortRows` / `maxFilterRows` from
|
|
280
|
+
`getLayout`. The grid then explains the limit to the user instead of sending requests that would fail.
|
|
281
|
+
|
|
282
|
+
### Custom filters
|
|
283
|
+
|
|
284
|
+
A custom filter is a component. It receives `{ value, setValue, apply, clear, close, column, title }`, and the
|
|
285
|
+
dialog's Apply button sends the value you set.
|
|
286
|
+
|
|
287
|
+
```jsx
|
|
288
|
+
function MinScore({ value, setValue }) {
|
|
289
|
+
const [min, setMin] = useState(value ?? 50);
|
|
290
|
+
useEffect(() => setValue(min), [min, setValue]);
|
|
291
|
+
return <input type="range" min={0} max={100} value={min} onChange={(e) => setMin(+e.target.value)} />;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
<VirtualGrid rows={rows} filterFns={{ atLeast: (cellValue, min) => cellValue >= min }}>
|
|
295
|
+
<Column field="score" type="number" filter={{ op: 'atLeast', render: (api) => <MinScore {...api} /> }} />
|
|
296
|
+
</VirtualGrid>
|
|
297
|
+
```
|
|
231
298
|
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
explains why filtering is unavailable instead of failing.
|
|
299
|
+
With `rows`, `filterFns[op](cellValue, value, row)` decides which rows stay. A server receives
|
|
300
|
+
`{ key: 'score', op: 'atLeast', value: 72 }` in the query's filter list.
|
|
235
301
|
|
|
236
302
|
## Controlled state
|
|
237
303
|
|
|
238
|
-
Pass a value to control it; leave it out
|
|
304
|
+
Pass a value to control it; leave it out to let the grid keep it (`defaultSort` and friends set where it
|
|
305
|
+
starts).
|
|
239
306
|
|
|
240
307
|
```jsx
|
|
241
308
|
const [sort, setSort] = useState([{ key: 'amount', direction: 'desc' }]);
|
|
@@ -248,107 +315,71 @@ const [filter, setFilter] = useState([]);
|
|
|
248
315
|
<button onClick={() => setFilter([])}>Clear filters</button>
|
|
249
316
|
```
|
|
250
317
|
|
|
251
|
-
| Value | Change event | Uncontrolled
|
|
318
|
+
| Value | Change event | Uncontrolled starting value |
|
|
252
319
|
|---|---|---|
|
|
253
320
|
| `sort` | `onSortChange` | `defaultSort` |
|
|
254
321
|
| `filter` | `onFilterChange` | `defaultFilter` |
|
|
255
322
|
| `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
|
-
```
|
|
323
|
+
| `selectedCells` | `onSelectionChange` | |
|
|
277
324
|
|
|
278
|
-
|
|
279
|
-
`
|
|
325
|
+
Values are compared by content, so a new array with the same items changes nothing. Sort and filter items may
|
|
326
|
+
name a column by `key` (its field) or `column` (its index).
|
|
280
327
|
|
|
281
328
|
## Selection and copy
|
|
282
329
|
|
|
283
|
-
Click, Shift+click, drag, ⌘/Ctrl+click to add ranges, ⌘/Ctrl+A. ⌘C / Ctrl+C copies
|
|
284
|
-
(pastes into
|
|
330
|
+
Click, Shift+click, drag, ⌘/Ctrl+click to add ranges, ⌘/Ctrl+A to select all. ⌘C / Ctrl+C copies the selection
|
|
331
|
+
as tab-separated text (it pastes into Excel and Google Sheets) and as an HTML table, loading cells that are not
|
|
332
|
+
on screen first.
|
|
285
333
|
|
|
286
334
|
```jsx
|
|
287
|
-
<VirtualGrid selection="single" onSelectionChange={(s) => setActive(s.active)} />
|
|
288
|
-
<VirtualGrid
|
|
335
|
+
<VirtualGrid selection="single" onSelectionChange={(s) => setActive(s.active)} /> {/* 'multi' | 'single' | 'none' */}
|
|
336
|
+
<VirtualGrid onCopy={(info) => toast(`Copied ${info.cells} cells`)} />
|
|
289
337
|
```
|
|
290
338
|
|
|
291
|
-
`onSelectionChange` receives `{ active: { r, c }, ranges, text, rows, cols, cells }`.
|
|
292
|
-
`selectedCells={{ active, ranges }}`.
|
|
339
|
+
`onSelectionChange` receives `{ active: { r, c }, ranges, text, rows, cols, cells }`. To control the selection,
|
|
340
|
+
pass `selectedCells={{ active, ranges }}`.
|
|
293
341
|
|
|
294
342
|
## Grid API (ref)
|
|
295
343
|
|
|
296
344
|
```jsx
|
|
297
345
|
const grid = useRef(null);
|
|
298
|
-
<VirtualGrid ref={grid} … />
|
|
299
346
|
|
|
300
|
-
grid
|
|
347
|
+
<VirtualGrid ref={grid} rows={rows} columns={columns} />
|
|
348
|
+
<button onClick={() => grid.current.scrollToCell(5000, 0)}>Go to row 5,000</button>
|
|
301
349
|
```
|
|
302
350
|
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
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 |
|
|
351
|
+
The most used methods are `scrollToCell(row, col)`, `refresh()` (the server's data changed), `toggleSort(field)`,
|
|
352
|
+
`openFilter(field)`, `getQuery()`, `getSelection()` and `copySelection()`. The full list is in the
|
|
353
|
+
[API reference](#grid-api).
|
|
329
354
|
|
|
330
355
|
## Styling and theming
|
|
331
356
|
|
|
332
357
|
```jsx
|
|
333
|
-
<VirtualGrid className="my-grid" style={{ height: '70vh' }} theme="dark" />
|
|
358
|
+
<VirtualGrid className="my-grid" style={{ height: '70vh' }} theme="dark" /> {/* 'auto' (default) | 'light' | 'dark' */}
|
|
334
359
|
```
|
|
335
360
|
|
|
336
|
-
|
|
337
|
-
properties):
|
|
361
|
+
`theme="auto"` follows the system's light or dark mode. Colors, fonts and lines are CSS variables, so the grid
|
|
362
|
+
fits any design system (with Tailwind, set them in your CSS or with arbitrary properties):
|
|
338
363
|
|
|
339
364
|
```css
|
|
340
365
|
.my-grid .vg {
|
|
341
|
-
--vg-bg: #
|
|
342
|
-
--vg-
|
|
366
|
+
--vg-bg: #ffffff;
|
|
367
|
+
--vg-fg: #111827;
|
|
368
|
+
--vg-muted: #6b7280;
|
|
369
|
+
--vg-line: #e5e7eb;
|
|
370
|
+
--vg-head: #f9fafb;
|
|
371
|
+
--vg-zebra: #fcfcfd;
|
|
372
|
+
--vg-accent: #7c3aed;
|
|
373
|
+
--vg-sel-fill: rgb(124 58 237 / 0.1);
|
|
343
374
|
--vg-font: 14px/1.4 Inter, sans-serif;
|
|
344
375
|
}
|
|
345
376
|
```
|
|
346
377
|
|
|
347
|
-
`rowHeight`, `headerHeight`, `columnWidth
|
|
348
|
-
`
|
|
349
|
-
`rowHeader={false}
|
|
378
|
+
Sizes are props (`rowHeight`, `headerHeight`, `columnWidth`), and `rowClass`, `cellClass`, `className` and
|
|
379
|
+
`headerClass` add your own classes. The row-number column is `rowHeader={{ width, title, label }}`, or
|
|
380
|
+
`rowHeader={false}` to hide it.
|
|
350
381
|
|
|
351
|
-
|
|
382
|
+
### Empty state
|
|
352
383
|
|
|
353
384
|
```jsx
|
|
354
385
|
<VirtualGrid rows={rows} emptyState={({ filtered }) => filtered
|
|
@@ -356,15 +387,21 @@ properties):
|
|
|
356
387
|
: <EmptyIllustration />} />
|
|
357
388
|
```
|
|
358
389
|
|
|
359
|
-
|
|
390
|
+
### Translations
|
|
360
391
|
|
|
361
|
-
Every text the grid shows is in `messages
|
|
392
|
+
Every text the grid shows is in `messages`. Pass the ones you want to change:
|
|
362
393
|
|
|
363
394
|
```jsx
|
|
364
|
-
<VirtualGrid messages={{
|
|
365
|
-
|
|
395
|
+
<VirtualGrid messages={{
|
|
396
|
+
noRows: 'Keine Zeilen',
|
|
397
|
+
apply: 'Anwenden',
|
|
398
|
+
clear: 'Zurücksetzen',
|
|
399
|
+
searchValues: (n) => `${n ?? ''} Werte durchsuchen`,
|
|
400
|
+
}} />
|
|
366
401
|
```
|
|
367
402
|
|
|
403
|
+
`DEFAULT_MESSAGES` from `@borealjs/grid-core` has the full list with the English texts.
|
|
404
|
+
|
|
368
405
|
## TypeScript
|
|
369
406
|
|
|
370
407
|
Types come from your row type:
|
|
@@ -372,8 +409,8 @@ Types come from your row type:
|
|
|
372
409
|
```tsx
|
|
373
410
|
type Customer = { id: number; name: string; amount: number; status: 'Active' | 'Closed' };
|
|
374
411
|
|
|
375
|
-
<VirtualGrid<Customer> rows={customers} onSortChange={(sort) =>
|
|
376
|
-
<Column<Customer, 'amount'> field="amount" format={(v) => v.toFixed(2)} />
|
|
412
|
+
<VirtualGrid<Customer> rows={customers} onSortChange={(sort) => setSort(sort)}>
|
|
413
|
+
<Column<Customer, 'amount'> field="amount" format={(v) => v.toFixed(2)} /> {/* v: number */}
|
|
377
414
|
</VirtualGrid>
|
|
378
415
|
```
|
|
379
416
|
|
|
@@ -381,28 +418,29 @@ For column arrays, `createColumnHelper` types each value exactly:
|
|
|
381
418
|
|
|
382
419
|
```tsx
|
|
383
420
|
import { createColumnHelper, type ColumnDef } from '@borealjs/react-grid';
|
|
421
|
+
|
|
384
422
|
const col = createColumnHelper<Customer>();
|
|
385
423
|
|
|
386
424
|
const columns: ColumnDef<Customer>[] = [
|
|
387
425
|
col.field('name', { title: 'Customer' }),
|
|
388
426
|
col.field('amount', { type: 'number', format: (v) => v.toFixed(2) }), // v: number
|
|
389
|
-
col.field('status', { renderCell: ({ value
|
|
427
|
+
col.field('status', { renderCell: ({ value }) => <Badge status={value} /> }), // value: 'Active' | 'Closed'
|
|
390
428
|
col.computed('label', (r) => `${r.name} #${r.id}`, { title: 'Label' }), // value: string
|
|
391
429
|
];
|
|
392
430
|
```
|
|
393
431
|
|
|
394
|
-
|
|
432
|
+
Type the ref as `GridApi`: `useRef<GridApi>(null)`.
|
|
395
433
|
|
|
396
|
-
## Next.js and
|
|
434
|
+
## Next.js and server rendering
|
|
397
435
|
|
|
398
|
-
The package is marked `'use client'
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
container only.
|
|
436
|
+
The package is marked `'use client'`. Render `<VirtualGrid>` from a Server Component when every prop is
|
|
437
|
+
serializable (`rows`, column props without functions); when you pass functions such as `renderCell`, wrap it in
|
|
438
|
+
your own client component. On the server the grid renders an empty container that fills in once the page loads.
|
|
402
439
|
|
|
403
440
|
```tsx
|
|
404
|
-
// app/customers/page.tsx (Server Component)
|
|
405
|
-
import { CustomersGrid } from './customers-grid'; // 'use client' component with your renderCell etc.
|
|
441
|
+
// app/customers/page.tsx (a Server Component)
|
|
442
|
+
import { CustomersGrid } from './customers-grid'; // a 'use client' component with your renderCell etc.
|
|
443
|
+
|
|
406
444
|
export default async function Page() {
|
|
407
445
|
return <CustomersGrid rows={await db.customers.findMany()} />;
|
|
408
446
|
}
|
|
@@ -410,106 +448,257 @@ export default async function Page() {
|
|
|
410
448
|
|
|
411
449
|
## Pivots
|
|
412
450
|
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
451
|
+
Connect a data source whose `getLayout` returns a pivot layout (see
|
|
452
|
+
[Pivots in the core guide](https://github.com/borealjs/grid/tree/main/packages/grid-core#pivots)) and the grid
|
|
453
|
+
draws grouped row and column headers, subtotals and expand/collapse. `grid.current.showLevel('rows', 1)`
|
|
454
|
+
collapses to a level and `grid.current.expandAll('rows')` opens everything again.
|
|
416
455
|
|
|
417
456
|
```jsx
|
|
418
457
|
const pivot = useMemo(() => createHttpSource({ baseUrl: '/api', params: { mode: 'pivot' } }), []);
|
|
419
|
-
|
|
458
|
+
|
|
459
|
+
<VirtualGrid dataSource={pivot} aria-label="Sales by region" onReady={(g) => setLevels(g.levels)} />
|
|
420
460
|
```
|
|
421
461
|
|
|
462
|
+
## Accessibility and keyboard
|
|
463
|
+
|
|
464
|
+
The grid follows the WAI-ARIA grid pattern: one tab stop, with row and column counts, selection, sort and
|
|
465
|
+
expanded state announced to screen readers. Name it with `aria-label`. <kbd>Ctrl</kbd> is <kbd>⌘</kbd> on macOS.
|
|
466
|
+
|
|
467
|
+
| Keys | Action |
|
|
468
|
+
|---|---|
|
|
469
|
+
| <kbd>←</kbd> <kbd>→</kbd> <kbd>↑</kbd> <kbd>↓</kbd> | Move to the next cell |
|
|
470
|
+
| <kbd>Ctrl</kbd>+arrow | Jump to the first or last row or column |
|
|
471
|
+
| <kbd>Home</kbd> / <kbd>End</kbd> | First or last cell of the row |
|
|
472
|
+
| <kbd>Ctrl</kbd>+<kbd>Home</kbd> / <kbd>Ctrl</kbd>+<kbd>End</kbd> | First or last cell of the grid |
|
|
473
|
+
| <kbd>Page Up</kbd> / <kbd>Page Down</kbd> | Move by one screen |
|
|
474
|
+
| <kbd>Shift</kbd>+any of the above | Extend the selection |
|
|
475
|
+
| <kbd>Enter</kbd> / <kbd>Shift</kbd>+<kbd>Enter</kbd> | Next or previous cell; inside a selection, cycle through it |
|
|
476
|
+
| <kbd>Ctrl</kbd>+<kbd>A</kbd> | Select all |
|
|
477
|
+
| <kbd>Ctrl</kbd>+<kbd>C</kbd> | Copy the selection |
|
|
478
|
+
| <kbd>Escape</kbd> | Reduce the selection to the active cell |
|
|
479
|
+
| <kbd>Alt</kbd>+<kbd>S</kbd> | Sort by the active column (<kbd>Shift</kbd> adds it to the sort) |
|
|
480
|
+
| <kbd>Alt</kbd>+<kbd>F</kbd> | Open the active column's filter |
|
|
481
|
+
| <kbd>Alt</kbd>+<kbd>Shift</kbd>+arrow | Collapse or expand a pivot group |
|
|
482
|
+
|
|
422
483
|
## Performance
|
|
423
484
|
|
|
424
|
-
|
|
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.
|
|
485
|
+
The grid stays fast with any amount of data. A few habits keep your own code from slowing it down.
|
|
433
486
|
|
|
434
|
-
|
|
487
|
+
**Use `format` for plain text.** It is much lighter than a component.
|
|
435
488
|
|
|
436
|
-
|
|
437
|
-
|
|
489
|
+
```jsx
|
|
490
|
+
// ✅ Good
|
|
491
|
+
<Column field="amount" format={(v) => money.format(v)} />
|
|
438
492
|
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
493
|
+
// ❌ Avoid: a React component per cell just to show text
|
|
494
|
+
<Column field="amount" renderCell={({ value }) => <>{money.format(value)}</>} />
|
|
495
|
+
```
|
|
496
|
+
|
|
497
|
+
**Derive rows with `useMemo`.** A new `rows` array tells the grid the data changed, so it sorts and filters
|
|
498
|
+
again.
|
|
499
|
+
|
|
500
|
+
```jsx
|
|
501
|
+
// ✅ Good: a new array only when the data or the search changes
|
|
502
|
+
const visible = useMemo(() => orders.filter((o) => o.region === region), [orders, region]);
|
|
503
|
+
<VirtualGrid rows={visible} />
|
|
504
|
+
|
|
505
|
+
// ❌ Avoid: a new array on every render
|
|
506
|
+
<VirtualGrid rows={orders.filter((o) => o.region === region)} />
|
|
507
|
+
```
|
|
508
|
+
|
|
509
|
+
**Keep column titles, types, widths and filters steady.** Changing one redraws the whole grid (scroll, sort and
|
|
510
|
+
filters are kept). Functions can change freely.
|
|
511
|
+
|
|
512
|
+
```jsx
|
|
513
|
+
// ❌ Avoid: the title changes on every update of `count`
|
|
514
|
+
<Column field="name" title={`Customers (${count})`} />
|
|
515
|
+
```
|
|
516
|
+
|
|
517
|
+
**Keep cell components light.** Load data for the grid through the data source, not inside cells.
|
|
518
|
+
|
|
519
|
+
**With `getColumn`** (thousands of columns), wrap the function in `useCallback`.
|
|
448
520
|
|
|
449
521
|
## Recipes
|
|
450
522
|
|
|
451
|
-
**
|
|
523
|
+
**Search box over server data**
|
|
452
524
|
|
|
453
525
|
```jsx
|
|
454
526
|
const [search, setSearch] = useState('');
|
|
455
|
-
const
|
|
456
|
-
const source = useDataSource({
|
|
527
|
+
const deferred = useDeferredValue(search); // or your own debounce hook
|
|
528
|
+
const source = useDataSource({
|
|
529
|
+
getLayout: ({ query, signal }) => api.count({ query, search: deferred }, signal),
|
|
530
|
+
getCells: ({ rects, query, signal }) => api.cells({ rects, query, search: deferred }, signal),
|
|
531
|
+
}, [deferred]);
|
|
457
532
|
```
|
|
458
533
|
|
|
459
|
-
**TanStack Query
|
|
534
|
+
**Cache with TanStack Query**
|
|
460
535
|
|
|
461
536
|
```jsx
|
|
462
537
|
const queryClient = useQueryClient();
|
|
463
538
|
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
539
|
getLayout: ({ query, signal }) =>
|
|
467
|
-
queryClient.fetchQuery({ queryKey: ['count', query], queryFn: () => api.count(query, signal) }),
|
|
540
|
+
queryClient.fetchQuery({ queryKey: ['orders', 'count', query], queryFn: () => api.count(query, signal) }),
|
|
541
|
+
getCells: ({ rects, query, signal }) =>
|
|
542
|
+
queryClient.fetchQuery({ queryKey: ['orders', 'cells', rects, query], queryFn: () => api.cells(rects, query, signal), staleTime: 60_000 }),
|
|
468
543
|
});
|
|
469
544
|
```
|
|
470
545
|
|
|
471
|
-
**Refresh after
|
|
546
|
+
**Refresh after saving**
|
|
472
547
|
|
|
473
548
|
```jsx
|
|
474
549
|
await api.updateOrder(id, patch);
|
|
475
|
-
grid.current.refresh();
|
|
476
|
-
setRows((rows) =>
|
|
550
|
+
grid.current.refresh(); // server data
|
|
551
|
+
setRows((rows) => rows.map((r) => (r.id === id ? { ...r, ...patch } : r))); // in-memory rows
|
|
477
552
|
```
|
|
478
553
|
|
|
479
|
-
**Row actions
|
|
554
|
+
**Row actions**
|
|
480
555
|
|
|
481
556
|
```jsx
|
|
482
557
|
<Column field="actions" title="" width={120} sortable={false} filter={false}
|
|
483
|
-
renderCell={({ row }) => <
|
|
558
|
+
renderCell={({ row }) => <RowMenu onEdit={() => edit(row)} onDelete={() => remove(row.id)} />} />
|
|
484
559
|
```
|
|
485
560
|
|
|
486
|
-
##
|
|
561
|
+
## API reference
|
|
562
|
+
|
|
563
|
+
### `<VirtualGrid>`
|
|
564
|
+
|
|
565
|
+
#### Data
|
|
566
|
+
|
|
567
|
+
| Prop | Type | Default | |
|
|
568
|
+
|---|---|---|---|
|
|
569
|
+
| `rows` | `Row[]` | | data in memory |
|
|
570
|
+
| `dataSource` | `DataSource` | | or your backend ([server data](#server-data-usedatasource)) |
|
|
571
|
+
| `columns` | `ColumnDef<Row>[]` | | or `<Column>` children |
|
|
572
|
+
| `columnCount`, `getColumn` | `number`, `(index) => ColumnDef` | | instead of `columns`, for thousands of columns |
|
|
573
|
+
| `rowCount` | `number` | | row count when the data source has no `getLayout` |
|
|
574
|
+
| `filterFns` | `{ [op]: (cellValue, value, row) => boolean }` | | custom filter operators for `rows` |
|
|
575
|
+
|
|
576
|
+
#### Features
|
|
577
|
+
|
|
578
|
+
| Prop | Type | Default | |
|
|
579
|
+
|---|---|---|---|
|
|
580
|
+
| `sortable` | `boolean` | `true` | |
|
|
581
|
+
| `multiSort` | `boolean` | `true` | Shift+click adds columns to the sort |
|
|
582
|
+
| `filterable` | `boolean` | `true` | |
|
|
583
|
+
| `resizable` | `boolean` | `true` | |
|
|
584
|
+
| `expandable` | `boolean` | `true` | expand and collapse pivot groups |
|
|
585
|
+
| `selection` | `'multi' \| 'single' \| 'none'` | `'multi'` | |
|
|
586
|
+
| `copy` | `boolean` | `true` | ⌘C / Ctrl+C |
|
|
587
|
+
| `keyboard` | `boolean` | `true` | |
|
|
588
|
+
| `notices` | `boolean` | `true` | a short message when a sort or filter is refused or fails |
|
|
589
|
+
| `columnChooser` | `boolean` | on when columns have a `group` | a corner menu to show and hide column groups |
|
|
590
|
+
|
|
591
|
+
#### Look
|
|
592
|
+
|
|
593
|
+
| Prop | Type | Default | |
|
|
594
|
+
|---|---|---|---|
|
|
595
|
+
| `className`, `style`, `id` | | | on the grid's container |
|
|
596
|
+
| `aria-label` | `string` | | the grid's name for screen readers |
|
|
597
|
+
| `theme` | `'auto' \| 'light' \| 'dark'` | `'auto'` | |
|
|
598
|
+
| `rowHeight` | `number` | `28` | px |
|
|
599
|
+
| `headerHeight` | `number` | `34` | px |
|
|
600
|
+
| `columnWidth` | `number` | `132` | px, for columns without `width` |
|
|
601
|
+
| `minColumnWidth` | `number` | `48` | px |
|
|
602
|
+
| `rowHeader` | `false \| { width, title, label(row) }` | row numbers | |
|
|
603
|
+
| `rowClass` | `(rowIndex) => string` | | |
|
|
604
|
+
| `format`, `cellClass`, `renderCell`, `renderHeader` | | | for columns without their own |
|
|
605
|
+
| `emptyState` | `ReactNode \| ({ filtered }) => ReactNode` | "No rows" | |
|
|
606
|
+
| `messages` | `Partial<Messages>` | English | |
|
|
607
|
+
|
|
608
|
+
#### State
|
|
609
|
+
|
|
610
|
+
| Prop | Type | |
|
|
611
|
+
|---|---|---|
|
|
612
|
+
| `sort`, `defaultSort` | `SortItem[]` | controlled, or the starting value |
|
|
613
|
+
| `filter`, `defaultFilter` | `FilterItem[]` | |
|
|
614
|
+
| `columnFilter`, `defaultColumnFilter` | `ColumnFilterItem[]` | which column groups are shown |
|
|
615
|
+
| `selectedCells` | `{ active, ranges }` | controlled selection |
|
|
616
|
+
|
|
617
|
+
#### Events
|
|
618
|
+
|
|
619
|
+
| Prop | Receives |
|
|
620
|
+
|---|---|
|
|
621
|
+
| `onSortChange` | `SortItem[]` |
|
|
622
|
+
| `onFilterChange` | `FilterItem[]` |
|
|
623
|
+
| `onColumnFilterChange` | `ColumnFilterItem[]` |
|
|
624
|
+
| `onSelectionChange` | `{ active, ranges, text, rows, cols, cells }` |
|
|
625
|
+
| `onCopy` | `{ ok, cells, rows, cols, ms, reason? }` |
|
|
626
|
+
| `onColumnResize` | `{ column, key, width }`, when the user lets go |
|
|
627
|
+
| `onViewChange` | `{ what, pending }` while a sort or filter runs, then `{ what, ok, rows, reason? }` |
|
|
628
|
+
| `onError` | `(error, { kind: 'layout' \| 'cells' \| 'labels' })`; errors are logged when this is not set |
|
|
629
|
+
| `onReady` | `(grid)` once the grid is drawn |
|
|
630
|
+
|
|
631
|
+
### `<Column>`
|
|
632
|
+
|
|
633
|
+
The same props work in a `columns` array.
|
|
634
|
+
|
|
635
|
+
| Prop | Type | |
|
|
636
|
+
|---|---|---|
|
|
637
|
+
| `field` | `string` | the row property, and the column's id in sort, filter and events (alias: `key`) |
|
|
638
|
+
| `title` | `string` | header text |
|
|
639
|
+
| `type` | `'text' \| 'number' \| 'date'` | alignment and the default filter |
|
|
640
|
+
| `width` | `number` | px |
|
|
641
|
+
| `align` | `'start' \| 'end' \| 'center'` | |
|
|
642
|
+
| `filter` | see [sorting and filtering](#sorting-and-filtering) | |
|
|
643
|
+
| `sortable`, `resizable`, `hidden` | `boolean` | |
|
|
644
|
+
| `group` | `string` | group name for the column chooser |
|
|
645
|
+
| `format` | `(value, ctx) => string` | text shown in the cell |
|
|
646
|
+
| `cellClass` | `(value, ctx) => string` | a class per cell |
|
|
647
|
+
| `className`, `headerClass` | `string` | classes for every cell, or the header |
|
|
648
|
+
| `renderCell` | `(ctx) => ReactNode` | your own cell content |
|
|
649
|
+
| `renderHeader` | `(ctx) => ReactNode` | your own header content |
|
|
650
|
+
| `value` | `(row) => any` | a computed value (with `rows`) |
|
|
651
|
+
| `compare` | `(a, b) => number` | a custom sort order (with `rows`) |
|
|
652
|
+
|
|
653
|
+
### Grid API
|
|
654
|
+
|
|
655
|
+
What the `ref` gives you.
|
|
656
|
+
|
|
657
|
+
| Method | |
|
|
658
|
+
|---|---|
|
|
659
|
+
| `scrollToCell(row, col?)` | bring a cell into view |
|
|
660
|
+
| `refresh()` | reload the visible data (it changed on the server) |
|
|
661
|
+
| `getQuery()`, `getSort()`, `getFilter()`, `getColumnFilter()` | the current sort and filters |
|
|
662
|
+
| `setSort(sort)`, `setFilter(filter)`, `setColumnFilter(list)` | change uncontrolled state; resolve to `false` if refused |
|
|
663
|
+
| `toggleSort(field, additive?)` | what a header click does |
|
|
664
|
+
| `openFilter(field)`, `closeFilter()` | the filter dialog |
|
|
665
|
+
| `getSelection()`, `setSelection(sel)`, `selectAll()`, `selectionInfo()` | selection |
|
|
666
|
+
| `copySelection()` | copy, as with ⌘C / Ctrl+C |
|
|
667
|
+
| `cellValue(row, col)`, `cellText(row, col)` | a loaded cell's value or text |
|
|
668
|
+
| `setColumnWidth(col, px)` | |
|
|
669
|
+
| `setMerges(merges)` | merged cells: `[{ r0, c0, nr, nc, label? }]` |
|
|
670
|
+
| `rowCount`, `columnCount`, `visibleRange` | sizes and what is on screen |
|
|
671
|
+
| `levels`, `showLevel(axis, level)`, `expandAll(axis)`, `toggleGroup(axis, level, group)` | pivots |
|
|
672
|
+
| `focus()` | |
|
|
673
|
+
|
|
674
|
+
### Hooks and helpers
|
|
487
675
|
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
`
|
|
491
|
-
|
|
492
|
-
`
|
|
493
|
-
|
|
494
|
-
Hooks: `format`, `cellClass`, `renderCell`, `renderHeader`.
|
|
495
|
-
Events: `onSortChange`, `onFilterChange`, `onColumnFilterChange`, `onSelectionChange`, `onCopy`, `onColumnResize`,
|
|
496
|
-
`onViewChange`, `onError`, `onReady`.
|
|
497
|
-
Other: `ref`, `id`, `aria-label`.
|
|
676
|
+
| | |
|
|
677
|
+
|---|---|
|
|
678
|
+
| `useDataSource(callbacks, deps)` | a data source from callbacks; when `deps` change, the grid reloads in place |
|
|
679
|
+
| `useArraySource(rows, options)` | an in-memory data source you can share or pass as `dataSource` |
|
|
680
|
+
| `createColumnHelper<Row>()` | typed column definitions ([TypeScript](#typescript)) |
|
|
681
|
+
| `createArraySource`, `createHttpSource` | the [ready-made sources](https://github.com/borealjs/grid/tree/main/packages/grid-core#ready-made-sources) from the core package |
|
|
498
682
|
|
|
499
683
|
## FAQ
|
|
500
684
|
|
|
501
|
-
**Nothing shows up.**
|
|
685
|
+
**Nothing shows up.** Give the grid a height (see [Quick start](#quick-start)).
|
|
686
|
+
|
|
687
|
+
**Can users edit cells?** Not built in yet. Render an input with `renderCell`, save the change, then update
|
|
688
|
+
`rows` or call `refresh()`.
|
|
689
|
+
|
|
690
|
+
**Can I export to Excel?** Copying a selection pastes straight into Excel and Google Sheets. File export is not
|
|
691
|
+
built in.
|
|
502
692
|
|
|
503
|
-
**
|
|
504
|
-
|
|
693
|
+
**Clicking a button in a cell selects the cell.** Links, buttons and form fields are handled for you; add
|
|
694
|
+
`data-vg-interactive` to other clickable elements.
|
|
505
695
|
|
|
506
|
-
**
|
|
507
|
-
|
|
696
|
+
**How do I show 10,000+ columns?** Use `columnCount` and `getColumn(index)` instead of an array. Titles you
|
|
697
|
+
leave out can come from the data source's `getLabels`.
|
|
508
698
|
|
|
509
|
-
**
|
|
510
|
-
|
|
699
|
+
**Can I use it without React?** Yes: [`@borealjs/grid-core`](https://www.npmjs.com/package/@borealjs/grid-core)
|
|
700
|
+
has the same features with a plain JavaScript API.
|
|
511
701
|
|
|
512
|
-
|
|
513
|
-
`refresh()` / update `rows`.
|
|
702
|
+
## License
|
|
514
703
|
|
|
515
|
-
|
|
704
|
+
[MIT](https://github.com/borealjs/grid/blob/main/LICENSE)
|
package/index.d.ts
CHANGED
|
@@ -52,7 +52,7 @@ type FieldValue<Row, F> = string extends F ? any : F extends keyof Row ? Row[F]
|
|
|
52
52
|
|
|
53
53
|
/**
|
|
54
54
|
* A column. With in-memory `rows`, `field` names the property to show (or use `value(row)`).
|
|
55
|
-
* Functions may be inline
|
|
55
|
+
* Functions may be inline. Changing a field, title, type, width or filter redraws the whole grid.
|
|
56
56
|
*/
|
|
57
57
|
export interface ColumnDef<Row = any, F extends string = string, V = FieldValue<Row, F>>
|
|
58
58
|
extends Omit<CoreColumnDef, 'key' | 'renderCell' | 'renderHeader' | 'filter' | 'format' | 'cellClass' | 'value' | 'compare'> {
|
|
@@ -81,7 +81,7 @@ export function createColumnHelper<Row>(): {
|
|
|
81
81
|
};
|
|
82
82
|
|
|
83
83
|
export interface VirtualGridProps<Row = any>
|
|
84
|
-
extends Omit<GridOptions, 'dataSource' | 'columns' | 'getColumn' | 'renderCell' | 'renderHeader' | 'renderEmpty' | 'format' | 'cellClass' | 'controlled'> {
|
|
84
|
+
extends Omit<GridOptions, 'ariaLabel' | 'dataSource' | 'columns' | 'getColumn' | 'renderCell' | 'renderHeader' | 'renderEmpty' | 'format' | 'cellClass' | 'controlled'> {
|
|
85
85
|
/** In-memory data (sorted, filtered and searched in the browser). New arrays update the grid in place. */
|
|
86
86
|
rows?: readonly Row[];
|
|
87
87
|
/** Or any data source (your backend: see useDataSource). */
|
|
@@ -89,7 +89,7 @@ export interface VirtualGridProps<Row = any>
|
|
|
89
89
|
columns?: ColumnDef<Row>[];
|
|
90
90
|
/** Or declare columns as <Column> children. */
|
|
91
91
|
children?: ReactNode;
|
|
92
|
-
/** Very wide tables: describe column i (wrap in useCallback; a new function
|
|
92
|
+
/** Very wide tables: describe column i (wrap in useCallback; a new function redraws the whole grid). */
|
|
93
93
|
getColumn?(index: number): ColumnDef<Row>;
|
|
94
94
|
/** In-memory rows: custom filter operators, { op: (cellValue, conditionValue, row) => boolean }. */
|
|
95
95
|
filterFns?: Record<string, (value: any, conditionValue: any, row: Row) => boolean>;
|
|
@@ -105,6 +105,7 @@ export interface VirtualGridProps<Row = any>
|
|
|
105
105
|
className?: string;
|
|
106
106
|
style?: CSSProperties;
|
|
107
107
|
id?: string;
|
|
108
|
+
/** Accessible name of the grid, read by screen readers. */
|
|
108
109
|
'aria-label'?: string;
|
|
109
110
|
ref?: Ref<Grid>;
|
|
110
111
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@borealjs/react-grid",
|
|
3
|
-
"version": "0.1.
|
|
4
|
-
"description": "React
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "React data grid for huge datasets: in-memory rows or any backend, React cells, headers and filters, sorting, filtering, pivots and copy.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"repository": {
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
],
|
|
32
32
|
"sideEffects": false,
|
|
33
33
|
"dependencies": {
|
|
34
|
-
"@borealjs/grid-core": "0.1.
|
|
34
|
+
"@borealjs/grid-core": "0.1.1"
|
|
35
35
|
},
|
|
36
36
|
"peerDependencies": {
|
|
37
37
|
"react": ">=18",
|
package/src/index.js
CHANGED
|
@@ -233,6 +233,7 @@ export const VirtualGrid = forwardRef(function VirtualGrid(props, ref) {
|
|
|
233
233
|
const options = {
|
|
234
234
|
...Object.fromEntries(PASS.map((k) => [k, props[k]])),
|
|
235
235
|
...stableObjects,
|
|
236
|
+
ariaLabel: props['aria-label'],
|
|
236
237
|
dataSource,
|
|
237
238
|
columns,
|
|
238
239
|
getColumn,
|
|
@@ -322,7 +323,7 @@ export const VirtualGrid = forwardRef(function VirtualGrid(props, ref) {
|
|
|
322
323
|
null,
|
|
323
324
|
createElement(
|
|
324
325
|
'div',
|
|
325
|
-
{ className, style: { position: 'relative', minHeight: 0, ...style }, id
|
|
326
|
+
{ className, style: { position: 'relative', minHeight: 0, ...style }, id },
|
|
326
327
|
createElement('div', { ref: hostRef, style: { position: 'absolute', inset: 0 } }),
|
|
327
328
|
),
|
|
328
329
|
createElement(Portals, { store }),
|