@gramlot/gramlot 0.3.30 → 0.3.31

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 (37) hide show
  1. package/dist/components/charts/__init__.py +1 -1
  2. package/dist/components/charts/assets/collection.js +1 -1
  3. package/dist/components/charts/assets/index.js +1 -1
  4. package/dist/components/grid/__init__.py +2 -2
  5. package/dist/components/grid/assets/collection.js +36 -20
  6. package/dist/components/grid/assets/files/0a1df3a083d0c010560aa342e87959c8c1070e6fd54545741f083f22d0c8b551-fflate.txt +21 -0
  7. package/dist/components/grid/assets/files/8cf9b31947daf7adb4a7a00a037459e58241af050cd0a603bfcf1756e533f75e-write-excel-file.txt +21 -0
  8. package/dist/components/grid/assets/index.js +1 -1
  9. package/dist/components/grid/assets/modules/browser-LVJHKBBV.js +19 -0
  10. package/dist/components/grid/assets/modules/chunk-RMRBEYTI.js +1 -0
  11. package/dist/components/grid/commands.json +42 -1
  12. package/dist/components/grid/grammar.json +384 -2
  13. package/dist/components/vizabi/__init__.py +1 -1
  14. package/dist/components/vizabi/assets/collection.js +1 -1
  15. package/dist/components/vizabi/assets/index.js +1 -1
  16. package/dist/gramlot.js +376 -21
  17. package/dist/gramlot.min.js +46 -46
  18. package/dist/standard-collections.js +1 -1
  19. package/package.json +3 -2
  20. package/src/binding/grid-struct.js +4 -1
  21. package/src/binding/runtime.js +2 -1
  22. package/src/builder/gramlot-builder.js +96 -7
  23. package/src/builder/source.js +18 -0
  24. package/src/components/grid-footer.js +120 -0
  25. package/src/components/grid-formulas.js +403 -0
  26. package/src/components/grid-grammar.json +87 -2
  27. package/src/components/grid-selection.js +118 -0
  28. package/src/components/grid-structure.js +27 -4
  29. package/src/components/grid-styles.js +14 -1
  30. package/src/components/grid-tools.js +229 -0
  31. package/src/components/grid.js +174 -8
  32. package/src/components/licenses/fflate.txt +21 -0
  33. package/src/components/licenses/write-excel-file.txt +21 -0
  34. package/src/editing-session.d.ts +2 -0
  35. package/src/editing-session.js +35 -3
  36. package/src/stores/bag-collection-store.js +14 -5
  37. package/src/stores/bag-collection-view.js +1 -1
@@ -9,6 +9,10 @@ import {GridCellEditor} from './grid-cell-editor.js';
9
9
  import {GridCheckSets} from './grid-check-sets.js';
10
10
  import {GridRows} from './grid-rows.js';
11
11
  import {GridStructure} from './grid-structure.js';
12
+ import {GridFormulas} from './grid-formulas.js';
13
+ import {GridFooter} from './grid-footer.js';
14
+ import {GridTools, registerGridCommands} from './grid-tools.js';
15
+ import {GridSelection, SELECTION_MODES} from './grid-selection.js';
12
16
  import {GridHeaderInteraction} from './grid-header-interaction.js';
13
17
  import {GridRowLayout} from './grid-row-layout.js';
14
18
  import {GridRowInteraction} from './grid-row-interaction.js';
