@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
@@ -4,7 +4,7 @@ import layout from "@gramlot/collections/layout";
4
4
  import tree from "@gramlot/collections/tree";
5
5
 
6
6
  // ../tools/gramlot-tools-inspector/src/inspector-bridge.js
7
- import { Bag } from "@gramlot/gramlot";
7
+ import { Bag, fromTytx, toTytx } from "@gramlot/gramlot";
8
8
 
9
9
  // src/editor-values.js
10
10
  var editorTypes = ["string", "number", "integer", "boolean", "date", "time", "datetime", "null"];
@@ -55,6 +55,166 @@ function readParameterEnums(node) {
55
55
  return Object.fromEntries(Object.entries(node._getMeta("gramlot_component")?.parameters ?? {}).filter(([, spec]) => spec.enum).map(([name, spec]) => [name, spec.enum]));
56
56
  }
57
57
 
58
+ // src/message-port-store.js
59
+ var PATH = /^[^.?#\[\]!:]+(?:\.[^.?#\[\]!:]+)*$/;
60
+ var OPERATIONS = /* @__PURE__ */ new Set(["subscribe", "unsubscribe", "change"]);
61
+ var nextStore = 0;
62
+ function intersects(left, right) {
63
+ return left === right || left.startsWith(right + ".") || right.startsWith(left + ".");
64
+ }
65
+ var MessagePortStore = class {
66
+ #subscribers = /* @__PURE__ */ new Map();
67
+ #changes = [];
68
+ #dispatching = false;
69
+ #subscription;
70
+ #receive;
71
+ /**
72
+ * `bag` is the served root; `receive(message)` gets the decoded messages that are not
73
+ * `subscribe`, `unsubscribe` or `change`, for the owner of the port.
74
+ */
75
+ constructor(bag, port, receive = null) {
76
+ this.bag = bag;
77
+ this.port = port;
78
+ this.closed = false;
79
+ this.#receive = receive;
80
+ this.#subscription = `gramlot-message-port-store-${++nextStore}`;
81
+ bag.subscribe(this.#subscription, { any: (event) => this.#changed(event) });
82
+ port.addEventListener("message", this.#listener);
83
+ port.start();
84
+ }
85
+ /** Send one message to the other end as the TYTX text of a Bag of its fields. */
86
+ post(message) {
87
+ if (this.closed) return;
88
+ const wire = new this.bag.constructor();
89
+ for (const [name, value] of Object.entries(message)) {
90
+ if (value !== void 0) wire.setItem(name, value);
91
+ }
92
+ this.port.postMessage(wire.toTytx("json"));
93
+ }
94
+ #listener = (event) => {
95
+ if (this.closed) return;
96
+ const message = this.bag.constructor.fromTytx(event.data, "json").asDict();
97
+ if (!OPERATIONS.has(message.op)) {
98
+ this.#receive?.(message);
99
+ return;
100
+ }
101
+ try {
102
+ if (message.op === "subscribe") this.subscribe(message.binderId, message.path);
103
+ else if (message.op === "unsubscribe") this.unsubscribe(message.binderId);
104
+ else this.change(message.binderId, message);
105
+ } catch (error) {
106
+ this.post({ op: "error", binderId: message.binderId, error: error.message });
107
+ }
108
+ };
109
+ /** Register a binder and send its snapshot before any later change. */
110
+ subscribe(binderId, path) {
111
+ if (typeof binderId !== "string" || !binderId) throw new TypeError("A binder requires an id");
112
+ if (typeof path !== "string" || !PATH.test(path)) throw new TypeError("A store path must contain dot-separated literal labels");
113
+ if (this.#subscribers.has(binderId)) throw new Error("Binder is already registered");
114
+ this.#subscribers.set(binderId, path);
115
+ const node = this.bag.getNode(path);
116
+ this.post({
117
+ op: "snapshot",
118
+ binderId,
119
+ path: "",
120
+ exists: node !== null,
121
+ value: node ? this.#copy(node.getValue(true)) : null,
122
+ attr: node ? { ...node.getAttr() } : {}
123
+ });
124
+ }
125
+ unsubscribe(binderId) {
126
+ this.#subscribers.delete(binderId);
127
+ }
128
+ /** Apply a change of a binder inside its branch; the dispatch skips that binder. */
129
+ change(binderId, message) {
130
+ const base = this.#subscribers.get(binderId);
131
+ if (base === void 0) throw new Error("Binder is not registered");
132
+ const relative = message.path;
133
+ if (typeof relative !== "string" || relative !== "" && !PATH.test(relative)) {
134
+ throw new TypeError("A change path must contain dot-separated literal labels");
135
+ }
136
+ if (message.fired) throw new Error("Fired events are outside the dataBinder protocol");
137
+ const path = relative ? base + "." + relative : base;
138
+ if (message.evt === "del") this.bag.popNode(path, binderId);
139
+ else if (message.evt === "upd_attrs") {
140
+ const node = this.bag.getNode(path);
141
+ if (!node) throw new Error("Attribute target does not exist");
142
+ node.setAttr(message.attr, binderId, false, false);
143
+ } else if (["ins", "upd_value", "upd"].includes(message.evt)) {
144
+ this.bag.setItem(path, message.value, message.attr, message.index ?? ">", false, false, binderId);
145
+ } else throw new Error("Unsupported datachange event");
146
+ }
147
+ /** A static copy: resolvers are never run, a resolver node travels with its cached value. */
148
+ #copy(value) {
149
+ if (!(value instanceof this.bag.constructor)) return value;
150
+ const copy = new this.bag.constructor();
151
+ for (const node of value.getNodes()) {
152
+ copy.setItem(node.label, this.#copy(node.getValue(true)), { ...node.getAttr() }, ">", false, false);
153
+ }
154
+ return copy;
155
+ }
156
+ #changed(event) {
157
+ if (event.reason === "autocreate") return;
158
+ const structural = event.evt === "ins" || event.evt === "del";
159
+ const pathlist = event.pathlist ?? [];
160
+ for (const node of Array.isArray(event.node) ? event.node : [event.node]) {
161
+ this.#changes.push({
162
+ path: (structural ? [...pathlist, node.label] : pathlist).join("."),
163
+ evt: event.evt,
164
+ origin: event.reason,
165
+ index: event.ind ?? null,
166
+ value: event.evt === "del" ? null : this.#copy(node.getValue(true)),
167
+ attr: { ...node.getAttr() }
168
+ });
169
+ }
170
+ if (this.#dispatching) return;
171
+ this.#dispatching = true;
172
+ try {
173
+ while (this.#changes.length) this.#dispatch(this.#changes.shift());
174
+ } finally {
175
+ this.#dispatching = false;
176
+ }
177
+ }
178
+ #dispatch({ path, evt, origin, index, value, attr }) {
179
+ for (const [binderId, base] of [...this.#subscribers]) {
180
+ if (binderId === origin || !intersects(path, base)) continue;
181
+ if (path === base || path.startsWith(base + ".")) {
182
+ this.post({
183
+ op: "change",
184
+ binderId,
185
+ path: path === base ? "" : path.slice(base.length + 1),
186
+ evt,
187
+ value,
188
+ attr,
189
+ index
190
+ });
191
+ } else {
192
+ if (evt === "upd_attrs") continue;
193
+ const child = evt !== "del" && value instanceof this.bag.constructor ? value.getNode(base.slice(path.length + 1)) : null;
194
+ this.post({
195
+ op: "change",
196
+ binderId,
197
+ path: "",
198
+ evt: child ? "upd_value" : "del",
199
+ value: child ? child.getValue(true) : null,
200
+ attr: child ? { ...child.getAttr() } : {},
201
+ index: null
202
+ });
203
+ }
204
+ }
205
+ }
206
+ /** Tell the other end that the store is closed, then release the Bag and the port listener. */
207
+ close() {
208
+ if (this.closed) return;
209
+ this.post({ op: "closed" });
210
+ this.closed = true;
211
+ this.bag.unsubscribe(this.#subscription, { any: true });
212
+ this.port.removeEventListener("message", this.#listener);
213
+ this.#subscribers.clear();
214
+ this.#changes = [];
215
+ }
216
+ };
217
+
58
218
  // ../tools/gramlot-tools-inspector/src/inspector-history.js
59
219
  var InspectorHistory = class {
60
220
  #undo = [];
@@ -346,25 +506,15 @@ var InspectorStyles = class {
346
506
 
347
507
  // ../tools/gramlot-tools-inspector/src/inspector-agent.js
348
508
  var roots = ["data", "source"];
349
- var forbidden = /* @__PURE__ */ new Set(["_meta", "__proto__", "prototype", "constructor"]);
509
+ var forbidden = /* @__PURE__ */ new Set(["_meta", "_inspector", "__proto__", "prototype", "constructor"]);
350
510
  function attachInspectorAgent(gramlot, port) {
351
511
  if (!gramlot || gramlot.state === "disposed") throw new TypeError("Expected a live Gramlot instance");
352
512
  const Bag3 = gramlot.data.constructor;
353
- const encodeScalar2 = (value) => {
354
- const wrapper = new Bag3();
355
- wrapper.setItem("value", value);
356
- return wrapper.toTytx("json");
357
- };
358
- const decodeScalar2 = (text) => {
359
- const value = Bag3.fromTytx(text, "json").getItem("value");
513
+ const checkScalar = (value) => {
360
514
  if (!scalarType(value)) throw new TypeError("The inspector edits scalar values only");
361
515
  return value;
362
516
  };
363
- function cell(value) {
364
- if (scalarType(value)) return { encoded: encodeScalar2(value) };
365
- const display = value instanceof Bag3 ? `Bag (${value.getNodes().length} nodes)` : value === void 0 ? "undefined" : typeof value === "function" ? "[Function]" : typeof value === "bigint" || typeof value === "symbol" ? String(value) : JSON.stringify(value);
366
- return { display, readonly: true };
367
- }
517
+ const display = (value) => value instanceof Bag3 ? `Bag (${value.getNodes().length} nodes)` : value === void 0 ? "undefined" : typeof value === "function" ? "[Function]" : typeof value === "bigint" || typeof value === "symbol" ? String(value) : JSON.stringify(value);
368
518
  const document = gramlot.src.renderer.destination.ownerDocument;
369
519
  const window = document.defaultView;
370
520
  const styles = new InspectorStyles(document);
@@ -382,32 +532,57 @@ function attachInspectorAgent(gramlot, port) {
382
532
  if (!identities.has(node)) identities.set(node, ++nextNode);
383
533
  return identities.get(node);
384
534
  };
385
- const describe = (store, root, ancestors = /* @__PURE__ */ new Set()) => {
386
- if (ancestors.has(store)) throw new Error("Inspector snapshots require an acyclic Bag");
387
- const next = /* @__PURE__ */ new Set([...ancestors, store]);
388
- return store.getNodes().map((node) => {
535
+ const projection = new Bag3();
536
+ for (const root of roots) projection.setItem(root, new Bag3());
537
+ const sameAttrs = (left, right) => {
538
+ const names = Object.keys(right);
539
+ return Object.keys(left).length === names.length && names.every((name) => name === "_inspector" ? JSON.stringify(left[name]) === JSON.stringify(right[name]) : Object.hasOwn(left, name) && Object.is(left[name], right[name]));
540
+ };
541
+ const reconcile = (copy, target, root, ancestors = /* @__PURE__ */ new Set()) => {
542
+ if (ancestors.has(target)) throw new Error("Inspector snapshots require an acyclic Bag");
543
+ const next = /* @__PURE__ */ new Set([...ancestors, target]);
544
+ const nodes = target.getNodes();
545
+ const labels = new Set(nodes.map((node) => node.label));
546
+ for (const node of copy.getNodes()) if (!labels.has(node.label)) copy.popNode(node.label);
547
+ for (const [index, node] of nodes.entries()) {
389
548
  const value = node.getValue(true);
390
549
  const branch = !node.resolver && value instanceof Bag3;
391
- return {
550
+ const attrs = {}, readonlyAttrs = [];
551
+ for (const [name, item2] of Object.entries(node.getAttr())) {
552
+ if (name === "_meta" || name === "_inspector") continue;
553
+ if (scalarType(item2)) attrs[name] = item2;
554
+ else {
555
+ attrs[name] = display(item2);
556
+ readonlyAttrs.push(name);
557
+ }
558
+ }
559
+ const scalar = branch ? null : scalarType(value) ? value : display(value);
560
+ attrs._inspector = {
392
561
  id: identity(node),
393
- label: node.label,
394
562
  revision: versions.get(node) ?? 0,
395
- value: branch ? null : cell(value),
396
- children: branch ? describe(value, root, next) : null,
397
- readonly: !!node.resolver,
398
- parameterEnums: root === "source" ? readParameterEnums(node) : {},
399
- attrs: Object.entries(node.getAttr()).filter(([name]) => name !== "_meta").map(([name, value2]) => [name, cell(value2)])
563
+ readonly: !!node.resolver || !branch && !scalarType(value),
564
+ readonlyAttrs,
565
+ parameterEnums: root === "source" ? readParameterEnums(node) : {}
400
566
  };
401
- });
567
+ let item = copy.getNode(node.label);
568
+ if (item && item.getAttr("_inspector")?.id !== attrs._inspector.id) {
569
+ copy.popNode(node.label);
570
+ item = null;
571
+ }
572
+ if (!item) item = copy.setItem(node.label, branch ? new Bag3() : scalar, attrs, index, false, false);
573
+ else {
574
+ const copied = item.getValue(true);
575
+ if (branch ? !(copied instanceof Bag3) : !Object.is(copied, scalar)) item.setValue(branch ? new Bag3() : scalar);
576
+ if (!sameAttrs(item.getAttr(), attrs)) item.setAttr(attrs, true, false, false);
577
+ const position = copy.getNodes().indexOf(item);
578
+ if (position !== index) copy.move(position, index);
579
+ }
580
+ if (branch) reconcile(item.getValue(true), value, root, next);
581
+ }
402
582
  };
403
- const snapshot = () => ({
404
- data: describe(bag("data"), "data"),
405
- source: describe(bag("source"), "source"),
406
- breakpoints: [...breakpoints.values()].map(({ test, ...record }) => record),
407
- history: history.state
408
- });
409
- const send = (data) => {
410
- if (!stopped) port.postMessage(data);
583
+ const update = () => {
584
+ for (const root of roots) reconcile(projection.getItem(root), bag(root), root);
585
+ store.post({ type: "state", breakpoints: [...breakpoints.values()].map(({ test, ...record }) => record), history: history.state });
411
586
  };
412
587
  const flush = () => {
413
588
  if (scheduled || stopped) return;
@@ -416,9 +591,9 @@ function attachInspectorAgent(gramlot, port) {
416
591
  scheduled = false;
417
592
  if (stopped) return;
418
593
  try {
419
- send({ type: "snapshot", snapshot: snapshot() });
594
+ update();
420
595
  } catch (error) {
421
- send({ type: "error", error: error.message });
596
+ store.post({ type: "error", error: error.message });
422
597
  }
423
598
  });
424
599
  };
@@ -468,14 +643,14 @@ function attachInspectorAgent(gramlot, port) {
468
643
  if (forbidden.has(name) || !Object.hasOwn(attrs, name) || !scalarType(attrs[name])) throw new Error(`Cannot remove attribute: ${name}`);
469
644
  delete attrs[name];
470
645
  }
471
- for (const [name, encoded] of command.set) {
646
+ for (const [name, value2] of command.set) {
472
647
  if (!name.trim() || forbidden.has(name) || Object.hasOwn(attrs, name) && !scalarType(attrs[name])) throw new Error(`Cannot edit attribute: ${name}`);
473
- attrs[name] = decodeScalar2(encoded);
648
+ attrs[name] = checkScalar(value2);
474
649
  }
475
650
  let value;
476
651
  if (Object.hasOwn(command, "value")) {
477
652
  if (node.resolver || !scalarType(node.getValue(true))) throw new Error("This value is read-only");
478
- value = decodeScalar2(command.value);
653
+ value = checkScalar(command.value);
479
654
  }
480
655
  history.edit(node, attrs, value, !!(command.set.length || command.remove.length), Object.hasOwn(command, "value"));
481
656
  };
@@ -488,8 +663,7 @@ function attachInspectorAgent(gramlot, port) {
488
663
  if (command.mode) breakpoints.set(key, { root: command.root, path: command.path, mode: command.mode, condition, hits: 0, error: "", test });
489
664
  else breakpoints.delete(key);
490
665
  };
491
- const receive = (event) => {
492
- const message = event.data;
666
+ const receive = (message) => {
493
667
  if (message.type === "disconnect") {
494
668
  dispose();
495
669
  return;
@@ -500,12 +674,12 @@ function attachInspectorAgent(gramlot, port) {
500
674
  if (message.type === "setStyle") styles.set(message.command.name, message.command.value);
501
675
  if (message.type === "resetStyle") styles.reset(message.command.name);
502
676
  if (message.type === "resetStyles") styles.dispose();
503
- send({ type: "result", id: message.id, ok: true, styles: styles.snapshot() });
677
+ store.post({ type: "result", id: message.id, ok: true, styles: styles.snapshot() });
504
678
  return;
505
679
  }
506
680
  let selection;
507
681
  if (message.type === "catalog") {
508
- send({ type: "result", id: message.id, ok: true, catalog: history.catalog(message.command.path) });
682
+ store.post({ type: "result", id: message.id, ok: true, catalog: history.catalog(message.command.path) });
509
683
  return;
510
684
  }
511
685
  if (["insert", "remove", "move"].includes(message.type)) {
@@ -523,53 +697,43 @@ function attachInspectorAgent(gramlot, port) {
523
697
  else if (message.type === "edit") edit(message.command);
524
698
  else if (message.type === "breakpoint") setBreakpoint(message.command);
525
699
  else if (message.type !== "refresh") throw new Error(`Unknown inspector command: ${message.type}`);
526
- send({ type: "result", id: message.id, ok: true, selection, snapshot: snapshot() });
700
+ update();
701
+ store.post({ type: "result", id: message.id, ok: true, selection });
527
702
  } catch (error) {
528
- send({ type: "result", id: message.id, ok: false, error: error.message });
703
+ store.post({ type: "result", id: message.id, ok: false, error: error.message });
529
704
  }
530
705
  };
531
706
  function dispose() {
532
707
  if (stopped) return;
533
- send({ type: "closed" });
534
708
  stopped = true;
709
+ store.close();
535
710
  for (const root of roots) bag(root).unsubscribe(subscriber, { any: true });
536
711
  breakpoints.clear();
537
712
  history.clear();
538
713
  styles.dispose();
539
- port.removeEventListener("message", receive);
540
714
  window.removeEventListener("pagehide", dispose);
541
715
  port.close();
542
716
  }
717
+ for (const root of roots) reconcile(projection.getItem(root), bag(root), root);
718
+ const store = new MessagePortStore(projection, port, receive);
543
719
  for (const root of roots) bag(root).subscribe(subscriber, { any: (event) => changed(root, event) });
544
- port.addEventListener("message", receive);
545
720
  window.addEventListener("pagehide", dispose);
546
- port.start();
547
- flush();
721
+ store.post({ type: "state", breakpoints: [], history: history.state });
548
722
  return { dispose };
549
723
  }
550
724
 
551
725
  // ../tools/gramlot-tools-inspector/src/inspector-bridge.js
552
- var roots2 = ["data", "source"];
553
- function encodeScalar(value) {
554
- if (!scalarType(value)) throw new TypeError("The inspector edits scalar values only");
555
- const wrapper = new Bag();
556
- wrapper.setItem("value", value);
557
- return wrapper.toTytx("json");
558
- }
559
- function decodeScalar(text) {
560
- const value = Bag.fromTytx(text, "json").getItem("value");
561
- if (!scalarType(value)) throw new TypeError("The inspector edits scalar values only");
562
- return value;
726
+ function messageText(message) {
727
+ const wire = new Bag();
728
+ for (const [name, value] of Object.entries(message)) wire.setItem(name, value);
729
+ return toTytx(wire);
563
730
  }
564
731
  var InspectorConnection = class {
565
- data = new Bag();
566
- source = new Bag();
567
732
  state = "connecting";
568
733
  error = "";
569
734
  breakpoints = [];
570
735
  styles = null;
571
736
  history = { undo: "", redo: "" };
572
- #info = /* @__PURE__ */ new WeakMap();
573
737
  #listeners = /* @__PURE__ */ new Set();
574
738
  #pending = /* @__PURE__ */ new Map();
575
739
  #next = 0;
@@ -579,8 +743,9 @@ var InspectorConnection = class {
579
743
  port.addEventListener("message", this.#receive);
580
744
  port.start();
581
745
  }
582
- nodeInfo(node) {
583
- return this.#info.get(node);
746
+ /** The port of the inspected page, shared with the panel's dataBinder connection. */
747
+ get port() {
748
+ return this.#port;
584
749
  }
585
750
  subscribe(callback) {
586
751
  this.#listeners.add(callback);
@@ -590,23 +755,20 @@ var InspectorConnection = class {
590
755
  for (const callback of this.#listeners) callback();
591
756
  }
592
757
  #receive = (event) => {
593
- const message = event.data;
594
- if (message.type === "closed") {
758
+ if (this.state === "disposed") return;
759
+ const message = fromTytx(event.data).asDict();
760
+ if (message.op === "closed") {
595
761
  this.close();
596
762
  return;
597
763
  }
598
- try {
599
- if (message.styles) this.styles = message.styles;
600
- if (message.snapshot) {
601
- for (const root of roots2) this.#reconcile(this[root], message.snapshot[root]);
602
- this.breakpoints = message.snapshot.breakpoints;
603
- this.history = message.snapshot.history;
604
- this.state = "started";
605
- this.error = "";
606
- } else if (message.type === "error") this.error = message.error;
607
- } catch (error) {
608
- this.error = error.message;
609
- }
764
+ if (message.op) return;
765
+ if (message.styles) this.styles = message.styles;
766
+ if (message.type === "state") {
767
+ this.breakpoints = message.breakpoints;
768
+ this.history = message.history;
769
+ this.state = "started";
770
+ this.error = "";
771
+ } else if (message.type === "error") this.error = message.error;
610
772
  if (message.type === "result") {
611
773
  const pending = this.#pending.get(message.id);
612
774
  if (pending) {
@@ -617,55 +779,17 @@ var InspectorConnection = class {
617
779
  }
618
780
  this.#notify();
619
781
  };
620
- #reconcile(store, rows) {
621
- const labels = new Set(rows.map((row) => row.label));
622
- for (const node of store.getNodes()) if (!labels.has(node.label)) store.popNode(node.label);
623
- for (const [index, row] of rows.entries()) {
624
- let node = store.getNode(row.label);
625
- let previous = node ? this.#info.get(node) : null;
626
- if (node && previous?.id !== row.id) {
627
- store.popNode(row.label);
628
- node = null;
629
- previous = null;
630
- }
631
- const branch = row.children !== null;
632
- const read = (descriptor) => descriptor.readonly ? descriptor.display : decodeScalar(descriptor.encoded);
633
- const value = branch ? previous?.branch ? node.getValue(true) : new Bag() : previous?.valueWire === JSON.stringify(row.value) ? node.getValue(true) : read(row.value);
634
- const attrs = {};
635
- for (const [name, descriptor] of row.attrs) {
636
- attrs[name] = previous?.attrsWire.get(name) === JSON.stringify(descriptor) ? node.getAttr(name) : read(descriptor);
637
- }
638
- if (!node) node = store.setItem(row.label, value, null, ">", false, false);
639
- else if (!Object.is(node.getValue(true), value)) node.setValue(value);
640
- if (!previous || previous.attrsWire.size !== row.attrs.length || row.attrs.some(([name, descriptor]) => previous.attrsWire.get(name) !== JSON.stringify(descriptor))) {
641
- node.setAttr(attrs, true, false, false);
642
- }
643
- this.#info.set(node, {
644
- id: row.id,
645
- revision: row.revision,
646
- branch,
647
- parameterEnums: row.parameterEnums,
648
- readonly: row.readonly || !!row.value?.readonly,
649
- readonlyAttrs: new Set(row.attrs.filter(([, descriptor]) => descriptor.readonly).map(([name]) => name)),
650
- valueWire: JSON.stringify(row.value),
651
- attrsWire: new Map(row.attrs.map(([name, descriptor]) => [name, JSON.stringify(descriptor)]))
652
- });
653
- if (branch) this.#reconcile(value, row.children);
654
- const position = store.getNodes().indexOf(node);
655
- if (position !== index) store.move(position, index);
656
- }
657
- }
658
782
  request(type, command = {}) {
659
783
  if (this.state === "disposed") return Promise.reject(new Error("Inspected page disconnected"));
660
784
  const id = ++this.#next;
661
785
  return new Promise((resolve, reject) => {
662
786
  this.#pending.set(id, { resolve, reject });
663
- this.#port.postMessage({ type, command, id });
787
+ this.#port.postMessage(messageText({ type, command, id }));
664
788
  });
665
789
  }
666
790
  close() {
667
791
  if (this.state === "disposed") return;
668
- this.#port.postMessage({ type: "disconnect" });
792
+ this.#port.postMessage(messageText({ type: "disconnect" }));
669
793
  this.#port.removeEventListener("message", this.#receive);
670
794
  this.#port.close();
671
795
  this.state = "disposed";
@@ -688,7 +812,8 @@ var GramlotToolsInspector = class extends HTMLElement {
688
812
  }
689
813
  }
690
814
  #target = null;
691
- #history = null;
815
+ // The agent and connection of a local target, on a MessageChannel of this palette.
816
+ #local = null;
692
817
  #insertTarget = null;
693
818
  #catalog = [];
694
819
  #connection = null;
@@ -698,19 +823,16 @@ var GramlotToolsInspector = class extends HTMLElement {
698
823
  #ui = null;
699
824
  #mount;
700
825
  #subscriber = `gramlot-tools-inspector-${++nextId}`;
701
- #subscriptions = [];
826
+ // Paths and agent identities of the copied nodes; the copies live in this palette's Data at `target`.
702
827
  #nodes = [];
703
- #nodeIds = /* @__PURE__ */ new WeakMap();
704
- #nextNodeId = 0;
828
+ #copies = null;
829
+ #applyAgain = null;
705
830
  #pending = false;
706
831
  #generation = 0;
707
832
  #snapshot = null;
708
833
  #nextRow = 0;
709
- #nextBreakpoint = 0;
710
- #breakpointTests = /* @__PURE__ */ new Map();
711
834
  #trees = {};
712
835
  #breakpointTarget = null;
713
- #styles = null;
714
836
  #styleNames = "";
715
837
  #styleRequest = 0;
716
838
  #styleDownloadUrl = null;
@@ -733,7 +855,6 @@ var GramlotToolsInspector = class extends HTMLElement {
733
855
  this.#target = value;
734
856
  this.#snapshot = null;
735
857
  this.#breakpointTarget = null;
736
- this.#breakpointTests.clear();
737
858
  if (this.#ui) {
738
859
  this.#renderTargets();
739
860
  this.#dialog().close();
@@ -780,7 +901,6 @@ var GramlotToolsInspector = class extends HTMLElement {
780
901
  this.#connection = entry.connection;
781
902
  this.#snapshot = null;
782
903
  this.#breakpointTarget = null;
783
- this.#breakpointTests.clear();
784
904
  if (this.#ui) {
785
905
  this.#dialog().close();
786
906
  this.#dialog("breakpoints").close();
@@ -802,10 +922,15 @@ var GramlotToolsInspector = class extends HTMLElement {
802
922
  this.#ui.data.setItem("targetId", this.#selectedTarget ?? this.#targets[0]?.id ?? "");
803
923
  }
804
924
  #state() {
805
- return (this.#connection ?? this.#target)?.state;
925
+ return this.#connection?.state;
806
926
  }
807
- #targetBag(root) {
808
- return this.#connection ? this.#connection[root] : root === "data" ? this.#target.data : this.#target.src.source;
927
+ /** The copied node at `path` of `root`, read from this palette's Data for the current call only. */
928
+ #copyNode(root, path) {
929
+ return this.#ui.data.getNode(`target.${root}.${path}`);
930
+ }
931
+ /** The agent's identity, revision and edit limits of the copied node at `path` of `root`. */
932
+ #info(root, path) {
933
+ return this.#copyNode(root, path)?.getAttr("_inspector") ?? null;
809
934
  }
810
935
  connectedCallback() {
811
936
  if (this.#ui) return;
@@ -1072,19 +1197,11 @@ var GramlotToolsInspector = class extends HTMLElement {
1072
1197
  inspector.#dialog("breakpoints").close();
1073
1198
  }
1074
1199
  removeBreakpoint(node) {
1075
- const id = node.getAttr("data-breakpoint");
1076
- if (inspector.#connection) {
1077
- const config = ui.data.getItem(`breakpoints.${id}`);
1078
- inspector.#connection.request("breakpoint", { root: config.getItem("root"), path: config.getItem("path"), mode: "", condition: "" }).then(() => {
1079
- inspector.#refresh();
1080
- inspector.#renderBreakpoints();
1081
- }).catch((error) => ui.data.setItem("breakpointError", error.message));
1082
- return;
1083
- }
1084
- ui.data.getItem("breakpoints").popNode(id);
1085
- inspector.#breakpointTests.delete(id);
1086
- inspector.#renderBreakpoints();
1087
- inspector.#refresh();
1200
+ const config = ui.data.getItem(`breakpoints.${node.getAttr("data-breakpoint")}`);
1201
+ inspector.#connection?.request("breakpoint", { root: config.getItem("root"), path: config.getItem("path"), mode: "", condition: "" }).then(() => {
1202
+ inspector.#refresh();
1203
+ inspector.#renderBreakpoints();
1204
+ }).catch((error) => ui.data.setItem("breakpointError", error.message));
1088
1205
  }
1089
1206
  }
1090
1207
  ui.src.logicRegistry.register(Logic, { group: "inspector", resource: "gramlot-tools-inspector" });
@@ -1117,7 +1234,7 @@ var GramlotToolsInspector = class extends HTMLElement {
1117
1234
  ui.data.setItem("insert", new Bag2({ kind: "html", tag: "", html: true, component: false, status: "" }));
1118
1235
  ui.data.setItem("editor", new Bag2({ dirty: false, disabled: true, status: "", mode: "", condition: "" }));
1119
1236
  ui.data.setItem("breakpoints", new Bag2());
1120
- ui.data.setItem("emptyTree", new Bag2());
1237
+ ui.data.setItem("target", new Bag2({ data: new Bag2(), source: new Bag2() }));
1121
1238
  ui.data.setItem("treeSelection", new Bag2({ data: null, source: null }));
1122
1239
  ui.data.setItem("breakpointDirty", false);
1123
1240
  ui.data.setItem("styles", new Bag2({ status: "", busy: false, noChanges: true, noDownload: true, downloadUrl: null, rows: new Bag2() }));
@@ -1138,6 +1255,7 @@ var GramlotToolsInspector = class extends HTMLElement {
1138
1255
  });
1139
1256
  const palette = window.frame.center.section({ node_label: "palette", class: "embedded-panel", "aria-label": "Gramlot inspector", connect_onkeydown: "inspector.historyKey" });
1140
1257
  root.dataController({ func: "inspector.close", open: "^inspectorOpen" });
1258
+ for (const name of ["data", "source"]) root.dataBinder({ destination_path: `target.${name}`, server_path: name, connection: "target" });
1141
1259
  const targetbar = palette.div({ node_label: "targetbar", class: "targetbar", hidden: "^singleTarget" });
1142
1260
  targetbar.select({ node_label: "targets", value: "^targetId", disabled: "^busy", "aria-label": "Inspected page", connect_onchange: "inspector.selectTarget" });
1143
1261
  const toolbar = palette.tabContainer({ node_label: "tabs", class: "inspector-tabs", tabMode: "underline", selectedPage: "^requestedTab" });
@@ -1162,7 +1280,7 @@ var GramlotToolsInspector = class extends HTMLElement {
1162
1280
  const sourceTree = trees.tree({
1163
1281
  node_label: name,
1164
1282
  "data-root": name,
1165
- storepath: "emptyTree",
1283
+ storepath: `target.${name}`,
1166
1284
  hideValues: true,
1167
1285
  resolveLazy: false,
1168
1286
  getLabel: "inspector.treeLabel",
@@ -1249,6 +1367,7 @@ var GramlotToolsInspector = class extends HTMLElement {
1249
1367
  insertActions.html_button("Cancel", { type: "button", connect_onclick: "inspector.closeInsert" });
1250
1368
  insertActions.html_button("Add", { type: "button", disabled: "^busy", connect_onclick: "inspector.addElement" });
1251
1369
  ui.src.startSource(builder.source);
1370
+ this.#copies = ui.src.binding.router.register({ path: "target", subtree: true, recipient: { receive: () => this.#schedule() } });
1252
1371
  for (const name of ["data", "source"]) this.#trees[name] = ui.dom.getDomNode(ui.src.source.getNode(`main.window.frame.center.palette.content.tree.${name}`));
1253
1372
  this.#renderTargets();
1254
1373
  this.#subscribe();
@@ -1258,6 +1377,8 @@ var GramlotToolsInspector = class extends HTMLElement {
1258
1377
  return this.#ui.dom.getDomNode(this.#ui.src.source.getNode(`main.window.frame.center.palette.${name}`));
1259
1378
  }
1260
1379
  disconnectedCallback() {
1380
+ this.#copies?.close();
1381
+ this.#copies = null;
1261
1382
  this.#unsubscribe();
1262
1383
  this.#ui?.dispose();
1263
1384
  this.#ui = null;
@@ -1265,29 +1386,23 @@ var GramlotToolsInspector = class extends HTMLElement {
1265
1386
  this.#trees = {};
1266
1387
  this.#breakpointTarget = null;
1267
1388
  this.#snapshot = null;
1268
- this.#breakpointTests.clear();
1269
1389
  }
1390
+ /** Connect the palette to its target: a local instance gets its agent on a new MessageChannel. */
1270
1391
  #subscribe() {
1271
- if (this.#connection) {
1272
- this.#connectionRelease = this.#connection.subscribe(() => this.#schedule());
1273
- return;
1392
+ if (this.#target && !this.#local) {
1393
+ const channel = new this.ownerDocument.defaultView.MessageChannel();
1394
+ const agent = attachInspectorAgent(this.#target, channel.port1);
1395
+ this.#local = { agent, connection: new InspectorConnection(channel.port2) };
1396
+ this.#connection = this.#local.connection;
1274
1397
  }
1275
- if (!this.#target) return;
1276
- this.#history = new InspectorHistory(this.#target);
1277
- this.#subscriptions = [this.#target.data, this.#target.src.source];
1278
- for (const [index, bag] of this.#subscriptions.entries()) bag.subscribe(this.#subscriber, { any: (event) => {
1279
- this.#checkBreakpoints(index === 0 ? "data" : "source", event);
1280
- this.#schedule();
1281
- } });
1398
+ if (!this.#connection) return;
1399
+ this.#connectionRelease = this.#connection.subscribe(() => this.#schedule());
1400
+ this.#ui.rpc.registerConnection("target", this.#connection.port);
1282
1401
  }
1283
1402
  #unsubscribe() {
1284
- this.#history?.clear();
1285
- this.#history = null;
1286
1403
  this.#insertTarget = null;
1287
1404
  if (this.#ui) this.#dialog("insert").close();
1288
1405
  ++this.#styleRequest;
1289
- this.#styles?.dispose();
1290
- this.#styles = null;
1291
1406
  if (this.#ui) {
1292
1407
  this.#renderStyles([]);
1293
1408
  this.#ui.data.setItem("styles.busy", false);
@@ -1297,8 +1412,17 @@ var GramlotToolsInspector = class extends HTMLElement {
1297
1412
  this.#connectionRelease = null;
1298
1413
  ++this.#generation;
1299
1414
  this.#pending = false;
1300
- for (const bag of this.#subscriptions) bag.unsubscribe(this.#subscriber, { any: true });
1301
- this.#subscriptions = [];
1415
+ this.#applyAgain = null;
1416
+ if (this.#ui) {
1417
+ this.#ui.rpc.unregisterConnection("target");
1418
+ for (const name of ["data", "source"]) this.#ui.data.setItem(`target.${name}`, new Bag2());
1419
+ }
1420
+ if (this.#local) {
1421
+ this.#local.connection.close();
1422
+ this.#local.agent.dispose();
1423
+ if (this.#connection === this.#local.connection) this.#connection = null;
1424
+ this.#local = null;
1425
+ }
1302
1426
  }
1303
1427
  #schedule() {
1304
1428
  if (this.#pending) return;
@@ -1310,9 +1434,6 @@ var GramlotToolsInspector = class extends HTMLElement {
1310
1434
  this.#refresh();
1311
1435
  });
1312
1436
  }
1313
- #bag() {
1314
- return this.#targetBag(this.#ui.data.getItem("root"));
1315
- }
1316
1437
  #refresh() {
1317
1438
  const ui = this.#ui;
1318
1439
  if (!ui) return;
@@ -1323,12 +1444,13 @@ var GramlotToolsInspector = class extends HTMLElement {
1323
1444
  ui.data.setItem("stylesActive", tab === "styles");
1324
1445
  ui.data.setItem("treeActive", tab !== "styles");
1325
1446
  if (this.#connection) {
1447
+ if (this.#state() === "disposed") ui.rpc.unregisterConnection("target");
1326
1448
  const configurations = new Bag2();
1327
1449
  for (const [index, record] of this.#connection.breakpoints.entries()) configurations.setItem(`b${index}`, new Bag2(record));
1328
1450
  ui.data.setItem("breakpoints", configurations);
1329
1451
  ui.data.setItem("breakpointError", this.#connection.breakpoints.filter((record) => record.error).map((record) => `${record.root}: ${record.path}: ${record.error}`).join("; "));
1330
1452
  }
1331
- const history = this.#connection ? this.#connection.history : this.#history?.state;
1453
+ const history = this.#connection?.history;
1332
1454
  for (const action of ["undo", "redo"]) {
1333
1455
  ui.data.setItem(`history.${action}`, history?.[action] ?? "");
1334
1456
  ui.data.setItem(`history.no${action === "undo" ? "Undo" : "Redo"}`, !history?.[action] || ui.data.getItem("busy") || this.#state() !== "started");
@@ -1338,15 +1460,11 @@ var GramlotToolsInspector = class extends HTMLElement {
1338
1460
  ui.data.setItem("noBreakpoints", count === 0);
1339
1461
  ui.data.setItem("dataActive", root === "data");
1340
1462
  ui.data.setItem("sourceActive", root === "source");
1341
- for (const name of ["data", "source"]) {
1342
- const sourceTree = ui.src.source.getNode(`main.window.frame.center.palette.content.tree.${name}`);
1343
- sourceTree.setTreeStore(this.#connection || this.#target ? this.#targetBag(name) : null);
1344
- }
1345
- if (this.#target || this.#connection) this.#index(this.#bag(), []);
1463
+ if (this.#connection) this.#index(ui.data.getItem(`target.${root}`), []);
1346
1464
  ui.data.setItem("selectionSync", true);
1347
1465
  ui.data.setItem(`treeSelection.${root}`, this.#selected()?.path.join(".") ?? null);
1348
1466
  ui.data.setItem("selectionSync", false);
1349
- ui.data.setItem("error", this.#connection ? this.#connection.error || (this.#state() === "disposed" ? "Inspected page disconnected." : this.#state() === "connecting" ? "Connecting\u2026" : "") : this.#target ? "" : "No Gramlot instance selected.");
1467
+ ui.data.setItem("error", this.#connection ? this.#connection.error || (this.#state() === "disposed" ? "Inspected page disconnected." : this.#state() === "connecting" ? "Connecting\u2026" : "") : "No Gramlot instance selected.");
1350
1468
  this.#details();
1351
1469
  } catch (error) {
1352
1470
  ui.data.setItem("error", error.message);
@@ -1360,21 +1478,10 @@ var GramlotToolsInspector = class extends HTMLElement {
1360
1478
  ui.data.setItem("styles.noDownload", true);
1361
1479
  ui.data.setItem("styles.status", "");
1362
1480
  try {
1363
- if (!this.#state() || this.#state() === "disposed" || this.#connection && this.#state() !== "started") {
1364
- throw new Error("Select a connected page before editing CSS variables");
1365
- }
1366
- let rows;
1367
- if (this.#connection) {
1368
- const connection = this.#connection;
1369
- await connection.request(type, command);
1370
- rows = connection.styles;
1371
- } else {
1372
- this.#styles ??= new InspectorStyles(this.#target.src.renderer.destination.ownerDocument);
1373
- if (type === "setStyle") this.#styles.set(command.name, command.value);
1374
- if (type === "resetStyle") this.#styles.reset(command.name);
1375
- if (type === "resetStyles") this.#styles.dispose();
1376
- rows = this.#styles.snapshot();
1377
- }
1481
+ if (!this.#connection || this.#state() === "disposed") throw new Error("Select a connected page before editing CSS variables");
1482
+ const connection = this.#connection;
1483
+ await connection.request(type, command);
1484
+ const rows = connection.styles;
1378
1485
  if (this.#ui !== ui || request !== this.#styleRequest) return;
1379
1486
  this.#renderStyles(rows, type, command);
1380
1487
  } catch (error) {
@@ -1478,35 +1585,54 @@ ${declarations}
1478
1585
  ui.data.setItem("styles.noChanges", !rows.some((row) => row.override));
1479
1586
  ui.src.source.getNode("main.window.frame.center.palette.styles.empty").setAttr({ hidden: rows.length !== 0 });
1480
1587
  }
1588
+ /** Record the path and the agent identity of every copied node below `bag`. */
1481
1589
  #index(bag, labels) {
1590
+ if (!bag) return;
1482
1591
  for (const node of bag.getNodes()) {
1483
1592
  const path = [...labels, node.label];
1484
- if (!this.#nodeIds.has(node)) this.#nodeIds.set(node, String(++this.#nextNodeId));
1485
- this.#nodes.push({ id: this.#nodeIds.get(node), node, path });
1593
+ this.#nodes.push({ id: String(node.getAttr("_inspector").id), path });
1486
1594
  const value = node.getValue(true);
1487
- if (!node.resolver && value instanceof Bag2) this.#index(value, path);
1595
+ if (value instanceof Bag2) this.#index(value, path);
1488
1596
  }
1489
1597
  }
1490
1598
  #details() {
1491
1599
  const ui = this.#ui;
1492
1600
  const entry = this.#selected();
1493
- const node = entry?.node;
1494
- ui.data.setItem("path", node ? entry.path.join(".") : "");
1495
- const bp = node ? this.#findBreakpoint(ui.data.getItem("root"), entry.path.join("."))?.value : null;
1601
+ ui.data.setItem("path", entry ? entry.path.join(".") : "");
1602
+ const bp = entry ? this.#findBreakpoint(ui.data.getItem("root"), entry.path.join("."))?.value : null;
1496
1603
  ui.data.setItem("breakpointLine", bp ? `Breakpoint: ${bp.getItem("mode")} \xB7 ${bp.getItem("hits")} hits${bp.getItem("condition") ? ` \xB7 if ${bp.getItem("condition")}` : ""}` : "");
1497
- if (!node || this.#snapshot?.node !== node || !ui.data.getItem("editor.dirty") && !this.#unchanged()) this.#loadEditor(entry);
1604
+ if (!entry || this.#snapshot?.id !== entry.id || !ui.data.getItem("editor.dirty") && !this.#unchanged()) this.#loadEditor(entry);
1498
1605
  else if (!this.#unchanged()) ui.data.setItem("editor.status", "Node changed outside this draft. Press Escape to reload the cell before saving.");
1499
1606
  }
1500
1607
  #selected() {
1501
1608
  return this.#nodes.find((item) => item.id === this.#ui.data.getItem("selection"));
1502
1609
  }
1610
+ /** The editor's copy of the selected node: path, identity, revision, value and attributes. */
1611
+ #read(entry) {
1612
+ const root = this.#ui.data.getItem("root");
1613
+ const node = entry ? this.#copyNode(root, entry.path.join(".")) : null;
1614
+ if (!node) return null;
1615
+ const info = node.getAttr("_inspector");
1616
+ const value = node.getValue(true);
1617
+ const attrs = { ...node.getAttr() };
1618
+ delete attrs._inspector;
1619
+ return {
1620
+ id: entry.id,
1621
+ nodeId: info.id,
1622
+ revision: info.revision,
1623
+ branch: value instanceof Bag2,
1624
+ value: value instanceof Bag2 ? null : value,
1625
+ attrs,
1626
+ readonly: info.readonly,
1627
+ readonlyAttrs: info.readonlyAttrs,
1628
+ parameterEnums: root === "source" ? info.parameterEnums : {}
1629
+ };
1630
+ }
1503
1631
  #unchanged() {
1504
1632
  const entry = this.#selected();
1505
1633
  const snapshot = this.#snapshot;
1506
- if (!entry || !snapshot || entry.node !== snapshot.node || !entry.node.parentBag || !entry.node.parentBag.getNodes().includes(entry.node) || this.#state() === "disposed") return false;
1507
- if (this.#connection && this.#connection.nodeInfo(entry.node)?.revision !== snapshot.revision) return false;
1508
- const attrs = entry.node.getAttr();
1509
- return Object.is(entry.node.getValue(true), snapshot.value) && entry.node.resolver === snapshot.resolver && Object.keys(attrs).length === Object.keys(snapshot.attrs).length && Object.entries(snapshot.attrs).every(([name, value]) => Object.is(attrs[name], value));
1634
+ if (!entry || !snapshot || entry.id !== snapshot.id || this.#state() === "disposed") return false;
1635
+ return this.#info(this.#ui.data.getItem("root"), entry.path.join("."))?.revision === snapshot.revision;
1510
1636
  }
1511
1637
  #inputType(type) {
1512
1638
  return { boolean: "checkbox", number: "number", integer: "number", date: "date", time: "time", datetime: "datetime-local" }[type] ?? "text";
@@ -1514,7 +1640,7 @@ ${declarations}
1514
1640
  #row(name, value, primary, locked = false) {
1515
1641
  const scalar = scalarType(value);
1516
1642
  const type = scalar === "null" ? "string" : scalar;
1517
- let text = value === null ? "" : type === "boolean" ? value : type ? scalarText(value, type) : this.#format(value);
1643
+ let text = value === null ? "" : type === "boolean" ? value : type ? scalarText(value, type) : String(value);
1518
1644
  if (type === "datetime") text = text.replace(/Z$/, "");
1519
1645
  return new Bag2({
1520
1646
  name,
@@ -1532,23 +1658,17 @@ ${declarations}
1532
1658
  }
1533
1659
  #loadEditor(entry) {
1534
1660
  const ui = this.#ui;
1535
- this.#snapshot = entry ? {
1536
- node: entry.node,
1537
- value: entry.node.getValue(true),
1538
- parameterEnums: ui.data.getItem("root") !== "source" ? {} : this.#connection ? this.#connection.nodeInfo(entry.node).parameterEnums : readParameterEnums(entry.node),
1539
- attrs: { ...entry.node.getAttr() },
1540
- resolver: entry.node.resolver,
1541
- revision: this.#connection?.nodeInfo(entry.node)?.revision
1542
- } : null;
1661
+ this.#snapshot = this.#read(entry);
1662
+ const snapshot = this.#snapshot;
1543
1663
  const rows = new Bag2();
1544
- if (entry) {
1545
- if (!(this.#snapshot.value instanceof Bag2)) rows.setItem(`r${++this.#nextRow}`, this.#row("value", this.#snapshot.value, true, !!entry.node.resolver || !!this.#connection?.nodeInfo(entry.node)?.readonly));
1546
- for (const [name, value] of Object.entries(this.#snapshot.attrs)) {
1547
- if (name !== "_meta") rows.setItem(`r${++this.#nextRow}`, this.#row(name, value, false, !!this.#connection?.nodeInfo(entry.node)?.readonlyAttrs.has(name)));
1664
+ if (snapshot) {
1665
+ if (!snapshot.branch) rows.setItem(`r${++this.#nextRow}`, this.#row("value", snapshot.value, true, snapshot.readonly));
1666
+ for (const [name, value] of Object.entries(snapshot.attrs)) {
1667
+ rows.setItem(`r${++this.#nextRow}`, this.#row(name, value, false, snapshot.readonlyAttrs.includes(name)));
1548
1668
  }
1549
1669
  }
1550
1670
  ui.data.setItem("editor.rows", rows);
1551
- ui.data.setItem("editor.disabled", !entry || this.#state() === "disposed");
1671
+ ui.data.setItem("editor.disabled", !snapshot || this.#state() === "disposed");
1552
1672
  ui.data.setItem("editor.dirty", false);
1553
1673
  ui.data.setItem("editor.status", "");
1554
1674
  this.#renderEditor();
@@ -1633,33 +1753,35 @@ ${declarations}
1633
1753
  this.#renderEditor();
1634
1754
  this.shadowRoot.querySelector('[aria-label="New attribute name"]').focus();
1635
1755
  }
1636
- #acceptEdit(target) {
1756
+ #acceptEdit() {
1637
1757
  this.#ui.data.setItem("editor.dirty", false);
1638
1758
  const rows = this.#ui.data.getItem("editor.rows").getNodes();
1639
- if (rows.some((row) => row.value.getItem("removed") || row.value.getItem("initialName") === "")) {
1759
+ const current = this.#read(this.#selected());
1760
+ if (!current || current.id !== this.#snapshot?.id || rows.some((row) => row.value.getItem("removed") || row.value.getItem("initialName") === "")) {
1640
1761
  this.#loadEditor(this.#selected());
1641
1762
  } else {
1642
- this.#snapshot = {
1643
- ...this.#snapshot,
1644
- node: target,
1645
- value: target.getValue(true),
1646
- attrs: { ...target.getAttr() },
1647
- resolver: target.resolver,
1648
- revision: this.#connection?.nodeInfo(target).revision
1649
- };
1763
+ this.#snapshot = current;
1764
+ let dirty = false;
1650
1765
  for (const row of rows) {
1651
- row.value.setItem("initialText", row.value.getItem("text"));
1652
- row.value.setItem("initialType", row.value.getItem("type"));
1766
+ const data = row.value, primary = data.getItem("primary");
1767
+ const committed = this.#row(data.getItem("name"), primary ? current.value : current.attrs[data.getItem("initialName")], primary);
1768
+ data.setItem("initialText", committed.getItem("text"));
1769
+ data.setItem("initialType", committed.getItem("type"));
1770
+ dirty ||= data.getItem("text") !== committed.getItem("text") || data.getItem("type") !== committed.getItem("type");
1653
1771
  }
1772
+ this.#ui.data.setItem("editor.dirty", dirty);
1654
1773
  }
1655
1774
  this.#ui.data.setItem("editor.status", "");
1656
1775
  }
1657
1776
  #applyEdit(after = () => {
1658
1777
  }, focusTarget = this.shadowRoot.activeElement) {
1659
- if (this.#ui.data.getItem("busy")) return false;
1778
+ if (this.#ui.data.getItem("busy")) {
1779
+ this.#applyAgain = { after, focusTarget };
1780
+ return false;
1781
+ }
1660
1782
  try {
1661
1783
  if (!this.#unchanged()) throw new Error("Node changed or was removed. Press Escape to reload the cell before saving.");
1662
- const attrs = Object.hasOwn(this.#snapshot.attrs, "_meta") ? { _meta: this.#snapshot.attrs._meta } : {};
1784
+ const attrs = {};
1663
1785
  let value = this.#snapshot.value;
1664
1786
  for (const node of this.#ui.data.getItem("editor.rows").getNodes()) {
1665
1787
  const row = node.getValue(true);
@@ -1668,7 +1790,7 @@ ${declarations}
1668
1790
  if (row.getItem("removed")) continue;
1669
1791
  if (!primary) {
1670
1792
  if (!name.trim()) throw new Error("Enter an attribute name.");
1671
- if (["__proto__", "prototype", "constructor"].includes(name) || name === "_meta" && !row.getItem("locked")) throw new Error("Unsupported attribute name.");
1793
+ if (["__proto__", "prototype", "constructor", "_meta", "_inspector"].includes(name)) throw new Error("Unsupported attribute name.");
1672
1794
  if (Object.hasOwn(attrs, name)) throw new Error(`Duplicate attribute: ${name}`);
1673
1795
  }
1674
1796
  const initialName = row.getItem("initialName");
@@ -1678,64 +1800,57 @@ ${declarations}
1678
1800
  if (primary) value = parsed;
1679
1801
  else attrs[name] = parsed;
1680
1802
  }
1681
- const target = this.#snapshot.node;
1682
- const changed = Object.keys(attrs).length !== Object.keys(this.#snapshot.attrs).length || Object.entries(attrs).some(([name, item]) => !Object.is(item, this.#snapshot.attrs[name]));
1683
- if (this.#connection) {
1684
- const connection = this.#connection;
1685
- const entry = this.#selected();
1686
- const command = {
1687
- root: this.#ui.data.getItem("root"),
1688
- path: entry.path.join("."),
1689
- nodeId: connection.nodeInfo(target).id,
1690
- revision: this.#snapshot.revision,
1691
- set: Object.entries(attrs).filter(([name, item]) => name !== "_meta" && !Object.is(item, this.#snapshot.attrs[name])).map(([name, item]) => [name, encodeScalar(item)]),
1692
- remove: Object.keys(this.#snapshot.attrs).filter((name) => name !== "_meta" && !Object.hasOwn(attrs, name))
1693
- };
1694
- if (!Object.is(value, this.#snapshot.value)) command.value = encodeScalar(value);
1695
- this.#ui.data.setItem("busy", true);
1696
- this.#ui.data.setItem("editor.disabled", true);
1697
- const generation = this.#generation;
1698
- connection.request("edit", command).then(() => {
1699
- if (!this.#ui || generation !== this.#generation) return;
1700
- this.#acceptEdit(target);
1701
- this.#ui.data.setItem("busy", false);
1702
- this.#ui.data.setItem("editor.disabled", false);
1703
- if (focusTarget?.isConnected && !this.shadowRoot.activeElement) focusTarget.focus();
1704
- this.#refresh();
1705
- after();
1706
- }).catch((error) => {
1707
- if (this.#ui && generation === this.#generation) this.#ui.data.setItem("editor.status", error.message);
1708
- }).finally(() => {
1709
- if (this.#ui && generation === this.#generation) {
1710
- this.#ui.data.setItem("busy", false);
1711
- this.#ui.data.setItem("editor.disabled", !this.#selected() || this.#state() === "disposed");
1712
- }
1713
- });
1714
- return false;
1715
- }
1716
- this.#history.edit(target, attrs, value, changed, !Object.is(value, this.#snapshot.value));
1717
- this.#acceptEdit(target);
1718
- this.#refresh();
1719
- this.#ui.data.setItem("editor.status", "");
1720
- after();
1721
- return true;
1803
+ const connection = this.#connection;
1804
+ const entry = this.#selected();
1805
+ const command = {
1806
+ root: this.#ui.data.getItem("root"),
1807
+ path: entry.path.join("."),
1808
+ nodeId: this.#snapshot.nodeId,
1809
+ revision: this.#snapshot.revision,
1810
+ set: Object.entries(attrs).filter(([name, item]) => !Object.is(item, this.#snapshot.attrs[name])),
1811
+ remove: Object.keys(this.#snapshot.attrs).filter((name) => !Object.hasOwn(attrs, name))
1812
+ };
1813
+ if (!Object.is(value, this.#snapshot.value)) command.value = value;
1814
+ this.#ui.data.setItem("busy", true);
1815
+ this.#ui.data.setItem("editor.disabled", true);
1816
+ const generation = this.#generation;
1817
+ connection.request("edit", command).then(() => {
1818
+ if (!this.#ui || generation !== this.#generation) return;
1819
+ this.#refresh();
1820
+ this.#acceptEdit();
1821
+ this.#ui.data.setItem("busy", false);
1822
+ this.#ui.data.setItem("editor.disabled", false);
1823
+ if (focusTarget?.isConnected && !this.shadowRoot.activeElement) focusTarget.focus();
1824
+ this.#refresh();
1825
+ after();
1826
+ }).catch((error) => {
1827
+ if (this.#ui && generation === this.#generation) this.#ui.data.setItem("editor.status", error.message);
1828
+ }).finally(() => {
1829
+ if (!this.#ui || generation !== this.#generation) return;
1830
+ this.#ui.data.setItem("busy", false);
1831
+ this.#ui.data.setItem("editor.disabled", !this.#selected() || this.#state() === "disposed");
1832
+ const again = this.#applyAgain;
1833
+ this.#applyAgain = null;
1834
+ if (again && this.#ui.data.getItem("editor.dirty")) this.#applyEdit(again.after, again.focusTarget);
1835
+ else again?.after();
1836
+ });
1837
+ return false;
1722
1838
  } catch (error) {
1723
1839
  this.#ui.data.setItem("editor.status", error.message);
1724
1840
  return false;
1725
1841
  }
1726
1842
  }
1727
1843
  #sourceCommand(path) {
1728
- const node = this.#targetBag("source").getNode(path);
1729
- if (!node) throw new Error("Source node no longer exists");
1730
- const info = this.#connection?.nodeInfo(node);
1731
- return { path, nodeId: info?.id, revision: info?.revision, ...this.#connection ? {} : { node } };
1844
+ const info = this.#info("source", path);
1845
+ if (!info) throw new Error("Source node no longer exists");
1846
+ return { path, nodeId: info.id, revision: info.revision };
1732
1847
  }
1733
1848
  async #openInsert(path) {
1734
1849
  if (this.#ui.data.getItem("busy")) return;
1735
1850
  const generation = this.#generation;
1736
1851
  try {
1737
1852
  this.#insertTarget = this.#sourceCommand(path);
1738
- this.#catalog = this.#connection ? (await this.#connection.request("catalog", { path })).catalog : this.#history.catalog(path);
1853
+ this.#catalog = (await this.#connection.request("catalog", { path })).catalog;
1739
1854
  if (!this.#ui || generation !== this.#generation) return;
1740
1855
  this.#ui.data.setItem("insert.kind", "html");
1741
1856
  this.#ui.data.setItem("insert.status", "");
@@ -1772,17 +1887,9 @@ ${declarations}
1772
1887
  ui.data.setItem("busy", true);
1773
1888
  ui.data.setItem("status", "");
1774
1889
  ui.data.setItem("insert.status", "");
1890
+ this.#refresh();
1775
1891
  try {
1776
- let selection;
1777
- if (this.#connection) ({ selection } = await this.#connection.request(type, command));
1778
- else {
1779
- if (command.path && this.#targetBag("source").getNode(command.path) !== command.node) throw new Error("Source node changed. Select it again.");
1780
- if (type === "insert") selection = this.#history.insert(command.path, command.tag, command.attrs);
1781
- if (type === "remove") selection = this.#history.remove(command.path);
1782
- if (type === "move") selection = this.#history.move(command.path, command.destination, command.placement);
1783
- if (type === "undo") this.#history.undo();
1784
- if (type === "redo") this.#history.redo();
1785
- }
1892
+ const { selection } = await this.#connection.request(type, command);
1786
1893
  if (!this.#ui || generation !== this.#generation) return;
1787
1894
  if (type === "insert") this.#dialog("insert").close();
1788
1895
  this.#snapshot = null;
@@ -1834,51 +1941,17 @@ ${declarations}
1834
1941
  const { root, path } = where;
1835
1942
  const mode = ui.data.getItem("editor.mode");
1836
1943
  const condition = ui.data.getItem("editor.condition").trim();
1837
- const existing = this.#findBreakpoint(root, path);
1838
- if (this.#connection) {
1839
- const generation = this.#generation;
1840
- this.#connection.request("breakpoint", { root, path, mode, condition }).then(() => {
1841
- if (!this.#ui || generation !== this.#generation) return;
1842
- ui.data.setItem("breakpointDirty", false);
1843
- ui.data.setItem("breakpointStatus", "");
1844
- this.#refresh();
1845
- after();
1846
- }).catch((error) => {
1847
- if (this.#ui && generation === this.#generation) ui.data.setItem("breakpointStatus", `Breakpoint not saved: ${error.message}`);
1848
- });
1849
- return false;
1850
- }
1851
- try {
1852
- if (!["", "debugger", "console"].includes(mode)) throw new Error("Unknown breakpoint mode");
1853
- const test = mode && condition ? new this.ownerDocument.defaultView.Function(
1854
- "evt",
1855
- "node",
1856
- "value",
1857
- "oldvalue",
1858
- "attrs_diff",
1859
- "reason",
1860
- "path",
1861
- `"use strict"; return (${condition});`
1862
- ) : null;
1863
- if (existing) {
1864
- ui.data.getItem("breakpoints").popNode(existing.label);
1865
- this.#breakpointTests.delete(existing.label);
1866
- }
1867
- if (mode) {
1868
- const id = `b${++this.#nextBreakpoint}`;
1869
- ui.data.getItem("breakpoints").setItem(id, new Bag2({ root, path, mode, condition, hits: 0 }));
1870
- if (test) this.#breakpointTests.set(id, test);
1871
- }
1944
+ const generation = this.#generation;
1945
+ this.#connection?.request("breakpoint", { root, path, mode, condition }).then(() => {
1946
+ if (!this.#ui || generation !== this.#generation) return;
1872
1947
  ui.data.setItem("breakpointDirty", false);
1873
- ui.data.setItem("breakpointError", "");
1874
- ui.data.setItem("breakpointStatus", mode ? `Breakpoint set on ${root}: ${path}` : "Breakpoint removed");
1948
+ ui.data.setItem("breakpointStatus", "");
1875
1949
  this.#refresh();
1876
1950
  after();
1877
- return true;
1878
- } catch (error) {
1879
- ui.data.setItem("breakpointStatus", `Breakpoint not saved: ${error.message}`);
1880
- return false;
1881
- }
1951
+ }).catch((error) => {
1952
+ if (this.#ui && generation === this.#generation) ui.data.setItem("breakpointStatus", `Breakpoint not saved: ${error.message}`);
1953
+ });
1954
+ return false;
1882
1955
  }
1883
1956
  #renderBreakpoints() {
1884
1957
  const builder = new GramlotBuilder();
@@ -1895,53 +1968,6 @@ ${declarations}
1895
1968
  }
1896
1969
  this.#ui.src.source.getNode("main.window.frame.center.palette.breakpoints.entries").setValue(this.#ui.src.prepareSource(builder.source));
1897
1970
  }
1898
- #checkBreakpoints(root, event) {
1899
- if (!this.#ui) return;
1900
- const structural = event.evt === "ins" || event.evt === "del";
1901
- const pathlist = event.pathlist === null ? [] : event.pathlist;
1902
- for (const node of Array.isArray(event.node) ? event.node : [event.node]) {
1903
- const path = (structural ? [...pathlist, node.label] : pathlist).join(".");
1904
- const config = this.#findBreakpoint(root, path);
1905
- if (!config) continue;
1906
- const fields = {
1907
- evt: event.evt,
1908
- node,
1909
- value: node.getValue(true),
1910
- oldvalue: event.oldvalue,
1911
- attrs_diff: event.attrs_diff,
1912
- reason: event.reason,
1913
- path
1914
- };
1915
- const test = this.#breakpointTests.get(config.label);
1916
- if (test) {
1917
- try {
1918
- if (!test(fields.evt, node, fields.value, fields.oldvalue, fields.attrs_diff, fields.reason, path)) continue;
1919
- } catch (error) {
1920
- this.#ui.data.setItem("breakpointStatus", `Condition failed on ${root}: ${path}: ${error.message}`);
1921
- this.#ui.data.setItem("breakpointError", `Condition failed on ${root}: ${path}: ${error.message}`);
1922
- continue;
1923
- }
1924
- }
1925
- const value = config.getValue(true);
1926
- value.setItem("hits", value.getItem("hits") + 1);
1927
- this.#ui.data.setItem("breakpointStatus", `Hit ${root}: ${path} (${event.evt})`);
1928
- this.#hitBreakpoint(value.getItem("mode"), root, fields);
1929
- }
1930
- }
1931
- #hitBreakpoint(mode, root, fields) {
1932
- if (mode === "debugger") {
1933
- debugger;
1934
- } else this.ownerDocument.defaultView.console.log("** Gramlot breakpoint **", root, fields);
1935
- }
1936
- #format(value) {
1937
- if (value instanceof Bag2) return `${value.constructor.name} (${value.getNodes().length} nodes)`;
1938
- if (typeof value === "string") return value;
1939
- if (value === void 0) return "undefined";
1940
- if (typeof value === "number" || typeof value === "boolean" || value === null) return String(value);
1941
- if (typeof value === "bigint") return `${value}n`;
1942
- if (value instanceof Date) return value.toISOString();
1943
- return JSON.stringify(value, null, 2);
1944
- }
1945
1971
  };
1946
1972
  customElements.define("gramlot-tools-inspector", GramlotToolsInspector);
1947
1973
  export {