@ember-lattice/editing 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,890 @@
1
+ import { tracked } from '@glimmer/tracking';
2
+ import is from '@sindresorhus/is';
3
+ import { lookupControl, runValidator } from '@ember-formwright/ember';
4
+ import { latticeLocale } from '@ember-lattice/core';
5
+ import Component from '@glimmer/component';
6
+ import { getOwner } from '@ember/owner';
7
+ import { precompileTemplate } from '@ember/template-compilation';
8
+ import { setComponentTemplate } from '@ember/component';
9
+ import { fn, get, hash } from '@ember/helper';
10
+ import templateOnly from '@ember/component/template-only';
11
+ import { State, Machine, transition } from '@switchyard-ts/core';
12
+ import { n, g, i } from 'decorator-transforms/runtime';
13
+ import { on } from '@ember/modifier';
14
+ import { guidFor } from '@ember/object/internals';
15
+ import { htmlSafe } from '@ember/template';
16
+ import { waitForPromise } from '@ember/test-waiters';
17
+
18
+ // The default editor of a typed column: a column with `meta.columnType` (from
19
+ // `@ember-lattice/column-types` `columnType()`) and `meta.lattice.editable`. The type is read
20
+ // structurally: the editing package does not import the column types package.
21
+
22
+ /** The part of a column type that editing reads. */
23
+
24
+ /** The Formwright control of each type name. Other types have no default editor. */
25
+ const TYPE_EDITORS = {
26
+ text: 'input',
27
+ email: 'email',
28
+ number: 'number',
29
+ date: 'date',
30
+ datetime: 'datetime',
31
+ boolean: 'checkbox',
32
+ enum: 'select',
33
+ // Value objects (Millwork): a text input with the plain text, read back through the type.
34
+ money: 'input',
35
+ decimal: 'input',
36
+ percent: 'input'
37
+ };
38
+
39
+ /** The length of the plain text that each control takes: ISO text for the date controls. */
40
+ const PLAIN_LENGTH = {
41
+ date: 10,
42
+ datetime: 16,
43
+ money: undefined,
44
+ decimal: undefined,
45
+ percent: undefined
46
+ };
47
+ const columnTypeOf = column => column.columnDef.meta?.columnType;
48
+
49
+ /** The editor of a column: `meta.lattice.editor`, else the editor of its type when editable. */
50
+ function editorOf(column) {
51
+ const meta = column.columnDef.meta?.lattice;
52
+ if (meta?.editor !== undefined) return meta.editor;
53
+ const type = columnTypeOf(column);
54
+ return meta?.editable && type ? TYPE_EDITORS[type.name] : undefined;
55
+ }
56
+
57
+ /**
58
+ * A text (a typed key, a paste) as a value: `meta.lattice.parse`, else the type parse. Text that
59
+ * the type does not read stays text, as with no parse, so the schema can report it.
60
+ */
61
+ function parserOf(column, locale) {
62
+ const parse = column.columnDef.meta?.lattice?.parse;
63
+ if (parse) return parse;
64
+ const type = columnTypeOf(column);
65
+ return type?.parse && (text => type.parse(text, locale) ?? text);
66
+ }
67
+
68
+ /**
69
+ * The value for the control: the plain text of a date (ISO text) or of a value object (money,
70
+ * decimal, percent). Other values, and text, go to the control as they are.
71
+ */
72
+ function toControl(column, value) {
73
+ const type = columnTypeOf(column);
74
+ if (!type?.plain || !(type.name in PLAIN_LENGTH)) return value;
75
+ if (is.nullOrUndefined(value) || is.string(value)) return value;
76
+ return type.plain(value).slice(0, PLAIN_LENGTH[type.name]);
77
+ }
78
+
79
+ /**
80
+ * The value from the control. Text from a plain-text control reads through the type parse when
81
+ * the row value is not text: the data keeps its form. Text that does not read stays text.
82
+ */
83
+ function fromControl(column, rowValue, value) {
84
+ const type = columnTypeOf(column);
85
+ if (!type?.parse || !(type.name in PLAIN_LENGTH)) return value;
86
+ if (!is.string(value) || is.string(rowValue)) return value;
87
+ return type.parse(value) ?? value;
88
+ }
89
+
90
+ // The cell editor: the Formwright control of the column (`meta.lattice.editor`), a control name
91
+ // or a component with the Formwright `ControlSignature`. An editable typed column with no editor
92
+ // gets the control of its type (`typed-editor.ts`).
93
+ class CellEditor extends Component {
94
+ get meta() {
95
+ return this.args.cell.column.columnDef.meta?.lattice;
96
+ }
97
+ get editor() {
98
+ return editorOf(this.args.cell.column);
99
+ }
100
+ get Control() {
101
+ const editor = this.editor;
102
+ return is.string(editor) ? lookupControl(editor) : editor;
103
+ }
104
+ /** The control name: Formwright controls such as `input` read their kind from it. */
105
+ get type() {
106
+ const editor = this.editor;
107
+ return is.string(editor) ? editor : 'custom';
108
+ }
109
+ get columnType() {
110
+ return columnTypeOf(this.args.cell.column);
111
+ }
112
+ /** `meta.lattice.options`, else the values of a closed type (an enum). */
113
+ get options() {
114
+ return this.meta?.options ?? this.columnType?.values?.();
115
+ }
116
+ /** The label of an option of a closed type: the type format. */
117
+ get optionLabel() {
118
+ const type = this.columnType;
119
+ const locale = latticeLocale(getOwner(this)).locale;
120
+ return type?.values ? option => type.format(option, locale) : undefined;
121
+ }
122
+ get value() {
123
+ return toControl(this.args.cell.column, this.args.value);
124
+ }
125
+ onChange = value => {
126
+ const {
127
+ column,
128
+ row
129
+ } = this.args.cell;
130
+ this.args.onChange(fromControl(column, row.getValue(column.id), value));
131
+ };
132
+ static {
133
+ setComponentTemplate(precompileTemplate("{{#if this.Control}}\n <this.Control @id={{@id}} @name={{@id}} @label={{@label}} @type={{this.type}} @value={{this.value}} @onChange={{this.onChange}} @invalid={{@invalid}} @options={{this.options}} @optionLabel={{this.optionLabel}} @search={{this.meta.search}} @item={{this.meta.optionComponent}} aria-label={{@label}} />\n{{/if}}", {
134
+ strictMode: true
135
+ }), this);
136
+ }
137
+ }
138
+
139
+ // The row editor of a full-row edit: the Formwright control of each editable column, over its
140
+ // cell. Tab moves between the controls, as in a form. The grid places each field on its cell.
141
+ const RowEditor = setComponentTemplate(precompileTemplate("{{#each @fields key=\"id\" as |field|}}\n <div class=\"lt-row-editor-field\" data-column-id={{field.column.id}}>\n <CellEditor @cell={{record row=@row column=field.column}} @id={{field.id}} @label={{field.label}} @value={{get @values field.column.id}} @onChange={{partial @onChange field.column.id}} @invalid={{false}} />\n </div>\n{{/each}}", {
142
+ strictMode: true,
143
+ scope: () => ({
144
+ CellEditor,
145
+ record: hash,
146
+ get,
147
+ partial: fn
148
+ })
149
+ }), templateOnly());
150
+
151
+ // The edit machine (plan section 7, decision 20). Each cell edit gets its own machine, so a save
152
+ // that is still in flight does not block the next edit.
153
+ class EditState extends State {
154
+ static Viewing = EditState.of('viewing');
155
+ static Editing = EditState.of('editing');
156
+ static Validating = EditState.of('validating');
157
+ static Saving = EditState.of('saving');
158
+ static Saved = EditState.of('saved');
159
+ static Failed = EditState.of('failed');
160
+ }
161
+ class EditMachine extends Machine {
162
+ static strict = true;
163
+ begin() {}
164
+ static {
165
+ n(this.prototype, "begin", [transition({
166
+ from: EditState.Viewing,
167
+ to: EditState.Editing
168
+ })]);
169
+ }
170
+ validate() {}
171
+
172
+ /** The value is not valid: the editor stays open with the errors. */
173
+ static {
174
+ n(this.prototype, "validate", [transition({
175
+ from: EditState.Editing,
176
+ to: EditState.Validating
177
+ })]);
178
+ }
179
+ invalid() {}
180
+ static {
181
+ n(this.prototype, "invalid", [transition({
182
+ from: EditState.Validating,
183
+ to: EditState.Editing
184
+ })]);
185
+ }
186
+ save() {}
187
+ static {
188
+ n(this.prototype, "save", [transition({
189
+ from: EditState.Validating,
190
+ to: EditState.Saving
191
+ })]);
192
+ }
193
+ resolve() {}
194
+ static {
195
+ n(this.prototype, "resolve", [transition({
196
+ from: EditState.Saving,
197
+ to: EditState.Saved
198
+ })]);
199
+ }
200
+ reject() {}
201
+ static {
202
+ n(this.prototype, "reject", [transition({
203
+ from: EditState.Saving,
204
+ to: EditState.Failed
205
+ })]);
206
+ }
207
+ cancel() {}
208
+ static {
209
+ n(this.prototype, "cancel", [transition({
210
+ from: [EditState.Editing, EditState.Validating],
211
+ to: EditState.Viewing
212
+ })]);
213
+ }
214
+ }
215
+
216
+ // The values of a fill-handle drag (plan section 7): a series of numbers, dates, or text with a
217
+ // trailing number extends; other values repeat.
218
+ const DAY = 86_400_000;
219
+ const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
220
+ const TRAILING_NUMBER = /^(.*?)(\d+)$/;
221
+
222
+ /** The step of the last two values, or `single` when there is one value. */
223
+ const stepOf = (list, single) => list.length >= 2 ? list[list.length - 1] - list[list.length - 2] : single;
224
+ const extend = (list, single, count, out) => {
225
+ const step = stepOf(list, single);
226
+ const last = list[list.length - 1];
227
+ return Array.from({
228
+ length: count
229
+ }, (_, i) => out(last + step * (i + 1)));
230
+ };
231
+
232
+ /** The `count` values after `source`. */
233
+ function fillSeries(source, count) {
234
+ if (source.length === 0) return [];
235
+ if (source.every(is.number)) return extend(source, 0, count, n => n);
236
+ if (source.every(is.date)) {
237
+ return extend(source.map(d => d.getTime()), DAY, count, n => new Date(n));
238
+ }
239
+ if (source.every(is.string)) {
240
+ if (source.every(s => ISO_DATE.test(s))) {
241
+ const times = source.map(s => Date.parse(`${s}T00:00:00Z`));
242
+ return extend(times, DAY, count, n => new Date(n).toISOString().slice(0, 10));
243
+ }
244
+ const parts = source.map(s => TRAILING_NUMBER.exec(s));
245
+ const prefix = parts[0]?.[1];
246
+ if (parts.every(p => p !== null && p[1] === prefix)) {
247
+ const digits = parts[parts.length - 1][2];
248
+ const numbers = parts.map(p => Number(p[2]));
249
+ return extend(numbers, 1, count, n => `${prefix}${String(n).padStart(digits.length, '0')}`);
250
+ }
251
+ }
252
+ return Array.from({
253
+ length: count
254
+ }, (_, i) => source[i % source.length]);
255
+ }
256
+
257
+ // Clipboard text: tab-separated values, with the quotes that spreadsheets write around a cell
258
+ // that holds a tab, a line end or a quote.
259
+
260
+ /** The rows of TSV text, each a list of cell texts. */
261
+ function parseTsv(text) {
262
+ const rows = [];
263
+ let row = [];
264
+ let cell = '';
265
+ let quoted = false;
266
+ for (let i = 0; i < text.length; i++) {
267
+ const c = text[i];
268
+ if (quoted) {
269
+ if (c === '"' && text[i + 1] === '"') cell += text[++i];else if (c === '"') quoted = false;else cell += c;
270
+ } else if (c === '"' && cell === '') quoted = true;else if (c === '\t') {
271
+ row.push(cell);
272
+ cell = '';
273
+ } else if (c === '\n' || c === '\r') {
274
+ if (c === '\r' && text[i + 1] === '\n') i++;
275
+ row.push(cell);
276
+ rows.push(row);
277
+ row = [];
278
+ cell = '';
279
+ } else cell += c;
280
+ }
281
+ if (cell !== '' || row.length > 0) rows.push([...row, cell]);
282
+ return rows;
283
+ }
284
+
285
+ // The undo and redo stack (plan section 7). An op holds the values before and after, so its
286
+ // inverse is the same op applied the other way.
287
+
288
+ class UndoStack {
289
+ done = [];
290
+ undone = [];
291
+ get canUndo() {
292
+ return this.done.length > 0;
293
+ }
294
+ get canRedo() {
295
+ return this.undone.length > 0;
296
+ }
297
+
298
+ /** A new op. It clears the redo list. */
299
+ push(op) {
300
+ this.done.push(op);
301
+ this.undone = [];
302
+ }
303
+
304
+ /** Removes an op that did not apply (a failed save). */
305
+ remove(op) {
306
+ this.done = this.done.filter(o => o !== op);
307
+ this.undone = this.undone.filter(o => o !== op);
308
+ }
309
+
310
+ /** The op to undo: apply its inverse. */
311
+ undo() {
312
+ const op = this.done.pop();
313
+ if (op !== undefined) this.undone.push(op);
314
+ return op;
315
+ }
316
+
317
+ /** The op to do again. */
318
+ redo() {
319
+ const op = this.undone.pop();
320
+ if (op !== undefined) this.done.push(op);
321
+ return op;
322
+ }
323
+ }
324
+
325
+ // The editing plug-in of `LatticeGrid` (`@editing`, plan section 7). It owns the values: the edit
326
+ // machine, validation through the column schema, the optimistic save, batch staging and undo.
327
+ // The grid owns the keys, the focus, the overlay and the range geometry.
328
+ const keyOf = (rowId, columnId) => `${rowId}\u0000${columnId}`;
329
+ const metaOf = column => column.columnDef.meta?.lattice;
330
+ const headerOf = column => {
331
+ const header = column.columnDef.header;
332
+ return is.string(header) ? header : column.id;
333
+ };
334
+ const messageOf = error => error instanceof Error ? error.message : String(error);
335
+
336
+ /** Give it to `LatticeGrid` as `@editing`: it fits the grid `GridEditing` interface. */
337
+ class EditController {
338
+ Editor = CellEditor;
339
+ RowEditor = RowEditor;
340
+ static {
341
+ g(this.prototype, "active", [tracked], function () {
342
+ return null;
343
+ });
344
+ }
345
+ #active = (i(this, "active"), void 0);
346
+ static {
347
+ g(this.prototype, "draft", [tracked], function () {
348
+ return undefined;
349
+ });
350
+ }
351
+ #draft = (i(this, "draft"), void 0);
352
+ static {
353
+ g(this.prototype, "state", [tracked], function () {
354
+ return EditState.Viewing.value;
355
+ });
356
+ }
357
+ #state = (i(this, "state"), void 0);
358
+ static {
359
+ g(this.prototype, "errors", [tracked], function () {
360
+ return [];
361
+ });
362
+ }
363
+ #errors = (i(this, "errors"), void 0);
364
+ static {
365
+ g(this.prototype, "lastError", [tracked], function () {
366
+ return null;
367
+ });
368
+ }
369
+ #lastError = (i(this, "lastError"), void 0);
370
+ /** The message of the last failed save, or null. */
371
+ static {
372
+ g(this.prototype, "message", [tracked], function () {
373
+ return '';
374
+ });
375
+ }
376
+ #message = (i(this, "message"), void 0);
377
+ /** The last result for the grid live region: a save, a failed save, a paste. */
378
+ static {
379
+ g(this.prototype, "activeRow", [tracked], function () {
380
+ return null;
381
+ });
382
+ }
383
+ #activeRow = (i(this, "activeRow"), void 0);
384
+ /** The row in a full-row edit, or null. */
385
+ static {
386
+ g(this.prototype, "rowDraft", [tracked], function () {
387
+ return {};
388
+ });
389
+ }
390
+ #rowDraft = (i(this, "rowDraft"), void 0);
391
+ /** The values of a full-row edit, by column ID. Each change replaces the object. */
392
+ rowColumns = [];
393
+ /** The values that are staged or in a save, by cell. Each change replaces the map. */
394
+ static {
395
+ g(this.prototype, "pending", [tracked], function () {
396
+ return new Map();
397
+ });
398
+ }
399
+ #pending = (i(this, "pending"), void 0);
400
+ machine = new EditMachine();
401
+ stack = new UndoStack();
402
+ options;
403
+ constructor(options) {
404
+ this.options = options;
405
+ }
406
+
407
+ /** The locale of the messages and of the type parse. */
408
+ get locale() {
409
+ return latticeLocale(this.options.owner, this.options.localeText, this.options.locale);
410
+ }
411
+ get batch() {
412
+ return this.options.batch ?? false;
413
+ }
414
+ get mode() {
415
+ return this.options.rowEdit ? 'row' : 'cell';
416
+ }
417
+
418
+ /** The number of staged values (batch edit). */
419
+ get dirtyCount() {
420
+ return [...this.pending.values()].filter(p => p.staged).length;
421
+ }
422
+
423
+ /** A column with an editor, or with an `<:editor>` block (the template form). */
424
+ canEdit = ({
425
+ column
426
+ }) => editorOf(column) !== undefined || metaOf(column)?.editorBlock === true;
427
+ pendingValue = (rowId, columnId) => this.pending.get(keyOf(rowId, columnId));
428
+ isDirty = (rowId, columnId) => this.pending.get(keyOf(rowId, columnId))?.staged ?? false;
429
+
430
+ /** The value that the cell shows: a staged or saving value, else the row value. */
431
+ valueOf(cell) {
432
+ const pending = this.pending.get(keyOf(cell.row.id, cell.column.id));
433
+ return pending ? pending.value : cell.row.getValue(cell.column.id);
434
+ }
435
+
436
+ /** A text (from a key, a paste) as a value of the column: its `parse`, else the text. */
437
+ parse(cell, text) {
438
+ const parse = parserOf(cell.column, this.locale.locale);
439
+ return parse ? parse(text) : text;
440
+ }
441
+ begin(cell, text) {
442
+ if (!this.canEdit(cell)) return;
443
+ this.newMachine().begin();
444
+ this.errors = [];
445
+ this.draft = text === undefined ? this.valueOf(cell) : this.parse(cell, text);
446
+ this.active = cell;
447
+ }
448
+
449
+ /** A new machine for each edit: a save in flight does not block the next edit. */
450
+ newMachine() {
451
+ const machine = new EditMachine();
452
+ machine.subscribe(m => {
453
+ if (this.machine === m && m.state.value !== this.state) this.state = m.state.value;
454
+ });
455
+ this.machine = machine;
456
+ return machine;
457
+ }
458
+ setDraft = value => {
459
+ this.draft = value;
460
+ };
461
+ cancel() {
462
+ if (this.machine.can.cancel) this.machine.cancel();
463
+ this.active = null;
464
+ this.activeRow = null;
465
+ this.errors = [];
466
+ }
467
+
468
+ /** Opens a full-row edit over the columns that it can edit. */
469
+ beginRow(row, columns) {
470
+ this.rowColumns = columns.filter(column => this.canEdit({
471
+ row,
472
+ column
473
+ }));
474
+ if (this.rowColumns.length === 0) return;
475
+ this.newMachine().begin();
476
+ this.errors = [];
477
+ this.rowDraft = Object.fromEntries(this.rowColumns.map(column => [column.id, this.valueOf({
478
+ row,
479
+ column
480
+ })]));
481
+ this.activeRow = row;
482
+ }
483
+ setRowValue = (columnId, value) => {
484
+ this.rowDraft = {
485
+ ...this.rowDraft,
486
+ [columnId]: value
487
+ };
488
+ };
489
+
490
+ /** Validates every field, then saves the changed values as one undo step. */
491
+ async commitRow() {
492
+ const row = this.activeRow;
493
+ if (!row) return true;
494
+ const machine = this.machine;
495
+ const draft = this.rowDraft;
496
+ const cells = this.rowColumns.map(column => ({
497
+ row,
498
+ column
499
+ }));
500
+ machine.validate();
501
+ const results = await Promise.all(cells.map(c => this.validate(c, draft[c.column.id])));
502
+ // A cancel or a new edit while the validation ran: this edit is over.
503
+ if (machine !== this.machine || this.activeRow !== row) return false;
504
+ const errors = results.flatMap((list, i) => list.map(error => `${headerOf(cells[i].column)}: ${error}`));
505
+ if (errors.length > 0) {
506
+ this.errors = errors;
507
+ machine.invalid();
508
+ return false;
509
+ }
510
+ machine.save();
511
+ this.activeRow = null;
512
+ const changes = cells.map(cell => ({
513
+ cell,
514
+ before: this.valueOf(cell),
515
+ after: draft[cell.column.id]
516
+ })).filter(change => !Object.is(change.before, change.after));
517
+ if (changes.length === 0) {
518
+ machine.resolve();
519
+ return true;
520
+ }
521
+ this.stack.push(changes);
522
+ void this.apply(changes, 'after').then(saved => {
523
+ if (saved) machine.resolve();else machine.reject();
524
+ if (this.batch) return;
525
+ const l = this.locale;
526
+ this.message = saved ? l.t('editing.savedRow') : l.t('editing.saveRowFailed', {
527
+ error: this.lastError ?? ''
528
+ });
529
+ });
530
+ return true;
531
+ }
532
+ async commit() {
533
+ const cell = this.active;
534
+ if (!cell) return true;
535
+ const machine = this.machine;
536
+ const value = this.draft;
537
+ machine.validate();
538
+ const errors = await this.validate(cell, value);
539
+ // A cancel or a new edit while the validation ran: this edit is over.
540
+ if (machine !== this.machine || this.active !== cell) return false;
541
+ if (errors.length > 0) {
542
+ this.errors = errors;
543
+ machine.invalid();
544
+ return false;
545
+ }
546
+ machine.save();
547
+ this.active = null;
548
+ const change = {
549
+ cell,
550
+ before: this.valueOf(cell),
551
+ after: value
552
+ };
553
+ if (Object.is(change.before, change.after)) {
554
+ machine.resolve();
555
+ return true;
556
+ }
557
+ const op = [change];
558
+ this.stack.push(op);
559
+ const name = headerOf(cell.column);
560
+ void this.apply(op, 'after').then(saved => {
561
+ if (saved) machine.resolve();else machine.reject();
562
+ if (this.batch) return;
563
+ const l = this.locale;
564
+ this.message = saved ? l.t('editing.savedCell', {
565
+ column: name
566
+ }) : l.t('editing.saveCellFailed', {
567
+ column: name,
568
+ error: this.lastError ?? ''
569
+ });
570
+ });
571
+ return true;
572
+ }
573
+ async validate(cell, value) {
574
+ const schema = metaOf(cell.column)?.schema;
575
+ if (!schema) return [];
576
+ const errors = await runValidator(schema, value);
577
+ return Object.values(errors).flatMap(list => list ?? []);
578
+ }
579
+ async undo() {
580
+ const op = this.stack.undo();
581
+ if (op) await this.apply(op, 'before');
582
+ }
583
+ async redo() {
584
+ const op = this.stack.redo();
585
+ if (op) await this.apply(op, 'after');
586
+ }
587
+ async paste(text, cellAt) {
588
+ const changes = [];
589
+ parseTsv(text).forEach((cells, r) => cells.forEach((cellText, c) => {
590
+ const cell = cellAt(r, c);
591
+ if (cell && this.canEdit(cell)) {
592
+ changes.push({
593
+ cell,
594
+ before: this.valueOf(cell),
595
+ after: this.parse(cell, cellText)
596
+ });
597
+ }
598
+ }));
599
+ const written = await this.write(changes);
600
+ const refused = changes.length - written;
601
+ const l = this.locale;
602
+ // Two whole sentences, each with its own plural; a space joins them.
603
+ const pasted = l.plural('editing.pastedCells', written);
604
+ this.message = refused > 0 ? `${pasted} ${l.plural('editing.refusedValues', refused)}` : pasted;
605
+ }
606
+ async fill(lines) {
607
+ const changes = [];
608
+ for (const {
609
+ source,
610
+ target
611
+ } of lines) {
612
+ const values = fillSeries(source.map(cell => this.valueOf(cell)), target.length);
613
+ target.forEach((cell, i) => {
614
+ if (this.canEdit(cell)) changes.push({
615
+ cell,
616
+ before: this.valueOf(cell),
617
+ after: values[i]
618
+ });
619
+ });
620
+ }
621
+ await this.write(changes);
622
+ }
623
+ async clear(cells) {
624
+ await this.write(cells.filter(cell => this.canEdit(cell)).map(cell => ({
625
+ cell,
626
+ before: this.valueOf(cell),
627
+ after: null
628
+ })));
629
+ }
630
+
631
+ /** Saves all staged values (batch edit). A failed save keeps its values staged. */
632
+ async commitAll() {
633
+ const staged = [...this.pending.values()].filter(p => p.staged);
634
+ this.mark(staged, false);
635
+ await Promise.all(staged.map(p => this.save(p)));
636
+ }
637
+
638
+ /** Drops all staged values (batch edit). */
639
+ discard() {
640
+ this.drop([...this.pending.values()].filter(p => p.staged));
641
+ }
642
+
643
+ /** Many changes as one undo step. It gives the number of values that the schema let through. */
644
+ async write(all) {
645
+ // The same path as a cell edit: a value that the column schema refuses is not written.
646
+ const errors = await Promise.all(all.map(c => this.validate(c.cell, c.after)));
647
+ const changes = all.filter((_, i) => errors[i]?.length === 0);
648
+ if (changes.length === 0) return 0;
649
+ this.stack.push(changes);
650
+ await this.apply(changes, 'after');
651
+ return changes.length;
652
+ }
653
+
654
+ /** Writes one side of the changes: staged in a batch, else an optimistic save. */
655
+ async apply(changes, side) {
656
+ const entries = changes.map(c => ({
657
+ cell: c.cell,
658
+ value: c[side],
659
+ staged: this.batch
660
+ }));
661
+ this.mark(entries, this.batch);
662
+ if (this.batch) return true;
663
+ const results = await Promise.all(entries.map(p => this.save(p)));
664
+ const saved = results.every(Boolean);
665
+ // A failed save has no undo step: an undo would write the old value again.
666
+ if (!saved && side === 'after') this.stack.remove(changes);
667
+ return saved;
668
+ }
669
+ async save(entry) {
670
+ const {
671
+ cell,
672
+ value
673
+ } = entry;
674
+ try {
675
+ await this.send(cell, value);
676
+ this.drop([entry]);
677
+ return true;
678
+ } catch (error) {
679
+ this.lastError = messageOf(error);
680
+ // A batch value stays staged, so the user can try again. Else the value rolls back.
681
+ if (this.batch) this.mark([entry], true);else this.drop([entry]);
682
+ return false;
683
+ }
684
+ }
685
+ async send(cell, value) {
686
+ const {
687
+ onCellEdit,
688
+ mutate
689
+ } = this.options;
690
+ if (mutate) {
691
+ const result = await mutate([{
692
+ type: 'update',
693
+ id: cell.row.id,
694
+ changes: {
695
+ [cell.column.id]: value
696
+ }
697
+ }]);
698
+ const error = result.results.find(r => r.status === 'error');
699
+ if (error) throw new Error(error.message ?? this.locale.t('editing.saveFailed'));
700
+ } else {
701
+ await onCellEdit?.(cell.row, cell.column.id, value);
702
+ }
703
+ }
704
+ mark(entries, staged) {
705
+ const next = new Map(this.pending);
706
+ for (const entry of entries) {
707
+ entry.staged = staged;
708
+ next.set(keyOf(entry.cell.row.id, entry.cell.column.id), entry);
709
+ }
710
+ this.pending = next;
711
+ }
712
+
713
+ /** Removes the entries. A newer value for the same cell stays. */
714
+ drop(entries) {
715
+ const next = new Map(this.pending);
716
+ for (const entry of entries) {
717
+ const key = keyOf(entry.cell.row.id, entry.cell.column.id);
718
+ if (next.get(key) === entry) next.delete(key);
719
+ }
720
+ this.pending = next;
721
+ }
722
+ }
723
+
724
+ // The status bar data of the cell ranges (plan section 7). It reads the engine cell selection,
725
+ // so a template or a getter that calls it renders again when the ranges change.
726
+ /** The count of the selected cells, and the sum and average of their numbers. */
727
+ function rangeSummary(table) {
728
+ const values = table.getSelectedCellRangesData().flat(2);
729
+ const numbers = values.filter(value => is.number(value) && !Number.isNaN(value));
730
+ const sum = numbers.reduce((total, n) => total + n, 0);
731
+ return {
732
+ count: values.length,
733
+ numericCount: numbers.length,
734
+ sum,
735
+ average: numbers.length > 0 ? sum / numbers.length : null
736
+ };
737
+ }
738
+
739
+ // Rich select: a cell editor that picks a value from a long list (APG combobox with a listbox
740
+ // popup). The text filters the list, and the first match is the value (typeahead). The arrow keys,
741
+ // Home, End, PageUp and PageDown move the value. The grid owns Enter, Tab and Escape: Enter commits
742
+ // the value. `@search` loads the list from a server. `@item` renders each option.
743
+ const ITEM_HEIGHT = 28;
744
+ const VISIBLE = 8;
745
+ const OVERSCAN = 4;
746
+ // The styles hold numbers only, so they are safe.
747
+ const LIST_STYLE = htmlSafe(`block-size: ${ITEM_HEIGHT * VISIBLE}px; overflow-y: auto; position: relative`);
748
+ class RichSelect extends Component {
749
+ // A Formwright control has a fixed signature, so it reads only the owner text.
750
+ get l() {
751
+ return latticeLocale(getOwner(this));
752
+ }
753
+ listId = `${guidFor(this)}-list`;
754
+ static {
755
+ g(this.prototype, "text", [tracked], function () {
756
+ return '';
757
+ });
758
+ }
759
+ #text = (i(this, "text"), void 0);
760
+ static {
761
+ g(this.prototype, "loaded", [tracked], function () {
762
+ return [];
763
+ });
764
+ }
765
+ #loaded = (i(this, "loaded"), void 0);
766
+ static {
767
+ g(this.prototype, "loading", [tracked], function () {
768
+ return false;
769
+ });
770
+ }
771
+ #loading = (i(this, "loading"), void 0);
772
+ static {
773
+ g(this.prototype, "scrollTop", [tracked], function () {
774
+ return 0;
775
+ });
776
+ }
777
+ #scrollTop = (i(this, "scrollTop"), void 0);
778
+ static {
779
+ g(this.prototype, "activeIndex", [tracked]);
780
+ }
781
+ #activeIndex = (i(this, "activeIndex"), void 0);
782
+ request = 0;
783
+ constructor(owner, args) {
784
+ super(owner, args);
785
+ if (args.search) this.load('');
786
+ }
787
+ label = option => this.args.optionLabel ? this.args.optionLabel(option) : String(option ?? '');
788
+ get list() {
789
+ if (this.args.search) return this.loaded;
790
+ const all = this.args.options ?? [];
791
+ const q = this.text.trim().toLowerCase();
792
+ return q ? all.filter(o => this.label(o).toLowerCase().includes(q)) : all;
793
+ }
794
+ /** The active option: the one the keys moved to, else the current value. */
795
+ get active() {
796
+ return this.activeIndex ?? this.list.indexOf(this.args.value);
797
+ }
798
+ get activeId() {
799
+ return this.active >= 0 ? `${this.listId}-${this.active}` : undefined;
800
+ }
801
+ get spacerStyle() {
802
+ return htmlSafe(`block-size: ${this.list.length * ITEM_HEIGHT}px`);
803
+ }
804
+ listStyle = LIST_STYLE;
805
+ // shortcut: fixed-height windowing, not `@ember-lattice/virtual`; upgrade for items of mixed height.
806
+ get rows() {
807
+ const list = this.list;
808
+ const start = Math.max(0, Math.floor(this.scrollTop / ITEM_HEIGHT) - OVERSCAN);
809
+ const end = Math.min(list.length, start + VISIBLE + 2 * OVERSCAN);
810
+ const active = this.active;
811
+ const rows = [];
812
+ for (let i = start; i < end; i++) {
813
+ rows.push({
814
+ option: list[i],
815
+ label: this.label(list[i]),
816
+ id: `${this.listId}-${i}`,
817
+ active: i === active,
818
+ selected: String(i === active),
819
+ posinset: i + 1,
820
+ style: htmlSafe(`position: absolute; inset-inline: 0; top: ${i * ITEM_HEIGHT}px; block-size: ${ITEM_HEIGHT}px`)
821
+ });
822
+ }
823
+ return rows;
824
+ }
825
+ load(text) {
826
+ const search = this.args.search;
827
+ if (!search) return;
828
+ const request = ++this.request;
829
+ this.loading = true;
830
+ void waitForPromise(search(text).then(list => this.loadedFor(request, text, list), () => this.loadedFor(request, text, [])));
831
+ }
832
+ loadedFor(request, text, list) {
833
+ if (request !== this.request) return; // A newer text has a newer list.
834
+ this.loaded = list;
835
+ this.loading = false;
836
+ if (text !== '') this.moveTo(0);
837
+ }
838
+ /** Makes option `i` active and the value, and scrolls it into the window. */
839
+ moveTo(i) {
840
+ const list = this.list;
841
+ if (list.length === 0) return;
842
+ const index = Math.min(Math.max(i, 0), list.length - 1);
843
+ this.activeIndex = index;
844
+ this.args.onChange(list[index]);
845
+ const element = document.getElementById(this.listId);
846
+ const top = index * ITEM_HEIGHT;
847
+ const view = ITEM_HEIGHT * VISIBLE;
848
+ let scrollTop = element?.scrollTop ?? this.scrollTop;
849
+ if (top < scrollTop) scrollTop = top;else if (top + ITEM_HEIGHT > scrollTop + view) scrollTop = top + ITEM_HEIGHT - view;
850
+ if (element) element.scrollTop = scrollTop;
851
+ this.scrollTop = scrollTop;
852
+ }
853
+ onInput = event => {
854
+ this.text = event.target.value;
855
+ if (this.args.search) {
856
+ this.load(this.text);
857
+ } else {
858
+ this.activeIndex = undefined;
859
+ this.moveTo(0);
860
+ }
861
+ };
862
+ onKeyDown = event => {
863
+ const steps = {
864
+ ArrowDown: this.active + 1,
865
+ ArrowUp: this.active - 1,
866
+ PageDown: this.active + VISIBLE,
867
+ PageUp: this.active - VISIBLE,
868
+ Home: 0,
869
+ End: this.list.length - 1
870
+ };
871
+ const next = steps[event.key];
872
+ if (!is.number(next)) return;
873
+ event.preventDefault();
874
+ this.moveTo(next);
875
+ };
876
+ onScroll = event => this.scrollTop = event.target.scrollTop;
877
+ pick = index => this.moveTo(index - 1);
878
+ static {
879
+ setComponentTemplate(precompileTemplate("<div class=\"lt-rich-select\">\n <input class=\"lt-rich-select-input\" id={{@id}} name={{@name}} type=\"text\" role=\"combobox\" autocomplete=\"off\" aria-autocomplete=\"list\" aria-expanded=\"true\" aria-controls={{this.listId}} aria-activedescendant={{this.activeId}} aria-invalid={{if @invalid \"true\"}} placeholder={{this.label @value}} value={{this.text}} {{on \"input\" this.onInput}} {{on \"keydown\" this.onKeyDown}} ...attributes />\n <div class=\"lt-rich-select-list\" id={{this.listId}} role=\"listbox\" aria-label={{this.l.t \"editing.richSelect.options\"}} aria-busy={{if this.loading \"true\"}} tabindex=\"-1\" style={{this.listStyle}} {{on \"scroll\" this.onScroll}}>\n <div style={{this.spacerStyle}}>\n {{#each this.rows key=\"id\" as |row|}}\n <div class=\"lt-rich-select-option\" id={{row.id}} role=\"option\" aria-selected={{row.selected}} aria-setsize={{this.list.length}} aria-posinset={{row.posinset}} data-active={{if row.active \"true\"}} style={{row.style}} {{on \"click\" (partial this.pick row.posinset)}}>\n {{#if @item}}\n <@item @option={{row.option}} @active={{row.active}} />\n {{else}}\n {{row.label}}\n {{/if}}\n </div>\n {{/each}}\n </div>\n </div>\n</div>", {
880
+ strictMode: true,
881
+ scope: () => ({
882
+ on,
883
+ partial: fn
884
+ })
885
+ }), this);
886
+ }
887
+ }
888
+
889
+ export { CellEditor, EditController, EditMachine, EditState, RichSelect, RowEditor, UndoStack, fillSeries, parseTsv, rangeSummary };
890
+ //# sourceMappingURL=index.js.map