foldkit-data-grid 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Patrick Glenn
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,498 @@
1
- # Temporary Holding Version
1
+ # foldkit-data-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
+ The model under a Foldkit data grid: which cells exist, in what order, and
4
+ where a move or a range lands. It is pure geometry over rows the application
5
+ supplies, so focus, selection, virtualization and the clipboard all ask one
6
+ value instead of reading positions from the DOM.
7
+
8
+ > **Status:** experimental, `0.1.0`, on npm from the 0.15.0 release. Phases 0 to 8 of
9
+ > [the DataGrid design](../../docs/design/data-grid-DESIGN.md), with the gaps
10
+ > under [Limits](#limits). This package draws nothing;
11
+ > [`foldkit-mixins-data-grid`](../mixins-data-grid/README.md) draws it.
12
+ > [`examples/data-grid`](../../examples/data-grid/README.md) is a 100,000-row
13
+ > product registry built on both, and
14
+ > [`examples/registry`](../../examples/registry/README.md) the same with a
15
+ > server: read through Remote, edited through Sync.
16
+
17
+ ## Who owns what
18
+
19
+ **The grid owns interaction state and geometry; the application owns the
20
+ records and domain mutations.**
21
+
22
+ | Fact | Owner |
23
+ | --- | --- |
24
+ | the records, their loading and caching | the application, Remote, or a local store |
25
+ | row order: a sort, a filter, a search | the application's Model or query input |
26
+ | column order, visibility and pinning | the grid, as a `ColumnLayout` |
27
+ | which cells exist and where they stand | `GridProjection`, derived from the three above |
28
+
29
+ The grid never sorts, filters or fetches. A sorted result is the order the
30
+ application hands it.
31
+
32
+ Use this package for an interactive grid: keyboard movement between cells,
33
+ ranges, editing. A readable, sortable list of records is
34
+ [`foldkit-crud`](../crud/README.md)'s `Crud.list` with
35
+ [`foldkit-mixins-crud`](../mixins-crud/README.md)'s table, which stays the
36
+ simple path.
37
+
38
+ ## Mental model
39
+
40
+ ```text
41
+ RowModel (rows by index, each with a stable key)
42
+ ×
43
+ Columns (typed, by stable id) + ColumnLayout (start | center | end, hidden)
44
+ ↓
45
+ GridProjection: visible cells in display order
46
+ ↓
47
+ moves, ranges, positions: every answer an Option
48
+ ```
49
+
50
+ A cell is named by identity, `{ row: key, column: id }`, never by position. A
51
+ re-sort moves a row to another index, and the address still names the same
52
+ cell; the projection says where it stands now.
53
+
54
+ ## Sixty seconds
55
+
56
+ ```ts
57
+ import { ColumnLayout, Columns, GridProjection, RowModel } from 'foldkit-data-grid'
58
+
59
+ interface Product {
60
+ readonly id: string
61
+ readonly sku: string
62
+ readonly price: number
63
+ }
64
+
65
+ const columns = Columns.define<Product>()({
66
+ sku: { header: 'SKU', value: product => product.sku, pinned: 'start' },
67
+ price: { header: 'Price', value: product => product.price },
68
+ })
69
+
70
+ const products: ReadonlyArray<Product> = [
71
+ { id: 'p1', sku: 'A-1', price: 9 },
72
+ { id: 'p2', sku: 'B-2', price: 2 },
73
+ ]
74
+ const productKey = (product: Product) => product.id
75
+
76
+ const grid = GridProjection.make({
77
+ rows: RowModel.fromArray(products, productKey),
78
+ columns,
79
+ layout: ColumnLayout.initial(columns),
80
+ })
81
+
82
+ grid.columns // ['sku', 'price']
83
+ grid.moveBy({ row: 'p1', column: 'sku' }, { rows: 1, columns: 1 })
84
+ // Option.some({ row: 'p2', column: 'price' })
85
+ grid.box({ row: 'p2', column: 'price' }, { row: 'p1', column: 'sku' })
86
+ // Option.some({ rows: { start: 0, end: 2 }, columns: ['sku', 'price'] })
87
+ ```
88
+
89
+ What each call does:
90
+
91
+ - **`Columns.define<Product>()({...})`** declares columns. Each key is a
92
+ column's stable id, typed as a literal, and each `value` keeps its own type.
93
+ It is called twice so the row type is given and the ids are inferred. It
94
+ throws for an id that is a number, which JavaScript would enumerate first,
95
+ and for `__proto__`.
96
+ - **`RowModel.fromArray(rows, key)`** reads an in-memory array. It indexes the
97
+ keys once per array and key function, so keep both stable across renders,
98
+ and it throws when two rows share a key. A paged or cursor source implements
99
+ the `RowModel` interface itself.
100
+ - **`RowModel.map(rows, input, make)`** transforms each row as it is read,
101
+ for local state laid over rows a server sent. `make` turns `input` (the
102
+ edits, say) into the per-row function once per `rows` and `input`, and the
103
+ result is the same model while both are, so the grid's projection is kept.
104
+ Keys, count and order are `rows`' own.
105
+ - **`ColumnLayout.initial(columns)`** is the layout the columns declare. A
106
+ layout is plain data, column ids only, so it can be saved.
107
+ - **`GridProjection.make(...)`** combines the three. It performs no I/O and
108
+ holds no state; rebuild it when any input changes.
109
+
110
+ ## Movement and ranges
111
+
112
+ `moveBy(address, { rows, columns })` steps in display order: it crosses from
113
+ the pinned start into the center, skips hidden columns, and stops at the
114
+ edges. `rowStart`, `rowEnd`, `first` and `last` jump to the edges.
115
+ `box(anchor, focus)` is the rectangle two cells span, from either corner, as
116
+ row indexes `[start, end)` and the columns it covers.
117
+
118
+ Every answer is an `Option`. A cell is absent when its column is hidden, its
119
+ row is gone, or its row is counted but not loaded yet.
120
+
121
+ ## Focus
122
+
123
+ Focus is the grid's first piece of state: which cell is current, held in the
124
+ Model by identity. Make it once per grid, then place its Bundle like any
125
+ other.
126
+
127
+ ```ts
128
+ import { Option } from 'effect'
129
+ import { GridFocus } from 'foldkit-data-grid'
130
+
131
+ const Focus = GridFocus.make(columns)
132
+ // Focus.bundle is placed with foldkit-bundle; Focus.Model holds
133
+ // { current: Option<CellAddress> }, stored as null when nothing is focused.
134
+
135
+ const next = GridFocus.target(grid, {
136
+ current: Option.some({ row: 'p1', column: 'sku' }),
137
+ key: 'ArrowDown',
138
+ modifiers: { shiftKey: false, ctrlKey: false, altKey: false, metaKey: false },
139
+ pageRows: 10,
140
+ })
141
+ // Option.some({ row: 'p2', column: 'sku' }): dispatch Focus.Message.Focused with it
142
+ ```
143
+
144
+ - **`GridFocus.make(columns)`** builds the Bundle, its Model and its one
145
+ Message, `Focused`. The stored column is one of these columns' ids, so a
146
+ saved focus naming a removed column fails to decode. Focusing the focused
147
+ cell again returns the Model it was given.
148
+ - **`GridFocus.target(projection, options)`** is the cell a key moves to:
149
+ arrows, Home and End (with Ctrl, the grid's corners), and PageUp and
150
+ PageDown by `pageRows`. Under `direction: 'rtl'` left and right swap. It
151
+ returns none for a key the grid leaves to the page, such as Enter, Tab, or
152
+ anything with Shift, Alt or Meta; a key it handles always lands somewhere,
153
+ staying put at an edge or before a row that has not loaded.
154
+ - **`GridFocus.tabStop(projection, current)`** is the cell holding the grid's
155
+ one tab stop: the focused cell while it is shown, else the first cell. A
156
+ focused cell in a hidden column stays in the Model, so focus comes back
157
+ when the column does.
158
+ - **`GridFocus.cellId(gridId, address)`** is a cell's DOM id, unique across
159
+ cells whatever their keys hold. The grid keeps DOM focus on its container
160
+ and points at the current cell with `aria-activedescendant`, so a cell can
161
+ scroll out of a virtual window without losing focus.
162
+
163
+ [`foldkit-mixins-data-grid`](../mixins-data-grid/README.md) wires these keys
164
+ onto the drawn grid.
165
+
166
+ ## Virtualization
167
+
168
+ A grid draws only what its scroll container shows. The container's scroll
169
+ offsets and size are the fact; `GridViewport` keeps them in the Model, and
170
+ `VirtualGrid.window` turns them into the rows and columns to draw.
171
+
172
+ ```ts
173
+ import { VirtualGrid } from 'foldkit-data-grid'
174
+
175
+ const shown = VirtualGrid.window({
176
+ projection: grid,
177
+ rowHeight: 32,
178
+ width: column => (column === 'sku' ? 120 : 80),
179
+ viewport: { top: 0, left: 0, width: 600, height: 320 },
180
+ overscan: { rows: 4, columns: 1 },
181
+ })
182
+ // shown.rows: { start: 0, end: 2, before: 0, after: 0 }: draw rows [start, end)
183
+ // shown.start, shown.centerColumns, shown.end: the columns to draw, in order
184
+ // shown.width, shown.height: the size of the scrollable content
185
+ ```
186
+
187
+ - **`VirtualGrid.window(options)`** is pure. Rows are one fixed height, so the
188
+ row window is arithmetic on the scroll offset and never walks the rows; the
189
+ center columns are found by binary search over their widths. Pinned
190
+ columns are always drawn, outside the horizontal window. `before` and
191
+ `after` are the space the undrawn rows and columns take, for spacers.
192
+ `headerHeight` leaves header rows inside the container out of the body.
193
+ It throws for a row height that is not a positive number.
194
+ - **`Grid.window({ rows, state, rowHeight, headerHeight, overscan })`** is
195
+ that window for a placed grid, as `foldkit-mixins-data-grid`'s view works
196
+ it out from the same input: to say how many rows are drawn, read it here
197
+ rather than estimating.
198
+ - **`VirtualGrid.reveal(options)`** is the least scroll that shows a cell,
199
+ as `{ top, left }`, or none when it is already in view. A pinned column
200
+ never scrolls, so only its row is brought in.
201
+ - **`GridViewport.bundle`** holds `{ top, left, width, height }`.
202
+ `GridViewport.Measure` is a Mount for the scroll container: it reports the
203
+ geometry when it mounts and on every scroll and resize. Readings that are
204
+ not numbers are ignored, and an overscroll reads as the edge.
205
+ - **`GridViewport.scrollTo(viewportId, offsets)`** is the Command that
206
+ applies a reveal: it scrolls the container and reports `Revealed`, so the
207
+ next window is drawn from the new offsets without waiting for the scroll
208
+ event.
209
+
210
+ `packages/data-grid/bench` measures this at 100,000 rows; see
211
+ [the benchmarks](../../docs/benchmarks.md#foldkit-data-grid-100000-rows).
212
+
213
+ ## One grid's state
214
+
215
+ `DataGrid.make({ id, columns })` joins focus, the viewport and the column
216
+ state into the one Bundle an application places for a grid. Its update is
217
+ the parts' own; what it adds is the seam between them: a key that moves
218
+ focus off screen scrolls the container.
219
+
220
+ ```ts
221
+ import { Option } from 'effect'
222
+ import { DataGrid } from 'foldkit-data-grid'
223
+
224
+ const Grid = DataGrid.make({ id: 'products', columns })
225
+
226
+ Grid.Message.Moved({
227
+ address: { row: 'p2', column: 'price' },
228
+ reveal: Option.some({ top: 64, left: 0 }),
229
+ })
230
+ // update focuses the cell and returns GridViewport.scrollTo('products', ...)
231
+ ```
232
+
233
+ - **`Focused`** is a cell focused by the pointer or the browser; it scrolls
234
+ nothing.
235
+ - **`Moved`** is a key's move, with `reveal` from `VirtualGrid.reveal`, worked
236
+ out by the view from the viewport it drew. When it is some, the update
237
+ issues the Command that scrolls the container whose DOM id is `id`.
238
+ - **`Measured`** and **`Revealed`** are the viewport's, from
239
+ `GridViewport.Measure` and the scroll Command.
240
+ - **`ColumnResized`**, **`ColumnHidden`**, **`ColumnShown`** and
241
+ **`ColumnMoved`** change the column state (below).
242
+ - **`ResizeStarted`**, **`ResizeMoved`** and **`ResizeEnded`** are a pointer
243
+ drag on a resize handle. The grid records the width the drag began at, so
244
+ each move is measured from there, not summed; a cancelled drag puts the
245
+ width back. A column that does not resize starts no drag.
246
+
247
+ The Model is `{ focus, viewport, columns, resizing }` and encodes to plain
248
+ data.
249
+ `Grid.project(rows, model.columns)` is the projection for that state, built
250
+ once per rows model and state, so the view and the application share it.
251
+ `GridFocus` and `GridViewport` stay available for a grid that composes its
252
+ own state.
253
+
254
+ ## Selection
255
+
256
+ Selection is the grid's and opt-in: `DataGrid.make({ id, columns, rowSelection:
257
+ 'multiple', cellSelection: true })`. Without the options the selection
258
+ Messages change nothing.
259
+
260
+ ```ts
261
+ const Picking = DataGrid.make({ id: 'picking', columns, rowSelection: 'multiple' })
262
+ const start = Picking.bundle.init(undefined).model
263
+ const picked = Picking.bundle.update(start, Picking.Message.RowSelected({ row: 'p1' }), undefined).model
264
+ GridSelection.isSelected(picked.selection.rows)('p1') // true
265
+ ```
266
+
267
+ - **Rows** are a `RowSelection`: `Keys({ keys })`, or `AllExcept({ except })`
268
+ after `AllRowsSelected`, so select-all holds every row whether loaded or
269
+ counted at all. `RowSelected` toggles a row in `'multiple'` mode and is the
270
+ selection in `'single'` mode; either way it becomes the anchor.
271
+ `RowsExtended({ rows, to })` adds a Shift range the view worked out with
272
+ `GridSelection.rowsBetween`; `RowsCleared` empties it.
273
+ - **Cells** are one rectangle, `CellsSelected({ anchor, focus })`, named by
274
+ its corners, so it survives a re-sort as the same two cells and
275
+ `GridSelection.boxOf(projection, range)` is what it covers now. A plain
276
+ click or key (`Focused`, `Moved`) lets it go: one focused cell is the
277
+ default selection. `GridSelection.extend` is the range a Shift key makes.
278
+ - **`GridSelection.isSelected(selection)`** indexes a selection once; call it
279
+ once per render, not per row.
280
+
281
+ ## Editing
282
+
283
+ A column with `edit` is editable. The grid owns the edit session (which
284
+ cell, the draft, an error); the application owns the value, and hears of a
285
+ commit as the grid's OutMessage. The column's `schema` says what its text
286
+ means, from the text typed to the value: a draft is committed only when it
287
+ decodes, and the failure's message is the cell's error.
288
+
289
+ ```ts
290
+ // Dollars as typed, with at most two decimals, and the number they mean.
291
+ const Price = Schema.String.check(
292
+ Schema.isPattern(/^\d+(\.\d{1,2})?$/, { message: 'A price, like 4.99' }),
293
+ ).pipe(
294
+ Schema.decodeTo(Schema.Number, {
295
+ decode: SchemaGetter.transform(text => Number(text)),
296
+ encode: SchemaGetter.transform(price => price.toFixed(2)),
297
+ }),
298
+ )
299
+ const priced = Columns.define<Product>()({
300
+ sku: { header: 'SKU', value: product => product.sku },
301
+ price: {
302
+ header: 'Price',
303
+ value: product => product.price,
304
+ edit: { schema: Price, draft: product => Schema.encodeSync(Price)(product.price) },
305
+ },
306
+ })
307
+ const Prices = DataGrid.make({ id: 'prices', columns: priced })
308
+ // Edited({ row, column, text }) | Pasted({ accepted, refused }) | Filled({ source, to })
309
+ // | UndoRequested | RedoRequested
310
+ type Out = typeof Prices.Out.Type
311
+
312
+ // In `onOut`: the committed text read back as its column's value, a number here.
313
+ const repriced = (cell: Extract<Out, { _tag: 'Edited' }>) =>
314
+ Prices.matchEdit(cell, { price: ({ row, value }) => ({ row, price: value }) })
315
+ ```
316
+
317
+ - **`EditStarted({ address, draft })`** opens an edit on an editable cell;
318
+ `EditChanged` keeps the draft; `EditCancelled` drops it.
319
+ - **`EditCommitted({ next, reveal })`** decodes the draft with the column's
320
+ `schema` (any text, without one). A draft it refuses keeps the edit with
321
+ the error, and nothing is reported. One it accepts ends the edit, moves
322
+ focus to `next`, and the update returns the OutMessage `Out.Edited({ row,
323
+ column, text })`, unless it is unchanged: the text the edit began from, or
324
+ text that decodes to the same value (`09.0` for `9.00`). An unchanged edit
325
+ closes as a changed one does and reports nothing. It is judged against the
326
+ text the edit began from, not the cell as it is now, so leaving an editor
327
+ as it opened never writes over a change another device made meanwhile.
328
+ - **`Grid.matchEdit(cell, handlers)`** reads a reported cell's value back:
329
+ one handler per editable column, each given its column's decoded type, so
330
+ the application parses nothing itself. The OutMessage stays text, which a
331
+ parent can store or send; a cell that does not decode, or names a column
332
+ that does not edit, was not the grid's, and throws.
333
+ - **A key typed on the grid is `EditTyped({ address, text, from })`:** it
334
+ starts the edit from `from`, the text the cell showed, or adds to the one
335
+ open on that cell, so keys faster than the editor opens all count. On a
336
+ choice column it finds the next option the key starts instead.
337
+ `EditStepped({ by })` moves a choice's draft through its options (`next`,
338
+ `previous`, `first`, `last`, `pageNext`, `pagePrevious`), and
339
+ `EditChosen({ draft })` keeps one a pointer chose. The grid's Messages carry what the user did and
340
+ `update` works out what it means, for the reason in
341
+ [Messages carry intent](../../docs/state-model.md#messages-carry-intent-not-results-worked-out-from-the-last-frame).
342
+ - **Place the grid with `onOut`.** Every placement handles the OutMessage, as
343
+ any Bundle's must; a grid that edits nothing passes `onOut: Bundle.ignore`.
344
+ - **A click on another cell commits first;** a refused draft keeps the edit
345
+ and the click waits. Hiding the edited column ends the edit.
346
+
347
+ ## The clipboard
348
+
349
+ Copy and paste speak the tab-separated text spreadsheets do. `Clipboard` is
350
+ pure: it writes and reads that text and lays a paste onto the grid; the view
351
+ wires it to the browser's copy, cut and paste events.
352
+
353
+ ```ts
354
+ Clipboard.toTsv([['SKU', 'Price'], ['A-1', '9']]) // 'SKU\tPrice\nA-1\t9'
355
+ Clipboard.parseTsv('a\t"b\tc"\r\n') // [['a', 'b\tc']]
356
+ ```
357
+
358
+ - **`Clipboard.copy(projection, box, textOf)`** is a box's cells as TSV,
359
+ rows in the projection's order and columns in display order.
360
+ - **`Clipboard.pasteAt(projection, anchor, matrix, { editable, from })`** is
361
+ where pasted text lands: laid from the anchor, dropping cells past the
362
+ edges, on columns that do not edit, or on rows not loaded. Each cell keeps
363
+ `from(address)`, the text it showed, as an edit would begin from.
364
+ - **`Fill`** carries a range on, as a spreadsheet's fill does, and is pure.
365
+ `Fill.plan(projection, { source, to })` is the source's box and the box
366
+ beyond it toward `to`, along one axis (`toward`: down, up, right or left;
367
+ rows win a diagonal). `Fill.cells(projection, plan, { editable, from })`
368
+ is the cells it writes, each lane of the source carried on by
369
+ `Fill.series(texts, count, backward)`: two or more numbers a constant step
370
+ apart continue their step, keeping the finest decimals, and anything else
371
+ repeats in order. Like a paste, it drops columns that do not edit and rows
372
+ not loaded, and keeps each cell's `from`.
373
+ - **`Pasted({ cells })`** hands those cells to the grid, which drops each one
374
+ its text leaves unchanged (as an edit judges it), checks the rest against
375
+ their columns' `schema`, and reports one `Out.Pasted({ accepted, refused
376
+ })`: one change for the application to apply, and say what it refused. A
377
+ paste or cut that changes no cell reports nothing. A paste while a cell is
378
+ edited is the field's.
379
+ - **`UndoRequested` and `RedoRequested`** (Ctrl or Meta with Z, with Shift or
380
+ Ctrl+Y to redo) report `Out.UndoRequested` and `Out.RedoRequested`. They
381
+ carry nothing: the grid keeps no history, since what an edit meant and how
382
+ to take it back are the application's, read from its Model when the
383
+ request arrives. While a cell is edited they are the field's.
384
+ - **A fill** comes from Ctrl or Meta with D (down) or R (right) over a range,
385
+ `FillRequested`, or from dragging the range's fill handle (`FillStarted`,
386
+ `FillDragged`, `FillEnded`, the drag held in the Model's `filling`), and
387
+ reports `Out.Filled({ source, to })`: the range, and the cell it was
388
+ carried to. The grid holds no rows, so the application works out what it
389
+ writes when it arrives, `Grid.fill(rows, model.grid, request)`, with the
390
+ rows it draws: `{ accepted, refused }`, judged as a paste's cells are
391
+ (`Fill.plan` and `Fill.cells`, above). A fill from a lone cell, or by key
392
+ from a range one row tall, carries on the cell above (or before) it.
393
+
394
+ ## Over a `foldkit-crud` list
395
+
396
+ `foldkit-data-grid/crud` reads a `Crud.list` and the Remote page it reads in
397
+ the grid's terms. Remote still owns the page, its loading, its retries and
398
+ its next page; this subpath fetches nothing and holds nothing.
399
+
400
+ ```ts
401
+ import { GridCrud } from 'foldkit-data-grid/crud'
402
+
403
+ const columns = GridCrud.columns(Posts) // a Crud.list
404
+ const Grid = DataGrid.make({ id: 'posts', columns })
405
+
406
+ const rows = GridCrud.rows(page, post => post.id) // page: RemoteData<Page<Row>>
407
+ const status = GridCrud.status(page) // RowStatus: Ready, Loading, Refreshing, Failed
408
+ ```
409
+
410
+ - **`GridCrud.columns(list, { columns, words })`** is a column per listed
411
+ member, headed by its label, its value the member's text as its Display
412
+ says it; a hidden Display (usually the id) starts hidden. `columns` adds
413
+ what only the grid knows, per member: `pinned`, `width`, `edit`, a
414
+ `header` of its own, or `hidden: false`. The value stays the Display's.
415
+ - **`GridCrud.rows(page, key)`** is the page's rows in its order. A page
416
+ with more after it counts as unknown, at least its rows; a failed read
417
+ keeps the rows it had. The same page value gives the same row model, so
418
+ what is built from it is kept across renders.
419
+ - **`GridCrud.status(page)`** is a `RowStatus` for the view to say.
420
+ - **Sorting stays the query's.** Pass `foldkit-crud`'s sort state to the
421
+ view's `sort`; a header sends its Message, and the application changes the
422
+ query input. `list.more` is the view's `onMore`, `list.refresh` behind its
423
+ `onRetry`.
424
+
425
+ The subpath needs `foldkit-crud` and `foldkit-remote`, optional peers of this
426
+ package; the core works without them.
427
+
428
+ ## Row counts
429
+
430
+ A `RowModel`'s `count` is a `RowCount`:
431
+
432
+ - **`Known({ total })`**: every row is counted. Rows past the loaded ones are
433
+ in range, but have no key until they load, so a move onto one finds no cell.
434
+ - **`Unknown({ atLeast })`**: a cursor that may have more. Movement stops at
435
+ the rows seen so far.
436
+
437
+ ## Column state
438
+
439
+ The grid owns where its columns stand and how wide they are: a
440
+ `ColumnLayout` plus the widths of the columns resized. A column's spec says
441
+ how it starts and what it allows: `width`, `minWidth`, `maxWidth`,
442
+ `resizable` and `hideable`.
443
+
444
+ ```ts
445
+ const State = Grid.columnState
446
+
447
+ const resized = State.resize(State.initial(), 'price', 90)
448
+ State.widthOf(resized)('price') // 90
449
+ State.move(resized, 'price', 'start', 0) // pinned first
450
+ const saved = JSON.stringify(State.hide(resized, 'sku'))
451
+
452
+ const { state, dropped } = State.restore(JSON.parse(saved))
453
+ // state is what was saved; dropped lists ids these columns no longer define
454
+ ```
455
+
456
+ - **Each operation returns the state it was given when it changes nothing**:
457
+ a resize to the width a column has, hiding a hidden column, a move to where
458
+ a column stands. A resize is clamped to the column's limits; a column that
459
+ is not `resizable` or `hideable` refuses.
460
+ - **The last column shown stays shown,** so the grid always has a cell to
461
+ focus.
462
+ - **`move(state, column, region, index)`** is a reorder within a region, or a
463
+ pin or an unpin across them; `index` counts the region with the column
464
+ taken out.
465
+ - **`dropAt(state, column, delta)`** is where a column dragged `delta`
466
+ pixels toward its region's end lands, as the `index` `move` takes: past
467
+ the middle of each shown neighbour it crossed. The grid's
468
+ `ColumnDragStarted`, `ColumnDragged` and `ColumnDragEnded` hold the drag
469
+ as the column and its delta, and work the drop out when it is let go,
470
+ from the widths and order as they are then.
471
+ - **A column's menu** gathers these for the pointer and the keyboard:
472
+ `Grid.menuItems(state, column)` lists pinning the column to each other
473
+ region, hiding it, and showing each hidden column, each only when it
474
+ changes something. `MenuOpened`, `MenuMoved`, `MenuChosen` and
475
+ `MenuClosed` hold which menu is open and its active item; a chosen item
476
+ is read from the menu as it stands then and sent as the column Message it
477
+ stands for, so hiding from the menu ends an edit on the column, takes its
478
+ header's focus and closes its menu, as `ColumnHidden` always does.
479
+ - **`restore(saved)`** reads a saved state leniently: an id the columns no
480
+ longer define, or one named twice, is dropped and listed in `dropped`; a
481
+ column the save predates takes its declared place; a width is clamped.
482
+ Input that is not a saved state is the initial state. The Model's own
483
+ Schema, by contrast, decodes only these columns' ids, so a stored Model
484
+ naming a removed column fails to decode: restore a saved layout with
485
+ `restore`, not by decoding it as the Model.
486
+ - **`widthOf(state)`** is the width each column is drawn at. Call it once per
487
+ state: it indexes the widths.
488
+
489
+ A projection built from a hand-written layout is lenient too: a column the
490
+ layout omits joins the center, an unknown id is dropped, and an id named
491
+ twice keeps its first place.
492
+
493
+ ## Limits
494
+
495
+ - Not built: a drag across regions to pin a column (the view's column
496
+ menu pins), a Shift-click row range,
497
+ more than one cell range, editors other than text, and a fill handle.
498
+ - Every row is one height.
@@ -0,0 +1,19 @@
1
+ import { l as ColumnSpec, n as RowModel, r as RowStatus, u as Columns } from "./rows-Dz9f6hWJ.mjs";
2
+ import { DisplayColumn, DisplayWords } from "foldkit-crud";
3
+ import { Page, RemoteData } from "foldkit-remote";
4
+ //#region src/crud.d.ts
5
+ /** What a grid adds to a listed member's column: where it stands, its size, and editing. */
6
+ type ColumnOptions<Row> = Partial<Omit<ColumnSpec<Row, string>, 'value'>>;
7
+ export declare const GridCrud: {
8
+ columns: <Key extends string, Row extends { readonly [K in Key]: unknown; }, Options extends { readonly [K in Key]?: ColumnOptions<Row>; }>(list: {
9
+ readonly columns: ReadonlyArray<DisplayColumn<Key>>;
10
+ readonly Row: Row;
11
+ }, options?: {
12
+ readonly words?: DisplayWords;
13
+ readonly columns?: Options;
14
+ }) => Columns<Row, { readonly [K in Key]: ColumnSpec<Row, string> & Options[K]; }>;
15
+ rows: <Row>(page: RemoteData<Page<Row>>, key: (row: Row) => string) => RowModel<Row>;
16
+ status: <Row>(page: RemoteData<Page<Row>>) => RowStatus;
17
+ };
18
+ //#endregion
19
+ //# sourceMappingURL=crud.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crud.d.mts","names":[],"sources":["../src/crud.ts"],"mappings":";;;;;KAcK,cAAc,OAAO,QAAQ,KAAK,WAAW;qBA+ErC;EApEX,UAAA,oBACA,wBAAwB,KAAK,kBAE7B,4BAA4B,KAAK,OAAO,cAAc,SAAM;aAE3C,SAAS,cAAc,cAAc;aAAgB,KAAK;KAAK;aAC5D,QAAQ;aAAuB,UAAU;QAC5D,QAAQ,iBAAiB,KAAK,MAAM,WAAW,eAAe,QAAQ;EA4B3D,OAAA,KAAG,MAAQ,WAAW,KAAK,OAAK,MAAQ,KAAK,mBAAiB,SAAS;EAuBrE,SAAA,KAAG,MAAQ,WAAW,KAAK,UAAQ"}
package/dist/crud.mjs ADDED
@@ -0,0 +1,80 @@
1
+ import { n as RowModel, o as Columns, r as RowStatus, t as RowCount } from "./rows-82I91peS.mjs";
2
+ import { Option } from "effect";
3
+ import { Display } from "foldkit-crud";
4
+ import { RemoteData } from "foldkit-remote";
5
+ //#region src/crud.ts
6
+ /**
7
+ * `foldkit-data-grid/crud` — a grid over a `foldkit-crud` list and the Remote
8
+ * page it reads. The list says the columns, their labels and how each value
9
+ * shows; Remote owns the page, its loading and its retries. This module only
10
+ * reads both into the grid's terms: columns, a row model, and a status. It
11
+ * fetches nothing and holds nothing.
12
+ */
13
+ /**
14
+ * The grid's columns for a list: one per listed member, keyed by its member
15
+ * key, headed by its label, its value the member's text as its Display says
16
+ * it. A member whose Display is hidden (usually the id) starts hidden: it is
17
+ * read, and can be shown, but is not drawn. `columns` adds what only the
18
+ * grid knows to a member's column: pinning, widths, `edit`, or another
19
+ * header; what it gives wins over what the list says.
20
+ */
21
+ const columns = (list, options = {}) => {
22
+ const specs = {};
23
+ for (const column of list.columns) specs[column.key] = {
24
+ header: column.label,
25
+ value: (row) => Display.show(column.display, row[column.key], options.words ?? {}),
26
+ ...column.display.shown ? {} : { hidden: true },
27
+ ...options.columns?.[column.key]
28
+ };
29
+ return Columns.define()(specs);
30
+ };
31
+ /**
32
+ * The rows of a page as the grid's row model, in the page's order. A page with
33
+ * more after it counts as unknown, at least its rows; a failed read keeps the
34
+ * rows it had. No answer yet, or none found, is no rows.
35
+ */
36
+ const pages = /* @__PURE__ */ new WeakMap();
37
+ const empty = [];
38
+ const rows = (page, key) => {
39
+ const items = (value) => {
40
+ const known = pages.get(value);
41
+ if (known !== void 0) return known;
42
+ const model = RowModel.fromArray(value.items, key);
43
+ const counted = value.hasNext ? {
44
+ ...model,
45
+ count: RowCount.Unknown({ atLeast: value.items.length })
46
+ } : model;
47
+ pages.set(value, counted);
48
+ return counted;
49
+ };
50
+ const none = RowModel.fromArray(empty, key);
51
+ return RemoteData.match(page, {
52
+ Initial: () => none,
53
+ Loading: () => none,
54
+ NotFound: () => none,
55
+ Ready: items,
56
+ Refreshing: items,
57
+ Failed: (_, previous) => Option.match(previous, {
58
+ onNone: () => none,
59
+ onSome: items
60
+ })
61
+ });
62
+ };
63
+ /** Where a page stands, for the grid to say. */
64
+ const status = (page) => RemoteData.match(page, {
65
+ Initial: () => RowStatus.Loading(),
66
+ Loading: () => RowStatus.Loading(),
67
+ NotFound: () => RowStatus.Ready(),
68
+ Ready: () => RowStatus.Ready(),
69
+ Refreshing: () => RowStatus.Refreshing(),
70
+ Failed: (error) => RowStatus.Failed({ message: error.message })
71
+ });
72
+ const GridCrud = {
73
+ columns,
74
+ rows,
75
+ status
76
+ };
77
+ //#endregion
78
+ export { GridCrud };
79
+
80
+ //# sourceMappingURL=crud.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crud.mjs","names":[],"sources":["../src/crud.ts"],"sourcesContent":["/**\n * `foldkit-data-grid/crud` — a grid over a `foldkit-crud` list and the Remote\n * page it reads. The list says the columns, their labels and how each value\n * shows; Remote owns the page, its loading and its retries. This module only\n * reads both into the grid's terms: columns, a row model, and a status. It\n * fetches nothing and holds nothing.\n */\nimport { Option } from 'effect'\nimport { Display, type DisplayColumn, type DisplayWords } from 'foldkit-crud'\nimport { type Page, RemoteData } from 'foldkit-remote'\nimport { Columns, type ColumnSpec } from './columns.js'\nimport { RowCount, RowModel, RowStatus } from './rows.js'\n\n/** What a grid adds to a listed member's column: where it stands, its size, and editing. */\ntype ColumnOptions<Row> = Partial<Omit<ColumnSpec<Row, string>, 'value'>>\n\n/**\n * The grid's columns for a list: one per listed member, keyed by its member\n * key, headed by its label, its value the member's text as its Display says\n * it. A member whose Display is hidden (usually the id) starts hidden: it is\n * read, and can be shown, but is not drawn. `columns` adds what only the\n * grid knows to a member's column: pinning, widths, `edit`, or another\n * header; what it gives wins over what the list says.\n */\nconst columns = <\n Key extends string,\n Row extends { readonly [K in Key]: unknown },\n // Each member's options as written, so an edit's schema types its value.\n Options extends { readonly [K in Key]?: ColumnOptions<Row> },\n>(\n list: { readonly columns: ReadonlyArray<DisplayColumn<Key>>; readonly Row: Row },\n options: { readonly words?: DisplayWords; readonly columns?: Options } = {},\n): Columns<Row, { readonly [K in Key]: ColumnSpec<Row, string> & Options[K] }> => {\n // Filled for every listed key below, so the record holds each Key.\n const specs = {} as Record<Key, ColumnSpec<Row, string>>\n for (const column of list.columns) {\n specs[column.key] = {\n header: column.label,\n value: row => Display.show(column.display, row[column.key], options.words ?? {}),\n ...(column.display.shown ? {} : { hidden: true }),\n ...options.columns?.[column.key],\n }\n }\n // Each spec is the member's column with its options spread over it, so it\n // holds what `Options` says of it.\n return Columns.define<Row>()(\n specs as { readonly [K in Key]: ColumnSpec<Row, string> & Options[K] },\n )\n}\n\n/**\n * The rows of a page as the grid's row model, in the page's order. A page with\n * more after it counts as unknown, at least its rows; a failed read keeps the\n * rows it had. No answer yet, or none found, is no rows.\n */\n// One row model per page value, so the projection built from it, and what is\n// worked out from that, is kept across renders while the page is unchanged.\nconst pages = new WeakMap<object, RowModel<unknown>>()\nconst empty: ReadonlyArray<never> = []\n\nconst rows = <Row>(page: RemoteData<Page<Row>>, key: (row: Row) => string): RowModel<Row> => {\n const items = (value: Page<Row>): RowModel<Row> => {\n const known = pages.get(value)\n if (known !== undefined) return known as RowModel<Row>\n const model = RowModel.fromArray(value.items, key)\n const counted = value.hasNext\n ? { ...model, count: RowCount.Unknown({ atLeast: value.items.length }) }\n : model\n pages.set(value, counted)\n return counted\n }\n const none = RowModel.fromArray<Row>(empty, key)\n return RemoteData.match<Page<Row>, RowModel<Row>>(page, {\n Initial: () => none,\n Loading: () => none,\n NotFound: () => none,\n Ready: items,\n Refreshing: items,\n Failed: (_, previous) => Option.match(previous, { onNone: () => none, onSome: items }),\n })\n}\n\n/** Where a page stands, for the grid to say. */\nconst status = <Row>(page: RemoteData<Page<Row>>): RowStatus =>\n RemoteData.match<Page<Row>, RowStatus>(page, {\n Initial: () => RowStatus.Loading(),\n Loading: () => RowStatus.Loading(),\n NotFound: () => RowStatus.Ready(),\n Ready: () => RowStatus.Ready(),\n Refreshing: () => RowStatus.Refreshing(),\n Failed: error => RowStatus.Failed({ message: error.message }),\n })\n\nexport const GridCrud = { columns, rows, status }\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAwBA,MAAM,WAMJ,MACA,UAAyE,CAAC,MACM;CAEhF,MAAM,QAAQ,CAAC;CACf,KAAK,MAAM,UAAU,KAAK,SACxB,MAAM,OAAO,OAAO;EAClB,QAAQ,OAAO;EACf,QAAO,QAAO,QAAQ,KAAK,OAAO,SAAS,IAAI,OAAO,MAAM,QAAQ,SAAS,CAAC,CAAC;EAC/E,GAAI,OAAO,QAAQ,QAAQ,CAAC,IAAI,EAAE,QAAQ,KAAK;EAC/C,GAAG,QAAQ,UAAU,OAAO;CAC9B;CAIF,OAAO,QAAQ,OAAY,CAAC,CAC1B,KACF;AACF;;;;;;AASA,MAAM,wBAAQ,IAAI,QAAmC;AACrD,MAAM,QAA8B,CAAC;AAErC,MAAM,QAAa,MAA6B,QAA6C;CAC3F,MAAM,SAAS,UAAoC;EACjD,MAAM,QAAQ,MAAM,IAAI,KAAK;EAC7B,IAAI,UAAU,KAAA,GAAW,OAAO;EAChC,MAAM,QAAQ,SAAS,UAAU,MAAM,OAAO,GAAG;EACjD,MAAM,UAAU,MAAM,UAClB;GAAE,GAAG;GAAO,OAAO,SAAS,QAAQ,EAAE,SAAS,MAAM,MAAM,OAAO,CAAC;EAAE,IACrE;EACJ,MAAM,IAAI,OAAO,OAAO;EACxB,OAAO;CACT;CACA,MAAM,OAAO,SAAS,UAAe,OAAO,GAAG;CAC/C,OAAO,WAAW,MAAgC,MAAM;EACtD,eAAe;EACf,eAAe;EACf,gBAAgB;EAChB,OAAO;EACP,YAAY;EACZ,SAAS,GAAG,aAAa,OAAO,MAAM,UAAU;GAAE,cAAc;GAAM,QAAQ;EAAM,CAAC;CACvF,CAAC;AACH;;AAGA,MAAM,UAAe,SACnB,WAAW,MAA4B,MAAM;CAC3C,eAAe,UAAU,QAAQ;CACjC,eAAe,UAAU,QAAQ;CACjC,gBAAgB,UAAU,MAAM;CAChC,aAAa,UAAU,MAAM;CAC7B,kBAAkB,UAAU,WAAW;CACvC,SAAQ,UAAS,UAAU,OAAO,EAAE,SAAS,MAAM,QAAQ,CAAC;AAC9D,CAAC;AAEH,MAAa,WAAW;CAAE;CAAS;CAAM;AAAO"}