@gramlot/gramlot 0.3.35 → 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 (117) 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/editors/__init__.py +2 -2
  9. package/dist/components/editors/assets/collection.js +4 -2
  10. package/dist/components/editors/assets/index.js +1 -1
  11. package/dist/components/editors/assets/modules/addon-fit-L6JK4OJX.js +12 -0
  12. package/dist/components/editors/assets/modules/xterm-BF3OSWRI.js +286 -0
  13. package/dist/components/editors/assets/modules/xterm-UBEXZEYY.js +47 -0
  14. package/dist/components/editors/grammar.json +207 -0
  15. package/dist/components/grid/__init__.py +1 -1
  16. package/dist/components/grid/assets/collection.js +6 -6
  17. package/dist/components/grid/assets/index.js +1 -1
  18. package/dist/components/grid/grammar.json +0 -2
  19. package/dist/components/inputs/__init__.py +1 -1
  20. package/dist/components/inputs/assets/collection.js +8 -8
  21. package/dist/components/inputs/assets/index.js +1 -1
  22. package/dist/components/inputs/grammar.json +2 -1
  23. package/dist/components/layout/__init__.py +1 -1
  24. package/dist/components/layout/assets/collection.js +9 -9
  25. package/dist/components/layout/assets/index.js +1 -1
  26. package/dist/components/layout/grammar.json +2 -2
  27. package/dist/components/selection_trial/__init__.py +1 -1
  28. package/dist/components/selection_trial/assets/collection.js +3 -3
  29. package/dist/components/selection_trial/assets/index.js +1 -1
  30. package/dist/components/tree/__init__.py +1 -1
  31. package/dist/components/tree/assets/collection.js +6 -6
  32. package/dist/components/tree/assets/index.js +1 -1
  33. package/dist/components/tree/grammar.json +0 -1
  34. package/dist/components/uploads/__init__.py +1 -1
  35. package/dist/components/uploads/assets/collection.js +3 -3
  36. package/dist/components/uploads/assets/index.js +1 -1
  37. package/dist/components/uploads/grammar.json +0 -3
  38. package/dist/gramlot.js +1238 -627
  39. package/dist/gramlot.min.js +45 -45
  40. package/dist/libraries.json +27 -0
  41. package/dist/standard-collections.js +1 -1
  42. package/package.json +4 -3
  43. package/src/binding/data-binder.js +11 -3
  44. package/src/binding/grid-struct.js +7 -4
  45. package/src/binding/runtime.js +203 -46
  46. package/src/builder/binding.json +23 -1
  47. package/src/builder/gramlot-builder.d.ts +1 -4
  48. package/src/builder/source.js +185 -29
  49. package/src/chat.js +26 -20
  50. package/src/components/attachment-manager.js +38 -34
  51. package/src/components/chart-data-view.js +4 -7
  52. package/src/components/chart-fields.js +18 -6
  53. package/src/components/chart-renderer.js +10 -3
  54. package/src/components/chart-timeline.js +7 -5
  55. package/src/components/charts.js +74 -67
  56. package/src/components/check-box-text-editor.js +3 -3
  57. package/src/components/check-box-text.js +7 -22
  58. package/src/components/check-box-tree.js +20 -16
  59. package/src/components/choice-editor.js +1 -1
  60. package/src/components/drawing.js +47 -34
  61. package/src/components/editors.js +3 -1
  62. package/src/components/grid-cell-editor.js +72 -29
  63. package/src/components/grid-column-filters.js +47 -40
  64. package/src/components/grid-formulas.js +22 -17
  65. package/src/components/grid-header-interaction.js +9 -11
  66. package/src/components/grid-row-interaction.js +25 -24
  67. package/src/components/grid-row-layout.js +28 -29
  68. package/src/components/grid-search-box.js +3 -3
  69. package/src/components/grid-search.js +3 -8
  70. package/src/components/grid-selection.js +33 -29
  71. package/src/components/grid-structure.js +48 -10
  72. package/src/components/grid-tools.js +14 -14
  73. package/src/components/grid.js +83 -79
  74. package/src/components/image-crop-dialog.js +2 -2
  75. package/src/components/image-crop.js +16 -9
  76. package/src/components/image-uploader.js +21 -28
  77. package/src/components/inputs.js +19 -1
  78. package/src/components/registry.js +3 -5
  79. package/src/components/terminal.js +158 -0
  80. package/src/components/tray-pane.js +85 -61
  81. package/src/components/tree.js +332 -239
  82. package/src/components/upload-engine.js +10 -2
  83. package/src/components/uploader.js +31 -27
  84. package/src/editing-session.d.ts +4 -1
  85. package/src/editing-session.js +120 -83
  86. package/src/experiments/window-selection.js +4 -6
  87. package/src/filesystem.js +2 -2
  88. package/src/gramlot.js +1 -0
  89. package/src/handlers/device-handler.js +219 -213
  90. package/src/handlers/rpc-handler.d.ts +17 -0
  91. package/src/handlers/rpc-handler.js +22 -0
  92. package/src/ide-documents.js +29 -11
  93. package/src/ide-runtime.js +33 -31
  94. package/src/index-page-runtime.d.ts +2 -2
  95. package/src/index-page-runtime.js +67 -48
  96. package/src/libraries.js +9 -0
  97. package/src/message-port-connection.js +100 -0
  98. package/src/message-port-store.js +158 -0
  99. package/src/page-store-connection.js +14 -1
  100. package/src/renderer/gramlot-renderer.js +21 -2
  101. package/src/source-picker.d.ts +2 -2
  102. package/src/source-picker.js +15 -6
  103. package/src/stores/bag-collection-store.js +25 -7
  104. package/src/stores/bag-collection-view.js +23 -22
  105. package/src/view/controls.js +1 -1
  106. package/src/view/html.js +45 -20
  107. package/src/visual-editor-canvas.js +1 -1
  108. package/src/visual-editor.js +18 -19
  109. package/tools/gramlot-tools-inspector.js +400 -374
  110. package/tools/inspector-agent.js +223 -49
  111. package/dist/components/vizabi/__init__.py +0 -13
  112. package/dist/components/vizabi/assets/collection.js +0 -4
  113. package/dist/components/vizabi/assets/index.js +0 -3
  114. package/dist/components/vizabi/commands.json +0 -7
  115. package/dist/components/vizabi/grammar.json +0 -128
  116. package/src/components/vizabi-session.js +0 -66
  117. package/src/components/vizabi.js +0 -66
