@gramlot/gramlot 0.3.36 → 0.3.37

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 (106) hide show
  1. package/dist/components/charts/__init__.py +1 -1
  2. package/dist/components/charts/assets/collection.js +9 -9
  3. package/dist/components/charts/assets/index.js +1 -1
  4. package/dist/components/charts/grammar.json +0 -30
  5. package/dist/components/drawing/__init__.py +1 -1
  6. package/dist/components/drawing/assets/collection.js +3 -3
  7. package/dist/components/drawing/assets/index.js +1 -1
  8. package/dist/components/grid/__init__.py +1 -1
  9. package/dist/components/grid/assets/collection.js +6 -6
  10. package/dist/components/grid/assets/index.js +1 -1
  11. package/dist/components/grid/grammar.json +0 -2
  12. package/dist/components/inputs/__init__.py +1 -1
  13. package/dist/components/inputs/assets/collection.js +8 -8
  14. package/dist/components/inputs/assets/index.js +1 -1
  15. package/dist/components/inputs/grammar.json +2 -1
  16. package/dist/components/layout/__init__.py +1 -1
  17. package/dist/components/layout/assets/collection.js +9 -9
  18. package/dist/components/layout/assets/index.js +1 -1
  19. package/dist/components/layout/grammar.json +2 -2
  20. package/dist/components/selection_trial/__init__.py +1 -1
  21. package/dist/components/selection_trial/assets/collection.js +3 -3
  22. package/dist/components/selection_trial/assets/index.js +1 -1
  23. package/dist/components/tree/__init__.py +1 -1
  24. package/dist/components/tree/assets/collection.js +6 -6
  25. package/dist/components/tree/assets/index.js +1 -1
  26. package/dist/components/tree/grammar.json +0 -1
  27. package/dist/components/uploads/__init__.py +1 -1
  28. package/dist/components/uploads/assets/collection.js +3 -3
  29. package/dist/components/uploads/assets/index.js +1 -1
  30. package/dist/components/uploads/grammar.json +0 -3
  31. package/dist/gramlot.js +1205 -627
  32. package/dist/gramlot.min.js +45 -45
  33. package/dist/standard-collections.js +1 -1
  34. package/package.json +2 -3
  35. package/src/binding/data-binder.js +11 -3
  36. package/src/binding/grid-struct.js +7 -4
  37. package/src/binding/runtime.js +203 -46
  38. package/src/builder/binding.json +23 -1
  39. package/src/builder/gramlot-builder.d.ts +1 -4
  40. package/src/builder/source.js +185 -29
  41. package/src/chat.js +26 -20
  42. package/src/components/attachment-manager.js +38 -34
  43. package/src/components/chart-data-view.js +4 -7
  44. package/src/components/chart-fields.js +18 -6
  45. package/src/components/chart-renderer.js +10 -3
  46. package/src/components/chart-timeline.js +7 -5
  47. package/src/components/charts.js +74 -67
  48. package/src/components/check-box-text-editor.js +3 -3
  49. package/src/components/check-box-text.js +7 -22
  50. package/src/components/check-box-tree.js +20 -16
  51. package/src/components/choice-editor.js +1 -1
  52. package/src/components/drawing.js +47 -34
  53. package/src/components/grid-cell-editor.js +72 -29
  54. package/src/components/grid-column-filters.js +47 -40
  55. package/src/components/grid-formulas.js +22 -17
  56. package/src/components/grid-header-interaction.js +9 -11
  57. package/src/components/grid-row-interaction.js +25 -24
  58. package/src/components/grid-row-layout.js +28 -29
  59. package/src/components/grid-search-box.js +3 -3
  60. package/src/components/grid-search.js +3 -8
  61. package/src/components/grid-selection.js +33 -29
  62. package/src/components/grid-structure.js +48 -10
  63. package/src/components/grid-tools.js +14 -14
  64. package/src/components/grid.js +83 -79
  65. package/src/components/image-crop-dialog.js +2 -2
  66. package/src/components/image-crop.js +16 -9
  67. package/src/components/image-uploader.js +21 -28
  68. package/src/components/inputs.js +19 -1
  69. package/src/components/registry.js +3 -5
  70. package/src/components/tray-pane.js +85 -61
  71. package/src/components/tree.js +332 -239
  72. package/src/components/upload-engine.js +10 -2
  73. package/src/components/uploader.js +31 -27
  74. package/src/editing-session.d.ts +4 -1
  75. package/src/editing-session.js +120 -83
  76. package/src/experiments/window-selection.js +4 -6
  77. package/src/filesystem.js +2 -2
  78. package/src/gramlot.js +1 -0
  79. package/src/handlers/device-handler.js +219 -213
  80. package/src/handlers/rpc-handler.d.ts +17 -0
  81. package/src/handlers/rpc-handler.js +22 -0
  82. package/src/ide-documents.js +29 -11
  83. package/src/ide-runtime.js +33 -31
  84. package/src/index-page-runtime.d.ts +2 -2
  85. package/src/index-page-runtime.js +67 -48
  86. package/src/message-port-connection.js +100 -0
  87. package/src/message-port-store.js +158 -0
  88. package/src/page-store-connection.js +6 -1
  89. package/src/renderer/gramlot-renderer.js +21 -2
  90. package/src/source-picker.d.ts +2 -2
  91. package/src/source-picker.js +15 -6
  92. package/src/stores/bag-collection-store.js +25 -7
  93. package/src/stores/bag-collection-view.js +23 -22
  94. package/src/view/controls.js +1 -1
  95. package/src/view/html.js +40 -20
  96. package/src/visual-editor-canvas.js +1 -1
  97. package/src/visual-editor.js +18 -19
  98. package/tools/gramlot-tools-inspector.js +400 -374
  99. package/tools/inspector-agent.js +223 -49
  100. package/dist/components/vizabi/__init__.py +0 -13
  101. package/dist/components/vizabi/assets/collection.js +0 -4
  102. package/dist/components/vizabi/assets/index.js +0 -3
  103. package/dist/components/vizabi/commands.json +0 -7
  104. package/dist/components/vizabi/grammar.json +0 -128
  105. package/src/components/vizabi-session.js +0 -66
  106. package/src/components/vizabi.js +0 -66
