foldkit-data-grid 0.3.2 → 0.5.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.
Files changed (62) hide show
  1. package/README.md +10 -3
  2. package/dist/clipboard.d.ts +44 -0
  3. package/dist/clipboard.d.ts.map +1 -0
  4. package/dist/clipboard.js +109 -0
  5. package/dist/clipboard.js.map +1 -0
  6. package/dist/columnState.d.ts +53 -0
  7. package/dist/columnState.d.ts.map +1 -0
  8. package/dist/columnState.js +201 -0
  9. package/dist/columnState.js.map +1 -0
  10. package/dist/{rows-D8siEVqF.d.mts → columns.d.ts} +15 -81
  11. package/dist/columns.d.ts.map +1 -0
  12. package/dist/columns.js +73 -0
  13. package/dist/columns.js.map +1 -0
  14. package/dist/{crud.d.mts → crud.d.ts} +3 -2
  15. package/dist/{crud.d.mts.map → crud.d.ts.map} +1 -1
  16. package/dist/{crud.mjs → crud.js} +3 -2
  17. package/dist/crud.js.map +1 -0
  18. package/dist/fill.d.ts +49 -0
  19. package/dist/fill.d.ts.map +1 -0
  20. package/dist/fill.js +113 -0
  21. package/dist/fill.js.map +1 -0
  22. package/dist/focus.d.ts +119 -0
  23. package/dist/focus.d.ts.map +1 -0
  24. package/dist/focus.js +150 -0
  25. package/dist/focus.js.map +1 -0
  26. package/dist/{index.d.mts → grid.d.ts} +31 -569
  27. package/dist/grid.d.ts.map +1 -0
  28. package/dist/grid.js +986 -0
  29. package/dist/grid.js.map +1 -0
  30. package/dist/index.d.ts +13 -0
  31. package/dist/index.js +13 -0
  32. package/dist/layout.d.ts +20 -0
  33. package/dist/layout.d.ts.map +1 -0
  34. package/dist/layout.js +27 -0
  35. package/dist/layout.js.map +1 -0
  36. package/dist/projection.d.ts +87 -0
  37. package/dist/projection.d.ts.map +1 -0
  38. package/dist/projection.js +102 -0
  39. package/dist/projection.js.map +1 -0
  40. package/dist/rows.d.ts +70 -0
  41. package/dist/rows.d.ts.map +1 -0
  42. package/dist/{rows-Dy1HPpGX.mjs → rows.js} +3 -71
  43. package/dist/rows.js.map +1 -0
  44. package/dist/selection.d.ts +65 -0
  45. package/dist/selection.d.ts.map +1 -0
  46. package/dist/selection.js +137 -0
  47. package/dist/selection.js.map +1 -0
  48. package/dist/viewport.d.ts +74 -0
  49. package/dist/viewport.d.ts.map +1 -0
  50. package/dist/viewport.js +123 -0
  51. package/dist/viewport.js.map +1 -0
  52. package/dist/virtual.d.ts +73 -0
  53. package/dist/virtual.d.ts.map +1 -0
  54. package/dist/virtual.js +112 -0
  55. package/dist/virtual.js.map +1 -0
  56. package/package.json +16 -16
  57. package/dist/crud.mjs.map +0 -1
  58. package/dist/index.d.mts.map +0 -1
  59. package/dist/index.mjs +0 -1982
  60. package/dist/index.mjs.map +0 -1
  61. package/dist/rows-D8siEVqF.d.mts.map +0 -1
  62. package/dist/rows-Dy1HPpGX.mjs.map +0 -1