@@ -1,5 +1,5 @@
1
1
  import {EditingSession} from '../editing-session.js';
2
- import {Bag, BagCbResolver} from '@genrojs/bag';
2
+ import {BagCbResolver} from '@genrojs/bag';
3
3
  import {SourceBag, SourceBagNode, sourceAttributeItems, wrapSource} from '@genrojs/builders';
4
4
  import {fromTytx, getSubtypeDict, setSubtypeDict, toTytx} from '@genrojs/tytx';
5
5
  import {pointerTransform, pointerDependencies} from '@genrojs/builders';
@@ -194,29 +194,45 @@ function structFormulaCode(grid) {
194
194
  return items;
195
195
  }
196
196
 
197
+ /** Source attributes of the symbolic resolution, which never reach the DOM: the metadata of a node like `_anchor`. */
198
+ export const SYMBOLIC_ATTRIBUTES = ['_workspace', '_workspace_path', 'childname'];
199
+
200
+ /** The legacy `stringHash` of a text: 32-bit `h * 31 + code` over its UTF-16 units, as a positive number. */
201
+ export function stringHash(text) {
202
+ let hash = 0;
203
+ for (let index = 0; index < text.length; index++) hash = (((hash << 5) - hash) + text.charCodeAt(index)) | 0;
204
+ return Math.abs(hash);
205
+ }
206
+
207
+ /** The nearest node of `bag` whose `childname` is `name`: direct children first, then unnamed children's descendants. */
208
+ function namedChild(bag, name) {
209
+ const nodes = bag.getNodes();
210
+ const direct = nodes.find(node => node.getAttr('childname') === name);
211
+ if (direct) return direct;
212
+ for (const node of nodes) {
213
+ if (node.getAttr('childname') != null || !(node.staticValue instanceof SourceBag)) continue;
214
+ const found = namedChild(node.staticValue, name);
215
+ if (found) return found;
216
+ }
217
+ return null;
218
+ }
219
+
197
220
  export class GramlotBuilderBagNode extends SourceBagNode {
198
221
  #formState = null;
199
- #treeStore = null;
222
+ #internal = null;
200
223
 
201
- /** An externally owned Bag attached to this tree's Source node. */
202
- get treeStore() { return this.#treeStore; }
224
+ /**
225
+ * Internal state of this node for its component or runtime (GC-225): a plain object, created on first read.
226
+ * It is not reactive, not an attribute, not Data and not serialized. It holds plain values and component helper
227
+ * instances that hold no Bag, BagNode or Source node and reach Data and structure by address; state an author may
228
+ * read or bind goes to `#WORKSPACE` in Data.
229
+ */
230
+ get _internal() { return this.#internal ??= {}; }
203
231
 
204
- setTreeStore(bag) {
205
- if (this.nodeTag !== 'tree') throw new TypeError('setTreeStore requires a tree Source node');
206
- if (bag !== null && !(bag instanceof Bag)) throw new TypeError('setTreeStore requires a Bag or null');
207
- if (bag === this.#treeStore) return;
208
- this.#treeStore = bag;
209
- const runtime = this.rootBuilder.binding;
210
- const binding = runtime?.bindingFor(this);
211
- if (binding && !binding.closed) {
212
- binding.rebind();
213
- if (runtime.renderer.attached(this)) runtime.renderer.project(this);
214
- }
215
- }
216
232
  /** The local form lifecycle owned by the nearest marked Source ancestor. */
217
233
  get formState() {
218
234
  for (let owner = this; owner; owner = owner.parentNode) {
219
- if (owner.#formState && owner._getMeta('gramlot_component')?.bagStore) return owner.#formState;
235
+ if (owner.#formState && owner._getMeta('gramlot_component')?.parameters?.storepath) return owner.#formState;
220
236
  if (owner.getAttr('formId') != null || owner.getAttr('form') === true) {
221
237
  const state = owner.#formState ??= new EditingSession(owner, this.rootBuilder.binding);
222
238
  state.rebind();
@@ -323,7 +339,7 @@ export class GramlotBuilderBagNode extends SourceBagNode {
323
339
  }
324
340
  }
325
341
  if (isExpression(this.staticValue) || this.nodeTag === 'script' && typeof this.staticValue === 'string') items.push(['', this.staticValue]);
326
- if (this._getMeta('gramlot_component')?.bagStruct) items.push(...structFormulaCode(this));
342
+ if (this._getMeta('gramlot_component')?.parameters?.structpath) items.push(...structFormulaCode(this));
327
343
  return items;
328
344
  }
329
345
 
@@ -517,10 +533,16 @@ export class GramlotBuilderBagNode extends SourceBagNode {
517
533
  };
518
534
  }
519
535
 
520
- /** Builder's absDatapath, keeping `?attr` on symbolic paths. */
521
- absDatapath(path) {
536
+ /**
537
+ * Builder's absDatapath, keeping `?attr` on symbolic paths. `row` is the row context of `#ROW`:
538
+ * the key (label) of the row inside the collection at the `storepath` of the nearest node that
539
+ * declares one; it is ignored by any other path. `#ROW` without a row context is an error.
540
+ */
541
+ absDatapath(path, {row = null} = {}) {
522
542
  path = pointerTransform(path)?.pointer ?? path;
523
543
  const bare = this.pointerType(path) ? path.slice(1) : path;
544
+ if (bare.startsWith('#') && bare.indexOf('?') !== bare.lastIndexOf('?')) throw new Error(`a symbolic path has one ?attr suffix at most: ${path}`);
545
+ if (bare === '#ROW' || bare.startsWith('#ROW.') || bare.startsWith('#ROW?')) return this.#rowDatapath(bare, row, path);
524
546
  if (bare.startsWith('#') && bare.includes('?')) {
525
547
  const [target, attr] = bare.split('?', 2);
526
548
  const resolved = super.absDatapath(target);
@@ -559,16 +581,150 @@ export class GramlotBuilderBagNode extends SourceBagNode {
559
581
  return path === null ? null : super._finalizeAbsPath(path, attr);
560
582
  }
561
583
 
562
- /** Builder's symbolic resolution; `#<nodeId>` reads the nodeId map of the page runtime when there is one (R06). */
584
+ /**
585
+ * Symbolic resolution of `#<head>[.relpath]`, in the legacy order: `#ROW`, `#WORKSPACE`,
586
+ * `#DATA`, then a start node (`#FORM`, `#ANCHOR`, `#<nodeId>`, `#/<childpath>`, each with an
587
+ * optional `/<childpath>`), from which `relpath` is resolved relatively.
588
+ */
563
589
  _resolveSymbolicDatapath(path, raw) {
564
- const symbol = path.slice(1).split('.', 1)[0];
565
- if (symbol === 'FORM' || symbol === 'ANCHOR') return super._resolveSymbolicDatapath(path, raw);
566
- const runtime = this.rootBuilder?.binding;
567
- if (!runtime) return super._resolveSymbolicDatapath(path, raw);
568
- const anchor = runtime.nodeIds.get(symbol);
569
- if (!anchor) throw new Error(`#<id>: cannot resolve ${raw}`);
570
- const relpath = path.slice(symbol.length + 2);
571
- return anchor.absDatapath(relpath ? `.${relpath}` : '.');
590
+ const symbolic = path.slice(1);
591
+ const dot = symbolic.indexOf('.');
592
+ const head = dot === -1 ? symbolic : symbolic.slice(0, dot);
593
+ const relpath = dot === -1 ? '' : symbolic.slice(dot + 1);
594
+ if (head === 'ROW') throw new Error(`#ROW: no row context for ${raw}`);
595
+ if (head === 'WORKSPACE') {
596
+ const base = this.#workspaceDatapath(raw);
597
+ return relpath ? `${base}.${relpath}` : base;
598
+ }
599
+ if (head === 'DATA') {
600
+ if (!relpath) throw new Error(`#DATA requires a path: ${raw}`);
601
+ return relpath;
602
+ }
603
+ return this.#symbolicNode(head, raw).absDatapath(relpath ? `.${relpath}` : '.');
604
+ }
605
+
606
+ /**
607
+ * The node reached by a child path from this node, as legacy `getChild`: the segments are
608
+ * separated by `/`; `parent` moves to the parent node, `#<nodeId>` (also `#FORM`, `#ANCHOR`) to the
609
+ * node of that symbol seen from the current node, any other segment to the nearest descendant whose
610
+ * `childname` is the segment (direct children first; a named node hides its descendants). Null when
611
+ * a step finds no node.
612
+ */
613
+ getChild(childpath) {
614
+ let node = this;
615
+ for (const segment of childpath.split('/')) {
616
+ if (segment === 'parent') node = node.parentNode;
617
+ else if (segment.startsWith('#')) node = node.#symbolicNode(segment.slice(1), childpath);
618
+ else {
619
+ this.#dependOn(`childname:${segment}`);
620
+ node = node.staticValue instanceof SourceBag ? namedChild(node.staticValue, segment) : null;
621
+ }
622
+ if (!node) return null;
623
+ this.#dependOn(node);
624
+ }
625
+ return node;
626
+ }
627
+
628
+ /**
629
+ * The name of the private Data area of this node: the `_workspace` string value, or for `true`
630
+ * the nodeId, else the tag followed by a hash of the node's Source path, as legacy. A node that
631
+ * declares no `_workspace` has the name it would have with `_workspace=true`.
632
+ */
633
+ get workspaceName() {
634
+ const value = this.getAttr('_workspace') ?? true;
635
+ if (value === true) return this.getAttr('nodeId') ?? `${this.nodeTag}_${stringHash(this.fullpath)}`;
636
+ if (typeof value === 'string' && value) return value;
637
+ throw new TypeError(`${this.nodeTag} '${this.label}': _workspace must be true or a name, not ${value}`);
638
+ }
639
+
640
+ /**
641
+ * The private Data area of this node, as `#WORKSPACE` sees it from the node that owns it:
642
+ * `_workspace_path` resolved from this node, else `_gramlot.workspace.<workspaceName>`. A component
643
+ * keeps its private states under the area of its own node, addressed by path.
644
+ */
645
+ get workspaceDatapath() {
646
+ const explicit = this.getAttr('_workspace_path');
647
+ return explicit == null ? `_gramlot.workspace.${this.workspaceName}` : this.absDatapath(explicit);
648
+ }
649
+
650
+ /** `#WORKSPACE`: the private Data area of the nearest node with `_workspace`. */
651
+ #workspaceDatapath(raw) {
652
+ const owner = this.attributeOwnerNode('_workspace');
653
+ if (!owner) throw new Error(`#WORKSPACE: no ancestor with _workspace for ${raw}`);
654
+ return owner.workspaceDatapath;
655
+ }
656
+
657
+ /**
658
+ * The inverse of `#ROW.<field>`: `{row, field}` when the absolute Data path `path` is a direct field of
659
+ * a row of the collection at the `storepath` of the nearest node that declares one, as `#ROW.<field>`
660
+ * gives it for that row key and `rowMode`; null for any other path.
661
+ */
662
+ rowField(path) {
663
+ const owner = this.attributeOwnerNode('storepath');
664
+ if (!owner) throw new Error(`#ROW: no ancestor with storepath for ${path}`);
665
+ const prefix = `${owner.absDatapath(owner.getAttr('storepath'))}.`;
666
+ const match = path.startsWith(prefix) ? /^([^.?]+)[.?]([^.?]+)$/.exec(path.slice(prefix.length)) : null;
667
+ if (!match) return null;
668
+ const [, row, field] = match;
669
+ return this.absDatapath(`#ROW.${field}`, {row}) === path ? {row, field} : null;
670
+ }
671
+
672
+ /** `#ROW[.field][?attr]` for the row `row` of the nearest node with `storepath`, following its `rowMode`. */
673
+ #rowDatapath(bare, row, raw) {
674
+ if (row === null) throw new Error(`#ROW: no row context for ${raw}`);
675
+ const owner = this.attributeOwnerNode('storepath');
676
+ if (!owner) throw new Error(`#ROW: no ancestor with storepath for ${raw}`);
677
+ const mode = owner.getAttr('rowMode');
678
+ if (mode !== 'values' && mode !== 'attributes') throw new Error(`#ROW: rowMode must be 'values' or 'attributes' for ${raw}`);
679
+ const rowpath = `${owner.absDatapath(owner.getAttr('storepath'))}.${row}`;
680
+ let [rest, attr = null] = bare.slice('#ROW'.length).split('?', 2);
681
+ if (mode === 'attributes' && rest) {
682
+ const field = rest.slice(1);
683
+ if (field.includes('.') || attr !== null) throw new Error(`#ROW: a row in rowMode 'attributes' has only attribute fields: ${raw}`);
684
+ return `${rowpath}?${field}`;
685
+ }
686
+ return `${rowpath}${rest}${attr === null ? '' : `?${attr}`}`;
687
+ }
688
+
689
+ /**
690
+ * The start node of a symbolic head, as legacy `nodeById`: `/<childpath>` from the nearest ancestor
691
+ * with a nodeId, through the `childname`s of the nodes in between; otherwise `<symbol>[/<childpath>]`
692
+ * where the symbol is `FORM`, `ANCHOR` or a nodeId of the page (R06: the nodeId map of the runtime).
693
+ */
694
+ #symbolicNode(head, raw) {
695
+ let node, childpath;
696
+ if (head.startsWith('/')) {
697
+ childpath = head.slice(1);
698
+ node = this;
699
+ while (node && node.getAttr('nodeId') == null) {
700
+ if (node.getAttr('childname') != null) childpath = `${node.getAttr('childname')}/${childpath}`;
701
+ node = node.parentNode;
702
+ }
703
+ if (!node) throw new Error(`#/: no ancestor with a nodeId for ${raw}`);
704
+ } else {
705
+ const slash = head.indexOf('/');
706
+ const symbol = slash === -1 ? head : head.slice(0, slash);
707
+ childpath = slash === -1 ? '' : head.slice(slash + 1);
708
+ if (symbol === 'FORM') node = this._findMarkedDatapathAncestor(true, false, raw);
709
+ else if (symbol === 'ANCHOR') node = this._findMarkedDatapathAncestor(false, true, raw);
710
+ else {
711
+ this.#dependOn(`id:${symbol}`);
712
+ const runtime = this.rootBuilder?.binding;
713
+ if (!runtime && !this.rootBuilder) throw new Error(`#<id>: cannot resolve ${raw} on a node without builder`);
714
+ node = runtime ? runtime.nodeIds.get(symbol) : this.rootBuilder.source.getNodeByAttr('nodeId', symbol);
715
+ if (!node) throw new Error(`#<id>: cannot resolve ${raw}`);
716
+ this.#dependOn(node);
717
+ }
718
+ }
719
+ if (!childpath) return node;
720
+ const child = node.getChild(childpath);
721
+ if (!child) throw new Error(`#<id>: no child '${childpath}' for ${raw}`);
722
+ return child;
723
+ }
724
+
725
+ /** Record, for the NodeBinding whose registrations are being resolved, that the resolution read `key`. */
726
+ #dependOn(key) {
727
+ this.rootBuilder?.binding?.dependOn(key);
572
728
  }
573
729
 
574
730
  /**
package/src/chat.js CHANGED
@@ -6,7 +6,6 @@ import {GramlotBuilder} from './builder/gramlot-builder.js';
6
6
  import {fromTytx, toTytx} from '@genrojs/tytx';
7
7
  import {randomId} from './random-id.js';
8
8
 
9
- const projections = new WeakMap();
10
9
  const LABEL = /^m_[a-f0-9]+$/;
11
10
 
12
11
  /** Reconcile message Source, preserving older fragments and their interactive Data. */
@@ -15,13 +14,14 @@ export function chatRender(page, node, {messages}) {
15
14
  const target = node.parentNode;
16
15
  const viewport = page.dom.getDomNode(target);
17
16
  if (!viewport) return;
18
- let state = projections.get(target);
17
+ // Rendered rows by label, as plain values on the target node (GC-225 `_internal`).
18
+ let state = target._internal.chatRows;
19
19
  if (!state) {
20
- state = {rows:new Map(), active:true}; projections.set(target,state);
20
+ state = target._internal.chatRows = {rows:{}, active:true};
21
21
  page.src.renderer.onDispose(target, () => {
22
22
  state.active=false;
23
- for (const label of state.rows.keys()) target.getRelativeData('.messageData').popNode(label);
24
- state.rows.clear(); projections.delete(target);
23
+ for (const label of Object.keys(state.rows)) target.getRelativeData('.messageData').popNode(label);
24
+ state.rows = {}; delete target._internal.chatRows;
25
25
  });
26
26
  }
27
27
  // Prepare all incoming content before changing the mounted conversation.
@@ -36,8 +36,11 @@ export function chatRender(page, node, {messages}) {
36
36
  const follow = viewport.scrollHeight-viewport.clientHeight-viewport.scrollTop < 48;
37
37
  const plans = [];
38
38
  for (const message of incoming) {
39
- const old = state.rows.get(message.label);
40
- if (old && old.value === message.staticValue && old.role === message.attr.role && old.author === message.attr.author) continue;
39
+ const old = state.rows[message.label];
40
+ // Compare by content: a message Source changed in place renders again.
41
+ const content = typeof message.staticValue === 'string' ? message.staticValue : message.staticValue.toTytx();
42
+ if (old && old.kind === typeof message.staticValue && old.content === content
43
+ && old.role === message.attr.role && old.author === message.attr.author) continue;
41
44
  const fragment = new GramlotBuilder();
42
45
  const article = fragment.root.article({node_label:message.label,
43
46
  datapath:target.absDatapath('.messageData.'+message.label),'data-role':message.attr.role,
@@ -51,20 +54,22 @@ export function chatRender(page, node, {messages}) {
51
54
  }
52
55
  const prepared = page.src.prepareSource(fragment.source);
53
56
  page.src.renderer.validateCandidate(prepared);
54
- plans.push({message,old,child:prepared.getNode(message.label)});
57
+ plans.push({message,old,content,child:prepared.getNode(message.label)});
55
58
  }
56
59
  const labels = new Set(incoming.map(message=>message.label));
57
- for (const [label] of state.rows) if (!labels.has(label)) {
60
+ for (const label of Object.keys(state.rows)) if (!labels.has(label)) {
58
61
  target.value.popNode(label);
59
62
  target.getRelativeData('.messageData').popNode(label);
60
- state.rows.delete(label);
63
+ delete state.rows[label];
61
64
  }
62
- for (const {message,old,child} of plans) {
65
+ for (const {message,old,content,child} of plans) {
66
+ // A rendered-again message keeps its place in the conversation.
67
+ const position = old ? '#'+target.value.keys().indexOf(message.label) : '>';
63
68
  if (old) target.value.popNode(message.label);
64
69
  if (!old) target.setRelativeData('.messageData.'+message.label,new Bag());
65
70
  // SourceBag insertion retains the same page renderer, bindings and Logic registry.
66
- page.src.builder.setChild(target.value,child.nodeTag,child.value,{...child.attr,node_label:message.label});
67
- state.rows.set(message.label,{value:message.staticValue,role:message.attr.role,author:message.attr.author});
71
+ page.src.builder.setChild(target.value,child.nodeTag,child.value,{...child.attr,node_label:message.label,node_position:position});
72
+ state.rows[message.label] = {kind:typeof message.staticValue,content,role:message.attr.role,author:message.attr.author};
68
73
  }
69
74
  if (follow) queueMicrotask(()=>{if(state.active) viewport.scrollTop=viewport.scrollHeight;});
70
75
  }
@@ -92,15 +97,16 @@ export function chatCompleted(page,node,{response}) {
92
97
  }
93
98
 
94
99
 
95
- const composerLayouts = new WeakMap();
100
+ // The composer layout lives on the composer body element it measures; the symbol is a constant key.
101
+ const COMPOSER_LAYOUT = Symbol('chat composer layout');
96
102
  /** Shared geometry: grow with wrapped text and content, cap the editor, release observers. */
97
103
  export function chatResize(page,node) {
98
104
  const source=node.parentNode;
99
- let layout=composerLayouts.get(source);
105
+ const body=page.dom.getDomNode(source);
106
+ // Data setters can notify before mounting; _onBuilt installs the layout.
107
+ if(!body)return;
108
+ let layout=body[COMPOSER_LAYOUT];
100
109
  if(!layout) {
101
- const body=page.dom.getDomNode(source);
102
- // Data setters can notify before mounting; _onBuilt installs the layout.
103
- if(!body)return;
104
110
  const composer=body.closest('[data-chat-composer]');
105
111
  const editor=body.querySelector('textarea');
106
112
  const top=composer.querySelector('[data-chat-top]');
@@ -121,8 +127,8 @@ export function chatResize(page,node) {
121
127
  const schedule=()=>{if(active&&!frame)frame=win.requestAnimationFrame(measure);};
122
128
  const observer=new win.ResizeObserver(schedule);
123
129
  for(const element of [body,top,toolbar]) observer.observe(element);
124
- page.src.renderer.onDispose(source,()=>{active=false;observer.disconnect();if(frame)win.cancelAnimationFrame(frame);composerLayouts.delete(source);});
125
- layout={schedule};composerLayouts.set(source,layout);
130
+ page.src.renderer.onDispose(source,()=>{active=false;observer.disconnect();if(frame)win.cancelAnimationFrame(frame);delete body[COMPOSER_LAYOUT];});
131
+ layout=body[COMPOSER_LAYOUT]={schedule};
126
132
  }
127
133
  layout.schedule();
128
134
  }
@@ -4,23 +4,26 @@ import {toTytx} from '@genrojs/tytx';
4
4
  import {defineComponent} from './registry.js';
5
5
  import {Container} from './container.js';
6
6
  import {readUploadContext} from './upload-engine.js';
7
- import {randomId} from '../random-id.js';
8
7
 
9
8
  export const AttachmentManager = defineComponent({
10
- name:'attachmentManager', tag:'gramlot-attachment-manager', base:Container, sourceContext:true, bagStore:true,
9
+ name:'attachmentManager', tag:'gramlot-attachment-manager', base:Container, sourceContext:true,
11
10
  parameters:{operation:{dtype:'T'},storepath:{dtype:'T'},contextPath:{dtype:'T'},
12
11
  ready:{dtype:'B',default:false,binding:'read'},listMethod:{dtype:'T'},readMethod:{dtype:'T'},removeMethod:{dtype:'T'},
13
12
  accept:{dtype:'T',default:'',binding:'read'},disabled:{dtype:'B',default:false,binding:'read'},
14
13
  selectedPath:{dtype:'T',nullable:true,default:null,binding:'twoWay'}},
15
14
  implementation: Base => class extends Base {
16
- #context; #store; #subscription; #generation=0; #listSequence=0; #previewSequence=0; #disposed=false; #removeToken=null;
17
- get #state() { return this.#context.sourceNode.attachmentState; }
18
- get #contextKey() { return this.#state.getItem('contextKey'); }
19
- set #contextKey(value) { this.#state.setItem('contextKey', value); }
20
- get #selected() { return this.#state.getItem('selected'); }
21
- set #selected(value) { this.#state.setItem('selected', value); }
22
- get #list() { return this.#state.getItem('items'); }
23
- set #list(value) { this.#state.setItem('items', value); }
15
+ // The router registration on the contextPath address: a change of the shared context reaches the manager by path.
16
+ #context; #contextRegistration=null; #generation=0; #listSequence=0; #previewSequence=0; #disposed=false; #removeToken=null;
17
+ /** The manager state lives in the private Data area of its node (`workspaceDatapath`), read and written by path. */
18
+ get #statePath() { return this.#context.sourceNode.workspaceDatapath; }
19
+ #state(key) { return this.#context.getStaticData(`${this.#statePath}.${key}`); }
20
+ #setState(key, value) { this.#context.sourceNode.data.setItem(`${this.#statePath}.${key}`, value); }
21
+ get #contextKey() { return this.#state('contextKey'); }
22
+ set #contextKey(value) { this.#setState('contextKey', value); }
23
+ get #selected() { return this.#state('selected'); }
24
+ set #selected(value) { this.#setState('selected', value); }
25
+ get #list() { return this.#state('items'); }
26
+ set #list(value) { this.#setState('items', value); }
24
27
  constructor() {
25
28
  super(); this.control.replaceChildren(); const doc=this.ownerDocument;
26
29
  const style=doc.createElement('style');
@@ -37,19 +40,14 @@ export const AttachmentManager = defineComponent({
37
40
  }
38
41
  setSourceContext(context) {
39
42
  this.#context=context;
40
- if (!context.sourceNode.attachmentState) {
41
- Object.defineProperty(context.sourceNode, 'attachmentState', {value:new Bag({
42
- contextKey:null, selected:null, items:new Bag(), preview:null, message:''
43
- }), configurable:true});
44
- }
45
- this.#message(this.#state.getItem('message'));
43
+ // The private area keeps the state of an earlier element of the same node (DOM relocation, rebuild).
44
+ if (!(this.#list instanceof Bag)) context.sourceNode.data.setItem(this.#statePath, new Bag({
45
+ contextKey:null, selected:null, items:new Bag(), preview:null, message:''
46
+ }));
47
+ this.#message(this.#state('message'));
46
48
  this.#renderPreview();
47
49
  this.uploader.setSourceContext({...context,callLogic:()=>this.#refresh()});
48
50
  }
49
- setStoreBag(store) {
50
- if (!(store instanceof Bag)) throw new TypeError('attachmentManager storepath must resolve to a Bag');
51
- this.#store=store; this.uploader.setStoreBag(store);
52
- }
53
51
  projectAttributes(attrs,adapt) {
54
52
  const rest=super.projectAttributes(attrs,adapt), p=this.parameters;
55
53
  for (const name of ['operation','contextPath','listMethod','readMethod','removeMethod']) {
@@ -58,28 +56,34 @@ export const AttachmentManager = defineComponent({
58
56
  this.uploader.projectAttributes({operation:p.operation,storepath:p.storepath,contextPath:p.contextPath,
59
57
  accept:p.accept,multiple:true,autoUpload:Boolean(p.ready),manualUpload:false,disabled:p.disabled,
60
58
  selectedPath:p.selectedPath,onComplete:'attachmentComplete'},adapt);
59
+ if (this.isConnected) this.#observeContext();
61
60
  this.#syncContext(); this.#render(); return rest;
62
61
  }
63
62
  connectedCallback() {
64
63
  this.#disposed=false;
65
- if (this.#context && !this.#subscription) {
66
- const {gramlot}=this.#context.upload(); this.#subscription=`attachment-manager-${randomId()}`;
67
- gramlot.data.subscribe(this.#subscription,{any:()=>this.#syncContext()});
68
- }
64
+ if (this.#context && this.parameters) this.#observeContext();
69
65
  this.#syncContext();
70
66
  }
67
+ /** Observe the shared context at the contextPath address; a new address moves the registration. */
68
+ #observeContext() {
69
+ const path=this.#context.attrDatapath('contextPath');
70
+ if (this.#contextRegistration?.path === path) return;
71
+ this.#contextRegistration?.close();
72
+ this.#contextRegistration=this.#context.sourceNode.rootBuilder.binding.router.register({path,subtree:true,
73
+ recipient:{receive:()=>this.#syncContext()}});
74
+ }
71
75
  disconnectedCallback() {
72
76
  // DOM relocation into a floating keeps the same Source owner and resources.
73
77
  this.ownerDocument.defaultView.queueMicrotask(() => {
74
78
  if (this.isConnected) return;
75
79
  this.#disposed=true; this.#generation++;
76
- if (this.#subscription) { this.#context.upload().gramlot.data.unsubscribe(this.#subscription,{any:true}); this.#subscription=null; }
80
+ this.#contextRegistration?.close(); this.#contextRegistration=null;
77
81
  });
78
82
  }
79
- #message(value) { this.#state.setItem('message',value); this.message.textContent=value; }
83
+ #message(value) { this.#setState('message',value); this.message.textContent=value; }
80
84
  #renderPreview() {
81
85
  this.preview.replaceChildren();
82
- const result=this.#state.getItem('preview');
86
+ const result=this.#state('preview');
83
87
  if (!result) return;
84
88
  if (result.getItem('kind') === 'image') {
85
89
  const image=this.ownerDocument.createElement('img'); image.src=result.getItem('src');
@@ -92,16 +96,16 @@ export const AttachmentManager = defineComponent({
92
96
  #syncContext() {
93
97
  if (!this.parameters || !this.#context || !this.isConnected || this.#disposed) return;
94
98
  if (!this.parameters.ready) {
95
- if (this.#contextKey !== null) { this.#contextKey=null; this.#generation++; this.#removeToken=null; this.#selected=null; this.#list=new Bag(); this.#state.setItem('preview',null); this.#renderPreview(); this.#render(); }
99
+ if (this.#contextKey !== null) { this.#contextKey=null; this.#generation++; this.#removeToken=null; this.#selected=null; this.#list=new Bag(); this.#setState('preview',null); this.#renderPreview(); this.#render(); }
96
100
  return;
97
101
  }
98
102
  try {
99
103
  const context=this.#value(), key=toTytx(context);
100
- if (key !== this.#contextKey) { this.#contextKey=key; this.#generation++; this.#removeToken=null; this.#selected=null; this.#list=new Bag(); this.#state.setItem('preview',null); this.#renderPreview(); this.#render(); void this.#refresh(); }
104
+ if (key !== this.#contextKey) { this.#contextKey=key; this.#generation++; this.#removeToken=null; this.#selected=null; this.#list=new Bag(); this.#setState('preview',null); this.#renderPreview(); this.#render(); void this.#refresh(); }
101
105
  } catch (error) {
102
106
  if (this.#contextKey !== null) {
103
107
  this.#contextKey=null; this.#generation++; this.#removeToken=null; this.#selected=null;
104
- this.#list=new Bag(); this.#state.setItem('preview',null); this.#renderPreview(); this.#render();
108
+ this.#list=new Bag(); this.#setState('preview',null); this.#renderPreview(); this.#render();
105
109
  }
106
110
  this.#message(error.message);
107
111
  }
@@ -115,7 +119,7 @@ export const AttachmentManager = defineComponent({
115
119
  if (!(result instanceof Bag)) throw new TypeError('Attachment list must be a Bag');
116
120
  for (const node of result.getNodes()) if (typeof node.getAttr('caption') !== 'string') throw new TypeError('Attachment caption must be text');
117
121
  this.#list=result;
118
- if (this.#selected && !this.#list.getNode(this.#selected)) { this.#selected=null; this.#previewSequence++; this.#state.setItem('preview',null); this.#renderPreview(); }
122
+ if (this.#selected && !this.#list.getNode(this.#selected)) { this.#selected=null; this.#previewSequence++; this.#setState('preview',null); this.#renderPreview(); }
119
123
  this.#message(''); this.#render();
120
124
  } catch (error) { if (generation === this.#generation && sequence === this.#listSequence && !this.#disposed) this.#message(`Attachments: ${error.message}`); }
121
125
  }
@@ -132,7 +136,7 @@ export const AttachmentManager = defineComponent({
132
136
  }
133
137
  async #read(selected) {
134
138
  if (!this.parameters.ready || this.parameters.disabled) return;
135
- this.#selected=selected; this.#render(); this.#state.setItem('preview',null); this.#renderPreview(); const generation=this.#generation, sequence=++this.#previewSequence;
139
+ this.#selected=selected; this.#render(); this.#setState('preview',null); this.#renderPreview(); const generation=this.#generation, sequence=++this.#previewSequence;
136
140
  try {
137
141
  const result=await this.#context.upload().gramlot.rpc.call('data',this.parameters.readMethod,{context:this.#value(),selected});
138
142
  if (generation !== this.#generation || sequence !== this.#previewSequence || this.#disposed) return;
@@ -140,7 +144,7 @@ export const AttachmentManager = defineComponent({
140
144
  const kind=result.getItem('kind'), text=result.getItem('text'), src=result.getItem('src');
141
145
  if (!((kind === 'image' && typeof src === 'string' && src) ||
142
146
  (['text','message'].includes(kind) && typeof text === 'string'))) throw new TypeError('Invalid attachment preview');
143
- this.#state.setItem('preview',result); this.#renderPreview();
147
+ this.#setState('preview',result); this.#renderPreview();
144
148
  this.#message('');
145
149
  } catch (error) { if (generation === this.#generation && sequence === this.#previewSequence && !this.#disposed) this.#message(`Preview: ${error.message}`); }
146
150
  }
@@ -152,7 +156,7 @@ export const AttachmentManager = defineComponent({
152
156
  const removed=await this.#context.upload().gramlot.rpc.call('data',this.parameters.removeMethod,{context:this.#value(),selected});
153
157
  if (generation !== this.#generation || this.#disposed) return;
154
158
  if (removed !== true) throw new Error('Attachment was not removed');
155
- this.#selected=null; this.#state.setItem('preview',null); this.#renderPreview(); await this.#refresh();
159
+ this.#selected=null; this.#setState('preview',null); this.#renderPreview(); await this.#refresh();
156
160
  } catch (error) { if (generation === this.#generation && !this.#disposed) this.#message(`Remove: ${error.message}`); }
157
161
  finally { if (this.#removeToken === token) { this.#removeToken=null; this.#render(); } }
158
162
  }
@@ -13,17 +13,14 @@ export class ChartDataView {
13
13
  this.#view.connect();
14
14
  }
15
15
 
16
- bindStore(store) {
17
- this.detach();
18
- this.#view.bindStore(store);
19
- }
20
-
21
16
  get view() { return this.#view; }
22
17
 
18
+ /** Follow the filter of `gridView`, a view over the same store key; following the same view again changes nothing. */
23
19
  follow(gridView) {
24
- if (gridView.bag !== this.#view.bag || gridView.rowMode !== this.#view.rowMode) {
25
- throw new TypeError('Chart and grid must use the same collection');
20
+ if (gridView.storeKey !== this.#view.storeKey) {
21
+ throw new TypeError(`Chart and grid must use the same collection: the grid reads ${gridView.storeKey}, the chart ${this.#view.storeKey}`);
26
22
  }
23
+ if (gridView === this.#gridView) return;
27
24
  this.#releaseGrid?.();
28
25
  this.#gridView = gridView;
29
26
  this.#filterSignature = undefined;
@@ -20,6 +20,19 @@ function measureAction(binding) {
20
20
  return chartLogic.get(binding);
21
21
  }
22
22
 
23
+ /**
24
+ * The rows of `store`, or null when its address holds no readable collection. Chart fields and the
25
+ * timeline derive configuration from the rows; the chart view, which reads the same address when it
26
+ * draws, shows that error in its notice.
27
+ */
28
+ export function chartRows(store) {
29
+ try { return store.getRows(); }
30
+ catch (error) {
31
+ if (error instanceof TypeError) return null;
32
+ throw error;
33
+ }
34
+ }
35
+
23
36
  /** Schema comes from the complete store, independently of any grid filter. */
24
37
  export function chartFields(store) {
25
38
  const rows = store.getRows();
@@ -34,25 +47,24 @@ export function chartFields(store) {
34
47
  }
35
48
 
36
49
  export const ChartFields = defineComponent({
37
- name:'chartFields',tag:'gramlot-chart-fields',base:Container,sourceContext:true,bagStore:true,
50
+ name:'chartFields',tag:'gramlot-chart-fields',base:Container,sourceContext:true,
38
51
  parameters:{timeFieldId:{dtype:'T'},storepath:{dtype:'T'},rowMode:{dtype:'T'},configpath:{dtype:'T'},categoryId:{dtype:'T'},mapMeasureId:{dtype:'T'},mapLabelId:{dtype:'T'},secondCategoryId:{dtype:'T'},geometryId:{dtype:'T'},measureMenuId:{dtype:'T'},measureRoleIds:{dtype:'T'}},
39
52
  implementation:Base => class extends Base {
40
- #context; #bag; #store; #release; #signature; #active=false;
53
+ #context; #store; #release; #signature; #active=false;
41
54
  constructor() { super(); const style=this.ownerDocument.createElement('style');style.textContent=':host{display:none}';this.shadowRoot.append(style); }
42
55
  setSourceContext(context) { this.#context=context; }
43
- setStoreBag(bag) { if(!(bag instanceof Bag))throw new TypeError('chartFields requires a Data Bag'); this.#bag=bag; }
44
56
  projectAttributes(attrs,adapt) { const rest=super.projectAttributes(attrs,adapt);if(this.#active)this.#connectStore();return rest; }
45
57
  connectedCallback() { this.#active=true;this.#connectStore(); }
46
58
  #connectStore() {
47
59
  const binding=this.#context.sourceNode.rootBuilder.binding;
48
- const store=binding.collectionStore(this.#bag,this.parameters.rowMode);
49
- if(store===this.#store)return;
60
+ const store=binding.collectionStore(this.#context.attrDatapath('storepath'),this.parameters.rowMode);
61
+ if(store.key===this.#store?.key)return;
50
62
  this.#release?.();this.#store=store;this.#signature=undefined;
51
63
  this.#release=store.subscribe(()=>this.#sync(store));
52
64
  this.#sync(store);
53
65
  }
54
66
  #sync(store) {
55
- if(!store.getRows().length)return;
67
+ if(!chartRows(store)?.length)return;
56
68
  const {fields,measures,dates}=chartFields(store);
57
69
  const signature=JSON.stringify([fields,measures,dates]);
58
70
  if(signature===this.#signature)return;
@@ -3,7 +3,7 @@ import {chartType} from './chart-types/index.js';
3
3
  import {requireChartCapability} from './chart-engines/index.js';
4
4
  import {checkChartSyntax} from './chart-syntax.js';
5
5
 
6
- /** Engine-independent context. Reading it never rewrites either Data Bag. */
6
+ /** Engine-independent context of one draw, built from values read at the draw. Reading it never rewrites Data. */
7
7
  export function chartContext(view,structure,seriesOptions) {
8
8
  if (!(seriesOptions instanceof Bag)) throw new TypeError('seriesOptions requires a Bag');
9
9
  const type = chartType(structure.getItem('chartType'));
@@ -27,9 +27,16 @@ export class ChartRenderer {
27
27
  constructor(element,view,options={}) { this.#element=element;this.#view=view;this.#options=options; }
28
28
  async prepare(engine,type) { await requireChartCapability(engine,type).load(type,this.#element.ownerDocument); }
29
29
  invalidate() { this.#revision++; }
30
- update(structure,seriesOptions) {
30
+ /**
31
+ * Draw. `structure` holds the parameter values of this draw; `seriesOptions` is the address of the
32
+ * options Bag in Data, `{data, path}` with `data` the page's Data root. The options are read here,
33
+ * without resolvers, where the context goes to the adapter that hands the values to the engine;
34
+ * nothing keeps the Bag after the draw.
35
+ */
36
+ update(structure,{data,path}) {
37
+ if (typeof path !== 'string' || !path) throw new TypeError(`seriesOptions requires a Data path: ${path}`);
31
38
  const engine=structure.getItem('engine') ?? 'echarts';
32
- const context=chartContext(this.#view,structure,seriesOptions);
39
+ const context=chartContext(this.#view,structure,data.getItem(path,null,true));
33
40
  context.domains=this.#options.domains ? this.#options.domains(context) : null;
34
41
  const Adapter=requireChartCapability(engine,context.type.id);
35
42
  const revision=++this.#revision;