@@ -23,7 +23,7 @@ import structureGrammar from './grid-grammar.json' with {type: 'json'};
23
23
 
24
24
  /** First grid: explicit Bag row representation and a separately observable Data struct. */
25
25
  export const Grid = defineComponent({
26
- name: 'grid', tag: 'gramlot-grid', base: Container, bagStore: true, bagStruct: true, sourceContext: true, subTags: 'struct,div',
26
+ name: 'grid', tag: 'gramlot-grid', base: Container, sourceContext: true, subTags: 'struct,div',
27
27
  parameters: {columnFilters: {dtype:'B', default:false, binding:'read'}, setFilter: {dtype:'T', default:'', binding:'read'}, windowInfo: {dtype:'X', nullable:true, default:null, binding:'read'},
28
28
  loading: {dtype:'B', default:false, binding:'read'},
29
29
  viewport: {dtype:'X', nullable:true, default:null, binding:'write'},
@@ -44,7 +44,6 @@ export const Grid = defineComponent({
44
44
  sortedBy: {dtype:'T', default:'', binding:'read'},
45
45
  filter: {annotation:{kind:'type',module:'builtins',name:'dict'}, nullable:true, default:null, binding:'read'}},
46
46
  implementation: Base => class extends Base {
47
- #store;
48
47
  #checkSets;
49
48
  #columnFilters;
50
49
  #cellEditor;
@@ -56,11 +55,10 @@ export const Grid = defineComponent({
56
55
  #selection;
57
56
  /** Click selects (single); Ctrl/Cmd+click toggles and Shift+click extends (multi). Double-click still edits. */
58
57
  #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;
58
+ const label = this.#labelOf(event.target.closest('tr[data-row]'));
59
+ if (label === null || this.#selection.mode === 'none') return;
62
60
  try {
63
- this.#selection.select(node, {toggle:event.ctrlKey || event.metaKey, range:event.shiftKey});
61
+ this.#selection.select(label, {toggle:event.ctrlKey || event.metaKey, range:event.shiftKey});
64
62
  this.#renderSelection();
65
63
  } catch (error) { this.#context.reportError(error, 'Grid selection'); }
66
64
  };
@@ -75,8 +73,8 @@ export const Grid = defineComponent({
75
73
  if (all) this.#selection.selectAll();
76
74
  else {
77
75
  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);
76
+ const label = this.#selection.move(step, event.shiftKey);
77
+ if (label !== null) this.#revealRow(label, field);
80
78
  }
81
79
  this.#renderSelection();
82
80
  } catch (error) { this.#context.reportError(error, 'Grid selection'); }
@@ -85,9 +83,9 @@ export const Grid = defineComponent({
85
83
  if (event.type === 'keydown' && !['Enter','F2'].includes(event.key)) return;
86
84
  const cell = event.target.closest('td[data-field]');
87
85
  if (!cell || !this.#structure) return;
88
- const row = [...this.#rows].find(([, tr]) => tr === cell.parentElement)?.[0];
86
+ const row = this.#labelOf(cell.parentElement);
89
87
  const column = this.#structure.columns.find(column => column.field === cell.dataset.field);
90
- if (row && column.edit) {
88
+ if (row !== null && column.edit) {
91
89
  event.preventDefault();
92
90
  try { this.#cellEditor.open(row, column, cell); }
93
91
  catch (error) { this.#context.reportError(error,'Grid editor'); }
@@ -97,9 +95,9 @@ export const Grid = defineComponent({
97
95
  #windowRequest;
98
96
  #context;
99
97
  #structure;
100
- #structBag;
101
98
  #structureDirty = true;
102
99
  #signature;
100
+ /** The rendered rows by row key (node label); the grid keeps keys, never row nodes. */
103
101
  #rows = new Map();
104
102
  #head;
105
103
  #body;
@@ -122,7 +120,7 @@ export const Grid = defineComponent({
122
120
  #refreshTimer = null;
123
121
  #pendingFull = false;
124
122
  #pendingRows = new Set();
125
- #visibleNodes = [];
123
+ #visibleLabels = [];
126
124
  #windowStart = -1;
127
125
  #windowEnd = -1;
128
126
  #topSpace;
@@ -199,10 +197,8 @@ export const Grid = defineComponent({
199
197
  this.#columnFilters = new GridColumnFilters(this, this.#head);
200
198
  this.#interaction = new GridHeaderInteraction(this.#head, this.control, () => this.#structure, (field, multiple) => this.#sort(field, multiple),
201
199
  () => this.#rowLayout, () => this.#scheduleLayout());
202
- this.#rowInteraction = new GridRowInteraction(this.#body, this.control, () => this.#rowLayout, row => {
203
- for (const [node, element] of this.#rows) if (element === row) return node;
204
- return null;
205
- }, () => this.#collectionView, () => this.parameters.selfDragRows, () => this.#scheduleLayout());
200
+ this.#rowInteraction = new GridRowInteraction(this.#body, this.control, () => this.#rowLayout, row => this.#labelOf(row),
201
+ () => this.#collectionView, () => this.parameters.selfDragRows, () => this.#scheduleLayout());
206
202
  this.#resizeObserver = new doc.defaultView.ResizeObserver(() => this.#scheduleLayout());
207
203
  }
208
204
  connectedCallback() {
@@ -296,10 +292,10 @@ export const Grid = defineComponent({
296
292
  this.#rowLayout.resetMeasurements(); this.#geometryKey = key; changed = true;
297
293
  }
298
294
  }
299
- for (const [node, row] of this.#rows) {
300
- changed = this.#rowLayout.measure(node, row.getBoundingClientRect().height) || changed;
295
+ for (const [label, row] of this.#rows) {
296
+ changed = this.#rowLayout.measure(label, row.getBoundingClientRect().height) || changed;
301
297
  }
302
- if (changed && this.#visibleNodes.length) {
298
+ if (changed && this.#visibleLabels.length) {
303
299
  // Keep the same visible row while estimated heights become exact.
304
300
  const top = this.#rowLayout.offset(anchor) + within;
305
301
  this.#setSpaces();
@@ -326,7 +322,7 @@ export const Grid = defineComponent({
326
322
  let {start, end} = this.#rowLayout.window(top, viewport.clientHeight);
327
323
  const info = this.#windowInfo();
328
324
  if (info) {
329
- const loadedEnd = info.start + this.#visibleNodes.length;
325
+ const loadedEnd = info.start + this.#visibleLabels.length;
330
326
  if (start < info.start || end > loadedEnd) {
331
327
  const count = Math.max(200, end - start);
332
328
  const requestedStart = Math.max(0, Math.min(Math.max(0, info.total - count), start));
@@ -346,7 +342,7 @@ export const Grid = defineComponent({
346
342
  else this.control.removeAttribute('aria-busy');
347
343
  if (force || start !== this.#windowStart || end !== this.#windowEnd) {
348
344
  const rows = new GridRows(this.#formulas, this.#context.format)
349
- .read(this.#structure.columns, this.#visibleNodes.slice(start-(info?.start ?? 0), end-(info?.start ?? 0)));
345
+ .read(this.#structure.columns, this.#rowNodes(this.#visibleLabels.slice(start-(info?.start ?? 0), end-(info?.start ?? 0))));
350
346
  this.#renderRows(rows, this.#structure.columns, start);
351
347
  this.#windowStart = start; this.#windowEnd = end;
352
348
  this.#scheduleLayout();
@@ -354,20 +350,21 @@ export const Grid = defineComponent({
354
350
  this.#setSpaces();
355
351
  this.#scrollTo(top);
356
352
  }
353
+ /** The provider window, read at the address of the `windowInfo` pointer at each use; never kept. */
357
354
  #windowInfo() {
358
- const value = this.parameters.windowInfo;
355
+ const value = this.#context.getStaticData(this.#context.attrDatapath('windowInfo'));
359
356
  if (value === null) return null;
360
357
  if (!(value instanceof Bag)) throw new TypeError('Grid windowInfo requires a Bag');
361
358
  return Object.fromEntries(['start', 'total', 'revision', 'sortedBy'].map(key => [key, value.getItem(key)]));
362
359
  }
363
360
  #nextEditor(row,field,step) {
364
- const rows = this.#collectionView.getRows(), columns = this.#structure.columns.filter(column => column.edit);
361
+ const rows = this.#collectionView.getRows().map(node => node.label), columns = this.#structure.columns.filter(column => column.edit);
365
362
  const index = rows.indexOf(row) * columns.length + columns.findIndex(column => column.field === field) + (typeof step === 'object' ? step.row * columns.length : step);
366
363
  if (index < 0 || index >= rows.length * columns.length) return;
367
364
  this.#openEditorAt(Math.floor(index / columns.length),columns[index % columns.length]);
368
365
  }
369
366
  #openEditorAt(rowIndex,column) {
370
- const next = this.#collectionView.getRows()[rowIndex];
367
+ const next = this.#collectionView.getRows()[rowIndex].label;
371
368
  this.#endPinned = false;
372
369
  const top = this.#rowLayout.offset(rowIndex), bottom = this.#rowLayout.offset(rowIndex + 1);
373
370
  if (top < this.#bodyViewport.scrollTop) this.#scrollTo(top);
@@ -386,14 +383,10 @@ export const Grid = defineComponent({
386
383
  this.#cellEditor.open(next,column,cell);
387
384
  }
388
385
  #focusField(path) {
389
- const prefix = this.#context.sourceNode.absDatapath(this.parameters.storepath) + '.';
390
- if (!path.startsWith(prefix)) return false;
391
- const relative = path.slice(prefix.length), separator = this.parameters.rowMode === 'attributes' ? '?' : '.';
392
- const split = relative.indexOf(separator);
393
- if (split < 0) return false;
394
- const row = this.#store.getNode(relative.slice(0,split));
395
- const column = this.#structure.columns.find(column => column.field === relative.slice(split+1) && column.edit);
396
- const index = this.#collectionView.getRows().indexOf(row);
386
+ const address = this.#context.sourceNode.rowField(path);
387
+ if (address === null) return false;
388
+ const column = this.#structure.columns.find(column => column.field === address.field && column.edit);
389
+ const index = this.#collectionView.getRows().findIndex(row => row.label === address.row);
397
390
  if (!column || index < 0) return false;
398
391
  this.#openEditorAt(index,column);
399
392
  return true;
@@ -410,35 +403,46 @@ export const Grid = defineComponent({
410
403
  mode:() => this.#selectionMode(), rowData:node => this.#rowData(node)});
411
404
  this.#tools = new GridTools(context, {columns:() => this.#structure.columns, rows:() => this.#collectionView.getRows(),
412
405
  selected:() => this.#selection.nodes, selectionMode:() => this.#selectionMode(),
413
- reader:() => this.#formulas, store:() => ({bag:this.#store, mode:this.parameters.rowMode}),
406
+ reader:() => this.#formulas, store:() => ({mode:this.parameters.rowMode}),
414
407
  parameters:() => this.parameters, document:this.ownerDocument});
415
408
  if (this.isConnected) this.#tools.connect();
416
409
  this.#columnFilters.setSourceContext(context);
417
410
  this.#checkSets = new GridCheckSets(context.sourceNode, this.#body,
418
411
  () => this.#structure?.columns ?? [],
419
- element => [...this.#rows].find(([,tr]) => tr === element)?.[0],
412
+ element => { const label = this.#labelOf(element); return label === null ? undefined : this.#rowNodes([label])[0]; },
420
413
  (node,field) => this.#collectionView.value(node,field),
421
414
  () => this.parameters.setFilter, () => this.#collectionView);
422
415
  if (this.isConnected) this.#checkSets.connect();
423
- this.#cellEditor = new GridCellEditor(this, context, (row, field) => this.#rows.get(row)?.querySelector(`td[data-field="${field}"]`), () => ({bag:this.#store, mode:this.parameters.rowMode, window:this.parameters.windowInfo}), () => this.#rows, (row,field,step) => this.#nextEditor(row,field,step), path => this.#focusField(path));
416
+ this.#cellEditor = new GridCellEditor(this, context, (row, field) => this.#rows.get(row)?.querySelector(`td[data-field="${field}"]`),
417
+ () => ({labels:() => this.#collectionStore().getRows().map(row => row.label), window:this.#windowInfo()}),
418
+ () => this.#rows, (row,field,step) => this.#nextEditor(row,field,step), path => this.#focusField(path));
424
419
  const node = context.sourceNode;
425
- if (!Object.hasOwn(node, 'gridRowLayout')) {
426
- Object.defineProperty(node, 'gridRowLayout', {value:new GridRowLayout(), configurable:true});
427
- }
428
- this.#rowLayout = node.gridRowLayout;
420
+ this.#rowLayout = node._internal.gridRowLayout ??= new GridRowLayout();
429
421
  }
430
- setStoreBag(bag) {
422
+ /** The rows Bag, read at its address at each use; the grid never keeps it. */
423
+ #storeBag() {
424
+ const bag = this.#context.getStaticData(this.#context.attrDatapath('storepath'));
431
425
  if (!(bag instanceof Bag)) throw new TypeError('grid storepath must resolve to a Bag');
432
- if (bag !== this.#store) this.#cellEditor?.replaceData();
433
- this.#store = bag;
434
- this.#rowLayout.bindStore(bag);
426
+ return bag;
427
+ }
428
+ /** The row nodes of the keys `labels` still in the rows Bag, read at their address at this call. */
429
+ #rowNodes(labels) {
430
+ const bag = this.#storeBag();
431
+ return labels.flatMap(label => bag.getNode(label) ?? []);
432
+ }
433
+ /** The key of a rendered row element of this grid, or null. */
434
+ #labelOf(tr) {
435
+ return tr && this.#rows.get(tr.dataset.row) === tr ? tr.dataset.row : null;
435
436
  }
436
- setStructBag(bag) { this.#structBag = bag; this.#structureDirty = true; }
437
- projectAttributes(attrs, adapt) {
437
+ projectAttributes(attrs, adapt, changedPath = null) {
438
438
  const rest = super.projectAttributes(attrs, adapt);
439
+ // The structure is read again at its address when a change reaches it, or on a full projection.
440
+ const structpath = this.#context.attrDatapath('structpath');
441
+ if (changedPath === null || changedPath === structpath || changedPath.startsWith(`${structpath}.`)
442
+ || structpath.startsWith(`${changedPath}.`)) this.#structureDirty = true;
439
443
  if (this.#windowInfo() && (this.parameters.columnFilters || this.#collectionView?.filterContributions.some(([name]) => name.startsWith('column:')))) throw new TypeError('grid columnFilters requires a complete resident store');
440
444
  if (this.#windowInfo() && this.parameters.setFilter !== '') throw new TypeError('grid setFilter requires a complete resident store');
441
- const store = this.#context.collectionView(this.#store, this.parameters.rowMode);
445
+ const store = this.#context.collectionView(this.#context.attrDatapath('storepath'), this.parameters.rowMode);
442
446
  if (this.#collectionView !== store) {
443
447
  this.#cancelRefresh();
444
448
  this.#unsubscribeStore?.(); this.#unsubscribeStore = null;
@@ -473,17 +477,17 @@ export const Grid = defineComponent({
473
477
  #invalidate({full, rows}) {
474
478
  this.#pendingFull ||= full;
475
479
  if (this.#pendingFull) this.#pendingRows.clear();
476
- else for (const node of rows) this.#pendingRows.add(node);
480
+ else for (const node of rows) this.#pendingRows.add(node.label);
477
481
  if (!this.isConnected || this.#refreshTimer !== null) return;
478
482
  this.#refreshTimer = this.ownerDocument.defaultView.setTimeout(() => {
479
- const full = this.#pendingFull, nodes = [...this.#pendingRows];
483
+ const full = this.#pendingFull, labels = [...this.#pendingRows];
480
484
  this.#refreshTimer = null;
481
485
  this.#pendingFull = false;
482
486
  this.#pendingRows.clear();
483
487
  try {
484
488
  if (full) this.#project();
485
489
  // View values (#, += and their dependents) of other rows can change too.
486
- else this.#projectRows(this.#formulas.viewFields.size ? [...this.#rows.keys()] : nodes);
490
+ else this.#projectRows(this.#formulas.viewFields.size ? [...this.#rows.keys()] : labels);
487
491
  } catch (error) {
488
492
  // Keep the last valid DOM. A later change retries a complete pull;
489
493
  // there is no automatic retry loop and no exception in Data delivery.
@@ -492,16 +496,18 @@ export const Grid = defineComponent({
492
496
  }
493
497
  }, 0);
494
498
  }
495
- #projectRows(nodes) {
496
- for (const node of nodes) this.#rowLayout.forget(node);
499
+ #projectRows(labels) {
500
+ for (const label of labels) this.#rowLayout.forget(label);
497
501
  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)));
502
+ const rows = new GridRows(this.#formulas, this.#context.format).read(this.#structure.columns, this.#rowNodes(labels.filter(label => this.#rows.has(label))));
499
503
  this.#rowInteraction.cancel();
500
- for (const {node, cells} of rows) this.#renderCells(this.#rows.get(node), cells, node);
504
+ for (const {node, cells} of rows) this.#renderCells(this.#rows.get(node.label), cells, node);
501
505
  this.#scheduleLayout();
502
506
  }
503
507
  #project() {
504
- const model = this.#structureDirty ? new GridStructure(this.#structBag) : this.#structure;
508
+ const structpath = this.#context.attrDatapath('structpath');
509
+ const model = this.#structureDirty
510
+ ? new GridStructure(this.#context.getStaticData(structpath), {data:this.#context.sourceNode.data, path:structpath}) : this.#structure;
505
511
  const store = this.#collectionStore();
506
512
  this.#formulas.configure(model, this.#collectionView, store);
507
513
  this.#requireStoredCriteria();
@@ -511,14 +517,14 @@ export const Grid = defineComponent({
511
517
  this.#cellEditor.configure(model.columns);
512
518
  this.#structure = model;
513
519
  this.#checkSets.configure();
514
- const nodes = this.#collectionView.getRows();
520
+ const labels = this.#collectionView.getRows().map(row => row.label);
515
521
  this.#rowInteraction.cancel(); this.#rowInteraction.cancelDrag();
516
- this.#rowLayout.retain(this.#store.getNodes());
522
+ this.#rowLayout.retain(store.getRows().map(row => row.label));
517
523
  if (this.#structureDirty) this.#rowLayout.resetMeasurements();
518
524
  const info = this.#windowInfo();
519
525
  this.#rowLayout.setWindow(info);
520
- this.#rowLayout.setRows(nodes);
521
- this.#visibleNodes = nodes;
526
+ this.#rowLayout.setRows(labels);
527
+ this.#visibleLabels = labels;
522
528
  if (info && this.#windowRevision !== info.revision) {
523
529
  this.#endPinned = false;
524
530
  this.#scrollTo(0);
@@ -567,11 +573,8 @@ export const Grid = defineComponent({
567
573
  const own = relative(selection);
568
574
  return own !== null && (path === own || path.startsWith(own + '.') || path.startsWith(own + '?'));
569
575
  })) 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);
576
+ const address = this.#context.sourceNode.rowField(path === '' ? base : `${base}.${path}`);
577
+ return address !== null && this.#formulas.dataFields.has(address.field);
575
578
  }
576
579
  #selectionMode() {
577
580
  const mode = this.parameters.selectionMode;
@@ -587,26 +590,26 @@ export const Grid = defineComponent({
587
590
  const mode = this.#selectionMode();
588
591
  if (mode === 'multi') this.control.setAttribute('aria-multiselectable', 'true');
589
592
  else this.control.removeAttribute('aria-multiselectable');
590
- for (const [node, tr] of this.#rows) {
591
- const selected = this.#selection.isSelected(node);
593
+ for (const [label, tr] of this.#rows) {
594
+ const selected = this.#selection.isSelected(label);
592
595
  if (mode === 'none') tr.removeAttribute('aria-selected');
593
596
  else tr.setAttribute('aria-selected', String(selected));
594
597
  tr.setAttribute('part', selected ? 'row selected-row' : 'row');
595
598
  }
596
599
  }
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
+ /** Scroll the view row of key `label` into the viewport; focus the cell of `field` when given. */
601
+ #revealRow(label, field) {
602
+ const index = this.#collectionView.getRows().findIndex(row => row.label === label);
600
603
  this.#endPinned = false;
601
604
  const top = this.#rowLayout.offset(index), bottom = this.#rowLayout.offset(index + 1);
602
605
  if (top < this.#bodyViewport.scrollTop) this.#scrollTo(top);
603
606
  else if (bottom > this.#bodyViewport.scrollTop + this.#bodyViewport.clientHeight) this.#scrollTo(Math.max(0, bottom - this.#bodyViewport.clientHeight));
604
607
  this.#renderWindow(true);
605
- if (field) this.#rows.get(node)?.querySelector(`td[data-field="${field}"]`)?.focus({preventScroll:true});
608
+ if (field) this.#rows.get(label)?.querySelector(`td[data-field="${field}"]`)?.focus({preventScroll:true});
606
609
  }
607
610
  /** The shared resident store under this grid's view. */
608
611
  #collectionStore() {
609
- return this.#context.sourceNode.rootBuilder.binding.collectionStore(this.#store, this.parameters.rowMode);
612
+ return this.#context.sourceNode.rootBuilder.binding.collectionStore(this.#context.attrDatapath('storepath'), this.parameters.rowMode);
610
613
  }
611
614
  /** Sort, column filter and search criteria apply to stored fields: a view value derives from the order. */
612
615
  #requireStoredCriteria() {
@@ -757,17 +760,18 @@ export const Grid = defineComponent({
757
760
  const keep = new Set(); let previous = null;
758
761
  this.#body.querySelector('.empty')?.parentElement.remove();
759
762
  for (const {node, cells} of rows) {
760
- let tr = this.#rows.get(node);
763
+ const label = node.label;
764
+ let tr = this.#rows.get(label);
761
765
  if (!tr) {
762
766
  tr = this.ownerDocument.createElement('tr'); tr.setAttribute('part', 'row');
763
767
  tr.setAttribute('role', 'row');
764
- tr.dataset.row = node.label;
765
- this.#rows.set(node, tr);
768
+ tr.dataset.row = label;
769
+ this.#rows.set(label, tr);
766
770
  }
767
771
  tr.classList.toggle('alternate', (start + keep.size) % 2 === 1);
768
- tr.setAttribute('part', this.#selection.isSelected(node) ? 'row selected-row' : 'row');
772
+ tr.setAttribute('part', this.#selection.isSelected(label) ? 'row selected-row' : 'row');
769
773
  if (this.#selection.mode === 'none') tr.removeAttribute('aria-selected');
770
- else tr.setAttribute('aria-selected', String(this.#selection.isSelected(node)));
774
+ else tr.setAttribute('aria-selected', String(this.#selection.isSelected(label)));
771
775
  // Under a filter the numbering covers the visible rows only.
772
776
  const partial = this.#collectionView.isFiltered();
773
777
  tr.draggable = this.parameters.selfDragRows;
@@ -826,13 +830,13 @@ export const Grid = defineComponent({
826
830
  for (const td of existing.values()) td.remove();
827
831
  tr.setAttribute('aria-rowindex', String(this.#headerRows + start + keep.size + 1));
828
832
  this.#renderCells(tr, cells, node);
829
- this.#cellEditor.decorate(tr, node);
833
+ this.#cellEditor.decorate(tr, label);
830
834
  const next = previous ? previous.nextSibling : this.#body.firstChild;
831
835
  if (next !== tr) this.#body.insertBefore(tr, next);
832
- this.#rowInteraction.project(tr, node);
833
- previous = tr; keep.add(node);
836
+ this.#rowInteraction.project(tr, label);
837
+ previous = tr; keep.add(label);
834
838
  }
835
- for (const [node, tr] of this.#rows) if (!keep.has(node)) { tr.remove(); this.#rows.delete(node); }
839
+ for (const [label, tr] of this.#rows) if (!keep.has(label)) { tr.remove(); this.#rows.delete(label); }
836
840
  if (!rows.length && this.#rowLayout.count === 0 && !this.parameters.loading) {
837
841
  const tr = this.ownerDocument.createElement('tr'), td = this.ownerDocument.createElement('td');
838
842
  tr.setAttribute('role', 'row'); tr.setAttribute('aria-rowindex', String(this.#headerRows + 1));
@@ -4,13 +4,13 @@ import {ImageCropSession} from './image-crop.js';
4
4
  export class ImageCropDialog {
5
5
  #document; #image; #session; #options; #dialog; #frameImage; #minZoom; #maxZoom;
6
6
  #resolve; #settled = false; #events; #frame; #points = new Map(); #gesture; #trackpadGesture;
7
- constructor({state, document, original, image, sourceWidth, sourceHeight, width, height,
7
+ constructor({data, path, document, original, image, sourceWidth, sourceHeight, width, height,
8
8
  x = 0, y = 0, zoom = 1, rotate = 0, outputWidth, outputHeight, type, quality}) {
9
9
  this.#document = document;
10
10
  this.#image = image;
11
11
  this.#options = {width,height,sourceWidth,sourceHeight,outputWidth,outputHeight,type,quality};
12
12
  this.#minZoom = zoom/5; this.#maxZoom = zoom*5;
13
- this.#session = new ImageCropSession({state,document,original,image,sourceWidth,sourceHeight,width,height,x,y,zoom,rotate});
13
+ this.#session = new ImageCropSession({data,path,document,original,image,sourceWidth,sourceHeight,width,height,x,y,zoom,rotate});
14
14
  const dialog = this.#dialog = document.createElement('dialog');
15
15
  dialog.setAttribute('aria-label', 'Edit image');
16
16
  dialog.className = 'gramlot-image-crop-dialog';
@@ -34,33 +34,40 @@ export async function renderImageCrop({document, image, sourceWidth, sourceHeigh
34
34
  });
35
35
  }
36
36
 
37
- /** One private editing session; the caller owns the original and decoded image. */
37
+ /**
38
+ * One private editing session; the caller owns the original and decoded image. The framing values
39
+ * `initial` and `transform` live in Data at `path` under the Data root `data`: the session keeps the root
40
+ * and the path and reads them at each use.
41
+ */
38
42
  export class ImageCropSession {
39
43
  #document; #original; #image; #sourceWidth; #sourceHeight; #width; #height;
40
- #state; #generation = 0; #closed = false; #rendering = false;
41
- constructor({state, document, original, image, sourceWidth, sourceHeight, width, height, x = 0, y = 0, zoom = 1, rotate = 0}) {
44
+ #data; #path; #generation = 0; #closed = false; #rendering = false;
45
+ constructor({data, path, document, original, image, sourceWidth, sourceHeight, width, height, x = 0, y = 0, zoom = 1, rotate = 0}) {
42
46
  const transform = {x, y, zoom, rotate};
43
47
  this.#validate(transform);
44
48
  if (!original || !image) throw new TypeError('An original and decoded image are required');
45
49
  this.#document = document; this.#original = original; this.#image = image;
46
50
  this.#sourceWidth = sourceWidth; this.#sourceHeight = sourceHeight;
47
51
  this.#width = width; this.#height = height;
48
- this.#state = state;
49
- state.setItem('initial', transform); state.setItem('transform', {...transform});
52
+ if (typeof path !== 'string' || !path) throw new TypeError(`An image editing session requires a Data path: ${path}`);
53
+ this.#data = data; this.#path = path;
54
+ this.#write('initial', transform); this.#write('transform', {...transform});
50
55
  }
56
+ #read(key) { return this.#data.getItem(`${this.#path}.${key}`, null, true); }
57
+ #write(key, value) { this.#data.setItem(`${this.#path}.${key}`, value); }
51
58
  #validate({x, y, zoom, rotate}) {
52
59
  if (![x, y, zoom, rotate].every(Number.isFinite) || zoom <= 0) throw new TypeError('Invalid image transform');
53
60
  }
54
61
  #open() { if (this.#closed) throw new Error('Image editing session is closed'); }
55
62
  get original() { return this.#original; }
56
- get transform() { return {...this.#state.getItem('transform')}; }
63
+ get transform() { return {...this.#read('transform')}; }
57
64
  setTransform(transform) {
58
65
  this.#open();
59
66
  if (!transform || Object.keys(transform).sort().join(',') !== 'rotate,x,y,zoom') throw new TypeError('Expected x, y, zoom and rotate');
60
67
  this.#validate(transform);
61
- this.#state.setItem('transform', {...transform}); this.#generation++;
68
+ this.#write('transform', {...transform}); this.#generation++;
62
69
  }
63
- reset() { this.#open(); this.#state.setItem('transform', {...this.#state.getItem('initial')}); this.#generation++; }
70
+ reset() { this.#open(); this.#write('transform', {...this.#read('initial')}); this.#generation++; }
64
71
  cancel() { this.#closed = true; this.#generation++; }
65
72
  async confirm({outputWidth, outputHeight, type, quality}) {
66
73
  this.#open();
@@ -70,7 +77,7 @@ export class ImageCropSession {
70
77
  try {
71
78
  const blob = await renderImageCrop({document:this.#document, image:this.#image,
72
79
  sourceWidth:this.#sourceWidth, sourceHeight:this.#sourceHeight, width:this.#width, height:this.#height,
73
- outputWidth, outputHeight, ...this.#state.getItem('transform'), type, quality});
80
+ outputWidth, outputHeight, ...this.#read('transform'), type, quality});
74
81
  if (this.#closed || this.#generation !== generation) throw new DOMException('Image edit cancelled or changed', 'AbortError');
75
82
  this.#closed = true;
76
83
  return blob;
@@ -1,22 +1,21 @@
1
1
  /** Editable image value backed by the shared upload engine when an operation is supplied. */
2
- import {Bag} from '@gramlot/gramlot';
3
2
  import {defineComponent} from './registry.js';
4
3
  import {controlElement} from './bases.js';
5
4
  import {UploadEngine, readUploadContext} from './upload-engine.js';
6
5
  import {ImageCropDialog} from './image-crop-dialog.js';
7
- import {randomId} from '../random-id.js';
8
6
  import {captureScreen} from './screen-capture.js';
9
7
 
10
8
  export const ImageUploader = defineComponent({
11
- name:'imageUploader', tag:'gramlot-image-uploader', base:controlElement, sourceContext:true, bagStore:true,
9
+ name:'imageUploader', tag:'gramlot-image-uploader', base:controlElement, sourceContext:true,
12
10
  parameters:{value:{dtype:'T', nullable:true, default:null, binding:'twoWay'},
13
11
  storepath:{dtype:'T'}, contextPath:{dtype:'T',nullable:true,default:null}, operation:{dtype:'T', nullable:true, default:null},
14
12
  cropWidth:{dtype:'L', default:256}, cropHeight:{dtype:'L', default:256},
15
13
  outputWidth:{dtype:'L', default:512}, outputHeight:{dtype:'L', default:512},
16
14
  disabled:{dtype:'B', default:false, binding:'read'}, onComplete:{dtype:'T', nullable:true, default:null}},
17
15
  implementation: Base => class extends Base {
18
- #context; #store; #engine; #original; #dialog; #pending; #generation = 0; #projected; #written;
19
- #cameraSubscription; #cameraToken = null; #cameraPending = false; #cameraAvailable = false; #cameraStatus; #screenRequest = null;
16
+ #context; #engine; #original; #dialog; #pending; #generation = 0; #projected; #written;
17
+ // The router registration on `_gramlot.device.camera`: the camera state reaches the uploader by path.
18
+ #cameraRegistration = null; #cameraToken = null; #cameraPending = false; #cameraAvailable = false; #cameraStatus; #screenRequest = null;
20
19
  constructor() {
21
20
  super();
22
21
  const doc = this.ownerDocument;
@@ -56,19 +55,14 @@ export const ImageUploader = defineComponent({
56
55
  this.cancelButton.addEventListener('click', () => { if (this.#pending) this.#engine.cancel(this.#pending.id); });
57
56
  this.checkButton.addEventListener('click', () => void this.#check());
58
57
  }
59
- setSourceContext(context) {
60
- this.#context = context;
61
- if (!context.sourceNode.imageCropState) Object.defineProperty(context.sourceNode,
62
- 'imageCropState', {value:new Bag(), configurable:true});
63
- }
58
+ setSourceContext(context) { this.#context = context; }
64
59
  readControlValue() { return this.parameters?.value ?? null; }
65
60
  writeControlValue(value) { if (this.parameters) { this.parameters.value = value; this.#render(); } }
66
- setStoreBag(store) {
67
- if (!(store instanceof Bag)) throw new TypeError('imageUploader storepath must resolve to a Bag');
68
- if (this.#store && this.#store !== store) { this.#invalidate(); this.#engine?.dispose(); this.#engine = null; }
69
- this.#store = store;
70
- }
71
61
  projectAttributes(attrs, adapt) {
62
+ // A new storepath address is a new queue: the engine of the previous one ends.
63
+ if (this.#engine && this.#engine.path !== this.#context.attrDatapath('storepath')) {
64
+ this.#invalidate(); this.#engine.dispose(); this.#engine = null;
65
+ }
72
66
  const rest = super.projectAttributes(attrs, adapt);
73
67
  const p = this.parameters;
74
68
  for (const key of ['cropWidth','cropHeight','outputWidth','outputHeight']) {
@@ -85,17 +79,15 @@ export const ImageUploader = defineComponent({
85
79
  // DOM relocation into a floating keeps the same Source owner and resources.
86
80
  this.ownerDocument.defaultView.queueMicrotask(() => {
87
81
  if (this.isConnected) return;
88
- if (this.#cameraSubscription) {
89
- this.#context.upload().gramlot.data.unsubscribe(this.#cameraSubscription,{any:true}); this.#cameraSubscription = null;
90
- }
82
+ this.#cameraRegistration?.close(); this.#cameraRegistration = null;
91
83
  this.#invalidate(); this.#engine?.dispose(); this.#engine = null;
92
84
  });
93
85
  }
94
86
  #observeCamera() {
95
- if (this.#cameraSubscription || !this.#context) return;
96
- const {gramlot} = this.#context.upload();
97
- this.#cameraSubscription = `image-uploader-camera-${randomId()}`;
98
- gramlot.data.subscribe(this.#cameraSubscription,{any:event => this.#syncCamera(event)});
87
+ if (this.#cameraRegistration || !this.#context) return;
88
+ // Attaching a device provider writes `_gramlot.device.camera` again, so availability follows too.
89
+ this.#cameraRegistration = this.#context.sourceNode.rootBuilder.binding.router.register({
90
+ path:'_gramlot.device.camera', subtree:true, recipient:{receive:event => this.#syncCamera(event)}});
99
91
  this.#syncCamera();
100
92
  }
101
93
  #syncCamera(event = null) {
@@ -143,9 +135,10 @@ export const ImageUploader = defineComponent({
143
135
  } catch (error) { if (token === this.#generation) this.message.textContent = `Image failed: ${error.message}`; }
144
136
  }
145
137
  #ensureEngine() {
146
- if (!this.#engine && this.#context && this.#store && this.parameters) {
138
+ if (!this.#engine && this.#context && this.parameters) {
147
139
  const {gramlot,window} = this.#context.upload();
148
- this.#engine = new UploadEngine({gramlot,window,store:this.#store,operation:this.parameters.operation,
140
+ this.#engine = new UploadEngine({gramlot,window,data:this.#context.sourceNode.data,
141
+ path:this.#context.attrDatapath('storepath'),operation:this.parameters.operation,
149
142
  onChange:() => this.#render(), getContext:() => readUploadContext(this.#context.sourceNode,this.parameters.contextPath), onComplete:(item,result) => this.#complete(item,result)});
150
143
  }
151
144
  }
@@ -160,7 +153,7 @@ export const ImageUploader = defineComponent({
160
153
  if (!this.parameters) return;
161
154
  const value = this.parameters.value;
162
155
  if (value) { this.preview.src = value; this.preview.hidden = false; } else { this.preview.removeAttribute('src'); this.preview.hidden = true; }
163
- const state = this.#pending && this.#store.getItem(this.#pending.id)?.getItem('status');
156
+ const state = this.#pending && this.#engine.store.getItem(this.#pending.id)?.getItem('status');
164
157
  const busy = Boolean(this.#pending || this.#cameraToken !== null || this.#screenRequest);
165
158
  this.screenButton.hidden = !this.ownerDocument.defaultView.navigator.mediaDevices?.getDisplayMedia;
166
159
  this.screenButton.disabled = Boolean(this.parameters.disabled || busy);
@@ -172,7 +165,7 @@ export const ImageUploader = defineComponent({
172
165
  this.clearButton.disabled ||= !value;
173
166
  this.cancelButton.hidden = !['preparing','uploading'].includes(state);
174
167
  this.checkButton.hidden = state !== 'uncertain';
175
- if (state) this.message.textContent = `Upload: ${state}${this.#store.getItem(this.#pending.id).getItem('error') ? ' — ' + this.#store.getItem(this.#pending.id).getItem('error') : ''}`;
168
+ if (state) this.message.textContent = `Upload: ${state}${this.#engine.store.getItem(this.#pending.id).getItem('error') ? ' — ' + this.#engine.store.getItem(this.#pending.id).getItem('error') : ''}`;
176
169
  }
177
170
  async #load(source, objectUrl = null) {
178
171
  const win = this.ownerDocument.defaultView, image = new win.Image();
@@ -205,7 +198,7 @@ export const ImageUploader = defineComponent({
205
198
  }
206
199
  async #crop(candidate,token) {
207
200
  const p = this.parameters;
208
- const dialog = this.#dialog = new ImageCropDialog({state:this.#context.sourceNode.imageCropState,document:this.ownerDocument, original:candidate.original, image:candidate.image,
201
+ const dialog = this.#dialog = new ImageCropDialog({data:this.#context.sourceNode.data,path:this.#context.sourceNode.workspaceDatapath,document:this.ownerDocument, original:candidate.original, image:candidate.image,
209
202
  sourceWidth:candidate.image.naturalWidth, sourceHeight:candidate.image.naturalHeight,
210
203
  width:p.cropWidth,height:p.cropHeight,outputWidth:p.outputWidth,outputHeight:p.outputHeight,type:'image/png',...candidate.transform});
211
204
  let result;
@@ -240,7 +233,7 @@ export const ImageUploader = defineComponent({
240
233
  }
241
234
  #settle(id) {
242
235
  if (!this.#pending || this.#pending.id !== id) return;
243
- const row = this.#store.getItem(id), state = row.getItem('status');
236
+ const row = this.#engine.store.getItem(id), state = row.getItem('status');
244
237
  if (['failed','cancelled','completed'].includes(state)) {
245
238
  const error = row.getItem('error');
246
239
  if (this.#pending.candidate !== this.#original) this.#release(this.#pending.candidate);
@@ -197,11 +197,29 @@ export const CallbackSelect = defineComponent({
197
197
  parameters: {callback: {dtype: 'T'}}, implementation: callbackChoices
198
198
  });
199
199
  export const ComboBox = defineComponent({
200
- name: 'comboBox', tag: 'gramlot-combo-box', base: ChoiceEditor, mixins: [Labelbox, FieldState],
200
+ name: 'comboBox', tag: 'gramlot-combo-box', base: ChoiceEditor, mixins: [Labelbox, FieldState], sourceContext: true,
201
201
  parameters: {values: {dtype: 'T', default: '', binding: 'read'}, separator: {dtype: 'T', default: ',', binding: 'read'},
202
202
  store: {dtype: 'X', nullable: true, default: null, binding: 'read'}},
203
203
  implementation: Base => class extends localChoices(Base) {
204
204
  static get constrained() { return false; }
205
+ // The store choices are read at the address of the `store` pointer when they load; the control
206
+ // keeps only the path. `#storeSource` holds the path and is renewed when a Data change reaches it.
207
+ #context; #storeSource = null;
208
+ setSourceContext(context) { this.#context = context; }
209
+ // `store` is a `^` parameter of dtype 'X': a change inside the choices Bag or a replacement at its
210
+ // address projects the control again, and the renewed source makes it read the choices again.
211
+ projectAttributes(attrs, adapt, changedPath = null) {
212
+ const path = this.#context.attrDatapath('store');
213
+ if (path === null) this.#storeSource = null;
214
+ else if (this.#storeSource?.path !== path || changedPath === null || changedPath === path
215
+ || changedPath.startsWith(`${path}.`) || path.startsWith(`${changedPath}.`)) this.#storeSource = {path};
216
+ return super.projectAttributes(attrs, adapt);
217
+ }
218
+ get choiceSource() { return this.#storeSource ?? super.choiceSource; }
219
+ loadChoices(keywords) {
220
+ const store = this.#context.getStaticData(this.#context.attrDatapath('store'));
221
+ return this.constructor.loadChoices({...this.parameters, store}, this.pageContext, keywords);
222
+ }
205
223
  }
206
224
  });
207
225
  export const DbSelect = defineComponent({