foldkit-data-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/dist/index.mjs ADDED
@@ -0,0 +1,1949 @@
1
+ import { a as CellEditor, i as addressableRows, n as RowModel, o as Columns, r as RowStatus, s as editorOf, t as RowCount } from "./rows-82I91peS.mjs";
2
+ import { Effect, Equal, Option, Queue, Result, Schema, Stream } from "effect";
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 * as Mount from "foldkit/mount";
8
+ //#region src/clipboard.ts
9
+ const needsQuotes = /[\t\n\r"]/;
10
+ const quote = (cell) => needsQuotes.test(cell) ? `"${cell.replaceAll("\"", "\"\"")}"` : cell;
11
+ /** Rows of cells as tab-separated text, the form spreadsheets copy and paste. */
12
+ const toTsv = (rows) => rows.map((row) => row.map(quote).join(" ")).join("\n");
13
+ /**
14
+ * Tab-separated text as rows of cells. Quoted cells may hold tabs, line
15
+ * breaks and doubled quotes; `\r\n` and `\r` end a row as `\n` does; the line
16
+ * break a spreadsheet adds after the last row makes no empty row.
17
+ */
18
+ const parseTsv = (text) => {
19
+ const rows = [];
20
+ let row = [];
21
+ let cell = "";
22
+ let quoted = false;
23
+ let index = 0;
24
+ const endCell = () => {
25
+ row.push(cell);
26
+ cell = "";
27
+ };
28
+ const endRow = () => {
29
+ endCell();
30
+ rows.push(row);
31
+ row = [];
32
+ };
33
+ while (index < text.length) {
34
+ const char = text[index];
35
+ if (quoted) {
36
+ if (char === "\"" && text[index + 1] === "\"") {
37
+ cell += "\"";
38
+ index += 2;
39
+ continue;
40
+ }
41
+ if (char === "\"") quoted = false;
42
+ else cell += char;
43
+ index += 1;
44
+ continue;
45
+ }
46
+ if (char === "\"" && cell === "") quoted = true;
47
+ else if (char === " ") endCell();
48
+ else if (char === "\r" || char === "\n") {
49
+ endRow();
50
+ if (char === "\r" && text[index + 1] === "\n") index += 1;
51
+ } else cell += char;
52
+ index += 1;
53
+ }
54
+ if (cell !== "" || row.length > 0) endRow();
55
+ return rows;
56
+ };
57
+ /**
58
+ * The text of the cells a box covers, row by row in the projection's order
59
+ * and column by column in display order. A row counted but not loaded copies
60
+ * as empty cells, so the shape is the box's.
61
+ */
62
+ const copy = (projection, box, textOf) => {
63
+ const rows = [];
64
+ for (let index = box.rows.start; index < box.rows.end; index++) {
65
+ const key = projection.rows.keyAt(index);
66
+ rows.push(box.columns.map((column) => Option.match(key, {
67
+ onNone: () => "",
68
+ onSome: (row) => textOf({
69
+ row,
70
+ column
71
+ })
72
+ })));
73
+ }
74
+ return toTsv(rows);
75
+ };
76
+ /**
77
+ * Where pasted cells land: the matrix laid from `anchor` across rows in the
78
+ * projection's order and columns in display order. Cells past the grid's
79
+ * edges are dropped, as are those landing on a column that does not edit or
80
+ * a row not loaded; the rest keep their place, each with `from`, the text
81
+ * the cell showed (the text an edit of it would begin from).
82
+ */
83
+ const pasteAt = (projection, anchor, matrix, cells) => Option.match(projection.positionOf(anchor), {
84
+ onNone: () => [],
85
+ onSome: (start) => {
86
+ const landed = [];
87
+ matrix.forEach((texts, down) => {
88
+ const key = projection.rows.keyAt(start.row + down);
89
+ if (Option.isNone(key)) return;
90
+ const row = key.value;
91
+ texts.forEach((text, across) => {
92
+ const column = projection.columns[start.column + across];
93
+ if (column !== void 0 && cells.editable(column)) landed.push({
94
+ row,
95
+ column,
96
+ text,
97
+ from: cells.from({
98
+ row,
99
+ column
100
+ })
101
+ });
102
+ });
103
+ });
104
+ return landed;
105
+ }
106
+ });
107
+ const Clipboard = {
108
+ toTsv,
109
+ parseTsv,
110
+ copy,
111
+ pasteAt
112
+ };
113
+ //#endregion
114
+ //#region src/fill.ts
115
+ const number = /^-?\d+(?:\.(\d+))?$/;
116
+ /**
117
+ * The texts that carry `source` on for `count` cells, the first of them next
118
+ * to it. Two or more numbers a constant step apart continue their step, with
119
+ * as many decimals as the most precise of them; anything else repeats, in
120
+ * order. `backward` carries the source on before its first text, as filling
121
+ * up or left does.
122
+ */
123
+ const series = (source, count, backward) => {
124
+ const at = (index) => source[(index % source.length + source.length) % source.length];
125
+ const repeated = Array.from({ length: count }, (_, index) => backward ? at(-1 - index) : at(source.length + index));
126
+ if (source.length < 2) return repeated;
127
+ const parsed = source.map((text) => number.exec(text.trim()));
128
+ if (parsed.some((match) => match === null)) return repeated;
129
+ const decimals = Math.max(...parsed.map((match) => match[1]?.length ?? 0));
130
+ const scale = 10 ** decimals;
131
+ const units = source.map((text) => Math.round(Number(text.trim()) * scale));
132
+ const step = units[1] - units[0];
133
+ if (units.some((unit, index) => index > 0 && unit - units[index - 1] !== step)) return repeated;
134
+ const from = backward ? units[0] : units[units.length - 1];
135
+ return Array.from({ length: count }, (_, index) => ((from + (backward ? -step : step) * (index + 1)) / scale).toFixed(decimals));
136
+ };
137
+ /** The source's box and the box beyond it toward `to`; none when `to` is inside it. */
138
+ const plan = (projection, request) => Option.flatMap(projection.box(request.source.anchor, request.source.focus), (source) => Option.flatMap(projection.positionOf(request.to), (to) => {
139
+ const first = projection.columns.indexOf(source.columns[0]);
140
+ const last = first + source.columns.length - 1;
141
+ const below = to.row - (source.rows.end - 1);
142
+ const above = source.rows.start - to.row;
143
+ const right = to.column - last;
144
+ const left = first - to.column;
145
+ const rows = Math.max(below, above);
146
+ const columns = Math.max(right, left);
147
+ if (rows <= 0 && columns <= 0) return Option.none();
148
+ if (rows >= columns) {
149
+ const target = below > 0 ? {
150
+ start: source.rows.end,
151
+ end: to.row + 1
152
+ } : {
153
+ start: to.row,
154
+ end: source.rows.start
155
+ };
156
+ return Option.some({
157
+ source,
158
+ target: {
159
+ rows: target,
160
+ columns: source.columns
161
+ },
162
+ toward: below > 0 ? "down" : "up"
163
+ });
164
+ }
165
+ const columnsOf = (start, end) => projection.columns.slice(start, end);
166
+ return Option.some({
167
+ source,
168
+ target: {
169
+ rows: source.rows,
170
+ columns: right > 0 ? columnsOf(last + 1, to.column + 1) : columnsOf(to.column, first)
171
+ },
172
+ toward: right > 0 ? "right" : "left"
173
+ });
174
+ }));
175
+ /**
176
+ * The cells a fill writes: each lane of the source (a column for a fill down
177
+ * or up, a row for one right or left) carried on through the target by
178
+ * `series`. Cells on a column that does not edit, or on a row not loaded, are
179
+ * dropped; each kept cell has `from`, the text it showed.
180
+ */
181
+ const cells = (projection, fill, options) => {
182
+ const rowsOf = (box) => Array.from({ length: box.end - box.start }, (_, offset) => box.start + offset);
183
+ const keyAt = (index) => projection.rows.keyAt(index);
184
+ const textAt = (index, column) => Option.match(keyAt(index), {
185
+ onNone: () => "",
186
+ onSome: (row) => options.from({
187
+ row,
188
+ column
189
+ })
190
+ });
191
+ const cell = (index, column, text) => options.editable(column) ? Option.match(keyAt(index), {
192
+ onNone: () => [],
193
+ onSome: (row) => [{
194
+ row,
195
+ column,
196
+ text,
197
+ from: options.from({
198
+ row,
199
+ column
200
+ })
201
+ }]
202
+ }) : [];
203
+ const backward = fill.toward === "up" || fill.toward === "left";
204
+ const away = (items) => backward ? [...items].reverse() : items;
205
+ if (fill.toward === "down" || fill.toward === "up") {
206
+ const targetRows = away(rowsOf(fill.target.rows));
207
+ return fill.source.columns.flatMap((column) => {
208
+ const texts = series(rowsOf(fill.source.rows).map((index) => textAt(index, column)), targetRows.length, backward);
209
+ return targetRows.flatMap((index, at) => cell(index, column, texts[at]));
210
+ });
211
+ }
212
+ const targetColumns = away(fill.target.columns);
213
+ return rowsOf(fill.source.rows).flatMap((index) => {
214
+ const texts = series(fill.source.columns.map((column) => textAt(index, column)), targetColumns.length, backward);
215
+ return targetColumns.flatMap((column, at) => cell(index, column, texts[at]));
216
+ });
217
+ };
218
+ const Fill = {
219
+ series,
220
+ plan,
221
+ cells
222
+ };
223
+ //#endregion
224
+ //#region src/layout.ts
225
+ const ColumnLayout = {
226
+ /** The layout the columns declare: definition order, each in its `pinned` region. */
227
+ initial: (columns) => {
228
+ const start = [];
229
+ const center = [];
230
+ const end = [];
231
+ const hidden = [];
232
+ const pinned = {
233
+ start,
234
+ end
235
+ };
236
+ for (const id of columns.ids) {
237
+ const column = columns.byId[id];
238
+ (column.pinned === void 0 ? center : pinned[column.pinned]).push(id);
239
+ if (column.hidden === true) hidden.push(id);
240
+ }
241
+ return {
242
+ start,
243
+ center,
244
+ end,
245
+ hidden
246
+ };
247
+ } };
248
+ //#endregion
249
+ //#region src/columnState.ts
250
+ const regions = [
251
+ "start",
252
+ "center",
253
+ "end"
254
+ ];
255
+ const Saved = Schema.Struct({
256
+ start: Schema.Array(Schema.String),
257
+ center: Schema.Array(Schema.String),
258
+ end: Schema.Array(Schema.String),
259
+ hidden: Schema.Array(Schema.String),
260
+ widths: Schema.Array(Schema.Struct({
261
+ column: Schema.String,
262
+ width: Schema.Number
263
+ }))
264
+ });
265
+ const without = (ids, id) => ids.filter((each) => each !== id);
266
+ /**
267
+ * Column state for one grid's columns: its Schema, which decodes only these
268
+ * columns' ids, and the operations a grid's Messages run. Every operation
269
+ * returns the state it was given when it changes nothing, so a no-op draws
270
+ * nothing.
271
+ */
272
+ const make$2 = (columns) => {
273
+ const Ids = Schema.Literals(columns.ids);
274
+ const Model = Schema.Struct({
275
+ start: Schema.Array(Ids),
276
+ center: Schema.Array(Ids),
277
+ end: Schema.Array(Ids),
278
+ hidden: Schema.Array(Ids),
279
+ widths: Schema.Array(Schema.Struct({
280
+ column: Ids,
281
+ width: Schema.Number
282
+ }))
283
+ });
284
+ const spec = (id) => columns.byId[id];
285
+ const isColumn = (id) => Object.hasOwn(columns.byId, id);
286
+ const clampWidth = (id, width) => {
287
+ const { minWidth = Columns.minWidth, maxWidth = Number.POSITIVE_INFINITY } = spec(id);
288
+ return Math.min(Math.max(width, minWidth), maxWidth);
289
+ };
290
+ const initial = () => ({
291
+ ...ColumnLayout.initial(columns),
292
+ widths: []
293
+ });
294
+ /** The width each column is drawn at: its resize, else its spec's. Call once per state. */
295
+ const widthOf = (state) => {
296
+ const resized = new Map(state.widths.map((entry) => [entry.column, entry.width]));
297
+ return (id) => resized.get(id) ?? spec(id).width ?? Columns.defaultWidth;
298
+ };
299
+ const regionOf = (state, id) => regions.find((region) => state[region].includes(id)) ?? "center";
300
+ /** Resizes a resizable column, within its `minWidth` and `maxWidth`. */
301
+ const resize = (state, id, width) => {
302
+ if (spec(id).resizable === false || !Number.isFinite(width)) return state;
303
+ const clamped = clampWidth(id, width);
304
+ if (clamped === widthOf(state)(id)) return state;
305
+ return {
306
+ ...state,
307
+ widths: [...state.widths.filter((entry) => entry.column !== id), {
308
+ column: id,
309
+ width: clamped
310
+ }]
311
+ };
312
+ };
313
+ const visibleCount = (state) => {
314
+ const hidden = new Set(state.hidden);
315
+ return regions.reduce((count, region) => count + state[region].filter((id) => !hidden.has(id)).length, 0);
316
+ };
317
+ /** Hides a hideable column; the last one shown stays, so the grid keeps a cell to focus. */
318
+ const hide = (state, id) => {
319
+ if (spec(id).hideable === false || state.hidden.includes(id) || visibleCount(state) <= 1) return state;
320
+ return {
321
+ ...state,
322
+ hidden: [...state.hidden, id]
323
+ };
324
+ };
325
+ const show = (state, id) => state.hidden.includes(id) ? {
326
+ ...state,
327
+ hidden: without(state.hidden, id)
328
+ } : state;
329
+ /**
330
+ * Moves a column to `index` among the columns of `region`, counted with it
331
+ * removed: a reorder within its region, or a pin or an unpin across them.
332
+ */
333
+ const move = (state, id, region, index) => {
334
+ const from = regionOf(state, id);
335
+ const target = without(state[region], id);
336
+ const at = Math.min(Math.max(0, Math.trunc(index)), target.length);
337
+ if (from === region && state[region].indexOf(id) === at) return state;
338
+ const placed = [
339
+ ...target.slice(0, at),
340
+ id,
341
+ ...target.slice(at)
342
+ ];
343
+ return {
344
+ ...state,
345
+ [from]: without(state[from], id),
346
+ [region]: placed
347
+ };
348
+ };
349
+ /**
350
+ * Where a column dragged `delta` pixels toward its region's end lands, as
351
+ * the index `move` takes in that region: past the middle of each shown
352
+ * neighbour it crossed. A column that crosses none stays where it is, so
353
+ * hidden columns keep their places; so do a hidden column and a delta that
354
+ * is not a number.
355
+ */
356
+ const dropAt = (state, id, delta) => {
357
+ const order = state[regionOf(state, id)];
358
+ const here = order.indexOf(id);
359
+ const hidden = new Set(state.hidden);
360
+ if (hidden.has(id) || !Number.isFinite(delta)) return here;
361
+ const width = widthOf(state);
362
+ const shown = [];
363
+ let dragged = 0;
364
+ let before = 0;
365
+ let edge = 0;
366
+ for (const each of order) {
367
+ if (hidden.has(each)) continue;
368
+ const middle = edge + width(each) / 2;
369
+ if (each === id) {
370
+ dragged = middle + delta;
371
+ before = shown.length;
372
+ } else shown.push({
373
+ id: each,
374
+ middle
375
+ });
376
+ edge += width(each);
377
+ }
378
+ const passed = shown.filter((other) => other.middle <= dragged).length;
379
+ if (passed === before) return here;
380
+ const others = without(order, id);
381
+ return passed < shown.length ? others.indexOf(shown[passed].id) : others.indexOf(shown[passed - 1].id) + 1;
382
+ };
383
+ /**
384
+ * A saved state read back leniently: an id these columns no longer define,
385
+ * or one named twice, is dropped and listed; a column the save predates
386
+ * takes its initial place; a width is clamped to its column's limits.
387
+ * Input that is not a saved state at all is the initial state, with nothing
388
+ * dropped, since nothing was read.
389
+ */
390
+ const restore = (saved) => Option.match(Schema.decodeUnknownOption(Saved)(saved), {
391
+ onNone: () => ({
392
+ state: initial(),
393
+ dropped: []
394
+ }),
395
+ onSome: (value) => {
396
+ const dropped = [];
397
+ const saved = /* @__PURE__ */ new Set();
398
+ const keep = (ids) => ids.filter((id) => {
399
+ if (!isColumn(id) || saved.has(id)) {
400
+ dropped.push(id);
401
+ return false;
402
+ }
403
+ saved.add(id);
404
+ return true;
405
+ });
406
+ const placed = {
407
+ start: keep(value.start),
408
+ center: keep(value.center),
409
+ end: keep(value.end)
410
+ };
411
+ const fresh = initial();
412
+ for (const region of regions) for (const id of fresh[region]) if (!saved.has(id)) placed[region].push(id);
413
+ const hidden = new Set(fresh.hidden.filter((id) => !saved.has(id)));
414
+ for (const id of value.hidden) if (isColumn(id)) hidden.add(id);
415
+ const widths = /* @__PURE__ */ new Map();
416
+ for (const entry of value.widths) if (isColumn(entry.column) && Number.isFinite(entry.width)) widths.set(entry.column, clampWidth(entry.column, entry.width));
417
+ return {
418
+ state: {
419
+ ...placed,
420
+ hidden: [...hidden],
421
+ widths: [...widths].map(([column, width]) => ({
422
+ column,
423
+ width
424
+ }))
425
+ },
426
+ dropped
427
+ };
428
+ }
429
+ });
430
+ return {
431
+ Model,
432
+ initial,
433
+ widthOf,
434
+ regionOf,
435
+ resize,
436
+ hide,
437
+ show,
438
+ move,
439
+ dropAt,
440
+ restore
441
+ };
442
+ };
443
+ const ColumnState = { make: make$2 };
444
+ //#endregion
445
+ //#region src/projection.ts
446
+ const CellAddress = {
447
+ /**
448
+ * An address as stored or sent: the row key as text, and the column as one
449
+ * of these columns' ids, so a saved address naming a removed column fails
450
+ * to decode instead of naming nothing.
451
+ */
452
+ schema: (columns) => Schema.Struct({
453
+ row: Schema.String,
454
+ column: Schema.Literals(columns.ids)
455
+ }) };
456
+ const clamp = (value, last) => Math.min(Math.max(value, 0), last);
457
+ const GridProjection = {
458
+ /**
459
+ * Projects rows through a column layout. A layout saved before a column
460
+ * was added does not mention it, so the column joins the center region in
461
+ * definition order; an id the columns do not define, or one named twice,
462
+ * keeps only its first place.
463
+ */
464
+ make: (options) => {
465
+ const { rows, columns, layout } = options;
466
+ const placed = /* @__PURE__ */ new Set();
467
+ const place = (ids) => ids.filter((id) => {
468
+ if (!Object.hasOwn(columns.byId, id) || placed.has(id)) return false;
469
+ placed.add(id);
470
+ return true;
471
+ });
472
+ const startPlaced = place(layout.start);
473
+ const centerPlaced = place(layout.center);
474
+ const endPlaced = place(layout.end);
475
+ centerPlaced.push(...columns.ids.filter((id) => !placed.has(id)));
476
+ const hidden = new Set(layout.hidden);
477
+ const shown = (ids) => ids.filter((id) => !hidden.has(id));
478
+ const start = shown(startPlaced);
479
+ const center = shown(centerPlaced);
480
+ const end = shown(endPlaced);
481
+ const visible = [
482
+ ...start,
483
+ ...center,
484
+ ...end
485
+ ];
486
+ const indexes = new Map(visible.map((id, index) => [id, index]));
487
+ const lastRow = addressableRows(rows.count) - 1;
488
+ const lastColumn = visible.length - 1;
489
+ const cellAt = (position) => {
490
+ const column = visible[position.column];
491
+ if (column === void 0) return Option.none();
492
+ return Option.map(rows.keyAt(position.row), (row) => ({
493
+ row,
494
+ column
495
+ }));
496
+ };
497
+ const positionOf = (address) => Option.flatMap(Option.fromUndefinedOr(indexes.get(address.column)), (column) => Option.map(rows.indexOf(address.row), (row) => ({
498
+ row,
499
+ column
500
+ })));
501
+ const within = (address, to) => Option.flatMap(positionOf(address), (position) => cellAt(to(position)));
502
+ return {
503
+ rows,
504
+ rowCount: rows.count,
505
+ columns: visible,
506
+ start,
507
+ center,
508
+ end,
509
+ columnIndex: (id) => Option.fromUndefinedOr(indexes.get(id)),
510
+ rowIndex: (key) => rows.indexOf(key),
511
+ cellAt,
512
+ positionOf,
513
+ moveBy: (address, offset) => within(address, ({ row, column }) => ({
514
+ row: clamp(row + Math.trunc(offset.rows ?? 0), lastRow),
515
+ column: clamp(column + Math.trunc(offset.columns ?? 0), lastColumn)
516
+ })),
517
+ rowStart: (address) => within(address, ({ row }) => ({
518
+ row,
519
+ column: 0
520
+ })),
521
+ rowEnd: (address) => within(address, ({ row }) => ({
522
+ row,
523
+ column: lastColumn
524
+ })),
525
+ first: () => cellAt({
526
+ row: 0,
527
+ column: 0
528
+ }),
529
+ last: () => cellAt({
530
+ row: lastRow,
531
+ column: lastColumn
532
+ }),
533
+ box: (anchor, focus) => Option.flatMap(positionOf(anchor), (from) => Option.map(positionOf(focus), (to) => ({
534
+ rows: {
535
+ start: Math.min(from.row, to.row),
536
+ end: Math.max(from.row, to.row) + 1
537
+ },
538
+ columns: visible.slice(Math.min(from.column, to.column), Math.max(from.column, to.column) + 1)
539
+ })))
540
+ };
541
+ } };
542
+ //#endregion
543
+ //#region src/focus.ts
544
+ const sameAddress = (a, b) => a.row === b.row && a.column === b.column;
545
+ /**
546
+ * The cell that holds the grid's one tab stop: the focused cell while it is
547
+ * shown, and otherwise the first cell. A focused cell whose column was hidden
548
+ * or whose row went away stays in the Model, so focus returns to it if it
549
+ * comes back, but the tab stop moves on until then.
550
+ */
551
+ const tabStop = (projection, current) => Option.orElse(Option.filter(current, (address) => Option.isSome(projection.positionOf(address))), () => projection.first());
552
+ const arrows$1 = /* @__PURE__ */ new Map([
553
+ ["ArrowUp", {
554
+ rows: -1,
555
+ columns: 0
556
+ }],
557
+ ["ArrowDown", {
558
+ rows: 1,
559
+ columns: 0
560
+ }],
561
+ ["ArrowLeft", {
562
+ rows: 0,
563
+ columns: -1
564
+ }],
565
+ ["ArrowRight", {
566
+ rows: 0,
567
+ columns: 1
568
+ }]
569
+ ]);
570
+ /**
571
+ * The cell a key moves focus to, or none when the key is not the grid's to
572
+ * handle, so the caller leaves it to the page. Arrows step one cell, Home and
573
+ * End go to the row's edges and, with Ctrl, to the grid's corners; PageUp and
574
+ * PageDown move `pageRows`. A key the grid handles always lands somewhere: at
575
+ * an edge, or onto a row that is counted but not loaded, focus stays where it
576
+ * is. Shift, Alt and Meta combinations are left alone: Shift extends a
577
+ * selection, which is not focus's to decide.
578
+ */
579
+ const target = (projection, options) => {
580
+ const { key, modifiers } = options;
581
+ if (modifiers.shiftKey || modifiers.altKey || modifiers.metaKey) return Option.none();
582
+ return Option.flatMap(tabStop(projection, options.current), (from) => {
583
+ const stay = (to) => Option.some(Option.getOrElse(to, () => from));
584
+ if (key === "Home") return stay(modifiers.ctrlKey ? projection.first() : projection.rowStart(from));
585
+ if (key === "End") return stay(modifiers.ctrlKey ? projection.last() : projection.rowEnd(from));
586
+ if (modifiers.ctrlKey) return Option.none();
587
+ if (key === "PageUp") return stay(projection.moveBy(from, { rows: -options.pageRows }));
588
+ if (key === "PageDown") return stay(projection.moveBy(from, { rows: options.pageRows }));
589
+ const step = arrows$1.get(key);
590
+ if (step === void 0) return Option.none();
591
+ const flip = options.direction === "rtl" ? -1 : 1;
592
+ return stay(projection.moveBy(from, {
593
+ rows: step.rows,
594
+ columns: step.columns * flip
595
+ }));
596
+ });
597
+ };
598
+ /**
599
+ * A cell's DOM id: the grid's id, the row key and the column id, each
600
+ * URI-encoded and joined by `:`, which encoding never leaves in a part, so no
601
+ * two cells share an id. The container points at it with
602
+ * `aria-activedescendant`.
603
+ */
604
+ const cellId = (grid, address) => [
605
+ grid,
606
+ address.row,
607
+ address.column
608
+ ].map(encodeURIComponent).join(":");
609
+ const decode = Option.liftThrowable(decodeURIComponent);
610
+ /**
611
+ * The address a `cellId` names, if it is one of this grid's: its row key and
612
+ * its column id as written, for the grid's columns to check. An id from
613
+ * another grid, or with a malformed escape, is none.
614
+ */
615
+ const cellOf = (grid, id) => Option.map(partsOf(grid, id, 3), ([row, column]) => ({
616
+ row,
617
+ column
618
+ }));
619
+ /** The parts of one of this grid's ids after the grid's own, when it has `count` parts in all. */
620
+ const partsOf = (grid, id, count) => {
621
+ const parts = id.split(":");
622
+ if (parts.length !== count) return Option.none();
623
+ return Option.flatMap(Option.all(parts.map((part) => decode(part))), ([owner, ...rest]) => owner === grid ? Option.some(rest) : Option.none());
624
+ };
625
+ /**
626
+ * A column header's DOM id: the grid's id and the column id, URI-encoded and
627
+ * joined by `:`. It has two parts where a cell's has three, so the two never
628
+ * meet.
629
+ */
630
+ const headerId = (grid, column) => [grid, column].map(encodeURIComponent).join(":");
631
+ /** The column a `headerId` names, if it is one of this grid's, as written. */
632
+ const headerOf = (grid, id) => Option.map(partsOf(grid, id, 2), ([column]) => column);
633
+ /**
634
+ * Focus for one grid: which cell is current, by identity. Make it once per
635
+ * grid from its columns, so a focus saved in the Model decodes only against
636
+ * columns that exist.
637
+ */
638
+ const make$1 = (columns) => {
639
+ const Address = CellAddress.schema(columns);
640
+ const Model = Schema.Struct({
641
+ /** The focused cell; stored as `null` when none is. */
642
+ current: Schema.OptionFromNullOr(Address),
643
+ /**
644
+ * The column header focus is on, when it is on the header row. The cell
645
+ * focused before stays in `current`, so going back down returns to it.
646
+ */
647
+ header: Schema.OptionFromNullOr(Address.fields.column)
648
+ });
649
+ const Message = defineMessageUnion({
650
+ /** A cell became current: the user focused it, or a key moved there. */
651
+ Focused: { address: Address },
652
+ /** Focus went up to a column's header. */
653
+ HeaderFocused: { column: Address.fields.column }
654
+ });
655
+ return {
656
+ Address,
657
+ Model,
658
+ Message,
659
+ bundle: Bundle.make("GridFocus", {
660
+ Model,
661
+ Message,
662
+ init: () => ({ model: {
663
+ current: Option.none(),
664
+ header: Option.none()
665
+ } }),
666
+ update: (model, message) => ({ model: Message.match(message, {
667
+ Focused: ({ address }) => Option.isNone(model.header) && Option.isSome(model.current) && sameAddress(model.current.value, address) ? model : modifyFields(model, {
668
+ current: () => Option.some(address),
669
+ header: () => Option.none()
670
+ }),
671
+ HeaderFocused: ({ column }) => Option.contains(model.header, column) ? model : modifyFields(model, { header: () => Option.some(column) })
672
+ }) })
673
+ })
674
+ };
675
+ };
676
+ const GridFocus = {
677
+ make: make$1,
678
+ target,
679
+ tabStop,
680
+ cellId,
681
+ cellOf,
682
+ headerId,
683
+ headerOf
684
+ };
685
+ //#endregion
686
+ //#region src/selection.ts
687
+ /**
688
+ * Which rows are selected. `Keys` names them; `AllExcept` is every row but
689
+ * these, so select-all holds whatever the rows are, loaded or not, and
690
+ * however many there turn out to be.
691
+ */
692
+ const RowSelection = defineTaggedUnion({
693
+ Keys: { keys: Schema.Array(Schema.String) },
694
+ AllExcept: { except: Schema.Array(Schema.String) }
695
+ });
696
+ const none = RowSelection.Keys({ keys: [] });
697
+ const lookups = /* @__PURE__ */ new WeakMap();
698
+ /** Whether a row is selected. Call it once per selection: it indexes the keys. */
699
+ const isSelected = (selection) => {
700
+ const cached = lookups.get(selection);
701
+ if (cached !== void 0) return cached;
702
+ const lookup = RowSelection.match(selection, {
703
+ Keys: ({ keys }) => {
704
+ const set = new Set(keys);
705
+ return (key) => set.has(key);
706
+ },
707
+ AllExcept: ({ except }) => {
708
+ const set = new Set(except);
709
+ return (key) => !set.has(key);
710
+ }
711
+ });
712
+ lookups.set(selection, lookup);
713
+ return lookup;
714
+ };
715
+ /** Selects a row, or deselects it if it is selected. */
716
+ const toggle = (selection, key) => {
717
+ const selected = isSelected(selection)(key);
718
+ return RowSelection.match(selection, {
719
+ Keys: ({ keys }) => RowSelection.Keys({ keys: selected ? keys.filter((each) => each !== key) : [...keys, key] }),
720
+ AllExcept: ({ except }) => RowSelection.AllExcept({ except: selected ? [...except, key] : except.filter((each) => each !== key) })
721
+ });
722
+ };
723
+ /** Selects every row in `keys`, keeping what was selected. */
724
+ const add = (selection, keys) => {
725
+ const selected = isSelected(selection);
726
+ const fresh = keys.filter((key) => !selected(key));
727
+ if (fresh.length === 0) return selection;
728
+ return RowSelection.match(selection, {
729
+ Keys: ({ keys: held }) => RowSelection.Keys({ keys: [...held, ...new Set(fresh)] }),
730
+ AllExcept: ({ except }) => {
731
+ const adding = new Set(fresh);
732
+ return RowSelection.AllExcept({ except: except.filter((key) => !adding.has(key)) });
733
+ }
734
+ });
735
+ };
736
+ /** The keys of the rows from `from` to `to`, in the projection's order, both included. */
737
+ const rowsBetween = (projection, from, to) => {
738
+ const keys = [];
739
+ const ends = Option.all([projection.rowIndex(from), projection.rowIndex(to)]);
740
+ if (Option.isNone(ends)) return keys;
741
+ const [a, b] = ends.value;
742
+ for (let index = Math.min(a, b); index <= Math.max(a, b); index++) {
743
+ const key = projection.rows.keyAt(index);
744
+ if (Option.isSome(key)) keys.push(key.value);
745
+ }
746
+ return keys;
747
+ };
748
+ /** The cells a range covers now, or none when a corner is hidden or gone. */
749
+ const boxOf = (projection, range) => projection.box(range.anchor, range.focus);
750
+ const arrows = /* @__PURE__ */ new Map([
751
+ ["ArrowUp", {
752
+ rows: -1,
753
+ columns: 0
754
+ }],
755
+ ["ArrowDown", {
756
+ rows: 1,
757
+ columns: 0
758
+ }],
759
+ ["ArrowLeft", {
760
+ rows: 0,
761
+ columns: -1
762
+ }],
763
+ ["ArrowRight", {
764
+ rows: 0,
765
+ columns: 1
766
+ }]
767
+ ]);
768
+ /** Where a Shift key takes a range's far corner, or none when it is not such a key. */
769
+ const farCorner = (projection, focus, options) => {
770
+ const step = arrows.get(options.key);
771
+ if (step !== void 0) {
772
+ const flip = options.direction === "rtl" ? -1 : 1;
773
+ return Option.some(projection.moveBy(focus, {
774
+ rows: step.rows,
775
+ columns: step.columns * flip
776
+ }));
777
+ }
778
+ const moves = {
779
+ PageDown: () => projection.moveBy(focus, { rows: options.pageRows }),
780
+ PageUp: () => projection.moveBy(focus, { rows: -options.pageRows }),
781
+ Home: () => projection.rowStart(focus),
782
+ End: () => projection.rowEnd(focus)
783
+ };
784
+ return Object.hasOwn(moves, options.key) ? Option.some(moves[options.key]()) : Option.none();
785
+ };
786
+ /**
787
+ * The range a Shift key makes, or none when the key is not one: Shift with an
788
+ * arrow moves the range's far corner a cell, with PageUp or PageDown a page,
789
+ * with Home or End to the row's edge. The near corner stays where the range
790
+ * began, the focused cell when there was none. As with focus, a key the grid
791
+ * handles always lands: at an edge, or before a row not loaded, the range
792
+ * stays as it is.
793
+ */
794
+ const extend = (projection, options) => {
795
+ const { modifiers } = options;
796
+ if (!modifiers.shiftKey || modifiers.altKey || modifiers.metaKey || modifiers.ctrlKey) return Option.none();
797
+ const start = Option.orElse(options.range, () => Option.map(options.current, (current) => ({
798
+ anchor: current,
799
+ focus: current
800
+ })));
801
+ return Option.flatMap(start, (range) => Option.map(farCorner(projection, range.focus, options), (to) => Option.match(to, {
802
+ onNone: () => range,
803
+ onSome: (focus) => ({
804
+ anchor: range.anchor,
805
+ focus
806
+ })
807
+ })));
808
+ };
809
+ const GridSelection = {
810
+ none,
811
+ isSelected,
812
+ toggle,
813
+ add,
814
+ rowsBetween,
815
+ boxOf,
816
+ extend
817
+ };
818
+ //#endregion
819
+ //#region src/viewport.ts
820
+ const Model = Schema.Struct({
821
+ top: Schema.Number,
822
+ left: Schema.Number,
823
+ width: Schema.Number,
824
+ height: Schema.Number
825
+ });
826
+ const Message = defineMessageUnion({
827
+ /** The scroll container moved or changed size; the Mount reports it. */
828
+ Measured: {
829
+ top: Schema.Number,
830
+ left: Schema.Number,
831
+ width: Schema.Number,
832
+ height: Schema.Number
833
+ },
834
+ /** A reveal set the scroll offsets; the container's own scroll event confirms it later. */
835
+ Revealed: {
836
+ top: Schema.Number,
837
+ left: Schema.Number
838
+ }
839
+ });
840
+ const write = (model, next) => {
841
+ const fields = {};
842
+ for (const [key, value] of next) {
843
+ const clean = Math.max(0, value);
844
+ if (Number.isFinite(value) && clean !== model[key]) fields[key] = () => clean;
845
+ }
846
+ return Object.keys(fields).length === 0 ? model : modifyFields(model, fields);
847
+ };
848
+ /**
849
+ * The scroll container's geometry, as the window math reads it. The grid
850
+ * owns no scroll position of its own: the container's is the fact, reported
851
+ * by the `Measure` Mount, and a reveal moves the container.
852
+ */
853
+ const bundle = Bundle.make("GridViewport", {
854
+ Model,
855
+ Message,
856
+ init: () => ({ model: {
857
+ top: 0,
858
+ left: 0,
859
+ width: 0,
860
+ height: 0
861
+ } }),
862
+ update: (model, message) => ({ model: Message.match(message, {
863
+ Measured: ({ top, left, width, height }) => write(model, [
864
+ ["top", top],
865
+ ["left", left],
866
+ ["width", width],
867
+ ["height", height]
868
+ ]),
869
+ Revealed: ({ top, left }) => write(model, [["top", top], ["left", left]])
870
+ }) })
871
+ });
872
+ /**
873
+ * Reports the element's scroll offsets and size: once when it mounts, then on
874
+ * every scroll and every resize. Attach it to the scroll container. Without
875
+ * `ResizeObserver` (a test DOM) it still reports scrolls.
876
+ */
877
+ const Measure = Mount.defineStream("GridViewportMeasure", {
878
+ messages: [Message.Measured],
879
+ execute: ({ element }) => Stream.callback((queue) => Effect.gen(function* () {
880
+ const scroller = element;
881
+ const report = () => Queue.offerUnsafe(queue, Message.Measured({
882
+ top: scroller.scrollTop,
883
+ left: scroller.scrollLeft,
884
+ width: scroller.clientWidth,
885
+ height: scroller.clientHeight
886
+ }));
887
+ const Observer = globalThis.ResizeObserver;
888
+ yield* Effect.acquireRelease(Effect.sync(() => {
889
+ const observer = Observer === void 0 ? void 0 : new Observer(report);
890
+ element.addEventListener("scroll", report, { passive: true });
891
+ observer?.observe(element);
892
+ report();
893
+ return observer;
894
+ }), (observer) => Effect.sync(() => {
895
+ element.removeEventListener("scroll", report);
896
+ observer?.disconnect();
897
+ }));
898
+ }))
899
+ });
900
+ /**
901
+ * Scrolls the container with this DOM id to `offsets` (from
902
+ * `VirtualGrid.reveal`) and reports `Revealed`, so the next window is drawn
903
+ * from the new offsets at once rather than after the scroll event.
904
+ */
905
+ const scrollTo = (viewportId, offsets) => ({
906
+ name: "GridViewport.scrollTo",
907
+ args: {
908
+ viewportId,
909
+ ...offsets
910
+ },
911
+ effect: Effect.sync(() => {
912
+ const element = typeof document === "undefined" ? null : document.getElementById(viewportId);
913
+ if (element !== null && typeof element.scrollTo === "function") element.scrollTo({
914
+ top: offsets.top,
915
+ left: offsets.left
916
+ });
917
+ return Message.Revealed(offsets);
918
+ })
919
+ });
920
+ const GridViewport = {
921
+ Model,
922
+ Message,
923
+ bundle,
924
+ Measure,
925
+ scrollTo
926
+ };
927
+ //#endregion
928
+ //#region src/virtual.ts
929
+ const sum = (values) => values.reduce((total, value) => total + value, 0);
930
+ /** `edges[i]` is where center column `i` begins; `edges[count]` is the center's width. */
931
+ const edgesOf = (ids, width) => {
932
+ const edges = new Float64Array(ids.length + 1);
933
+ ids.forEach((id, index) => {
934
+ edges[index + 1] = edges[index] + Math.max(0, width(id));
935
+ });
936
+ return edges;
937
+ };
938
+ /** How many of `0..count-1` satisfy `holds`, which holds for a prefix of them: a binary search. */
939
+ const prefixWhere = (count, holds) => {
940
+ let low = 0;
941
+ let high = count;
942
+ while (low < high) {
943
+ const middle = low + high >>> 1;
944
+ if (holds(middle)) low = middle + 1;
945
+ else high = middle;
946
+ }
947
+ return low;
948
+ };
949
+ const layoutOf = (geometry, viewport) => {
950
+ const { projection, width, rowHeight } = geometry;
951
+ if (!(Number.isFinite(rowHeight) && rowHeight > 0)) throw new Error(`VirtualGrid: rowHeight must be a positive number of pixels, not ${rowHeight}.`);
952
+ const startWidth = sum(projection.start.map((id) => Math.max(0, width(id))));
953
+ const endWidth = sum(projection.end.map((id) => Math.max(0, width(id))));
954
+ return {
955
+ rowCount: addressableRows(projection.rowCount),
956
+ bodyHeight: Math.max(0, viewport.height - (geometry.headerHeight ?? 0)),
957
+ centerWidth: Math.max(0, viewport.width - startWidth - endWidth),
958
+ edges: edgesOf(projection.center, width),
959
+ startWidth,
960
+ endWidth,
961
+ center: projection.center
962
+ };
963
+ };
964
+ /**
965
+ * What to render for a viewport: the rows and center columns it shows, plus
966
+ * overscan, and the space the rest take. Rows are one fixed height, so the
967
+ * row window is arithmetic on the scroll offset and never walks the rows; the
968
+ * column window is a binary search over the center columns' widths. The
969
+ * pinned columns are always rendered, outside the horizontal window.
970
+ */
971
+ const window = (options) => {
972
+ const { viewport, rowHeight } = options;
973
+ const layout = layoutOf(options, viewport);
974
+ const overRows = Math.max(0, Math.trunc(options.overscan?.rows ?? 0));
975
+ const overColumns = Math.max(0, Math.trunc(options.overscan?.columns ?? 0));
976
+ const top = Math.max(0, viewport.top);
977
+ const firstRow = Math.floor(top / rowHeight);
978
+ const pastRow = Math.ceil((top + layout.bodyHeight) / rowHeight);
979
+ const rowStart = Math.min(layout.rowCount, Math.max(0, firstRow - overRows));
980
+ const rowEnd = Math.min(layout.rowCount, Math.max(rowStart, pastRow + overRows));
981
+ const { edges } = layout;
982
+ const count = layout.center.length;
983
+ const totalCenter = edges[count];
984
+ const left = Math.max(0, viewport.left);
985
+ const right = left + layout.centerWidth;
986
+ const firstColumn = prefixWhere(count, (index) => edges[index + 1] <= left);
987
+ const pastColumn = Math.max(firstColumn, prefixWhere(count, (index) => edges[index] < right));
988
+ const columnStart = Math.max(0, firstColumn - overColumns);
989
+ const columnEnd = Math.min(count, pastColumn + overColumns);
990
+ return {
991
+ rows: {
992
+ start: rowStart,
993
+ end: rowEnd,
994
+ before: rowStart * rowHeight,
995
+ after: (layout.rowCount - rowEnd) * rowHeight
996
+ },
997
+ center: {
998
+ start: columnStart,
999
+ end: columnEnd,
1000
+ before: edges[columnStart],
1001
+ after: totalCenter - edges[columnEnd]
1002
+ },
1003
+ centerColumns: layout.center.slice(columnStart, columnEnd),
1004
+ start: options.projection.start,
1005
+ end: options.projection.end,
1006
+ width: layout.startWidth + totalCenter + layout.endWidth,
1007
+ height: (options.headerHeight ?? 0) + layout.rowCount * rowHeight
1008
+ };
1009
+ };
1010
+ /**
1011
+ * The scroll offsets that bring a cell fully into view, moving each axis the
1012
+ * least it can, or none when it is already in view. A pinned column never
1013
+ * scrolls, so only its row is brought in.
1014
+ */
1015
+ const reveal = (options) => {
1016
+ const { viewport, position, rowHeight, projection } = options;
1017
+ const layout = layoutOf(options, viewport);
1018
+ const nearest = (offset, from, size, span) => {
1019
+ if (from < offset) return from;
1020
+ if (from + size > offset + span) return Math.max(0, from + size - span);
1021
+ return offset;
1022
+ };
1023
+ const top = nearest(viewport.top, position.row * rowHeight, rowHeight, layout.bodyHeight);
1024
+ const centerIndex = position.column - projection.start.length;
1025
+ const left = layout.center[centerIndex] !== void 0 ? nearest(viewport.left, layout.edges[centerIndex], layout.edges[centerIndex + 1] - layout.edges[centerIndex], layout.centerWidth) : viewport.left;
1026
+ return top === viewport.top && left === viewport.left ? Option.none() : Option.some({
1027
+ top,
1028
+ left
1029
+ });
1030
+ };
1031
+ const VirtualGrid = {
1032
+ window,
1033
+ reveal
1034
+ };
1035
+ //#endregion
1036
+ //#region src/grid.ts
1037
+ const Offsets = Schema.Struct({
1038
+ top: Schema.Number,
1039
+ left: Schema.Number
1040
+ });
1041
+ /** How a choice's draft moves through its options (`EditStepped`). */
1042
+ const choiceSteps = [
1043
+ "next",
1044
+ "previous",
1045
+ "first",
1046
+ "last",
1047
+ "pageNext",
1048
+ "pagePrevious"
1049
+ ];
1050
+ /**
1051
+ * One grid's interaction state: focus, the viewport and the column state, as
1052
+ * one Bundle. Its update is the parts' own, joined: a key that moves focus
1053
+ * off screen carries the scroll that reveals the cell, and the grid issues it.
1054
+ *
1055
+ * `id` names the grid in the DOM: the scroll container's id, and the prefix
1056
+ * of every cell's id (`GridFocus.cellId`). Selection is opt-in:
1057
+ * `rowSelection` lets rows be selected one at a time or several, and
1058
+ * `cellSelection` lets a rectangle of cells be selected; without them their
1059
+ * Messages change nothing.
1060
+ */
1061
+ const make = (options) => {
1062
+ const focus = GridFocus.make(options.columns);
1063
+ const columnState = ColumnState.make(options.columns);
1064
+ const Column = focus.Address.fields.column;
1065
+ const CellText = Schema.Struct({
1066
+ row: Schema.String,
1067
+ column: Column,
1068
+ text: Schema.String
1069
+ });
1070
+ const PastedCell = Schema.Struct({
1071
+ ...CellText.fields,
1072
+ from: Schema.String
1073
+ });
1074
+ const Range = Schema.Struct({
1075
+ anchor: focus.Address,
1076
+ focus: focus.Address
1077
+ });
1078
+ /** A fill: the range carried on, and the cell it is carried to. */
1079
+ const FillRequest = Schema.Struct({
1080
+ source: Range,
1081
+ to: focus.Address
1082
+ });
1083
+ const Model = Schema.Struct({
1084
+ focus: focus.Model,
1085
+ viewport: GridViewport.Model,
1086
+ columns: columnState.Model,
1087
+ /** A column being resized by the pointer, and its width when the drag began. */
1088
+ resizing: Schema.OptionFromNullOr(Schema.Struct({
1089
+ column: Column,
1090
+ from: Schema.Number
1091
+ })),
1092
+ /**
1093
+ * A column header being dragged by the pointer, and how far toward its
1094
+ * region's end. Where it lands is worked out when it is let go.
1095
+ */
1096
+ dragging: Schema.OptionFromNullOr(Schema.Struct({
1097
+ column: Column,
1098
+ delta: Schema.Number
1099
+ })),
1100
+ /** The column whose menu is open, and the item the keyboard is on (`menuItems`). */
1101
+ menu: Schema.OptionFromNullOr(Schema.Struct({
1102
+ column: Column,
1103
+ active: Schema.Number
1104
+ })),
1105
+ /**
1106
+ * A fill being dragged from the range's handle: the range, and the cell
1107
+ * the pointer is over. What it writes is worked out when it is let go.
1108
+ */
1109
+ filling: Schema.OptionFromNullOr(FillRequest),
1110
+ selection: Schema.Struct({
1111
+ rows: RowSelection,
1112
+ /** Where the last plain row selection happened; a Shift range extends from it. */
1113
+ anchor: Schema.OptionFromNullOr(Schema.String),
1114
+ /** A rectangle of cells, by its corners; a single focused cell is none. */
1115
+ cells: Schema.OptionFromNullOr(Range)
1116
+ }),
1117
+ /**
1118
+ * The cell being edited, the text it began from, its draft, and the error
1119
+ * that refused it, if one did.
1120
+ */
1121
+ editing: Schema.OptionFromNullOr(Schema.Struct({
1122
+ address: focus.Address,
1123
+ from: Schema.String,
1124
+ draft: Schema.String,
1125
+ error: Schema.OptionFromNullOr(Schema.String)
1126
+ }))
1127
+ });
1128
+ const Region = Schema.Literals([
1129
+ "start",
1130
+ "center",
1131
+ "end"
1132
+ ]);
1133
+ /**
1134
+ * What a column's menu offers: pinning it to another region, hiding it,
1135
+ * and showing each hidden column. Each is a column Message the grid
1136
+ * already has; the menu only gathers them.
1137
+ */
1138
+ const MenuItem = defineTaggedUnion({
1139
+ Pin: { region: Region },
1140
+ Hide: {},
1141
+ Show: { column: Column }
1142
+ });
1143
+ const Message = defineMessageUnion({
1144
+ /** The pointer or the browser focused a cell. */
1145
+ Focused: { address: focus.Address },
1146
+ /**
1147
+ * A key moved focus. `reveal` is the scroll that brings the cell into
1148
+ * view, worked out by the view from the viewport it drew, or none when
1149
+ * the cell is shown.
1150
+ */
1151
+ Moved: {
1152
+ address: focus.Address,
1153
+ reveal: Schema.OptionFromNullOr(Offsets)
1154
+ },
1155
+ /** A key moved focus up to a column's header, revealing it when scrolled away. */
1156
+ HeaderFocused: {
1157
+ column: Column,
1158
+ reveal: Schema.OptionFromNullOr(Offsets)
1159
+ },
1160
+ /** The scroll container moved or changed size: `GridViewport.Measure` reports it. */
1161
+ Measured: {
1162
+ ...Offsets.fields,
1163
+ width: Schema.Number,
1164
+ height: Schema.Number
1165
+ },
1166
+ /** The reveal a `Moved` asked for has scrolled the container. */
1167
+ Revealed: Offsets.fields,
1168
+ /** A column was resized; the width is clamped to its limits. */
1169
+ ColumnResized: {
1170
+ column: Column,
1171
+ width: Schema.Number
1172
+ },
1173
+ ColumnHidden: { column: Column },
1174
+ ColumnShown: { column: Column },
1175
+ /** A column moved to `index` in `region`: a reorder, a pin or an unpin. */
1176
+ ColumnMoved: {
1177
+ column: Column,
1178
+ region: Region,
1179
+ index: Schema.Number
1180
+ },
1181
+ /** The pointer went down on a column's resize handle. */
1182
+ ResizeStarted: { column: Column },
1183
+ /**
1184
+ * The pointer moved `delta` pixels toward the column's end edge since the
1185
+ * resize began: positive widens it, in either direction of text.
1186
+ */
1187
+ ResizeMoved: { delta: Schema.Number },
1188
+ /** The pointer let go, or the drag was cancelled and the width goes back. */
1189
+ ResizeEnded: { completed: Schema.Boolean },
1190
+ /**
1191
+ * The pointer began dragging the column header whose DOM id is `header`
1192
+ * (`GridFocus.headerId`). The id comes from the page, so one that is not
1193
+ * a shown column of this grid changes nothing.
1194
+ */
1195
+ ColumnDragStarted: { header: Schema.String },
1196
+ /** The pointer is `delta` pixels toward the region's end from where the drag began. */
1197
+ ColumnDragged: { delta: Schema.Number },
1198
+ /**
1199
+ * The pointer let go and the column moves where it was dropped
1200
+ * (`ColumnState.dropAt`), or the drag was cancelled and nothing moves.
1201
+ */
1202
+ ColumnDragEnded: { completed: Schema.Boolean },
1203
+ /**
1204
+ * A column's menu opened, from its button or a key on its header; focus
1205
+ * goes to the header, so closing the menu returns there.
1206
+ */
1207
+ MenuOpened: { column: Column },
1208
+ /** The keyboard moved to item `active` of the open menu. */
1209
+ MenuMoved: { active: Schema.Number },
1210
+ /**
1211
+ * Item `index` of the open menu was chosen. It is read from the menu as
1212
+ * it stands now, and the menu closes.
1213
+ */
1214
+ MenuChosen: { index: Schema.Number },
1215
+ MenuClosed: {},
1216
+ /** A row was chosen: in single mode it is the selection, in multiple it toggles. */
1217
+ RowSelected: { row: Schema.String },
1218
+ /** A Shift range of rows, worked out by the view from the projection it drew. */
1219
+ RowsExtended: {
1220
+ rows: Schema.Array(Schema.String),
1221
+ to: Schema.String
1222
+ },
1223
+ AllRowsSelected: {},
1224
+ RowsCleared: {},
1225
+ /**
1226
+ * A rectangle of cells, from Shift with a key. `reveal` scrolls its far
1227
+ * corner into view, as `Moved`'s does for a focused cell.
1228
+ */
1229
+ CellsSelected: {
1230
+ anchor: focus.Address,
1231
+ focus: focus.Address,
1232
+ reveal: Schema.OptionFromNullOr(Offsets)
1233
+ },
1234
+ /**
1235
+ * The pointer pressed the cell whose DOM id is `cell` (`GridFocus.cellId`).
1236
+ * With Shift it spans a range from the focused cell, with Ctrl or Meta it
1237
+ * toggles the cell's row, and plainly it focuses the cell. The id comes
1238
+ * from the page, so one that is not this grid's cell changes nothing.
1239
+ */
1240
+ CellPressed: {
1241
+ cell: Schema.String,
1242
+ shiftKey: Schema.Boolean,
1243
+ toggleKey: Schema.Boolean
1244
+ },
1245
+ CellsCleared: {},
1246
+ /** An edit began on an editable cell, with the text it starts from. */
1247
+ EditStarted: {
1248
+ address: focus.Address,
1249
+ draft: Schema.String
1250
+ },
1251
+ /**
1252
+ * A key typed on the grid itself, over an editable cell: it starts an
1253
+ * edit with the text, or, when that cell's edit is already open (the
1254
+ * keys came faster than the editor took focus), adds to its draft.
1255
+ * On a choice it picks the next option starting with the key instead,
1256
+ * after the draft's, as a select finds one. `from` is the text the cell
1257
+ * showed, which a new edit began from.
1258
+ */
1259
+ EditTyped: {
1260
+ address: focus.Address,
1261
+ text: Schema.String,
1262
+ from: Schema.String
1263
+ },
1264
+ EditChanged: { draft: Schema.String },
1265
+ /**
1266
+ * A choice's draft moved through its column's options: the next or
1267
+ * previous, the first or last, or a page of ten either way, stopping at
1268
+ * the ends. The view sends the step; `update` works out the option from
1269
+ * the draft as it is. On a column that is no choice it changes nothing.
1270
+ */
1271
+ EditStepped: { by: Schema.Literals(choiceSteps) },
1272
+ /** A pointer chose one of a choice's options: it is the draft, committed in place. */
1273
+ EditChosen: { draft: Schema.String },
1274
+ /**
1275
+ * The draft is to be kept. When the column accepts it the edit ends, focus
1276
+ * goes to `next` (the cell below, or beside, worked out by the view), and
1277
+ * the grid reports `Out.Edited`, unless the draft is the text the edit
1278
+ * began from or decodes to the same value; when it refuses it, the edit
1279
+ * stays with the error.
1280
+ */
1281
+ EditCommitted: {
1282
+ next: Schema.OptionFromNullOr(focus.Address),
1283
+ reveal: Schema.OptionFromNullOr(Offsets)
1284
+ },
1285
+ EditCancelled: {},
1286
+ /**
1287
+ * Text pasted, or a cut's cleared cells, laid onto editable cells by the
1288
+ * view (`Clipboard.pasteAt`). A cell its text leaves unchanged (as an
1289
+ * edit judges it, against `from`) is dropped; the rest are checked against
1290
+ * their columns and reported as one `Pasted`, or nothing when none is left.
1291
+ */
1292
+ Pasted: { cells: Schema.Array(PastedCell) },
1293
+ /**
1294
+ * Ctrl or Meta with Z on the grid, or with Shift (or Ctrl+Y) for redo.
1295
+ * An open edit keeps them, since the editor's own undo is the field's.
1296
+ */
1297
+ UndoRequested: {},
1298
+ RedoRequested: {},
1299
+ /** Ctrl+D or Ctrl+R over a range, worked out by the view: carry `source` on to `to`. */
1300
+ FillRequested: FillRequest.fields,
1301
+ /** The range's fill handle was pressed and moved: a fill begins from the range. */
1302
+ FillStarted: {},
1303
+ /** The pointer, filling, is over the cell whose DOM id is `cell`. */
1304
+ FillDragged: { cell: Schema.String },
1305
+ /** The fill handle was let go, or the drag cancelled (`completed` false). */
1306
+ FillEnded: { completed: Schema.Boolean }
1307
+ });
1308
+ /**
1309
+ * What the grid reports to its parent: one cell's committed text, or a
1310
+ * paste's, as one change. Turning text into values and writing them is the
1311
+ * application's, and so is taking them back: `UndoRequested` and
1312
+ * `RedoRequested` carry nothing, since what to undo is the application's
1313
+ * history, read when the request arrives.
1314
+ */
1315
+ const Out = defineTaggedUnion({
1316
+ Edited: {
1317
+ row: Schema.String,
1318
+ column: Column,
1319
+ text: Schema.String
1320
+ },
1321
+ /** The cells their columns accepted, and those they refused, with why. */
1322
+ Pasted: {
1323
+ accepted: Schema.Array(CellText),
1324
+ refused: Schema.Array(Schema.Struct({
1325
+ ...CellText.fields,
1326
+ error: Schema.String
1327
+ }))
1328
+ },
1329
+ UndoRequested: {},
1330
+ RedoRequested: {},
1331
+ /**
1332
+ * A fill: carry `source` on to `to`. What it writes is worked out from the
1333
+ * rows by `fill`, which the application holds.
1334
+ */
1335
+ Filled: FillRequest.fields
1336
+ });
1337
+ const focusTo = (model, address) => {
1338
+ const next = focus.bundle.update(model.focus, focus.Message.Focused({ address }), void 0).model;
1339
+ return next === model.focus ? model : modifyFields(model, { focus: () => next });
1340
+ };
1341
+ const viewportBy = (model, message) => {
1342
+ const next = GridViewport.bundle.update(model.viewport, message, void 0).model;
1343
+ return next === model.viewport ? model : modifyFields(model, { viewport: () => next });
1344
+ };
1345
+ const columnsBy = (model, next) => next === model.columns ? model : modifyFields(model, { columns: () => next });
1346
+ const selectionBy = (model, next) => next === model.selection ? model : modifyFields(model, { selection: () => next });
1347
+ const clearCells = (model) => Option.isNone(model.selection.cells) ? model : selectionBy(model, {
1348
+ ...model.selection,
1349
+ cells: Option.none()
1350
+ });
1351
+ const isColumn = (column) => Object.hasOwn(options.columns.byId, column);
1352
+ /** The address of one of this grid's cells, from its DOM id. */
1353
+ const addressOf = (cell) => Option.flatMap(GridFocus.cellOf(options.id, cell), ({ row, column }) => isColumn(column) ? Option.some({
1354
+ row,
1355
+ column
1356
+ }) : Option.none());
1357
+ const pressed = (model, address, shiftKey, toggleKey) => {
1358
+ if (shiftKey && options.cellSelection === true) {
1359
+ const anchor = Option.getOrElse(Option.orElse(Option.map(model.selection.cells, (cells) => cells.anchor), () => model.focus.current), () => address);
1360
+ return { model: selectionBy(model, {
1361
+ ...model.selection,
1362
+ cells: Option.some({
1363
+ anchor,
1364
+ focus: address
1365
+ })
1366
+ }) };
1367
+ }
1368
+ const focused = clearCells(focusTo(model, address));
1369
+ if (toggleKey && options.rowSelection !== void 0) return { model: selectionBy(focused, choose(focused.selection, address.row)) };
1370
+ return { model: focused };
1371
+ };
1372
+ const decoders = /* @__PURE__ */ new Map();
1373
+ const editors = /* @__PURE__ */ new Map();
1374
+ for (const id of options.columns.ids) {
1375
+ const edit = options.columns.byId[id].edit;
1376
+ if (edit === void 0) continue;
1377
+ decoders.set(id, Schema.decodeUnknownResult(edit.schema ?? Schema.String));
1378
+ editors.set(id, editorOf(edit.schema));
1379
+ }
1380
+ /** How a column's cells are edited: as text, a number, or a choice; none when it does not edit. */
1381
+ const editorFor = (column) => Option.fromUndefinedOr(editors.get(column));
1382
+ /** Why a column refuses a text, or none when it takes it. */
1383
+ const errorOf = (column, text) => Option.flatMap(Option.fromUndefinedOr(decoders.get(column)), (decode) => Result.match(decode(text), {
1384
+ onSuccess: () => Option.none(),
1385
+ onFailure: (error) => Option.some(error.message)
1386
+ }));
1387
+ /**
1388
+ * A reported cell's value, decoded by its column's schema, handed to the
1389
+ * handler for that column: one for each column that edits, each given its
1390
+ * own value type. The grid reports only text its column accepted, so a cell
1391
+ * that does not decode, or names a column that does not edit, was not the
1392
+ * grid's, and throws.
1393
+ */
1394
+ const matchEdit = (cell, handlers) => {
1395
+ const decode = decoders.get(cell.column);
1396
+ if (decode === void 0) throw new Error(`DataGrid.matchEdit: the ${cell.column} column does not edit.`);
1397
+ return Result.match(decode(cell.text), {
1398
+ onFailure: (error) => {
1399
+ throw new Error(`DataGrid.matchEdit: the ${cell.column} column refuses "${cell.text}" (${error.message}); the grid reports only text its column accepted.`);
1400
+ },
1401
+ onSuccess: (value) => handlers[cell.column]({
1402
+ row: cell.row,
1403
+ value
1404
+ })
1405
+ });
1406
+ };
1407
+ /**
1408
+ * Whether a column's new text says what its old text did: the same text,
1409
+ * or two that decode to equal values (`01.73` and `1.73`). An edit is
1410
+ * judged against the text it began from, not the cell as it is now, so
1411
+ * one left as it opened never writes over a change made meanwhile.
1412
+ */
1413
+ const unchanged = (column, from, text) => text === from || Option.exists(Option.fromUndefinedOr(decoders.get(column)), (decode) => Result.match(Result.all([decode(from), decode(text)]), {
1414
+ onSuccess: ([before, after]) => Equal.equals(before, after),
1415
+ onFailure: () => false
1416
+ }));
1417
+ /** A choice column's options, or none for a column that is no choice. */
1418
+ const optionsOf = (column) => Option.flatMap(editorFor(column), CellEditor.match({
1419
+ Text: () => Option.none(),
1420
+ Number: () => Option.none(),
1421
+ Choice: ({ options }) => Option.some(options)
1422
+ }));
1423
+ /** The option after `current` that starts with `key`, ignoring case, wrapping round; else `current`. */
1424
+ const typedOption = (options, current, key) => {
1425
+ const start = options.indexOf(current);
1426
+ const wanted = key.toLowerCase();
1427
+ for (let offset = 1; offset <= options.length; offset++) {
1428
+ const option = options[(start + offset) % options.length];
1429
+ if (option.toLowerCase().startsWith(wanted)) return option;
1430
+ }
1431
+ return current;
1432
+ };
1433
+ const page = 10;
1434
+ const steppedIndex = (by, at, count) => Math.max(0, Math.min(count - 1, {
1435
+ next: at + 1,
1436
+ previous: at - 1,
1437
+ first: 0,
1438
+ last: count - 1,
1439
+ pageNext: at + page,
1440
+ pagePrevious: at - page
1441
+ }[by]));
1442
+ const sameCell = (a, b) => a.row === b.row && a.column === b.column;
1443
+ /**
1444
+ * Cells laid by a paste or a fill, as their columns judge them: those that
1445
+ * pass and those refused, with why. A cell on a column that does not edit,
1446
+ * or one its text leaves unchanged, is dropped.
1447
+ */
1448
+ const judged = (cells) => {
1449
+ const accepted = [];
1450
+ const refused = [];
1451
+ for (const { from, ...cell } of cells) {
1452
+ if (options.columns.byId[cell.column].edit === void 0) continue;
1453
+ if (unchanged(cell.column, from, cell.text)) continue;
1454
+ Option.match(errorOf(cell.column, cell.text), {
1455
+ onNone: () => accepted.push(cell),
1456
+ onSome: (error) => refused.push({
1457
+ ...cell,
1458
+ error
1459
+ })
1460
+ });
1461
+ }
1462
+ return {
1463
+ accepted,
1464
+ refused
1465
+ };
1466
+ };
1467
+ /**
1468
+ * Ends an edit with its draft: none to report when nothing was edited or
1469
+ * the draft is unchanged, `refused` with the column's error when the draft
1470
+ * does not pass, or the edit closed and `Edited` to report.
1471
+ */
1472
+ const finish = (model) => Option.match(model.editing, {
1473
+ onNone: () => ({
1474
+ model,
1475
+ edited: Option.none(),
1476
+ refused: false
1477
+ }),
1478
+ onSome: (editing) => {
1479
+ const { address, from, draft } = editing;
1480
+ if (unchanged(address.column, from, draft)) return {
1481
+ model: modifyFields(model, { editing: () => Option.none() }),
1482
+ edited: Option.none(),
1483
+ refused: false
1484
+ };
1485
+ return Option.match(errorOf(address.column, draft), {
1486
+ onSome: (message) => ({
1487
+ model: modifyFields(model, { editing: () => Option.some({
1488
+ ...editing,
1489
+ error: Option.some(message)
1490
+ }) }),
1491
+ edited: Option.none(),
1492
+ refused: true
1493
+ }),
1494
+ onNone: () => ({
1495
+ model: modifyFields(model, { editing: () => Option.none() }),
1496
+ edited: Option.some(Out.Edited({
1497
+ row: address.row,
1498
+ column: address.column,
1499
+ text: draft
1500
+ })),
1501
+ refused: false
1502
+ })
1503
+ });
1504
+ }
1505
+ });
1506
+ /**
1507
+ * Keeps a draft: the column refusing it leaves the edit open with the
1508
+ * error; otherwise the edit ends, focus goes to `next`, and `Edited` is
1509
+ * reported unless the draft is unchanged.
1510
+ */
1511
+ const committed = (model, next, reveal) => {
1512
+ const finished = finish(model);
1513
+ if (finished.refused) return { model: finished.model };
1514
+ return {
1515
+ model: Option.match(next, {
1516
+ onNone: () => finished.model,
1517
+ onSome: (address) => focusTo(finished.model, address)
1518
+ }),
1519
+ ...Option.match(finished.edited, {
1520
+ onNone: () => ({}),
1521
+ onSome: (outMessage) => ({ outMessage })
1522
+ }),
1523
+ commands: Option.match(reveal, {
1524
+ onNone: () => [],
1525
+ onSome: (offsets) => [GridViewport.scrollTo(options.id, offsets)]
1526
+ })
1527
+ };
1528
+ };
1529
+ /**
1530
+ * The pointer leaving an edit commits it first, as a spreadsheet does; a
1531
+ * draft the column refuses keeps the edit, and the pointer's change waits.
1532
+ */
1533
+ const afterEdit = (model, then) => {
1534
+ const finished = finish(model);
1535
+ if (finished.refused) return { model: finished.model };
1536
+ const next = then(finished.model);
1537
+ return Option.match(finished.edited, {
1538
+ onNone: () => next,
1539
+ onSome: (outMessage) => ({
1540
+ ...next,
1541
+ outMessage
1542
+ })
1543
+ });
1544
+ };
1545
+ const choose = (selection, row) => {
1546
+ if (options.rowSelection === "single") return {
1547
+ ...selection,
1548
+ rows: RowSelection.Keys({ keys: [row] }),
1549
+ anchor: Option.some(row)
1550
+ };
1551
+ return {
1552
+ ...selection,
1553
+ rows: GridSelection.toggle(selection.rows, row),
1554
+ anchor: Option.some(row)
1555
+ };
1556
+ };
1557
+ /**
1558
+ * The items of a column's menu, in order: pin to each other region, hide
1559
+ * when it can be hidden, and show each hidden column. An item is offered
1560
+ * only when it changes something.
1561
+ */
1562
+ const menuItems = (state, column) => [
1563
+ ...[
1564
+ "start",
1565
+ "end",
1566
+ "center"
1567
+ ].filter((region) => region !== columnState.regionOf(state, column)).map((region) => MenuItem.Pin({ region })),
1568
+ ...columnState.hide(state, column) === state ? [] : [MenuItem.Hide()],
1569
+ ...state.hidden.map((other) => MenuItem.Show({ column: other }))
1570
+ ];
1571
+ /** The column Message a menu item stands for. */
1572
+ const messageOf = (state, column, item) => MenuItem.match(item, {
1573
+ Pin: ({ region }) => Message.ColumnMoved({
1574
+ column,
1575
+ region,
1576
+ index: {
1577
+ start: state.start.length,
1578
+ end: 0,
1579
+ center: columnState.regionOf(state, column) === "start" ? 0 : state.center.length
1580
+ }[region]
1581
+ }),
1582
+ Hide: () => Message.ColumnHidden({ column }),
1583
+ Show: ({ column: other }) => Message.ColumnShown({ column: other })
1584
+ });
1585
+ const closeMenu = (model) => Option.isNone(model.menu) ? model : modifyFields(model, { menu: () => Option.none() });
1586
+ const bundle = Bundle.make("DataGrid", {
1587
+ Model,
1588
+ Message,
1589
+ init: () => ({ model: {
1590
+ focus: focus.bundle.init(void 0).model,
1591
+ viewport: GridViewport.bundle.init(void 0).model,
1592
+ columns: columnState.initial(),
1593
+ resizing: Option.none(),
1594
+ dragging: Option.none(),
1595
+ menu: Option.none(),
1596
+ filling: Option.none(),
1597
+ selection: {
1598
+ rows: GridSelection.none,
1599
+ anchor: Option.none(),
1600
+ cells: Option.none()
1601
+ },
1602
+ editing: Option.none()
1603
+ } }),
1604
+ update: (model, message) => Message.match(message, {
1605
+ Focused: ({ address }) => afterEdit(model, (settled) => ({ model: clearCells(focusTo(settled, address)) })),
1606
+ Moved: ({ address, reveal }) => ({
1607
+ model: clearCells(focusTo(model, address)),
1608
+ commands: Option.match(reveal, {
1609
+ onNone: () => [],
1610
+ onSome: (offsets) => [GridViewport.scrollTo(options.id, offsets)]
1611
+ })
1612
+ }),
1613
+ HeaderFocused: ({ column, reveal }) => {
1614
+ const next = focus.bundle.update(model.focus, focus.Message.HeaderFocused({ column }), void 0).model;
1615
+ return {
1616
+ model: next === model.focus ? model : modifyFields(model, { focus: () => next }),
1617
+ commands: Option.match(reveal, {
1618
+ onNone: () => [],
1619
+ onSome: (offsets) => [GridViewport.scrollTo(options.id, offsets)]
1620
+ })
1621
+ };
1622
+ },
1623
+ Measured: (fields) => ({ model: viewportBy(model, GridViewport.Message.Measured(fields)) }),
1624
+ Revealed: (fields) => ({ model: viewportBy(model, GridViewport.Message.Revealed(fields)) }),
1625
+ ColumnResized: ({ column, width }) => ({ model: columnsBy(model, columnState.resize(model.columns, column, width)) }),
1626
+ ColumnHidden: ({ column }) => {
1627
+ const hidden = columnsBy(model, columnState.hide(model.columns, column));
1628
+ if (hidden === model) return { model };
1629
+ const off = (on) => Option.contains(on, column);
1630
+ return { model: modifyFields(hidden, {
1631
+ editing: (editing) => off(Option.map(editing, (each) => each.address.column)) ? Option.none() : editing,
1632
+ focus: (current) => off(current.header) ? {
1633
+ ...current,
1634
+ header: Option.none()
1635
+ } : current,
1636
+ menu: (menu) => off(Option.map(menu, (each) => each.column)) ? Option.none() : menu
1637
+ }) };
1638
+ },
1639
+ ColumnShown: ({ column }) => ({ model: columnsBy(model, columnState.show(model.columns, column)) }),
1640
+ ColumnMoved: ({ column, region, index }) => ({ model: columnsBy(model, columnState.move(model.columns, column, region, index)) }),
1641
+ ResizeStarted: ({ column }) => ({ model: options.columns.byId[column].resizable === false ? model : modifyFields(model, { resizing: () => Option.some({
1642
+ column,
1643
+ from: columnState.widthOf(model.columns)(column)
1644
+ }) }) }),
1645
+ ResizeMoved: ({ delta }) => ({ model: Option.match(model.resizing, {
1646
+ onNone: () => model,
1647
+ onSome: ({ column, from }) => columnsBy(model, columnState.resize(model.columns, column, from + delta))
1648
+ }) }),
1649
+ MenuOpened: ({ column }) => model.columns.hidden.includes(column) ? { model } : afterEdit(model, (settled) => {
1650
+ const focused = focus.bundle.update(settled.focus, focus.Message.HeaderFocused({ column }), void 0).model;
1651
+ return { model: modifyFields(settled, {
1652
+ focus: () => focused,
1653
+ menu: () => Option.some({
1654
+ column,
1655
+ active: 0
1656
+ })
1657
+ }) };
1658
+ }),
1659
+ MenuMoved: ({ active }) => ({ model: Option.match(model.menu, {
1660
+ onNone: () => model,
1661
+ onSome: (menu) => {
1662
+ const last = menuItems(model.columns, menu.column).length - 1;
1663
+ const clamped = Math.min(Math.max(0, Math.trunc(active)), Math.max(0, last));
1664
+ return clamped === menu.active ? model : modifyFields(model, { menu: () => Option.some({
1665
+ ...menu,
1666
+ active: clamped
1667
+ }) });
1668
+ }
1669
+ }) }),
1670
+ MenuChosen: ({ index }) => Option.match(model.menu, {
1671
+ onNone: () => ({ model }),
1672
+ onSome: ({ column }) => Option.match(Option.fromUndefinedOr(menuItems(model.columns, column)[index]), {
1673
+ onNone: () => ({ model: closeMenu(model) }),
1674
+ onSome: (item) => bundle.update(closeMenu(model), messageOf(model.columns, column, item), void 0)
1675
+ })
1676
+ }),
1677
+ MenuClosed: () => ({ model: closeMenu(model) }),
1678
+ ColumnDragStarted: ({ header }) => ({ model: Option.match(Option.filter(Option.flatMap(GridFocus.headerOf(options.id, header), (column) => isColumn(column) ? Option.some(column) : Option.none()), (column) => !model.columns.hidden.includes(column)), {
1679
+ onNone: () => model,
1680
+ onSome: (column) => modifyFields(model, { dragging: () => Option.some({
1681
+ column,
1682
+ delta: 0
1683
+ }) })
1684
+ }) }),
1685
+ ColumnDragged: ({ delta }) => ({ model: Option.match(model.dragging, {
1686
+ onNone: () => model,
1687
+ onSome: (dragging) => dragging.delta === delta ? model : modifyFields(model, { dragging: () => Option.some({
1688
+ ...dragging,
1689
+ delta
1690
+ }) })
1691
+ }) }),
1692
+ ColumnDragEnded: ({ completed }) => ({ model: Option.match(model.dragging, {
1693
+ onNone: () => model,
1694
+ onSome: ({ column, delta }) => {
1695
+ const dropped = completed ? columnsBy(model, columnState.move(model.columns, column, columnState.regionOf(model.columns, column), columnState.dropAt(model.columns, column, delta))) : model;
1696
+ return modifyFields(dropped, { dragging: () => Option.none() });
1697
+ }
1698
+ }) }),
1699
+ RowSelected: ({ row }) => ({ model: options.rowSelection === void 0 ? model : selectionBy(model, choose(model.selection, row)) }),
1700
+ RowsExtended: ({ rows, to }) => {
1701
+ if (options.rowSelection !== "multiple") return { model };
1702
+ const added = GridSelection.add(model.selection.rows, rows);
1703
+ const anchor = Option.orElse(model.selection.anchor, () => Option.some(to));
1704
+ return { model: added === model.selection.rows && Option.isSome(model.selection.anchor) ? model : selectionBy(model, {
1705
+ ...model.selection,
1706
+ rows: added,
1707
+ anchor
1708
+ }) };
1709
+ },
1710
+ AllRowsSelected: () => ({ model: options.rowSelection !== "multiple" ? model : selectionBy(model, {
1711
+ ...model.selection,
1712
+ rows: RowSelection.AllExcept({ except: [] })
1713
+ }) }),
1714
+ RowsCleared: () => {
1715
+ return { model: RowSelection.match(model.selection.rows, {
1716
+ Keys: ({ keys }) => keys.length === 0,
1717
+ AllExcept: () => false
1718
+ }) && Option.isNone(model.selection.anchor) ? model : selectionBy(model, {
1719
+ ...model.selection,
1720
+ rows: GridSelection.none,
1721
+ anchor: Option.none()
1722
+ }) };
1723
+ },
1724
+ CellsSelected: ({ anchor, focus: far, reveal }) => options.cellSelection === true ? {
1725
+ model: selectionBy(model, {
1726
+ ...model.selection,
1727
+ cells: Option.some({
1728
+ anchor,
1729
+ focus: far
1730
+ })
1731
+ }),
1732
+ commands: Option.match(reveal, {
1733
+ onNone: () => [],
1734
+ onSome: (offsets) => [GridViewport.scrollTo(options.id, offsets)]
1735
+ })
1736
+ } : { model },
1737
+ CellPressed: ({ cell, shiftKey, toggleKey }) => Option.match(addressOf(cell), {
1738
+ onNone: () => ({ model }),
1739
+ onSome: (address) => Option.exists(model.editing, (editing) => sameCell(editing.address, address)) ? { model } : afterEdit(model, (settled) => pressed(settled, address, shiftKey, toggleKey))
1740
+ }),
1741
+ EditStarted: ({ address, draft }) => options.columns.byId[address.column].edit === void 0 ? { model } : { model: modifyFields(clearCells(focusTo(model, address)), { editing: () => Option.some({
1742
+ address,
1743
+ from: draft,
1744
+ draft,
1745
+ error: Option.none()
1746
+ }) }) },
1747
+ EditTyped: ({ address, text, from }) => {
1748
+ if (options.columns.byId[address.column].edit === void 0) return { model };
1749
+ const open = Option.filter(model.editing, (editing) => sameCell(editing.address, address));
1750
+ const typed = (draft) => Option.match(optionsOf(address.column), {
1751
+ onNone: () => draft + text,
1752
+ onSome: (choices) => typedOption(choices, draft, text)
1753
+ });
1754
+ const editing = Option.match(open, {
1755
+ onNone: () => ({
1756
+ address,
1757
+ from,
1758
+ draft: Option.isSome(optionsOf(address.column)) ? typed(from) : text,
1759
+ error: Option.none()
1760
+ }),
1761
+ onSome: (edit) => ({
1762
+ ...edit,
1763
+ draft: typed(edit.draft),
1764
+ error: Option.none()
1765
+ })
1766
+ });
1767
+ return { model: modifyFields(clearCells(focusTo(model, address)), { editing: () => Option.some(editing) }) };
1768
+ },
1769
+ EditChanged: ({ draft }) => ({ model: Option.match(model.editing, {
1770
+ onNone: () => model,
1771
+ onSome: (editing) => editing.draft === draft && Option.isNone(editing.error) ? model : modifyFields(model, { editing: () => Option.some({
1772
+ ...editing,
1773
+ draft,
1774
+ error: Option.none()
1775
+ }) })
1776
+ }) }),
1777
+ EditStepped: ({ by }) => Option.match(model.editing, {
1778
+ onNone: () => ({ model }),
1779
+ onSome: (editing) => Option.match(optionsOf(editing.address.column), {
1780
+ onNone: () => ({ model }),
1781
+ onSome: (choices) => {
1782
+ const draft = choices[steppedIndex(by, choices.indexOf(editing.draft), choices.length)];
1783
+ return draft === void 0 || draft === editing.draft ? { model } : { model: modifyFields(model, { editing: () => Option.some({
1784
+ ...editing,
1785
+ draft,
1786
+ error: Option.none()
1787
+ }) }) };
1788
+ }
1789
+ })
1790
+ }),
1791
+ EditChosen: ({ draft }) => Option.match(model.editing, {
1792
+ onNone: () => ({ model }),
1793
+ onSome: (editing) => committed(modifyFields(model, { editing: () => Option.some({
1794
+ ...editing,
1795
+ draft
1796
+ }) }), Option.none(), Option.none())
1797
+ }),
1798
+ EditCommitted: ({ next, reveal }) => committed(model, next, reveal),
1799
+ Pasted: ({ cells }) => {
1800
+ if (Option.isSome(model.editing) || cells.length === 0) return { model };
1801
+ const { accepted, refused } = judged(cells);
1802
+ return accepted.length === 0 && refused.length === 0 ? { model } : {
1803
+ model,
1804
+ outMessage: Out.Pasted({
1805
+ accepted,
1806
+ refused
1807
+ })
1808
+ };
1809
+ },
1810
+ FillRequested: (request) => Option.isSome(model.editing) ? { model } : {
1811
+ model,
1812
+ outMessage: Out.Filled({
1813
+ source: request.source,
1814
+ to: request.to
1815
+ })
1816
+ },
1817
+ FillStarted: () => {
1818
+ if (Option.isSome(model.editing)) return { model };
1819
+ const source = Option.orElse(model.selection.cells, () => Option.map(model.focus.current, (address) => ({
1820
+ anchor: address,
1821
+ focus: address
1822
+ })));
1823
+ return { model: Option.match(source, {
1824
+ onNone: () => model,
1825
+ onSome: (range) => modifyFields(model, { filling: () => Option.some({
1826
+ source: range,
1827
+ to: range.focus
1828
+ }) })
1829
+ }) };
1830
+ },
1831
+ FillDragged: ({ cell }) => ({ model: Option.match(Option.zipWith(model.filling, addressOf(cell), (filling, to) => ({
1832
+ filling,
1833
+ to
1834
+ })), {
1835
+ onNone: () => model,
1836
+ onSome: ({ filling, to }) => sameCell(filling.to, to) ? model : modifyFields(model, { filling: () => Option.some({
1837
+ ...filling,
1838
+ to
1839
+ }) })
1840
+ }) }),
1841
+ FillEnded: ({ completed }) => Option.match(model.filling, {
1842
+ onNone: () => ({ model }),
1843
+ onSome: ({ source, to }) => {
1844
+ const ended = modifyFields(model, { filling: () => Option.none() });
1845
+ return completed ? {
1846
+ model: ended,
1847
+ outMessage: Out.Filled({
1848
+ source,
1849
+ to
1850
+ })
1851
+ } : { model: ended };
1852
+ }
1853
+ }),
1854
+ UndoRequested: () => Option.isSome(model.editing) ? { model } : {
1855
+ model,
1856
+ outMessage: Out.UndoRequested()
1857
+ },
1858
+ RedoRequested: () => Option.isSome(model.editing) ? { model } : {
1859
+ model,
1860
+ outMessage: Out.RedoRequested()
1861
+ },
1862
+ EditCancelled: () => ({ model: Option.isNone(model.editing) ? model : modifyFields(model, { editing: () => Option.none() }) }),
1863
+ CellsCleared: () => ({ model: clearCells(model) }),
1864
+ ResizeEnded: ({ completed }) => ({ model: Option.match(model.resizing, {
1865
+ onNone: () => model,
1866
+ onSome: ({ column, from }) => {
1867
+ const settled = completed ? model : columnsBy(model, columnState.resize(model.columns, column, from));
1868
+ return modifyFields(settled, { resizing: () => Option.none() });
1869
+ }
1870
+ }) })
1871
+ })
1872
+ });
1873
+ const projections = /* @__PURE__ */ new WeakMap();
1874
+ /** The text an edit of a cell begins from: its column's `draft`, or the text it shows. */
1875
+ const draftOf = (projection, address) => Option.match(Option.flatMap(projection.rowIndex(address.row), (index) => projection.rows.rowAt(index)), {
1876
+ onNone: () => "",
1877
+ onSome: (row) => {
1878
+ const column = options.columns.byId[address.column];
1879
+ return column.edit?.draft?.(row) ?? Columns.textOf(column.value(row));
1880
+ }
1881
+ });
1882
+ /**
1883
+ * What an `Out.Filled` writes, judged as a paste's cells are: those their
1884
+ * columns accept and those they refuse, over `rows` as they are now and the
1885
+ * grid's column state. Nothing when `to` is inside the source.
1886
+ */
1887
+ const fill = (rows, state, request) => {
1888
+ const projection = project(rows, state.columns);
1889
+ return Option.match(Fill.plan(projection, request), {
1890
+ onNone: () => judged([]),
1891
+ onSome: (plan) => judged(Fill.cells(projection, plan, {
1892
+ editable: (column) => options.columns.byId[column].edit !== void 0,
1893
+ from: (address) => draftOf(projection, address)
1894
+ }))
1895
+ });
1896
+ };
1897
+ /** The grid as presented: the rows through the column state in the Model. */
1898
+ const project = (rows, state) => {
1899
+ const cached = projections.get(rows);
1900
+ if (cached !== void 0 && cached.state === state) return cached.projection;
1901
+ const projection = GridProjection.make({
1902
+ rows,
1903
+ columns: options.columns,
1904
+ layout: state
1905
+ });
1906
+ projections.set(rows, {
1907
+ state,
1908
+ projection
1909
+ });
1910
+ return projection;
1911
+ };
1912
+ /**
1913
+ * The rows and columns the view draws for this input, as the view itself
1914
+ * works them out: a count of what is drawn, read from here, is what is drawn.
1915
+ */
1916
+ const window = (input) => VirtualGrid.window({
1917
+ projection: project(input.rows, input.state.columns),
1918
+ rowHeight: input.rowHeight,
1919
+ width: columnState.widthOf(input.state.columns),
1920
+ headerHeight: input.headerHeight,
1921
+ viewport: input.state.viewport,
1922
+ ...input.overscan === void 0 ? {} : { overscan: input.overscan }
1923
+ });
1924
+ return {
1925
+ id: options.id,
1926
+ matchEdit,
1927
+ editorFor,
1928
+ MenuItem,
1929
+ menuItems,
1930
+ columns: options.columns,
1931
+ rowSelection: options.rowSelection,
1932
+ cellSelection: options.cellSelection === true,
1933
+ focus,
1934
+ columnState,
1935
+ project,
1936
+ window,
1937
+ fill,
1938
+ draftOf,
1939
+ Out,
1940
+ Model,
1941
+ Message,
1942
+ bundle
1943
+ };
1944
+ };
1945
+ const DataGrid = { make };
1946
+ //#endregion
1947
+ export { CellAddress, CellEditor, Clipboard, ColumnLayout, ColumnState, Columns, DataGrid, Fill, GridFocus, GridProjection, GridSelection, GridViewport, RowCount, RowModel, RowSelection, RowStatus, VirtualGrid, addressableRows };
1948
+
1949
+ //# sourceMappingURL=index.mjs.map