@@ -26,6 +30,15 @@ export const Grid = defineComponent({
26
30
  sortRequest: {dtype:'T', default:'', binding:'write'},
27
31
  storepath: {dtype: 'T'}, structpath: {dtype: 'T'}, rowMode: {dtype: 'T'},
28
32
  rowHeaders: {dtype:'B', default:false, binding:'read'},
33
+ footer: {dtype:['B','T'], default:false, binding:'read'},
34
+ selectionMode: {dtype:'T', default:'multi', binding:'read'},
35
+ selectedId: {dtype:'T', nullable:true, default:null, binding:'write'},
36
+ selectedIndex: {dtype:'L', nullable:true, default:null, binding:'write'},
37
+ selectedLabel: {dtype:'T', nullable:true, default:null, binding:'write'},
38
+ selectedPkeys: {dtype:'X', nullable:true, default:null, binding:'write'},
39
+ selectedRowidx: {dtype:'T', nullable:true, default:null, binding:'write'},
40
+ selectedNodes: {dtype:'X', nullable:true, default:null, binding:'write'},
41
+ selectedRowData: {dtype:'X', nullable:true, default:null, binding:'write'},
29
42
  rowResize: {dtype:'B', default:false, binding:'read'},
30
43
  selfDragRows: {dtype:'B', default:false, binding:'read'},
31
44
  sortedBy: {dtype:'T', default:'', binding:'read'},
@@ -35,6 +48,39 @@ export const Grid = defineComponent({
35
48
  #checkSets;
36
49
  #columnFilters;
37
50
  #cellEditor;
51
+ #formulas;
52
+ #footer;
53
+ #tools;
54
+ #derivedSession = null;
55
+ #releaseDerived = null;
56
+ #selection;
57
+ /** Click selects (single); Ctrl/Cmd+click toggles and Shift+click extends (multi). Double-click still edits. */
58
+ #selectRow = event => {
59
+ const tr = event.target.closest('tr[data-row]');
60
+ const node = tr && [...this.#rows].find(([, row]) => row === tr)?.[0];
61
+ if (!node || this.#selection.mode === 'none') return;
62
+ try {
63
+ this.#selection.select(node, {toggle:event.ctrlKey || event.metaKey, range:event.shiftKey});
64
+ this.#renderSelection();
65
+ } catch (error) { this.#context.reportError(error, 'Grid selection'); }
66
+ };
67
+ /** Without an open editor: Up/Down move the current row, Shift extends (multi), Ctrl/Cmd+A selects all visible rows. */
68
+ #selectionKey = event => {
69
+ if (this.#selection.mode === 'none' || event.altKey) return;
70
+ const all = (event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'a';
71
+ const step = {ArrowUp:-1, ArrowDown:1}[event.key];
72
+ if (!all && (step === undefined || event.ctrlKey || event.metaKey)) return;
73
+ event.preventDefault();
74
+ try {
75
+ if (all) this.#selection.selectAll();
76
+ else {
77
+ const field = event.target.closest?.('td[data-field]')?.dataset.field;
78
+ const node = this.#selection.move(step, event.shiftKey);
79
+ if (node) this.#revealRow(node, field);
80
+ }
81
+ this.#renderSelection();
82
+ } catch (error) { this.#context.reportError(error, 'Grid selection'); }
83
+ };
38
84
  #editCell = event => {
39
85
  if (event.type === 'keydown' && !['Enter','F2'].includes(event.key)) return;
40
86
  const cell = event.target.closest('td[data-field]');
@@ -98,6 +144,7 @@ export const Grid = defineComponent({
98
144
  }
99
145
  this.#adjustedScroll = null;
100
146
  this.#headerViewport.scrollLeft = this.#bodyViewport.scrollLeft;
147
+ if (this.#footer) this.#footer.viewport.scrollLeft = this.#bodyViewport.scrollLeft;
101
148
  this.#scheduleLayout();
102
149
  };
103
150
  constructor() {
@@ -161,8 +208,11 @@ export const Grid = defineComponent({
161
208
  connectedCallback() {
162
209
  this.#body.addEventListener('dblclick', this.#editCell);
163
210
  this.#body.addEventListener('keydown', this.#editCell);
211
+ this.#body.addEventListener('click', this.#selectRow);
212
+ this.#bodyViewport.addEventListener('keydown', this.#selectionKey);
164
213
  this.#cellEditor?.connect();
165
214
  this.#checkSets?.connect();
215
+ this.#tools?.connect();
166
216
  this.#columnFilters.connect();
167
217
  this.#observeStore();
168
218
  if (this.#collectionView) this.#invalidate({full:true, rows:[]});
@@ -177,9 +227,14 @@ export const Grid = defineComponent({
177
227
  disconnectedCallback() {
178
228
  this.#body.removeEventListener('dblclick', this.#editCell);
179
229
  this.#body.removeEventListener('keydown', this.#editCell);
230
+ this.#body.removeEventListener('click', this.#selectRow);
231
+ this.#bodyViewport.removeEventListener('keydown', this.#selectionKey);
180
232
  this.#cellEditor?.disconnect();
181
233
  this.#checkSets?.disconnect();
234
+ this.#tools.disconnect();
235
+ this.#releaseDerived?.(); this.#releaseDerived = null; this.#derivedSession = null;
182
236
  this.#columnFilters.disconnect();
237
+ this.#formulas.disconnect();
183
238
  this.#cancelRefresh();
184
239
  gridSearch(this.#context.sourceNode).detach(this.#collectionView);
185
240
  this.#collectionView?.disconnect();
@@ -210,6 +265,7 @@ export const Grid = defineComponent({
210
265
  if (handle) handle.setAttribute('aria-valuenow', String(Math.round(row.getBoundingClientRect().height)));
211
266
  }
212
267
  this.#headerViewport.scrollLeft = this.#bodyViewport.scrollLeft;
268
+ this.#footer.viewport.scrollLeft = this.#bodyViewport.scrollLeft;
213
269
  if (!this.#structure) return;
214
270
  try { this.#layoutWindow(); this.#cellEditor.position(); }
215
271
  catch (error) { this.#context.reportError(error, 'Grid viewport'); }
@@ -289,7 +345,7 @@ export const Grid = defineComponent({
289
345
  if (loading) this.control.setAttribute('aria-busy', 'true');
290
346
  else this.control.removeAttribute('aria-busy');
291
347
  if (force || start !== this.#windowStart || end !== this.#windowEnd) {
292
- const rows = new GridRows(this.#collectionView, this.#context.format)
348
+ const rows = new GridRows(this.#formulas, this.#context.format)
293
349
  .read(this.#structure.columns, this.#visibleNodes.slice(start-(info?.start ?? 0), end-(info?.start ?? 0)));
294
350
  this.#renderRows(rows, this.#structure.columns, start);
295
351
  this.#windowStart = start; this.#windowEnd = end;
@@ -342,8 +398,21 @@ export const Grid = defineComponent({
342
398
  this.#openEditorAt(index,column);
343
399
  return true;
344
400
  }
401
+ /** The last error of each formula field, by field name. */
402
+ get formulaErrors() { return this.#formulas.errors; }
403
+ /** The last error of each totalized column, by field name. */
404
+ get totalErrors() { return this.#footer.errors; }
345
405
  setSourceContext(context) {
346
406
  this.#context = context;
407
+ this.#formulas = new GridFormulas(context.sourceNode);
408
+ this.#footer = new GridFooter(context.sourceNode, context.format, this.#bodyViewport.parentElement);
409
+ this.#selection = new GridSelection(context, {view:() => this.#collectionView, store:() => this.#collectionStore(),
410
+ mode:() => this.#selectionMode(), rowData:node => this.#rowData(node)});
411
+ this.#tools = new GridTools(context, {columns:() => this.#structure.columns, rows:() => this.#collectionView.getRows(),
412
+ selected:() => this.#selection.nodes, selectionMode:() => this.#selectionMode(),
413
+ reader:() => this.#formulas, store:() => ({bag:this.#store, mode:this.parameters.rowMode}),
414
+ parameters:() => this.parameters, document:this.ownerDocument});
415
+ if (this.isConnected) this.#tools.connect();
347
416
  this.#columnFilters.setSourceContext(context);
348
417
  this.#checkSets = new GridCheckSets(context.sourceNode, this.#body,
349
418
  () => this.#structure?.columns ?? [],
@@ -413,7 +482,8 @@ export const Grid = defineComponent({
413
482
  this.#pendingRows.clear();
414
483
  try {
415
484
  if (full) this.#project();
416
- else this.#projectRows(nodes);
485
+ // View values (#, += and their dependents) of other rows can change too.
486
+ else this.#projectRows(this.#formulas.viewFields.size ? [...this.#rows.keys()] : nodes);
417
487
  } catch (error) {
418
488
  // Keep the last valid DOM. A later change retries a complete pull;
419
489
  // there is no automatic retry loop and no exception in Data delivery.
@@ -424,13 +494,20 @@ export const Grid = defineComponent({
424
494
  }
425
495
  #projectRows(nodes) {
426
496
  for (const node of nodes) this.#rowLayout.forget(node);
427
- const rows = new GridRows(this.#collectionView, this.#context.format).read(this.#structure.columns, nodes.filter(node => this.#rows.has(node)));
497
+ this.#footer.update(this.#formulas, this.#collectionStore().getRows());
498
+ const rows = new GridRows(this.#formulas, this.#context.format).read(this.#structure.columns, nodes.filter(node => this.#rows.has(node)));
428
499
  this.#rowInteraction.cancel();
429
500
  for (const {node, cells} of rows) this.#renderCells(this.#rows.get(node), cells, node);
430
501
  this.#scheduleLayout();
431
502
  }
432
503
  #project() {
433
504
  const model = this.#structureDirty ? new GridStructure(this.#structBag) : this.#structure;
505
+ const store = this.#collectionStore();
506
+ this.#formulas.configure(model, this.#collectionView, store);
507
+ this.#requireStoredCriteria();
508
+ this.#tools.requireEditableTools(model.columns);
509
+ this.#selection.prune();
510
+ const structureChanged = this.#structureDirty;
434
511
  this.#cellEditor.configure(model.columns);
435
512
  this.#structure = model;
436
513
  this.#checkSets.configure();
@@ -449,24 +526,101 @@ export const Grid = defineComponent({
449
526
  }
450
527
  this.#windowRevision = info?.revision;
451
528
  this.#structureDirty = false;
452
- gridSearch(this.#context.sourceNode).update(this.#collectionView, model.columns.filter(column => !column.check));
529
+ // View values (#, += and their dependents) derive from the order: they are not searchable.
530
+ gridSearch(this.#context.sourceNode).update(this.#collectionView,
531
+ model.columns.filter(column => !column.check && !this.#formulas.viewFields.has(column.field)));
453
532
  const rowHeaders = this.parameters.rowHeaders || this.parameters.rowResize;
454
- const signature = JSON.stringify([model.groups, rowHeaders, this.parameters.columnFilters]);
533
+ const signature = JSON.stringify([model.groups, rowHeaders, this.parameters.columnFilters, this.parameters.footer]);
455
534
  this.#rowHeaders = rowHeaders;
456
535
  if (signature !== this.#signature) {
536
+ this.#footer.configure(this.parameters.footer, model.columns, rowHeaders);
457
537
  this.#renderHeader(model);
458
538
  this.#signature = signature;
459
539
  }
540
+ this.#footer.update(this.#formulas, store.getRows());
541
+ this.#declareDerived(structureChanged);
460
542
  this.#columnFilters.update(this.#collectionView, model.columns, this.parameters.columnFilters, this.#context.format);
461
543
  this.#renderSort();
462
544
  this.#renderWindow(true);
545
+ this.#renderSelection();
463
546
  this.control.setAttribute('aria-colcount', String(model.columns.length + Number(this.#rowHeaders)));
464
547
  this.control.setAttribute('aria-rowcount', String(this.#headerRows + Math.max(this.#rowLayout.count, 1)));
465
548
  this.#scheduleLayout();
466
549
  }
550
+ /** Formula results, published totals and the published selection are derived values of the editing session, never changes. */
551
+ #declareDerived(structureChanged) {
552
+ const session = this.#context.sourceNode.formState;
553
+ if (session === this.#derivedSession) {
554
+ if (structureChanged) session?.updateChanges();
555
+ return;
556
+ }
557
+ this.#releaseDerived?.();
558
+ this.#derivedSession = session;
559
+ this.#releaseDerived = session === null ? null : session.registerDerived(path => this.#derivedPath(path));
560
+ }
561
+ #derivedPath(path) {
562
+ const base = this.#derivedSession.path;
563
+ const relative = absolute => absolute === base ? '' : absolute.startsWith(base + '.') ? absolute.slice(base.length + 1) : null;
564
+ if (this.#footer.totalPaths().some(total => relative(total) === path)) return true;
565
+ // A published selection Bag (selectedNodes, selectedRowData) is derived with its content.
566
+ if (this.#selection.paths().some(selection => {
567
+ const own = relative(selection);
568
+ return own !== null && (path === own || path.startsWith(own + '.') || path.startsWith(own + '?'));
569
+ })) return true;
570
+ const store = relative(this.#context.sourceNode.absDatapath(this.parameters.storepath));
571
+ if (store === null || store !== '' && !path.startsWith(store + '.')) return false;
572
+ const row = store === '' ? path : path.slice(store.length + 1);
573
+ const field = (this.parameters.rowMode === 'attributes' ? /^[^.?]+\?([^.?]+)$/ : /^[^.?]+\.([^.?]+)$/).exec(row)?.[1];
574
+ return field !== undefined && this.#formulas.dataFields.has(field);
575
+ }
576
+ #selectionMode() {
577
+ const mode = this.parameters.selectionMode;
578
+ if (!SELECTION_MODES.includes(mode)) throw new TypeError('grid selectionMode requires none, single or multi');
579
+ return mode;
580
+ }
581
+ /** The plain field values of a row, as published by selectedNodes and selectedRowData. */
582
+ #rowData(node) {
583
+ if (this.parameters.rowMode === 'attributes') return {...node.getAttr()};
584
+ return Object.fromEntries(node.staticValue.getNodes().filter(cell => !(cell.staticValue instanceof Bag)).map(cell => [cell.label, cell.staticValue]));
585
+ }
586
+ #renderSelection() {
587
+ const mode = this.#selectionMode();
588
+ if (mode === 'multi') this.control.setAttribute('aria-multiselectable', 'true');
589
+ else this.control.removeAttribute('aria-multiselectable');
590
+ for (const [node, tr] of this.#rows) {
591
+ const selected = this.#selection.isSelected(node);
592
+ if (mode === 'none') tr.removeAttribute('aria-selected');
593
+ else tr.setAttribute('aria-selected', String(selected));
594
+ tr.setAttribute('part', selected ? 'row selected-row' : 'row');
595
+ }
596
+ }
597
+ /** Scroll the view row `node` into the viewport; focus the cell of `field` when given. */
598
+ #revealRow(node, field) {
599
+ const index = this.#collectionView.getRows().indexOf(node);
600
+ this.#endPinned = false;
601
+ const top = this.#rowLayout.offset(index), bottom = this.#rowLayout.offset(index + 1);
602
+ if (top < this.#bodyViewport.scrollTop) this.#scrollTo(top);
603
+ else if (bottom > this.#bodyViewport.scrollTop + this.#bodyViewport.clientHeight) this.#scrollTo(Math.max(0, bottom - this.#bodyViewport.clientHeight));
604
+ this.#renderWindow(true);
605
+ if (field) this.#rows.get(node)?.querySelector(`td[data-field="${field}"]`)?.focus({preventScroll:true});
606
+ }
607
+ /** The shared resident store under this grid's view. */
608
+ #collectionStore() {
609
+ return this.#context.sourceNode.rootBuilder.binding.collectionStore(this.#store, this.parameters.rowMode);
610
+ }
611
+ /** Sort, column filter and search criteria apply to stored fields: a view value derives from the order. */
612
+ #requireStoredCriteria() {
613
+ const view = this.#collectionView, fields = this.#formulas.viewFields;
614
+ const used = [...view.criteria.map(({field}) => ['sort by', field]),
615
+ ...view.filterContributions.flatMap(([name, {definition}]) => name.startsWith('column:') ? [['filter', name.slice('column:'.length)]]
616
+ : name === 'sets' ? [] : definition.columns.map(field => ['search', field]))];
617
+ const [kind, field] = used.find(([, field]) => fields.has(field)) ?? [];
618
+ if (field !== undefined) throw new TypeError(`grid cannot ${kind} the view value '${field}'`);
619
+ }
467
620
  #sort(field, multiple) {
468
621
  if (this.#structure.columns.find(column => column.field === field)?.check) return;
469
622
  try {
623
+ if (this.#formulas.viewFields.has(field)) throw new TypeError(`grid cannot sort by the view value '${field}'`);
470
624
  const criteria = this.#windowInfo() ? parseSort(this.#windowInfo().sortedBy) : this.#collectionView.criteria;
471
625
  const current = criteria.find(item => item.field === field);
472
626
  const direction = current?.direction === 'a' ? 'd' : 'a';
@@ -526,7 +680,7 @@ export const Grid = defineComponent({
526
680
  indicator.setAttribute('aria-hidden', 'true');
527
681
  const arrow = doc.createElementNS(SVG_NS, 'path');
528
682
  arrow.setAttribute('d', 'M4 10L8 6L12 10'); indicator.append(arrow); cell.append(indicator);
529
- if (this.parameters.columnFilters && !column.check) cell.append(this.#columnFilters.button(column));
683
+ if (this.parameters.columnFilters && !column.check && !this.#formulas.viewFields.has(column.field)) cell.append(this.#columnFilters.button(column));
530
684
  const handle = doc.createElement('span');
531
685
  handle.className = 'column-resize'; handle.tabIndex = 0;
532
686
  handle.setAttribute('role', 'separator');
@@ -578,7 +732,8 @@ export const Grid = defineComponent({
578
732
  if (this.#rowHeaders) widths.unshift('max(var(--grid-row-header-min-width, 0px), var(--grid-row-header-width, var(--gramlot-grid-row-header-width, 44px)))');
579
733
  this.control.style.setProperty('--grid-columns-width', `calc(${widths.join(' + ')})`);
580
734
  // Identical colgroups and table constraints keep one CSS sizing policy for both areas.
581
- for (const table of [this.#headerTable, this.#bodyTable]) {
735
+ const footer = this.parameters.footer === false ? [] : [this.#footer.table];
736
+ for (const table of [this.#headerTable, this.#bodyTable, ...footer]) {
582
737
  for (const group of table.querySelectorAll(':scope > colgroup')) group.remove();
583
738
  table.prepend(...model.groups.map(group => {
584
739
  const element = doc.createElement('colgroup');
@@ -610,6 +765,11 @@ export const Grid = defineComponent({
610
765
  this.#rows.set(node, tr);
611
766
  }
612
767
  tr.classList.toggle('alternate', (start + keep.size) % 2 === 1);
768
+ tr.setAttribute('part', this.#selection.isSelected(node) ? 'row selected-row' : 'row');
769
+ if (this.#selection.mode === 'none') tr.removeAttribute('aria-selected');
770
+ else tr.setAttribute('aria-selected', String(this.#selection.isSelected(node)));
771
+ // Under a filter the numbering covers the visible rows only.
772
+ const partial = this.#collectionView.isFiltered();
613
773
  tr.draggable = this.parameters.selfDragRows;
614
774
  let heading = tr.querySelector('th[scope=row]');
615
775
  if (this.#rowHeaders) {
@@ -622,6 +782,7 @@ export const Grid = defineComponent({
622
782
  caption.className = 'row-number'; heading.append(caption); tr.prepend(heading);
623
783
  }
624
784
  heading.querySelector('.row-number').textContent = String(start + keep.size + 1);
785
+ heading.classList.toggle('filtered-numbering', partial);
625
786
  let handle = heading.querySelector('.row-height-handle');
626
787
  if (this.parameters.rowResize) {
627
788
  if (!handle) {
@@ -647,6 +808,7 @@ export const Grid = defineComponent({
647
808
  td.append(content);
648
809
  }
649
810
  if (column.edit) td.tabIndex = 0; else td.removeAttribute('tabindex');
811
+ td.classList.toggle('filtered-numbering', partial && this.#formulas.viewFields.has(column.field));
650
812
  const content = td.firstElementChild;
651
813
  const capped = column.max_height != null;
652
814
  if (capped) td.style.setProperty('--grid-cell-max-height',column.max_height);
@@ -717,7 +879,11 @@ class GridCollection extends ComponentCollection {
717
879
  metadata: [{kind: 'regex', pattern: '^(values|attributes)$', flags: 0}]};
718
880
  }
719
881
  Object.assign(document.elements, structuredClone(structureGrammar.elements));
882
+ // selected_<field> is a declared parameter family: composites route it to the grid (frameGrid).
883
+ document.elements.grid._meta.parameterPattern = '^selected_[A-Za-z_][A-Za-z0-9_]*$';
720
884
  return document;
721
885
  }
722
886
  }
723
- export default new GridCollection({name: 'grid', components: [Grid, SearchBox], dependencies:[inputs]});
887
+ export default new GridCollection({name: 'grid', components: [Grid, SearchBox], dependencies:[inputs], registerCommands:registerGridCommands,
888
+ // The lazily loaded Excel writer and its compression library ship their licenses with the collection.
889
+ assets:{writeExcelFileLicense:new URL('./licenses/write-excel-file.txt', import.meta.url), fflateLicense:new URL('./licenses/fflate.txt', import.meta.url)}});
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Arjun Barrett
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2018 gitlab.com/catamphetamine
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -19,6 +19,8 @@ export class EditingSession {
19
19
  readonly changeEntries: ReadonlyArray<{path: string; previous: unknown; current: unknown; existed: boolean; exists: boolean}>;
20
20
  focusField(path: string): boolean;
21
21
  registerNavigator(navigate: (path: string) => boolean): () => void;
22
+ /** Declare derived values (grid formula results, totals) that are never changes; returns the release. */
23
+ registerDerived(match: (path: string) => boolean): () => void;
22
24
  load(data: Bag): void;
23
25
  validate(): Promise<boolean>;
24
26
  accept(): boolean;
@@ -33,6 +33,8 @@ export class EditingSession {
33
33
  this.validationRevision = 0;
34
34
  this.validatedRevision = -1;
35
35
  this.fullValidation = null;
36
+ this.derived = new Set(); // predicates of derived paths, never changes
37
+
36
38
  if (!(this.data instanceof Bag)) throw new TypeError('A form requires a Bag at its datapath.');
37
39
  this.registers.setItem('baseline', copy(this.data));
38
40
  for (const name of ['changes', 'errors', 'pending', 'drafts']) this.registers.setItem(name, new Bag());
@@ -55,6 +57,32 @@ export class EditingSession {
55
57
  }
56
58
  }
57
59
  get data() { return this.runtime.gramlot.data.getItem(this.path); }
60
+ /**
61
+ * Declare derived values (grid formula results, published totals): `match(path)` receives a path
62
+ * relative to the session, `<path>?<attribute>` for an attribute. Derived values are never changes.
63
+ * Returns the release.
64
+ */
65
+ registerDerived(match) {
66
+ this.derived.add(match);
67
+ this.updateChanges();
68
+ // Releasing recomputes nothing: later Data events reconcile only their own subtree.
69
+ return () => { this.derived.delete(match); };
70
+ }
71
+ isDerived(path) {
72
+ for (const match of this.derived) if (match(path)) return true;
73
+ return false;
74
+ }
75
+ /** The attributes of the node at `path` that are not derived. */
76
+ ownAttributes(node, path) {
77
+ return Object.fromEntries(Object.entries(node.attr).filter(([name]) => !this.isDerived(`${path}?${name}`)));
78
+ }
79
+ /** A node, possibly absent, that holds only derived values. */
80
+ onlyDerived(node, path) {
81
+ if (!node) return true;
82
+ if (Object.keys(this.ownAttributes(node, path)).length) return false;
83
+ if (node.value instanceof Bag) return node.value.getNodes().every(child => this.onlyDerived(child, path ? `${path}.${child.label}` : child.label));
84
+ return this.isDerived(path);
85
+ }
58
86
  subscribe(listener) { this.listeners.add(listener); return () => this.listeners.delete(listener); }
59
87
  /** Read-only reports derived from the canonical registers, never a second journal. */
60
88
  get errorEntries() {
@@ -398,13 +426,17 @@ export class EditingSession {
398
426
  const relative = changedPath === this.path ? '' : changedPath?.startsWith(this.path + '.')
399
427
  ? changedPath.slice(this.path.length + 1).split('?')[0] : '';
400
428
  const visit = (a, b, path) => {
401
- if (a && b && a.value instanceof Bag && b.value instanceof Bag && same(a.attr,b.attr)) {
429
+ if (path && this.isDerived(path)) return;
430
+ const attrsA = a && this.ownAttributes(a, path), attrsB = b && this.ownAttributes(b, path);
431
+ if (a && b && a.value instanceof Bag && b.value instanceof Bag && same(attrsA,attrsB)) {
402
432
  const labels = new Set([...a.value.getNodes(), ...b.value.getNodes()].map(n => n.label));
403
433
  for (const label of labels) visit(a.value.getNode(label), b.value.getNode(label), path ? path + '.' + label : label);
404
- } else if (!a || !b || !same([a.value,a.attr],[b.value,b.attr])) {
434
+ } else if (a && b ? !same([a.value,attrsA],[b.value,attrsB])
435
+ // A node appearing or disappearing with derived values only is not an edit.
436
+ : !(this.onlyDerived(a, path) && this.onlyDerived(b, path))) {
405
437
  changes.setItem(encoded(path), new Bag({path, existed:Boolean(a), exists:Boolean(b),
406
438
  previous:a ? copy(a.value) : null, current:b ? copy(b.value) : null,
407
- previousAttributes:a ? copy(a.attr) : null, currentAttributes:b ? copy(b.attr) : null}));
439
+ previousAttributes:a ? copy(attrsA) : null, currentAttributes:b ? copy(attrsB) : null}));
408
440
  }
409
441
  };
410
442
  const baseline = this.registers.getItem('baseline');
@@ -14,9 +14,14 @@ export class BagCollectionStore {
14
14
  this.#listeners.add(listener);
15
15
  return () => this.#listeners.delete(listener);
16
16
  }
17
- /** Called by the page's single Data subscription. Each view reconciles independently. */
18
- receiveData(event, row = null) {
19
- publishCollection(this.#listeners, {full:row === null, rows:row ? [row] : []});
17
+ /**
18
+ * Called by the page's single Data subscription. Each view reconciles independently.
19
+ * `row` is the row node the event is inside, null for a change of the row list itself;
20
+ * `field` is the label directly under the row on the event path, null when the event
21
+ * targets the row node or inserts/deletes its direct children.
22
+ */
23
+ receiveData(event, row = null, field = null) {
24
+ publishCollection(this.#listeners, {full:row === null, rows:row ? [row] : [], event, field});
20
25
  }
21
26
  getRows() {
22
27
  const nodes = this.bag.getNodes();
@@ -39,10 +44,14 @@ export class BagCollectionStore {
39
44
  }
40
45
  }
41
46
 
42
- /** One invalidation protocol at both collection levels; failures cannot skip siblings. */
47
+ /**
48
+ * One invalidation protocol at both collection levels; failures cannot skip siblings.
49
+ * A store notice also carries its Data `event` and changed `field`; a view notice carries null.
50
+ */
43
51
  export function publishCollection(listeners, change) {
44
52
  const errors = [];
45
- const notice = Object.freeze({full:change.full, rows:Object.freeze([...change.rows])});
53
+ const notice = Object.freeze({full:change.full, rows:Object.freeze([...change.rows]),
54
+ event:change.event ?? null, field:change.field ?? null});
46
55
  for (const listener of [...listeners]) {
47
56
  if (!listeners.has(listener)) continue;
48
57
  try { listener(notice); } catch (error) { errors.push(error); }
@@ -62,7 +62,7 @@ export class BagCollectionView {
62
62
  }
63
63
  synchronize(change = {full:true, rows:[]}) {
64
64
  if (!change.full && !this.#sortedBy && !this.#filters.size) {
65
- publishCollection(this.#listeners,change);
65
+ publishCollection(this.#listeners,{full:change.full, rows:change.rows});
66
66
  return;
67
67
  }
68
68
  this.#commit(this.#sorted(this.#orderedNodes(),this.criteria),this.#sortedBy,this.#filters,change);