package/dist/grid.js ADDED
@@ -0,0 +1,986 @@
1
+ import { Equal, Option, Result, Schema } from "effect";
2
+ import { CellEditor, Columns, editorOf } from "./columns.js";
3
+ import { defineTaggedUnion } from "foldkit/schema";
4
+ import { defineMessageUnion } from "foldkit/message";
5
+ import { modifyFields } from "foldkit/struct";
6
+ import { Bundle } from "foldkit-bundle";
7
+ import { GridProjection } from "./projection.js";
8
+ import { ColumnState } from "./columnState.js";
9
+ import { Fill } from "./fill.js";
10
+ import { GridFocus } from "./focus.js";
11
+ import { GridSelection, RowSelection } from "./selection.js";
12
+ import { GridViewport } from "./viewport.js";
13
+ import { VirtualGrid } from "./virtual.js";
14
+ // src/grid.ts
15
+ const Offsets = Schema.Struct({
16
+ top: Schema.Number,
17
+ left: Schema.Number
18
+ });
19
+ /** How a choice's draft moves through its options (`EditStepped`). */
20
+ const choiceSteps = [
21
+ "next",
22
+ "previous",
23
+ "first",
24
+ "last",
25
+ "pageNext",
26
+ "pagePrevious"
27
+ ];
28
+ /**
29
+ * One grid's interaction state: focus, the viewport and the column state, as
30
+ * one Bundle. Its update is the parts' own, joined: a key that moves focus
31
+ * off screen carries the scroll that reveals the cell, and the grid issues it.
32
+ *
33
+ * `id` names the grid in the DOM: the scroll container's id, and the prefix
34
+ * of every cell's id (`GridFocus.cellId`). Selection is opt-in:
35
+ * `rowSelection` lets rows be selected one at a time or several, and
36
+ * `cellSelection` lets a rectangle of cells be selected; without them their
37
+ * Messages change nothing.
38
+ */
39
+ const make = (options) => {
40
+ const focus = GridFocus.make(options.columns);
41
+ const columnState = ColumnState.make(options.columns);
42
+ const Column = focus.Address.fields.column;
43
+ const CellText = Schema.Struct({
44
+ row: Schema.String,
45
+ column: Column,
46
+ text: Schema.String
47
+ });
48
+ const PastedCell = Schema.Struct({
49
+ ...CellText.fields,
50
+ from: Schema.String
51
+ });
52
+ const Range = Schema.Struct({
53
+ anchor: focus.Address,
54
+ focus: focus.Address
55
+ });
56
+ /** A fill: the range carried on, and the cell it is carried to. */
57
+ const FillRequest = Schema.Struct({
58
+ source: Range,
59
+ to: focus.Address
60
+ });
61
+ const Model = Schema.Struct({
62
+ focus: focus.Model,
63
+ viewport: GridViewport.Model,
64
+ columns: columnState.Model,
65
+ /** A column being resized by the pointer, and its width when the drag began. */
66
+ resizing: Schema.OptionFromNullOr(Schema.Struct({
67
+ column: Column,
68
+ from: Schema.Number
69
+ })),
70
+ /**
71
+ * A column header being dragged by the pointer, and how far toward its
72
+ * region's end. Where it lands is worked out when it is let go.
73
+ */
74
+ dragging: Schema.OptionFromNullOr(Schema.Struct({
75
+ column: Column,
76
+ delta: Schema.Number
77
+ })),
78
+ /** The column whose menu is open, and the item the keyboard is on (`menuItems`). */
79
+ menu: Schema.OptionFromNullOr(Schema.Struct({
80
+ column: Column,
81
+ active: Schema.Number
82
+ })),
83
+ /**
84
+ * A fill being dragged from the range's handle: the range, and the cell
85
+ * the pointer is over. What it writes is worked out when it is let go.
86
+ */
87
+ filling: Schema.OptionFromNullOr(FillRequest),
88
+ selection: Schema.Struct({
89
+ rows: RowSelection,
90
+ /** Where the last plain row selection happened; a Shift range extends from it. */
91
+ anchor: Schema.OptionFromNullOr(Schema.String),
92
+ /** A rectangle of cells, by its corners; a single focused cell is none. */
93
+ cells: Schema.OptionFromNullOr(Range)
94
+ }),
95
+ /**
96
+ * The cell being edited, the text it began from, its draft, and the error
97
+ * that refused it, if one did.
98
+ */
99
+ editing: Schema.OptionFromNullOr(Schema.Struct({
100
+ address: focus.Address,
101
+ from: Schema.String,
102
+ draft: Schema.String,
103
+ error: Schema.OptionFromNullOr(Schema.String)
104
+ }))
105
+ });
106
+ const Region = Schema.Literals([
107
+ "start",
108
+ "center",
109
+ "end"
110
+ ]);
111
+ /**
112
+ * What a column's menu offers: pinning it to another region, hiding it,
113
+ * and showing each hidden column. Each is a column Message the grid
114
+ * already has; the menu only gathers them.
115
+ */
116
+ const MenuItem = defineTaggedUnion({
117
+ Pin: { region: Region },
118
+ Hide: {},
119
+ Show: { column: Column }
120
+ });
121
+ const Message = defineMessageUnion({
122
+ /** The pointer or the browser focused a cell. */
123
+ Focused: { address: focus.Address },
124
+ /**
125
+ * A key moved focus. `reveal` is the scroll that brings the cell into
126
+ * view, worked out by the view from the viewport it drew, or none when
127
+ * the cell is shown.
128
+ */
129
+ Moved: {
130
+ address: focus.Address,
131
+ reveal: Schema.OptionFromNullOr(Offsets)
132
+ },
133
+ /** A key moved focus up to a column's header, revealing it when scrolled away. */
134
+ HeaderFocused: {
135
+ column: Column,
136
+ reveal: Schema.OptionFromNullOr(Offsets)
137
+ },
138
+ /** The scroll container moved or changed size: `GridViewport.Measure` reports it. */
139
+ Measured: {
140
+ ...Offsets.fields,
141
+ width: Schema.Number,
142
+ height: Schema.Number
143
+ },
144
+ /** The reveal a `Moved` asked for has scrolled the container. */
145
+ Revealed: Offsets.fields,
146
+ /** A column was resized; the width is clamped to its limits. */
147
+ ColumnResized: {
148
+ column: Column,
149
+ width: Schema.Number
150
+ },
151
+ ColumnHidden: { column: Column },
152
+ ColumnShown: { column: Column },
153
+ /** A column moved to `index` in `region`: a reorder, a pin or an unpin. */
154
+ ColumnMoved: {
155
+ column: Column,
156
+ region: Region,
157
+ index: Schema.Number
158
+ },
159
+ /**
160
+ * The pointer went down on the resize handle of the column header whose
161
+ * DOM id is `header` (`GridFocus.headerId`). The id comes from the page,
162
+ * so one that is not a resizable column of this grid starts nothing.
163
+ */
164
+ ResizeStarted: { header: Schema.String },
165
+ /**
166
+ * The pointer moved `delta` pixels toward the column's end edge since the
167
+ * resize began: positive widens it, in either direction of text.
168
+ */
169
+ ResizeMoved: { delta: Schema.Number },
170
+ /** The pointer let go, or the drag was cancelled and the width goes back. */
171
+ ResizeEnded: { completed: Schema.Boolean },
172
+ /**
173
+ * The pointer began dragging the column header whose DOM id is `header`
174
+ * (`GridFocus.headerId`). The id comes from the page, so one that is not
175
+ * a shown column of this grid changes nothing.
176
+ */
177
+ ColumnDragStarted: { header: Schema.String },
178
+ /** The pointer is `delta` pixels toward the region's end from where the drag began. */
179
+ ColumnDragged: { delta: Schema.Number },
180
+ /**
181
+ * The pointer let go and the column moves where it was dropped
182
+ * (`ColumnState.dropAt`), or the drag was cancelled and nothing moves.
183
+ */
184
+ ColumnDragEnded: { completed: Schema.Boolean },
185
+ /**
186
+ * A column's menu opened, from its button or a key on its header; focus
187
+ * goes to the header, so closing the menu returns there.
188
+ */
189
+ MenuOpened: { column: Column },
190
+ /** The keyboard moved to item `active` of the open menu. */
191
+ MenuMoved: { active: Schema.Number },
192
+ /**
193
+ * Item `index` of the open menu was chosen. It is read from the menu as
194
+ * it stands now, and the menu closes.
195
+ */
196
+ MenuChosen: { index: Schema.Number },
197
+ MenuClosed: {},
198
+ /** A row was chosen: in single mode it is the selection, in multiple it toggles. */
199
+ RowSelected: { row: Schema.String },
200
+ /** A Shift range of rows, worked out by the view from the projection it drew. */
201
+ RowsExtended: {
202
+ rows: Schema.Array(Schema.String),
203
+ to: Schema.String
204
+ },
205
+ AllRowsSelected: {},
206
+ RowsCleared: {},
207
+ /**
208
+ * A rectangle of cells, from Shift with a key. `reveal` scrolls its far
209
+ * corner into view, as `Moved`'s does for a focused cell.
210
+ */
211
+ CellsSelected: {
212
+ anchor: focus.Address,
213
+ focus: focus.Address,
214
+ reveal: Schema.OptionFromNullOr(Offsets)
215
+ },
216
+ /**
217
+ * The pointer pressed the cell whose DOM id is `cell` (`GridFocus.cellId`).
218
+ * With Shift it spans a range from the focused cell, with Ctrl or Meta it
219
+ * toggles the cell's row, and plainly it focuses the cell. The id comes
220
+ * from the page, so one that is not this grid's cell changes nothing.
221
+ */
222
+ CellPressed: {
223
+ cell: Schema.String,
224
+ shiftKey: Schema.Boolean,
225
+ toggleKey: Schema.Boolean
226
+ },
227
+ CellsCleared: {},
228
+ /**
229
+ * One of the view's Mounts started: a pointer listener (the header row's
230
+ * or the body's), or what holds focus in an open editor, choice list or
231
+ * column menu. Nothing changes: it is their answer on start, so a Scene
232
+ * test resolves them with a Message the runtime sends too.
233
+ */
234
+ MountStarted: {},
235
+ /** An edit began on an editable cell, with the text it starts from. */
236
+ EditStarted: {
237
+ address: focus.Address,
238
+ draft: Schema.String
239
+ },
240
+ /**
241
+ * A key typed on the grid itself, over an editable cell: it starts an
242
+ * edit with the text, or, when that cell's edit is already open (the
243
+ * keys came faster than the editor took focus), adds to its draft.
244
+ * On a choice it picks the next option starting with the key instead,
245
+ * after the draft's, as a select finds one. `from` is the text the cell
246
+ * showed, which a new edit began from.
247
+ */
248
+ EditTyped: {
249
+ address: focus.Address,
250
+ text: Schema.String,
251
+ from: Schema.String
252
+ },
253
+ EditChanged: { draft: Schema.String },
254
+ /**
255
+ * A choice's draft moved through its column's options: the next or
256
+ * previous, the first or last, or a page of ten either way, stopping at
257
+ * the ends. The view sends the step; `update` works out the option from
258
+ * the draft as it is. On a column that is no choice it changes nothing.
259
+ */
260
+ EditStepped: { by: Schema.Literals(choiceSteps) },
261
+ /** A pointer chose one of a choice's options: it is the draft, committed in place. */
262
+ EditChosen: { draft: Schema.String },
263
+ /**
264
+ * The draft is to be kept. When the column accepts it the edit ends, focus
265
+ * goes to `next` (the cell below, or beside, worked out by the view), and
266
+ * the grid reports `Out.Edited`, unless the draft is the text the edit
267
+ * began from or decodes to the same value; when it refuses it, the edit
268
+ * stays with the error.
269
+ */
270
+ EditCommitted: {
271
+ next: Schema.OptionFromNullOr(focus.Address),
272
+ reveal: Schema.OptionFromNullOr(Offsets)
273
+ },
274
+ EditCancelled: {},
275
+ /**
276
+ * Text pasted, or a cut's cleared cells, laid onto editable cells by the
277
+ * view (`Clipboard.pasteAt`). A cell its text leaves unchanged (as an
278
+ * edit judges it, against `from`) is dropped; the rest are checked against
279
+ * their columns and reported as one `Pasted`, or nothing when none is left.
280
+ */
281
+ Pasted: { cells: Schema.Array(PastedCell) },
282
+ /**
283
+ * Ctrl or Meta with Z on the grid, or with Shift (or Ctrl+Y) for redo.
284
+ * An open edit keeps them, since the editor's own undo is the field's.
285
+ */
286
+ UndoRequested: {},
287
+ RedoRequested: {},
288
+ /** Ctrl+D or Ctrl+R over a range, worked out by the view: carry `source` on to `to`. */
289
+ FillRequested: FillRequest.fields,
290
+ /** The range's fill handle was pressed and moved: a fill begins from the range. */
291
+ FillStarted: {},
292
+ /** The pointer, filling, is over the cell whose DOM id is `cell`. */
293
+ FillDragged: { cell: Schema.String },
294
+ /** The fill handle was let go, or the drag cancelled (`completed` false). */
295
+ FillEnded: { completed: Schema.Boolean }
296
+ });
297
+ /**
298
+ * What the grid reports to its parent: one cell's committed text, or a
299
+ * paste's, as one change. Turning text into values and writing them is the
300
+ * application's, and so is taking them back: `UndoRequested` and
301
+ * `RedoRequested` carry nothing, since what to undo is the application's
302
+ * history, read when the request arrives.
303
+ */
304
+ const Out = defineTaggedUnion({
305
+ Edited: {
306
+ row: Schema.String,
307
+ column: Column,
308
+ text: Schema.String
309
+ },
310
+ /** The cells their columns accepted, and those they refused, with why. */
311
+ Pasted: {
312
+ accepted: Schema.Array(CellText),
313
+ refused: Schema.Array(Schema.Struct({
314
+ ...CellText.fields,
315
+ error: Schema.String
316
+ }))
317
+ },
318
+ UndoRequested: {},
319
+ RedoRequested: {},
320
+ /**
321
+ * A fill: carry `source` on to `to`. What it writes is worked out from the
322
+ * rows by `fill`, which the application holds.
323
+ */
324
+ Filled: FillRequest.fields,
325
+ /**
326
+ * A Shift-click range of rows, from the anchor to the clicked row. Which
327
+ * rows lie between is worked out from the rows by `extendRows`, which the
328
+ * application holds.
329
+ */
330
+ RowsRequested: {
331
+ from: Schema.String,
332
+ to: Schema.String
333
+ }
334
+ });
335
+ const focusTo = (model, address) => {
336
+ const next = focus.bundle.update(model.focus, focus.Message.Focused({ address }), void 0).model;
337
+ return next === model.focus ? model : modifyFields(model, { focus: () => next });
338
+ };
339
+ const viewportBy = (model, message) => {
340
+ const next = GridViewport.bundle.update(model.viewport, message, void 0).model;
341
+ return next === model.viewport ? model : modifyFields(model, { viewport: () => next });
342
+ };
343
+ const columnsBy = (model, next) => next === model.columns ? model : modifyFields(model, { columns: () => next });
344
+ const selectionBy = (model, next) => next === model.selection ? model : modifyFields(model, { selection: () => next });
345
+ const clearCells = (model) => Option.isNone(model.selection.cells) ? model : selectionBy(model, {
346
+ ...model.selection,
347
+ cells: Option.none()
348
+ });
349
+ const isColumn = (column) => Object.hasOwn(options.columns.byId, column);
350
+ /** One of this grid's columns, from its header's DOM id. */
351
+ const columnOf = (header) => Option.flatMap(GridFocus.headerOf(options.id, header), (column) => isColumn(column) ? Option.some(column) : Option.none());
352
+ /** The address of one of this grid's cells, from its DOM id. */
353
+ const addressOf = (cell) => Option.flatMap(GridFocus.cellOf(options.id, cell), ({ row, column }) => isColumn(column) ? Option.some({
354
+ row,
355
+ column
356
+ }) : Option.none());
357
+ const pressed = (model, address, shiftKey, toggleKey) => {
358
+ if (shiftKey && options.cellSelection === true) {
359
+ const anchor = Option.getOrElse(Option.orElse(Option.map(model.selection.cells, (cells) => cells.anchor), () => model.focus.current), () => address);
360
+ return { model: selectionBy(model, {
361
+ ...model.selection,
362
+ cells: Option.some({
363
+ anchor,
364
+ focus: address
365
+ })
366
+ }) };
367
+ }
368
+ const focused = clearCells(focusTo(model, address));
369
+ if (shiftKey && options.rowSelection === "multiple") {
370
+ const from = Option.getOrElse(Option.orElse(model.selection.anchor, () => Option.map(model.focus.current, (current) => current.row)), () => address.row);
371
+ return {
372
+ model: Option.isSome(focused.selection.anchor) ? focused : selectionBy(focused, {
373
+ ...focused.selection,
374
+ anchor: Option.some(from)
375
+ }),
376
+ outMessage: Out.RowsRequested({
377
+ from,
378
+ to: address.row
379
+ })
380
+ };
381
+ }
382
+ if (toggleKey && options.rowSelection !== void 0) return { model: selectionBy(focused, choose(focused.selection, address.row)) };
383
+ return { model: focused };
384
+ };
385
+ const decoders = /* @__PURE__ */ new Map();
386
+ const editors = /* @__PURE__ */ new Map();
387
+ for (const id of options.columns.ids) {
388
+ const edit = options.columns.byId[id].edit;
389
+ if (edit === void 0) continue;
390
+ decoders.set(id, Schema.decodeUnknownResult(edit.schema ?? Schema.String));
391
+ editors.set(id, editorOf(edit.schema));
392
+ }
393
+ /** How a column's cells are edited: as text, a number, or a choice; none when it does not edit. */
394
+ const editorFor = (column) => Option.fromUndefinedOr(editors.get(column));
395
+ /** Why a column refuses a text, or none when it takes it. */
396
+ const errorOf = (column, text) => Option.flatMap(Option.fromUndefinedOr(decoders.get(column)), (decode) => Result.match(decode(text), {
397
+ onSuccess: () => Option.none(),
398
+ onFailure: (error) => Option.some(error.message)
399
+ }));
400
+ /**
401
+ * A reported cell's value, decoded by its column's schema, handed to the
402
+ * handler for that column: one for each column that edits, each given its
403
+ * own value type. The grid reports only text its column accepted, so a cell
404
+ * that does not decode, or names a column that does not edit, was not the
405
+ * grid's, and throws.
406
+ */
407
+ const matchEdit = (cell, handlers) => {
408
+ const decode = decoders.get(cell.column);
409
+ if (decode === void 0) throw new Error(`DataGrid.matchEdit: the ${cell.column} column does not edit.`);
410
+ return Result.match(decode(cell.text), {
411
+ onFailure: (error) => {
412
+ throw new Error(`DataGrid.matchEdit: the ${cell.column} column refuses "${cell.text}" (${error.message}); the grid reports only text its column accepted.`);
413
+ },
414
+ onSuccess: (value) => handlers[cell.column]({
415
+ row: cell.row,
416
+ value
417
+ })
418
+ });
419
+ };
420
+ /**
421
+ * Whether a column's new text says what its old text did: the same text,
422
+ * or two that decode to equal values (`01.73` and `1.73`). An edit is
423
+ * judged against the text it began from, not the cell as it is now, so
424
+ * one left as it opened never writes over a change made meanwhile.
425
+ */
426
+ const unchanged = (column, from, text) => text === from || Option.exists(Option.fromUndefinedOr(decoders.get(column)), (decode) => Result.match(Result.all([decode(from), decode(text)]), {
427
+ onSuccess: ([before, after]) => Equal.equals(before, after),
428
+ onFailure: () => false
429
+ }));
430
+ /** A choice column's options, or none for a column that is no choice. */
431
+ const optionsOf = (column) => Option.flatMap(editorFor(column), CellEditor.match({
432
+ Text: () => Option.none(),
433
+ Number: () => Option.none(),
434
+ Date: () => Option.none(),
435
+ Choice: ({ options }) => Option.some(options)
436
+ }));
437
+ /** The option after `current` that starts with `key`, ignoring case, wrapping round; else `current`. */
438
+ const typedOption = (options, current, key) => {
439
+ const start = options.indexOf(current);
440
+ const wanted = key.toLowerCase();
441
+ for (let offset = 1; offset <= options.length; offset++) {
442
+ const option = options[(start + offset) % options.length];
443
+ if (option.toLowerCase().startsWith(wanted)) return option;
444
+ }
445
+ return current;
446
+ };
447
+ const page = 10;
448
+ const steppedIndex = (by, at, count) => Math.max(0, Math.min(count - 1, {
449
+ next: at + 1,
450
+ previous: at - 1,
451
+ first: 0,
452
+ last: count - 1,
453
+ pageNext: at + page,
454
+ pagePrevious: at - page
455
+ }[by]));
456
+ const sameCell = (a, b) => a.row === b.row && a.column === b.column;
457
+ /**
458
+ * Cells laid by a paste or a fill, as their columns judge them: those that
459
+ * pass and those refused, with why. A cell on a column that does not edit,
460
+ * or one its text leaves unchanged, is dropped.
461
+ */
462
+ const judged = (cells) => {
463
+ const accepted = [];
464
+ const refused = [];
465
+ for (const { from, ...cell } of cells) {
466
+ if (options.columns.byId[cell.column].edit === void 0) continue;
467
+ if (unchanged(cell.column, from, cell.text)) continue;
468
+ Option.match(errorOf(cell.column, cell.text), {
469
+ onNone: () => accepted.push(cell),
470
+ onSome: (error) => refused.push({
471
+ ...cell,
472
+ error
473
+ })
474
+ });
475
+ }
476
+ return {
477
+ accepted,
478
+ refused
479
+ };
480
+ };
481
+ /**
482
+ * Ends an edit with its draft: none to report when nothing was edited or
483
+ * the draft is unchanged, `refused` with the column's error when the draft
484
+ * does not pass, or the edit closed and `Edited` to report.
485
+ */
486
+ const finish = (model) => Option.match(model.editing, {
487
+ onNone: () => ({
488
+ model,
489
+ edited: Option.none(),
490
+ refused: false
491
+ }),
492
+ onSome: (editing) => {
493
+ const { address, from, draft } = editing;
494
+ if (unchanged(address.column, from, draft)) return {
495
+ model: modifyFields(model, { editing: () => Option.none() }),
496
+ edited: Option.none(),
497
+ refused: false
498
+ };
499
+ return Option.match(errorOf(address.column, draft), {
500
+ onSome: (message) => ({
501
+ model: modifyFields(model, { editing: () => Option.some({
502
+ ...editing,
503
+ error: Option.some(message)
504
+ }) }),
505
+ edited: Option.none(),
506
+ refused: true
507
+ }),
508
+ onNone: () => ({
509
+ model: modifyFields(model, { editing: () => Option.none() }),
510
+ edited: Option.some(Out.Edited({
511
+ row: address.row,
512
+ column: address.column,
513
+ text: draft
514
+ })),
515
+ refused: false
516
+ })
517
+ });
518
+ }
519
+ });
520
+ /**
521
+ * Keeps a draft: the column refusing it leaves the edit open with the
522
+ * error; otherwise the edit ends, focus goes to `next`, and `Edited` is
523
+ * reported unless the draft is unchanged.
524
+ */
525
+ const committed = (model, next, reveal) => {
526
+ const finished = finish(model);
527
+ if (finished.refused) return { model: finished.model };
528
+ return {
529
+ model: Option.match(next, {
530
+ onNone: () => finished.model,
531
+ onSome: (address) => focusTo(finished.model, address)
532
+ }),
533
+ ...Option.match(finished.edited, {
534
+ onNone: () => ({}),
535
+ onSome: (outMessage) => ({ outMessage })
536
+ }),
537
+ commands: Option.match(reveal, {
538
+ onNone: () => [],
539
+ onSome: (offsets) => [GridViewport.scrollTo(options.id, offsets)]
540
+ })
541
+ };
542
+ };
543
+ /**
544
+ * The pointer leaving an edit commits it first, as a spreadsheet does; a
545
+ * draft the column refuses keeps the edit, and the pointer's change waits.
546
+ */
547
+ const afterEdit = (model, then) => {
548
+ const finished = finish(model);
549
+ if (finished.refused) return { model: finished.model };
550
+ const next = then(finished.model);
551
+ return Option.match(finished.edited, {
552
+ onNone: () => next,
553
+ onSome: (outMessage) => ({
554
+ ...next,
555
+ outMessage
556
+ })
557
+ });
558
+ };
559
+ const choose = (selection, row) => {
560
+ if (options.rowSelection === "single") return {
561
+ ...selection,
562
+ rows: RowSelection.Keys({ keys: [row] }),
563
+ anchor: Option.some(row)
564
+ };
565
+ return {
566
+ ...selection,
567
+ rows: GridSelection.toggle(selection.rows, row),
568
+ anchor: Option.some(row)
569
+ };
570
+ };
571
+ /**
572
+ * The items of a column's menu, in order: pin to each other region, hide
573
+ * when it can be hidden, and show each hidden column. An item is offered
574
+ * only when it changes something.
575
+ */
576
+ const menuItems = (state, column) => [
577
+ ...[
578
+ "start",
579
+ "end",
580
+ "center"
581
+ ].filter((region) => region !== columnState.regionOf(state, column)).map((region) => MenuItem.Pin({ region })),
582
+ ...columnState.hide(state, column) === state ? [] : [MenuItem.Hide()],
583
+ ...state.hidden.map((other) => MenuItem.Show({ column: other }))
584
+ ];
585
+ /** The column Message a menu item stands for. */
586
+ const messageOf = (state, column, item) => MenuItem.match(item, {
587
+ Pin: ({ region }) => Message.ColumnMoved({
588
+ column,
589
+ region,
590
+ index: {
591
+ start: state.start.length,
592
+ end: 0,
593
+ center: columnState.regionOf(state, column) === "start" ? 0 : state.center.length
594
+ }[region]
595
+ }),
596
+ Hide: () => Message.ColumnHidden({ column }),
597
+ Show: ({ column: other }) => Message.ColumnShown({ column: other })
598
+ });
599
+ const closeMenu = (model) => Option.isNone(model.menu) ? model : modifyFields(model, { menu: () => Option.none() });
600
+ const bundle = Bundle.make("DataGrid", {
601
+ Model,
602
+ Message,
603
+ init: () => ({ model: {
604
+ focus: focus.bundle.init(void 0).model,
605
+ viewport: GridViewport.bundle.init(void 0).model,
606
+ columns: columnState.initial(),
607
+ resizing: Option.none(),
608
+ dragging: Option.none(),
609
+ menu: Option.none(),
610
+ filling: Option.none(),
611
+ selection: {
612
+ rows: GridSelection.none,
613
+ anchor: Option.none(),
614
+ cells: Option.none()
615
+ },
616
+ editing: Option.none()
617
+ } }),
618
+ update: (model, message) => Message.match(message, {
619
+ Focused: ({ address }) => afterEdit(model, (settled) => ({ model: clearCells(focusTo(settled, address)) })),
620
+ Moved: ({ address, reveal }) => ({
621
+ model: clearCells(focusTo(model, address)),
622
+ commands: Option.match(reveal, {
623
+ onNone: () => [],
624
+ onSome: (offsets) => [GridViewport.scrollTo(options.id, offsets)]
625
+ })
626
+ }),
627
+ HeaderFocused: ({ column, reveal }) => {
628
+ const next = focus.bundle.update(model.focus, focus.Message.HeaderFocused({ column }), void 0).model;
629
+ return {
630
+ model: next === model.focus ? model : modifyFields(model, { focus: () => next }),
631
+ commands: Option.match(reveal, {
632
+ onNone: () => [],
633
+ onSome: (offsets) => [GridViewport.scrollTo(options.id, offsets)]
634
+ })
635
+ };
636
+ },
637
+ Measured: (fields) => ({ model: viewportBy(model, GridViewport.Message.Measured(fields)) }),
638
+ Revealed: (fields) => ({ model: viewportBy(model, GridViewport.Message.Revealed(fields)) }),
639
+ ColumnResized: ({ column, width }) => ({ model: columnsBy(model, columnState.resize(model.columns, column, width)) }),
640
+ ColumnHidden: ({ column }) => {
641
+ const hidden = columnsBy(model, columnState.hide(model.columns, column));
642
+ if (hidden === model) return { model };
643
+ const off = (on) => Option.contains(on, column);
644
+ return { model: modifyFields(hidden, {
645
+ editing: (editing) => off(Option.map(editing, (each) => each.address.column)) ? Option.none() : editing,
646
+ focus: (current) => off(current.header) ? {
647
+ ...current,
648
+ header: Option.none()
649
+ } : current,
650
+ menu: (menu) => off(Option.map(menu, (each) => each.column)) ? Option.none() : menu
651
+ }) };
652
+ },
653
+ ColumnShown: ({ column }) => ({ model: columnsBy(model, columnState.show(model.columns, column)) }),
654
+ ColumnMoved: ({ column, region, index }) => ({ model: columnsBy(model, columnState.move(model.columns, column, region, index)) }),
655
+ ResizeStarted: ({ header }) => ({ model: Option.match(Option.filter(columnOf(header), (column) => options.columns.byId[column].resizable !== false), {
656
+ onNone: () => model,
657
+ onSome: (column) => modifyFields(model, { resizing: () => Option.some({
658
+ column,
659
+ from: columnState.widthOf(model.columns)(column)
660
+ }) })
661
+ }) }),
662
+ ResizeMoved: ({ delta }) => ({ model: Option.match(model.resizing, {
663
+ onNone: () => model,
664
+ onSome: ({ column, from }) => columnsBy(model, columnState.resize(model.columns, column, from + delta))
665
+ }) }),
666
+ MenuOpened: ({ column }) => model.columns.hidden.includes(column) ? { model } : afterEdit(model, (settled) => {
667
+ const focused = focus.bundle.update(settled.focus, focus.Message.HeaderFocused({ column }), void 0).model;
668
+ return { model: modifyFields(settled, {
669
+ focus: () => focused,
670
+ menu: () => Option.some({
671
+ column,
672
+ active: 0
673
+ })
674
+ }) };
675
+ }),
676
+ MenuMoved: ({ active }) => ({ model: Option.match(model.menu, {
677
+ onNone: () => model,
678
+ onSome: (menu) => {
679
+ const last = menuItems(model.columns, menu.column).length - 1;
680
+ const clamped = Math.min(Math.max(0, Math.trunc(active)), Math.max(0, last));
681
+ return clamped === menu.active ? model : modifyFields(model, { menu: () => Option.some({
682
+ ...menu,
683
+ active: clamped
684
+ }) });
685
+ }
686
+ }) }),
687
+ MenuChosen: ({ index }) => Option.match(model.menu, {
688
+ onNone: () => ({ model }),
689
+ onSome: ({ column }) => Option.match(Option.fromUndefinedOr(menuItems(model.columns, column)[index]), {
690
+ onNone: () => ({ model: closeMenu(model) }),
691
+ onSome: (item) => bundle.update(closeMenu(model), messageOf(model.columns, column, item), void 0)
692
+ })
693
+ }),
694
+ MenuClosed: () => ({ model: closeMenu(model) }),
695
+ ColumnDragStarted: ({ header }) => ({ model: Option.match(Option.filter(columnOf(header), (column) => !model.columns.hidden.includes(column)), {
696
+ onNone: () => model,
697
+ onSome: (column) => modifyFields(model, { dragging: () => Option.some({
698
+ column,
699
+ delta: 0
700
+ }) })
701
+ }) }),
702
+ ColumnDragged: ({ delta }) => ({ model: Option.match(model.dragging, {
703
+ onNone: () => model,
704
+ onSome: (dragging) => dragging.delta === delta ? model : modifyFields(model, { dragging: () => Option.some({
705
+ ...dragging,
706
+ delta
707
+ }) })
708
+ }) }),
709
+ ColumnDragEnded: ({ completed }) => ({ model: Option.match(model.dragging, {
710
+ onNone: () => model,
711
+ onSome: ({ column, delta }) => {
712
+ const dropped = completed ? columnsBy(model, columnState.move(model.columns, column, columnState.regionOf(model.columns, column), columnState.dropAt(model.columns, column, delta))) : model;
713
+ return modifyFields(dropped, { dragging: () => Option.none() });
714
+ }
715
+ }) }),
716
+ RowSelected: ({ row }) => ({ model: options.rowSelection === void 0 ? model : selectionBy(model, choose(model.selection, row)) }),
717
+ RowsExtended: ({ rows, to }) => {
718
+ if (options.rowSelection !== "multiple") return { model };
719
+ const added = GridSelection.add(model.selection.rows, rows);
720
+ const anchor = Option.orElse(model.selection.anchor, () => Option.some(to));
721
+ return { model: added === model.selection.rows && Option.isSome(model.selection.anchor) ? model : selectionBy(model, {
722
+ ...model.selection,
723
+ rows: added,
724
+ anchor
725
+ }) };
726
+ },
727
+ AllRowsSelected: () => ({ model: options.rowSelection !== "multiple" ? model : selectionBy(model, {
728
+ ...model.selection,
729
+ rows: RowSelection.AllExcept({ except: [] })
730
+ }) }),
731
+ RowsCleared: () => {
732
+ return { model: RowSelection.match(model.selection.rows, {
733
+ Keys: ({ keys }) => keys.length === 0,
734
+ AllExcept: () => false
735
+ }) && Option.isNone(model.selection.anchor) ? model : selectionBy(model, {
736
+ ...model.selection,
737
+ rows: GridSelection.none,
738
+ anchor: Option.none()
739
+ }) };
740
+ },
741
+ CellsSelected: ({ anchor, focus: far, reveal }) => options.cellSelection === true ? {
742
+ model: selectionBy(model, {
743
+ ...model.selection,
744
+ cells: Option.some({
745
+ anchor,
746
+ focus: far
747
+ })
748
+ }),
749
+ commands: Option.match(reveal, {
750
+ onNone: () => [],
751
+ onSome: (offsets) => [GridViewport.scrollTo(options.id, offsets)]
752
+ })
753
+ } : { model },
754
+ CellPressed: ({ cell, shiftKey, toggleKey }) => Option.match(addressOf(cell), {
755
+ onNone: () => ({ model }),
756
+ onSome: (address) => Option.exists(model.editing, (editing) => sameCell(editing.address, address)) ? { model } : afterEdit(model, (settled) => pressed(settled, address, shiftKey, toggleKey))
757
+ }),
758
+ EditStarted: ({ address, draft }) => options.columns.byId[address.column].edit === void 0 ? { model } : { model: modifyFields(clearCells(focusTo(model, address)), { editing: () => Option.some({
759
+ address,
760
+ from: draft,
761
+ draft,
762
+ error: Option.none()
763
+ }) }) },
764
+ EditTyped: ({ address, text, from }) => {
765
+ if (options.columns.byId[address.column].edit === void 0) return { model };
766
+ const open = Option.filter(model.editing, (editing) => sameCell(editing.address, address));
767
+ const typed = (draft) => Option.match(optionsOf(address.column), {
768
+ onNone: () => draft + text,
769
+ onSome: (choices) => typedOption(choices, draft, text)
770
+ });
771
+ const editing = Option.match(open, {
772
+ onNone: () => ({
773
+ address,
774
+ from,
775
+ draft: Option.isSome(optionsOf(address.column)) ? typed(from) : text,
776
+ error: Option.none()
777
+ }),
778
+ onSome: (edit) => ({
779
+ ...edit,
780
+ draft: typed(edit.draft),
781
+ error: Option.none()
782
+ })
783
+ });
784
+ return { model: modifyFields(clearCells(focusTo(model, address)), { editing: () => Option.some(editing) }) };
785
+ },
786
+ EditChanged: ({ draft }) => ({ model: Option.match(model.editing, {
787
+ onNone: () => model,
788
+ onSome: (editing) => editing.draft === draft && Option.isNone(editing.error) ? model : modifyFields(model, { editing: () => Option.some({
789
+ ...editing,
790
+ draft,
791
+ error: Option.none()
792
+ }) })
793
+ }) }),
794
+ EditStepped: ({ by }) => Option.match(model.editing, {
795
+ onNone: () => ({ model }),
796
+ onSome: (editing) => Option.match(optionsOf(editing.address.column), {
797
+ onNone: () => ({ model }),
798
+ onSome: (choices) => {
799
+ const draft = choices[steppedIndex(by, choices.indexOf(editing.draft), choices.length)];
800
+ return draft === void 0 || draft === editing.draft ? { model } : { model: modifyFields(model, { editing: () => Option.some({
801
+ ...editing,
802
+ draft,
803
+ error: Option.none()
804
+ }) }) };
805
+ }
806
+ })
807
+ }),
808
+ EditChosen: ({ draft }) => Option.match(model.editing, {
809
+ onNone: () => ({ model }),
810
+ onSome: (editing) => committed(modifyFields(model, { editing: () => Option.some({
811
+ ...editing,
812
+ draft
813
+ }) }), Option.none(), Option.none())
814
+ }),
815
+ EditCommitted: ({ next, reveal }) => committed(model, next, reveal),
816
+ Pasted: ({ cells }) => {
817
+ if (Option.isSome(model.editing) || cells.length === 0) return { model };
818
+ const { accepted, refused } = judged(cells);
819
+ return accepted.length === 0 && refused.length === 0 ? { model } : {
820
+ model,
821
+ outMessage: Out.Pasted({
822
+ accepted,
823
+ refused
824
+ })
825
+ };
826
+ },
827
+ FillRequested: (request) => Option.isSome(model.editing) ? { model } : {
828
+ model,
829
+ outMessage: Out.Filled({
830
+ source: request.source,
831
+ to: request.to
832
+ })
833
+ },
834
+ FillStarted: () => {
835
+ if (Option.isSome(model.editing)) return { model };
836
+ const source = Option.orElse(model.selection.cells, () => Option.map(model.focus.current, (address) => ({
837
+ anchor: address,
838
+ focus: address
839
+ })));
840
+ return { model: Option.match(source, {
841
+ onNone: () => model,
842
+ onSome: (range) => modifyFields(model, { filling: () => Option.some({
843
+ source: range,
844
+ to: range.focus
845
+ }) })
846
+ }) };
847
+ },
848
+ FillDragged: ({ cell }) => ({ model: Option.match(Option.zipWith(model.filling, addressOf(cell), (filling, to) => ({
849
+ filling,
850
+ to
851
+ })), {
852
+ onNone: () => model,
853
+ onSome: ({ filling, to }) => sameCell(filling.to, to) ? model : modifyFields(model, { filling: () => Option.some({
854
+ ...filling,
855
+ to
856
+ }) })
857
+ }) }),
858
+ FillEnded: ({ completed }) => Option.match(model.filling, {
859
+ onNone: () => ({ model }),
860
+ onSome: ({ source, to }) => {
861
+ const ended = modifyFields(model, { filling: () => Option.none() });
862
+ return completed ? {
863
+ model: ended,
864
+ outMessage: Out.Filled({
865
+ source,
866
+ to
867
+ })
868
+ } : { model: ended };
869
+ }
870
+ }),
871
+ UndoRequested: () => Option.isSome(model.editing) ? { model } : {
872
+ model,
873
+ outMessage: Out.UndoRequested()
874
+ },
875
+ RedoRequested: () => Option.isSome(model.editing) ? { model } : {
876
+ model,
877
+ outMessage: Out.RedoRequested()
878
+ },
879
+ EditCancelled: () => ({ model: Option.isNone(model.editing) ? model : modifyFields(model, { editing: () => Option.none() }) }),
880
+ CellsCleared: () => ({ model: clearCells(model) }),
881
+ MountStarted: () => ({ model }),
882
+ ResizeEnded: ({ completed }) => ({ model: Option.match(model.resizing, {
883
+ onNone: () => model,
884
+ onSome: ({ column, from }) => {
885
+ const settled = completed ? model : columnsBy(model, columnState.resize(model.columns, column, from));
886
+ return modifyFields(settled, { resizing: () => Option.none() });
887
+ }
888
+ }) })
889
+ })
890
+ });
891
+ const projections = /* @__PURE__ */ new WeakMap();
892
+ /** The text an edit of a cell begins from: its column's `draft`, or the text it shows. */
893
+ const draftOf = (projection, address) => Option.match(Option.flatMap(projection.rowIndex(address.row), (index) => projection.rows.rowAt(index)), {
894
+ onNone: () => "",
895
+ onSome: (row) => {
896
+ const column = options.columns.byId[address.column];
897
+ const authored = column.edit?.draft?.(row);
898
+ if (authored !== void 0) return authored;
899
+ const value = column.value(row);
900
+ if (value instanceof Date && !Number.isNaN(value.getTime())) {
901
+ const editor = editorFor(address.column);
902
+ if (Option.exists(editor, CellEditor.guards.Date)) {
903
+ const month = String(value.getMonth() + 1).padStart(2, "0");
904
+ const day = String(value.getDate()).padStart(2, "0");
905
+ return `${value.getFullYear()}-${month}-${day}`;
906
+ }
907
+ }
908
+ return Columns.textOf(value);
909
+ }
910
+ });
911
+ /**
912
+ * What an `Out.Filled` writes, judged as a paste's cells are: those their
913
+ * columns accept and those they refuse, over `rows` as they are now and the
914
+ * grid's column state. Nothing when `to` is inside the source.
915
+ */
916
+ const fill = (rows, state, request) => {
917
+ const projection = project(rows, state.columns);
918
+ return Option.match(Fill.plan(projection, request), {
919
+ onNone: () => judged([]),
920
+ onSome: (plan) => judged(Fill.cells(projection, plan, {
921
+ editable: (column) => options.columns.byId[column].edit !== void 0,
922
+ from: (address) => draftOf(projection, address)
923
+ }))
924
+ });
925
+ };
926
+ /**
927
+ * The grid's Model with an `Out.RowsRequested` range added to its row
928
+ * selection, over `rows` as they are now.
929
+ */
930
+ const extendRows = (rows, model, request) => bundle.update(model, Message.RowsExtended({
931
+ rows: GridSelection.rowsBetween(project(rows, model.columns), request.from, request.to),
932
+ to: request.to
933
+ }), void 0).model;
934
+ /** The grid as presented: the rows through the column state in the Model. */
935
+ const project = (rows, state) => {
936
+ const cached = projections.get(rows);
937
+ if (cached !== void 0 && cached.state === state) return cached.projection;
938
+ const projection = GridProjection.make({
939
+ rows,
940
+ columns: options.columns,
941
+ layout: state
942
+ });
943
+ projections.set(rows, {
944
+ state,
945
+ projection
946
+ });
947
+ return projection;
948
+ };
949
+ /**
950
+ * The rows and columns the view draws for this input, as the view itself
951
+ * works them out: a count of what is drawn, read from here, is what is drawn.
952
+ */
953
+ const window = (input) => VirtualGrid.window({
954
+ projection: project(input.rows, input.state.columns),
955
+ rowHeight: input.rowHeight,
956
+ width: columnState.widthOf(input.state.columns),
957
+ headerHeight: input.headerHeight,
958
+ viewport: input.state.viewport,
959
+ ...input.overscan === void 0 ? {} : { overscan: input.overscan }
960
+ });
961
+ return {
962
+ id: options.id,
963
+ matchEdit,
964
+ editorFor,
965
+ MenuItem,
966
+ menuItems,
967
+ columns: options.columns,
968
+ rowSelection: options.rowSelection,
969
+ cellSelection: options.cellSelection === true,
970
+ focus,
971
+ columnState,
972
+ project,
973
+ window,
974
+ fill,
975
+ extendRows,
976
+ draftOf,
977
+ Out,
978
+ Model,
979
+ Message,
980
+ bundle
981
+ };
982
+ };
983
+ const DataGrid = { make };
984
+ export { DataGrid };
985
+
986
+ //# sourceMappingURL=grid.js.map