@borealjs/react-grid 0.0.0-stage → 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/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,704 @@
1
- # Temporary Holding Version
1
+ # @borealjs/react-grid
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm](https://img.shields.io/npm/v/@borealjs/react-grid)](https://www.npmjs.com/package/@borealjs/react-grid)
4
+ [![Types](https://img.shields.io/npm/types/@borealjs/react-grid)](https://github.com/borealjs/grid/blob/main/packages/react-grid/index.d.ts)
5
+ [![React 18 and 19](https://img.shields.io/badge/React-18%20%7C%2019-087ea4?logo=react)](https://react.dev)
6
+ [![License](https://img.shields.io/npm/l/@borealjs/react-grid)](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>
18
+
19
+ ```jsx
20
+ <VirtualGrid rows={customers} style={{ height: 600 }}>
21
+ <Column field="name" title="Customer" />
22
+ <Column field="status" title="Status" filter="values" renderCell={({ value }) => <Badge status={value} />} />
23
+ <Column field="amount" title="Amount" type="number" format={(v) => money.format(v)} />
24
+ </VirtualGrid>
25
+ ```
26
+
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.
36
+
37
+ ## Contents
38
+
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
59
+
60
+ ```bash
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
66
+ ```
67
+
68
+ Import the styles once, for example in your root layout or `main.jsx`:
69
+
70
+ ```js
71
+ import '@borealjs/grid-core/style.css';
72
+ ```
73
+
74
+ Works with React 18 and 19 in all current browsers.
75
+
76
+ ## Quick start
77
+
78
+ ```jsx
79
+ import { VirtualGrid, Column } from '@borealjs/react-grid';
80
+ import '@borealjs/grid-core/style.css';
81
+
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() {
89
+ return (
90
+ <VirtualGrid rows={customers} style={{ height: 600 }} aria-label="Customers">
91
+ <Column field="id" title="ID" type="number" width={80} />
92
+ <Column field="name" title="Customer" width={220} />
93
+ <Column field="status" title="Status" filter="values" />
94
+ <Column field="amount" title="Amount" type="number" format={(v) => `$${v.toFixed(2)}`} />
95
+ <Column field="signed" title="Signed" type="date" />
96
+ </VirtualGrid>
97
+ );
98
+ }
99
+ ```
100
+
101
+ That grid already sorts (click a header; Shift+click adds a column), filters (the funnel in each header),
102
+ resizes columns, selects ranges, copies with ⌘C / Ctrl+C and works from the keyboard.
103
+
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.
107
+
108
+ ## Columns
109
+
110
+ Columns can be JSX children or an array. Both take the same props.
111
+
112
+ ```jsx
113
+ const columns = [
114
+ { field: 'name', title: 'Customer', width: 220 },
115
+ { field: 'amount', title: 'Amount', type: 'number' },
116
+ ];
117
+
118
+ <VirtualGrid rows={rows} columns={columns} />
119
+ ```
120
+
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).
124
+
125
+ No memoizing needed: inline arrays and functions are fine, and they always see your latest state.
126
+
127
+ ```jsx
128
+ const [term, setTerm] = useState('');
129
+
130
+ <Column field="name" renderCell={({ value }) => <Highlight text={value} term={term} />} />
131
+ ```
132
+
133
+ ## Custom cells
134
+
135
+ There are three ways to customize a cell, from lightest to most flexible:
136
+
137
+ | Prop | Use it for |
138
+ |---|---|
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 |
142
+
143
+ ```jsx
144
+ <Column field="status" renderCell={({ value }) => <span className={`badge badge-${value}`}>{value}</span>} />
145
+ <Column field="progress" type="number" renderCell={({ value }) => <ProgressBar value={value} />} />
146
+ <Column field="actions" title="" sortable={false} filter={false}
147
+ renderCell={({ row }) => <button onClick={() => openCustomer(row.id)}>Open</button>} />
148
+ ```
149
+
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.
166
+
167
+ `format`, `cellClass`, `renderCell` and `renderHeader` on `<VirtualGrid>` apply to every column that has none of
168
+ its own, and to pivots.
169
+
170
+ ## Data
171
+
172
+ ### In memory: `rows`
173
+
174
+ ```jsx
175
+ const [rows, setRows] = useState(initialRows);
176
+
177
+ <VirtualGrid rows={rows} columns={columns} />
178
+ ```
179
+
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).
184
+
185
+ ### Server data: `useDataSource`
186
+
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.
189
+
190
+ ```jsx
191
+ import { VirtualGrid, Column, useDataSource } from '@borealjs/react-grid';
192
+
193
+ function Orders({ customerId }) {
194
+ const source = useDataSource({
195
+ // How many rows match the current filter.
196
+ async getLayout({ query, signal }) {
197
+ const res = await fetch(`/api/orders/count?${toParams(customerId, query)}`, { signal });
198
+ return { rowCount: (await res.json()).count };
199
+ },
200
+
201
+ // The cells of one or more rectangles.
202
+ async getCells({ rects, query, signal }) {
203
+ const res = await fetch('/api/orders/cells', {
204
+ method: 'POST',
205
+ headers: { 'Content-Type': 'application/json' },
206
+ body: JSON.stringify({ customerId, rects, query }),
207
+ signal,
208
+ });
209
+ return (await res.json()).cells; // one entry per rect: [[a, b], [c, d]]
210
+ },
211
+
212
+ // Optional: values for value-list filters.
213
+ async getFilterValues({ key, search, limit, signal }) {
214
+ const res = await fetch(`/api/orders/values?field=${key}&q=${encodeURIComponent(search)}&limit=${limit}`, { signal });
215
+ return res.json(); // { values: ['Lamp', 'Desk', …], total: 3120, matches: 41 }
216
+ },
217
+ }, [customerId]); // when these change, the grid reloads in place
218
+
219
+ return (
220
+ <VirtualGrid dataSource={source} style={{ height: 600 }} aria-label="Orders">
221
+ <Column field="id" title="Order" type="number" />
222
+ <Column field="product" title="Product" filter="values" />
223
+ <Column field="total" title="Total" type="number" />
224
+ </VirtualGrid>
225
+ );
226
+ }
227
+ ```
228
+
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).
235
+
236
+ The query describes the current sort and filters:
237
+
238
+ ```js
239
+ {
240
+ sort: [{ key: 'total', column: 2, direction: 'desc' }],
241
+ filter: [
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'
244
+ { key: 'note', column: 4, op: 'contains', text: 'urgent' },
245
+ { key: 'score', column: 5, op: 'atLeast', value: 90 }, // custom filters
246
+ ],
247
+ columnFilter: [],
248
+ }
249
+ ```
250
+
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.
257
+
258
+ ## Sorting and filtering
259
+
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.
262
+
263
+ Each column gets a filter dialog from its `filter` prop, or else from its `type`:
264
+
265
+ | Column | Dialog |
266
+ |---|---|
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 |
272
+ | `filter={{ op, render }}` | your component ([custom filters](#custom-filters)) |
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
+ ```
298
+
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.
301
+
302
+ ## Controlled state
303
+
304
+ Pass a value to control it; leave it out to let the grid keep it (`defaultSort` and friends set where it
305
+ starts).
306
+
307
+ ```jsx
308
+ const [sort, setSort] = useState([{ key: 'amount', direction: 'desc' }]);
309
+ const [filter, setFilter] = useState([]);
310
+
311
+ <VirtualGrid rows={rows} columns={columns}
312
+ sort={sort} onSortChange={setSort}
313
+ filter={filter} onFilterChange={setFilter} />
314
+
315
+ <button onClick={() => setFilter([])}>Clear filters</button>
316
+ ```
317
+
318
+ | Value | Change event | Uncontrolled starting value |
319
+ |---|---|---|
320
+ | `sort` | `onSortChange` | `defaultSort` |
321
+ | `filter` | `onFilterChange` | `defaultFilter` |
322
+ | `columnFilter` | `onColumnFilterChange` | `defaultColumnFilter` |
323
+ | `selectedCells` | `onSelectionChange` | |
324
+
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).
327
+
328
+ ## Selection and copy
329
+
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.
333
+
334
+ ```jsx
335
+ <VirtualGrid selection="single" onSelectionChange={(s) => setActive(s.active)} /> {/* 'multi' | 'single' | 'none' */}
336
+ <VirtualGrid onCopy={(info) => toast(`Copied ${info.cells} cells`)} />
337
+ ```
338
+
339
+ `onSelectionChange` receives `{ active: { r, c }, ranges, text, rows, cols, cells }`. To control the selection,
340
+ pass `selectedCells={{ active, ranges }}`.
341
+
342
+ ## Grid API (ref)
343
+
344
+ ```jsx
345
+ const grid = useRef(null);
346
+
347
+ <VirtualGrid ref={grid} rows={rows} columns={columns} />
348
+ <button onClick={() => grid.current.scrollToCell(5000, 0)}>Go to row 5,000</button>
349
+ ```
350
+
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).
354
+
355
+ ## Styling and theming
356
+
357
+ ```jsx
358
+ <VirtualGrid className="my-grid" style={{ height: '70vh' }} theme="dark" /> {/* 'auto' (default) | 'light' | 'dark' */}
359
+ ```
360
+
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):
363
+
364
+ ```css
365
+ .my-grid .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);
374
+ --vg-font: 14px/1.4 Inter, sans-serif;
375
+ }
376
+ ```
377
+
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.
381
+
382
+ ### Empty state
383
+
384
+ ```jsx
385
+ <VirtualGrid rows={rows} emptyState={({ filtered }) => filtered
386
+ ? <p>No matches. <button onClick={() => setFilter([])}>Clear filters</button></p>
387
+ : <EmptyIllustration />} />
388
+ ```
389
+
390
+ ### Translations
391
+
392
+ Every text the grid shows is in `messages`. Pass the ones you want to change:
393
+
394
+ ```jsx
395
+ <VirtualGrid messages={{
396
+ noRows: 'Keine Zeilen',
397
+ apply: 'Anwenden',
398
+ clear: 'Zurücksetzen',
399
+ searchValues: (n) => `${n ?? ''} Werte durchsuchen`,
400
+ }} />
401
+ ```
402
+
403
+ `DEFAULT_MESSAGES` from `@borealjs/grid-core` has the full list with the English texts.
404
+
405
+ ## TypeScript
406
+
407
+ Types come from your row type:
408
+
409
+ ```tsx
410
+ type Customer = { id: number; name: string; amount: number; status: 'Active' | 'Closed' };
411
+
412
+ <VirtualGrid<Customer> rows={customers} onSortChange={(sort) => setSort(sort)}>
413
+ <Column<Customer, 'amount'> field="amount" format={(v) => v.toFixed(2)} /> {/* v: number */}
414
+ </VirtualGrid>
415
+ ```
416
+
417
+ For column arrays, `createColumnHelper` types each value exactly:
418
+
419
+ ```tsx
420
+ import { createColumnHelper, type ColumnDef } from '@borealjs/react-grid';
421
+
422
+ const col = createColumnHelper<Customer>();
423
+
424
+ const columns: ColumnDef<Customer>[] = [
425
+ col.field('name', { title: 'Customer' }),
426
+ col.field('amount', { type: 'number', format: (v) => v.toFixed(2) }), // v: number
427
+ col.field('status', { renderCell: ({ value }) => <Badge status={value} /> }), // value: 'Active' | 'Closed'
428
+ col.computed('label', (r) => `${r.name} #${r.id}`, { title: 'Label' }), // value: string
429
+ ];
430
+ ```
431
+
432
+ Type the ref as `GridApi`: `useRef<GridApi>(null)`.
433
+
434
+ ## Next.js and server rendering
435
+
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.
439
+
440
+ ```tsx
441
+ // app/customers/page.tsx (a Server Component)
442
+ import { CustomersGrid } from './customers-grid'; // a 'use client' component with your renderCell etc.
443
+
444
+ export default async function Page() {
445
+ return <CustomersGrid rows={await db.customers.findMany()} />;
446
+ }
447
+ ```
448
+
449
+ ## Pivots
450
+
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.
455
+
456
+ ```jsx
457
+ const pivot = useMemo(() => createHttpSource({ baseUrl: '/api', params: { mode: 'pivot' } }), []);
458
+
459
+ <VirtualGrid dataSource={pivot} aria-label="Sales by region" onReady={(g) => setLevels(g.levels)} />
460
+ ```
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
+
483
+ ## Performance
484
+
485
+ The grid stays fast with any amount of data. A few habits keep your own code from slowing it down.
486
+
487
+ **Use `format` for plain text.** It is much lighter than a component.
488
+
489
+ ```jsx
490
+ // ✅ Good
491
+ <Column field="amount" format={(v) => money.format(v)} />
492
+
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`.
520
+
521
+ ## Recipes
522
+
523
+ **Search box over server data**
524
+
525
+ ```jsx
526
+ const [search, setSearch] = useState('');
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]);
532
+ ```
533
+
534
+ **Cache with TanStack Query**
535
+
536
+ ```jsx
537
+ const queryClient = useQueryClient();
538
+ const source = useDataSource({
539
+ getLayout: ({ 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 }),
543
+ });
544
+ ```
545
+
546
+ **Refresh after saving**
547
+
548
+ ```jsx
549
+ await api.updateOrder(id, patch);
550
+ grid.current.refresh(); // server data
551
+ setRows((rows) => rows.map((r) => (r.id === id ? { ...r, ...patch } : r))); // in-memory rows
552
+ ```
553
+
554
+ **Row actions**
555
+
556
+ ```jsx
557
+ <Column field="actions" title="" width={120} sortable={false} filter={false}
558
+ renderCell={({ row }) => <RowMenu onEdit={() => edit(row)} onDelete={() => remove(row.id)} />} />
559
+ ```
560
+
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
675
+
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 |
682
+
683
+ ## FAQ
684
+
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.
692
+
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.
695
+
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`.
698
+
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.
701
+
702
+ ## License
703
+
704
+ [MIT](https://github.com/borealjs/grid/blob/main/LICENSE)
package/index.d.ts ADDED
@@ -0,0 +1,137 @@
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. Changing a field, title, type, width or filter redraws the whole 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, 'ariaLabel' | '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 redraws the whole 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
+ /** Accessible name of the grid, read by screen readers. */
109
+ 'aria-label'?: string;
110
+ ref?: Ref<Grid>;
111
+ }
112
+
113
+ /**
114
+ * The grid. Give it a size (CSS height, or a flex child with min-height: 0).
115
+ * `sort` / `filter` / `columnFilter` / `selectedCells` are controlled when passed (update them from the
116
+ * on…Change callbacks); use defaultSort etc. for uncontrolled state. The ref is the Grid API.
117
+ */
118
+ export declare function VirtualGrid<Row = any>(props: VirtualGridProps<Row>): ReactElement | null;
119
+
120
+ /** Declares a column as JSX inside <VirtualGrid>; takes the same props as a column object. */
121
+ export declare function Column<Row = any, F extends Extract<keyof Row, string> | (string & {}) = string>(props: ColumnDef<Row, F>): null;
122
+
123
+ /**
124
+ * A data source from callbacks that may close over props and state. Stays the same object; when `deps`
125
+ * change the grid reloads what is visible (keeping scroll, sort and filter).
126
+ */
127
+ export function useDataSource(spec: DataSource, deps?: readonly unknown[]): DataSource & { version: number };
128
+
129
+ /** An in-memory data source object that stays the same while rows and options do. */
130
+ export function useArraySource<Row = any>(
131
+ rows: Row[],
132
+ options?: {
133
+ columns?: (ColumnDef<Row> | string | number)[];
134
+ filterFns?: Record<string, (value: any, conditionValue: any, row: Row) => boolean>;
135
+ compare?(a: unknown, b: unknown): number;
136
+ },
137
+ ): ArraySource<Row>;
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "@borealjs/react-grid",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
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
+ "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.1"
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,368 @@
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
+ ariaLabel: props['aria-label'],
237
+ dataSource,
238
+ columns,
239
+ getColumn,
240
+ ...hooks,
241
+ ...callbacks,
242
+ // Controlled when the prop is given: the grid reports changes and waits for the new prop.
243
+ sort: props.sort,
244
+ filter: props.filter,
245
+ columnFilter: props.columnFilter,
246
+ controlled: { sort: props.sort !== undefined, filter: props.filter !== undefined, columnFilter: props.columnFilter !== undefined },
247
+ };
248
+ const optionsRef = useRef(options);
249
+ optionsRef.current = options;
250
+
251
+ const ready = !!(dataSource || props.model);
252
+ useIsoLayoutEffect(() => {
253
+ if (!ready) return undefined;
254
+ const grid = createGrid(hostRef.current, optionsRef.current);
255
+ gridRef.current = grid;
256
+ grid.ready.catch(() => {}); // reported through onError
257
+ return () => {
258
+ grid.destroy();
259
+ gridRef.current = null;
260
+ };
261
+ }, [ready]);
262
+
263
+ useImperativeHandle(ref, () => gridRef.current, [ready]);
264
+
265
+ // Later renders: hand the grid what changed (it decides between redraw, query change and rebuild).
266
+ const mounted = useRef(false);
267
+ useEffect(() => {
268
+ if (!mounted.current) {
269
+ mounted.current = true;
270
+ return;
271
+ }
272
+ const grid = gridRef.current;
273
+ if (!grid) return;
274
+ const prev = grid.options;
275
+ const next = { ...optionsRef.current };
276
+ // Controlled queries compare by content (a new array with the same items is no change).
277
+ for (const k of QUERY) if (next[k] !== undefined && sameJson(next[k], grid.getQuery()[k])) next[k] = prev[k];
278
+ if (shallowEqual(next.controlled, prev.controlled)) next.controlled = prev.controlled;
279
+ grid.setOptions(next).catch(() => {});
280
+ });
281
+
282
+ // New functions in columns (same structure): redraw what is visible.
283
+ const lastFnVersion = useRef(fnVersion);
284
+ useEffect(() => {
285
+ if (lastFnVersion.current === fnVersion) return;
286
+ lastFnVersion.current = fnVersion;
287
+ gridRef.current?.repaint();
288
+ }, [fnVersion]);
289
+
290
+ // New rows for the in-memory source: keep scroll, sort and filter, reload what is visible.
291
+ useEffect(() => {
292
+ if (!rowsSource || rowsSource.rows === props.rows) return;
293
+ rowsSource.setRows(props.rows);
294
+ gridRef.current?.refresh();
295
+ }, [props.rows, rowsSource]);
296
+
297
+ // useDataSource: its dependencies changed -> reload (same source object, new version).
298
+ const version = props.dataSource?.version;
299
+ const lastVersion = useRef(version);
300
+ useEffect(() => {
301
+ if (lastVersion.current === version) return;
302
+ lastVersion.current = version;
303
+ gridRef.current?.refresh();
304
+ }, [version]);
305
+
306
+ // Controlled selection: apply when it differs from the grid's.
307
+ const selected = props.selectedCells;
308
+ useEffect(() => {
309
+ const grid = gridRef.current;
310
+ if (!grid || !selected) return;
311
+ const apply = () => {
312
+ const cur = grid.getSelection();
313
+ const want = { active: selected.active ?? cur?.active, ranges: selected.ranges ?? cur?.ranges };
314
+ if (!cur || !sameJson({ active: cur.active, ranges: cur.ranges }, want)) grid.setSelection(selected);
315
+ };
316
+ if (grid.engine) apply();
317
+ else grid.ready.then(apply, () => {});
318
+ }, [selected]);
319
+
320
+ const { className, style, id } = props;
321
+ return createElement(
322
+ Fragment,
323
+ null,
324
+ createElement(
325
+ 'div',
326
+ { className, style: { position: 'relative', minHeight: 0, ...style }, id },
327
+ createElement('div', { ref: hostRef, style: { position: 'absolute', inset: 0 } }),
328
+ ),
329
+ createElement(Portals, { store }),
330
+ );
331
+ });
332
+ VirtualGrid.displayName = 'VirtualGrid';
333
+
334
+ // ------------------------------------------------------------------ hooks
335
+
336
+ /**
337
+ * A data source from callbacks that may close over props and state. It stays the same object (the grid
338
+ * is not rebuilt); when `deps` change, the grid reloads what is visible, keeping scroll, sort and filter.
339
+ *
340
+ * const source = useDataSource({
341
+ * getLayout: async ({ query, signal }) => ({ rowCount: await api.count(search, query, signal) }),
342
+ * getCells: ({ rects, query, signal }) => api.cells(search, rects, query, signal),
343
+ * }, [search]);
344
+ */
345
+ export function useDataSource(spec, deps = []) {
346
+ const ref = useRef(spec);
347
+ ref.current = spec;
348
+ const [source] = useState(() => {
349
+ const s = { version: 0 };
350
+ for (const name of ['getCells', 'getLayout', 'getLabels', 'getFilterValues', 'rowAt']) {
351
+ if (typeof spec[name] === 'function') s[name] = (...args) => ref.current[name](...args);
352
+ }
353
+ for (const name of ['maxRectsPerRequest', 'maxCellsPerRequest']) if (spec[name] !== undefined) s[name] = spec[name];
354
+ return s;
355
+ });
356
+ const prevDeps = useRef(deps);
357
+ if (deps.length !== prevDeps.current.length || deps.some((d, i) => !Object.is(d, prevDeps.current[i]))) {
358
+ prevDeps.current = deps;
359
+ source.version++;
360
+ }
361
+ return source;
362
+ }
363
+
364
+ /** An in-memory data source that stays the same object while `rows` and the options do. */
365
+ export function useArraySource(rows, options) {
366
+ const { columns, filterFns, compare } = options ?? {};
367
+ return useMemo(() => createArraySource(rows, { columns, filterFns, compare }), [rows, columns, filterFns, compare]);
368
+ }