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