@gramlot/gramlot 0.3.9 → 0.3.15

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 (95) hide show
  1. package/dist/components/editors/__init__.py +13 -0
  2. package/dist/components/{editors.js → editors/assets/collection.js} +354 -418
  3. package/dist/components/editors/assets/index.js +2 -0
  4. package/dist/components/editors/commands.json +7 -0
  5. package/dist/components/editors/grammar.json +7045 -0
  6. package/dist/components/inputs/__init__.py +13 -0
  7. package/dist/components/{inputs.js → inputs/assets/collection.js} +291 -200
  8. package/dist/components/inputs/assets/index.js +2 -0
  9. package/dist/components/inputs/commands.json +7 -0
  10. package/dist/components/inputs/grammar.json +42881 -0
  11. package/dist/components/layout/__init__.py +13 -0
  12. package/dist/components/layout/assets/collection.js +25737 -0
  13. package/dist/components/layout/assets/index.js +2 -0
  14. package/dist/components/layout/commands.json +7 -0
  15. package/dist/components/layout/grammar.json +1798 -0
  16. package/dist/components/tree/__init__.py +13 -0
  17. package/dist/components/{tree.js → tree/assets/collection.js} +62 -175
  18. package/dist/components/tree/assets/index.js +2 -0
  19. package/dist/components/tree/commands.json +7 -0
  20. package/dist/components/tree/grammar.json +339 -0
  21. package/dist/components/typst/__init__.py +13 -0
  22. package/dist/components/typst/assets/collection.js +4 -0
  23. package/dist/components/typst/assets/index.js +2 -0
  24. package/dist/components/typst/commands.json +7 -0
  25. package/dist/components/typst/grammar.json +81 -0
  26. package/dist/gramlot.js +2525 -905
  27. package/dist/gramlot.min.js +109 -28
  28. package/dist/runtime-notices.json +0 -196
  29. package/package.json +1 -1
  30. package/src/binding/ask-dialog.js +1 -1
  31. package/src/binding/installation.js +5 -6
  32. package/src/binding/remote.js +9 -2
  33. package/src/binding/runtime.js +12 -5
  34. package/src/bootstrap.d.ts +1 -1
  35. package/src/bootstrap.js +52 -30
  36. package/src/builder/binding.json +25 -0
  37. package/src/builder/gramlot-builder.js +16 -3
  38. package/src/builder/source.js +41 -4
  39. package/src/collection-artifact.d.ts +11 -0
  40. package/src/collection-artifact.js +57 -0
  41. package/src/commands.d.ts +9 -0
  42. package/src/commands.js +36 -0
  43. package/src/components/bases.js +1 -1
  44. package/src/components/border-container.js +33 -2
  45. package/src/components/buttons.js +84 -161
  46. package/src/components/choice-editor.js +31 -10
  47. package/src/components/database-choices.js +110 -0
  48. package/src/components/inputs.js +15 -2
  49. package/src/components/layout.js +5 -3
  50. package/src/components/menus.js +346 -0
  51. package/src/components/popup.js +15 -2
  52. package/src/components/registry.js +18 -3
  53. package/src/components/toolbar-overflow.js +181 -0
  54. package/src/components/tree.js +14 -4
  55. package/src/components/validation.js +1 -1
  56. package/src/components/windows.js +284 -0
  57. package/src/gramlot.d.ts +2 -0
  58. package/src/gramlot.js +4 -2
  59. package/src/handlers/rpc-handler.d.ts +6 -1
  60. package/src/handlers/rpc-handler.js +7 -2
  61. package/src/handlers/source-handler.d.ts +2 -1
  62. package/src/handlers/source-handler.js +10 -1
  63. package/src/index-page-styles.js +1 -1
  64. package/src/index-theme.js +1 -1
  65. package/src/index.d.ts +5 -0
  66. package/src/index.js +5 -0
  67. package/src/renderer/attributes.js +11 -2
  68. package/src/renderer/gramlot-html-renderer.js +1 -0
  69. package/src/renderer/gramlot-renderer.js +13 -3
  70. package/src/server/assets.js +2 -2
  71. package/src/server/gramlot-file-server.d.ts +2 -0
  72. package/src/server/gramlot-file-server.js +45 -1
  73. package/src/server/gramlot-server.d.ts +20 -2
  74. package/src/server/gramlot-server.js +86 -6
  75. package/src/server/page-base.js +1 -0
  76. package/src/server/page.d.ts +3 -0
  77. package/src/view/button.js +47 -3
  78. package/src/view/controls.js +8 -0
  79. package/src/view/html.js +8 -0
  80. package/src/view/menu-command.js +45 -0
  81. package/src/view/menu.js +87 -0
  82. package/themes/gramlot-compact/README.md +19 -0
  83. package/themes/gramlot-compact/theme.css +138 -45
  84. package/themes/joanna/README.md +19 -0
  85. package/themes/joanna/theme.css +134 -78
  86. package/themes/mela/theme.css +184 -0
  87. package/themes/mimi/README.md +19 -0
  88. package/themes/mimi/theme.css +133 -77
  89. package/themes/palettes/README.md +3 -0
  90. package/themes/palettes/compact.css +86 -0
  91. package/themes/palettes/joanna.css +86 -0
  92. package/themes/palettes/mimi.css +86 -0
  93. package/tools/gramlot-tools-inspector.js +3 -3
  94. package/dist/components/layout.js +0 -1402
  95. package/dist/components/typst.js +0 -4
package/dist/gramlot.js CHANGED
@@ -60,7 +60,7 @@ var require_conventions = __commonJS({
60
60
  }
61
61
  }
62
62
  }
63
- function freeze2(object, oc) {
63
+ function freeze3(object, oc) {
64
64
  if (oc === void 0) {
65
65
  oc = Object;
66
66
  }
@@ -83,7 +83,7 @@ var require_conventions = __commonJS({
83
83
  }
84
84
  return target;
85
85
  }
86
- var HTML_BOOLEAN_ATTRIBUTES = freeze2({
86
+ var HTML_BOOLEAN_ATTRIBUTES = freeze3({
87
87
  allowfullscreen: true,
88
88
  async: true,
89
89
  autofocus: true,
@@ -112,7 +112,7 @@ var require_conventions = __commonJS({
112
112
  function isHTMLBooleanAttribute(name) {
113
113
  return hasOwn(HTML_BOOLEAN_ATTRIBUTES, name.toLowerCase());
114
114
  }
115
- var HTML_VOID_ELEMENTS = freeze2({
115
+ var HTML_VOID_ELEMENTS = freeze3({
116
116
  area: true,
117
117
  base: true,
118
118
  br: true,
@@ -131,7 +131,7 @@ var require_conventions = __commonJS({
131
131
  function isHTMLVoidElement(tagName) {
132
132
  return hasOwn(HTML_VOID_ELEMENTS, tagName.toLowerCase());
133
133
  }
134
- var HTML_RAW_TEXT_ELEMENTS = freeze2({
134
+ var HTML_RAW_TEXT_ELEMENTS = freeze3({
135
135
  script: false,
136
136
  style: false,
137
137
  textarea: true,
@@ -151,7 +151,7 @@ var require_conventions = __commonJS({
151
151
  function hasDefaultHTMLNamespace(mimeType) {
152
152
  return isHTMLMimeType(mimeType) || mimeType === MIME_TYPE.XML_XHTML_APPLICATION;
153
153
  }
154
- var MIME_TYPE = freeze2({
154
+ var MIME_TYPE = freeze3({
155
155
  /**
156
156
  * `text/html`, the only mime type that triggers treating an XML document as HTML.
157
157
  *
@@ -204,7 +204,7 @@ var require_conventions = __commonJS({
204
204
  function isValidMimeType(mimeType) {
205
205
  return _MIME_TYPES.indexOf(mimeType) > -1;
206
206
  }
207
- var NAMESPACE = freeze2({
207
+ var NAMESPACE = freeze3({
208
208
  /**
209
209
  * The XHTML namespace.
210
210
  *
@@ -232,7 +232,7 @@ var require_conventions = __commonJS({
232
232
  });
233
233
  exports.assign = assign;
234
234
  exports.find = find;
235
- exports.freeze = freeze2;
235
+ exports.freeze = freeze3;
236
236
  exports.HTML_BOOLEAN_ATTRIBUTES = HTML_BOOLEAN_ATTRIBUTES;
237
237
  exports.HTML_RAW_TEXT_ELEMENTS = HTML_RAW_TEXT_ELEMENTS;
238
238
  exports.HTML_VOID_ELEMENTS = HTML_VOID_ELEMENTS;
@@ -387,10 +387,10 @@ var require_errors = __commonJS({
387
387
  INVALID_NODE_TYPE_ERR: 24,
388
388
  DATA_CLONE_ERR: 25
389
389
  };
390
- var entries = Object.entries(ExceptionCode);
391
- for (i = 0; i < entries.length; i++) {
392
- key = entries[i][0];
393
- DOMException[key] = entries[i][1];
390
+ var entries2 = Object.entries(ExceptionCode);
391
+ for (i = 0; i < entries2.length; i++) {
392
+ key = entries2[i][0];
393
+ DOMException[key] = entries2[i][1];
394
394
  }
395
395
  var key;
396
396
  var i;
@@ -2700,23 +2700,23 @@ var require_dom = __commonJS({
2700
2700
  substringData: function(offset, count) {
2701
2701
  return this.data.substring(offset, offset + count);
2702
2702
  },
2703
- appendData: function(text) {
2704
- text = this.data + text;
2705
- this.nodeValue = this.data = text;
2706
- this.length = text.length;
2703
+ appendData: function(text2) {
2704
+ text2 = this.data + text2;
2705
+ this.nodeValue = this.data = text2;
2706
+ this.length = text2.length;
2707
2707
  },
2708
- insertData: function(offset, text) {
2709
- this.replaceData(offset, 0, text);
2708
+ insertData: function(offset, text2) {
2709
+ this.replaceData(offset, 0, text2);
2710
2710
  },
2711
2711
  deleteData: function(offset, count) {
2712
2712
  this.replaceData(offset, count, "");
2713
2713
  },
2714
- replaceData: function(offset, count, text) {
2714
+ replaceData: function(offset, count, text2) {
2715
2715
  var start = this.data.substring(0, offset);
2716
2716
  var end = this.data.substring(offset + count);
2717
- text = start + text + end;
2718
- this.nodeValue = this.data = text;
2719
- this.length = text.length;
2717
+ text2 = start + text2 + end;
2718
+ this.nodeValue = this.data = text2;
2719
+ this.length = text2.length;
2720
2720
  }
2721
2721
  };
2722
2722
  _extends(CharacterData, Node);
@@ -2727,11 +2727,11 @@ var require_dom = __commonJS({
2727
2727
  nodeName: "#text",
2728
2728
  nodeType: TEXT_NODE,
2729
2729
  splitText: function(offset) {
2730
- var text = this.data;
2731
- var newText = text.substring(offset);
2732
- text = text.substring(0, offset);
2733
- this.data = this.nodeValue = text;
2734
- this.length = text.length;
2730
+ var text2 = this.data;
2731
+ var newText = text2.substring(offset);
2732
+ text2 = text2.substring(0, offset);
2733
+ this.data = this.nodeValue = text2;
2734
+ this.length = text2.length;
2735
2735
  var newNode = this.ownerDocument.createTextNode(newText);
2736
2736
  if (this.parentNode) {
2737
2737
  this.parentNode.insertBefore(newNode, this.nextSibling);
@@ -3286,15 +3286,15 @@ var require_dom = __commonJS({
3286
3286
  var require_entities = __commonJS({
3287
3287
  "node_modules/@xmldom/xmldom/lib/entities.js"(exports) {
3288
3288
  "use strict";
3289
- var freeze2 = require_conventions().freeze;
3290
- exports.XML_ENTITIES = freeze2({
3289
+ var freeze3 = require_conventions().freeze;
3290
+ exports.XML_ENTITIES = freeze3({
3291
3291
  amp: "&",
3292
3292
  apos: "'",
3293
3293
  gt: ">",
3294
3294
  lt: "<",
3295
3295
  quot: '"'
3296
3296
  });
3297
- exports.HTML_ENTITIES = freeze2({
3297
+ exports.HTML_ENTITIES = freeze3({
3298
3298
  Aacute: "\xC1",
3299
3299
  aacute: "\xE1",
3300
3300
  Abreve: "\u0102",
@@ -5526,12 +5526,12 @@ var require_sax = __commonJS({
5526
5526
  }
5527
5527
  if (!source.substring(start).match(/^\s*$/)) {
5528
5528
  var doc = domBuilder.doc;
5529
- var text = doc.createTextNode(source.substring(start));
5529
+ var text2 = doc.createTextNode(source.substring(start));
5530
5530
  if (doc.documentElement) {
5531
5531
  return errorHandler.error("Extra content at the end of the document");
5532
5532
  }
5533
- doc.appendChild(text);
5534
- domBuilder.currentElement = text;
5533
+ doc.appendChild(text2);
5534
+ domBuilder.currentElement = text2;
5535
5535
  }
5536
5536
  return;
5537
5537
  }
@@ -5916,11 +5916,11 @@ var require_sax = __commonJS({
5916
5916
  if (elEndStart < 0) {
5917
5917
  return elStartEnd + 1;
5918
5918
  }
5919
- var text = source.substring(elStartEnd + 1, elEndStart);
5919
+ var text2 = source.substring(elStartEnd + 1, elEndStart);
5920
5920
  if (isEscapableRaw) {
5921
- text = text.replace(ENTITY_REG, entityReplacer);
5921
+ text2 = text2.replace(ENTITY_REG, entityReplacer);
5922
5922
  }
5923
- domBuilder.characters(text, 0, text.length);
5923
+ domBuilder.characters(text2, 0, text2.length);
5924
5924
  return elEndStart;
5925
5925
  }
5926
5926
  return elStartEnd + 1;
@@ -5957,11 +5957,11 @@ var require_sax = __commonJS({
5957
5957
  function substringFromIndex() {
5958
5958
  return source.substring(index);
5959
5959
  }
5960
- function substringStartsWith(text) {
5961
- return source.substring(index, index + text.length) === text;
5960
+ function substringStartsWith(text2) {
5961
+ return source.substring(index, index + text2.length) === text2;
5962
5962
  }
5963
- function substringStartsWithCaseInsensitive(text) {
5964
- return source.substring(index, index + text.length).toUpperCase() === text.toUpperCase();
5963
+ function substringStartsWithCaseInsensitive(text2) {
5964
+ return source.substring(index, index + text2.length).toUpperCase() === text2.toUpperCase();
5965
5965
  }
5966
5966
  function getMatch(args) {
5967
5967
  var expr = g.reg("^", args);
@@ -6519,6 +6519,40 @@ var require_lib = __commonJS({
6519
6519
  }
6520
6520
  });
6521
6521
 
6522
+ // src/commands.js
6523
+ var CommandRegistry = class {
6524
+ #groups = /* @__PURE__ */ new Map();
6525
+ registerGroup(namespace, metadata = {}) {
6526
+ if (typeof namespace !== "string" || !namespace || namespace.includes(":")) {
6527
+ throw new TypeError("Extension command namespace must be nonempty and unqualified");
6528
+ }
6529
+ if (this.#groups.has(namespace)) throw new Error(`Duplicate command namespace: ${namespace}`);
6530
+ if (!metadata || typeof metadata !== "object" || Array.isArray(metadata) || Object.keys(metadata).some((key) => !["author", "description"].includes(key)) || Object.values(metadata).some((value) => typeof value !== "string")) {
6531
+ throw new TypeError(`Invalid command group metadata: ${namespace}`);
6532
+ }
6533
+ const commands = /* @__PURE__ */ new Map();
6534
+ this.#groups.set(namespace, { metadata: { ...metadata }, commands });
6535
+ return Object.freeze({ register(name, definition) {
6536
+ if (typeof name !== "string" || !name || name.includes(":")) throw new TypeError("Invalid command name");
6537
+ if (commands.has(name)) throw new Error(`Duplicate command: ${namespace}:${name}`);
6538
+ if (!definition || typeof definition !== "object" || Array.isArray(definition) || !Object.hasOwn(definition, "label") || !Object.hasOwn(definition, "publish") || Object.keys(definition).some((key) => !["label", "publish", "icon", "iconSrc", "tooltip"].includes(key)) || Object.values(definition).some((value) => typeof value !== "string")) {
6539
+ throw new TypeError(`Invalid command definition: ${namespace}:${name}`);
6540
+ }
6541
+ commands.set(name, Object.freeze({ ...definition }));
6542
+ } });
6543
+ }
6544
+ get(command) {
6545
+ const separator = command.indexOf(":");
6546
+ return this.#groups.get(command.slice(0, separator))?.commands.get(command.slice(separator + 1));
6547
+ }
6548
+ toDocument() {
6549
+ return {
6550
+ document_format: { name: "gramlot_commands", version: "1.0" },
6551
+ groups: Object.fromEntries([...this.#groups].map(([name, { metadata, commands }]) => [name, { ...metadata, commands: Object.fromEntries(commands) }]))
6552
+ };
6553
+ }
6554
+ };
6555
+
6522
6556
  // src/http-transport.js
6523
6557
  var HttpTransport = class {
6524
6558
  constructor(rpcUrl, {
@@ -6537,13 +6571,13 @@ var HttpTransport = class {
6537
6571
  get supportsCallSync() {
6538
6572
  return true;
6539
6573
  }
6540
- async call(text, signal) {
6574
+ async call(text2, signal) {
6541
6575
  const response = await this.fetcher(this.rpcUrl, {
6542
6576
  method: "POST",
6543
6577
  credentials: "same-origin",
6544
6578
  signal,
6545
6579
  headers: { "Content-Type": "application/json" },
6546
- body: text
6580
+ body: text2
6547
6581
  });
6548
6582
  if (response.status !== 200) throw new Error(`rpc failed: HTTP ${response.status}`);
6549
6583
  return response.text();
@@ -6553,11 +6587,11 @@ var HttpTransport = class {
6553
6587
  * a non-200 status throws. Browsers deprecate the synchronous request on the main thread: the page is
6554
6588
  * blocked until the answer arrives.
6555
6589
  */
6556
- callSync(text) {
6590
+ callSync(text2) {
6557
6591
  const request = new this.XMLHttpRequest();
6558
6592
  request.open("POST", this.rpcUrl, false);
6559
6593
  request.setRequestHeader("Content-Type", "application/json");
6560
- request.send(text);
6594
+ request.send(text2);
6561
6595
  if (request.status !== 200) throw new Error(`rpc failed: HTTP ${request.status}`);
6562
6596
  return request.responseText;
6563
6597
  }
@@ -6624,7 +6658,7 @@ function pointerTemplate(body, read) {
6624
6658
  }
6625
6659
  function pointerExpression(body) {
6626
6660
  const slots = [], identifiers = /* @__PURE__ */ new Set();
6627
- let text = "", operand = true;
6661
+ let text2 = "", operand = true;
6628
6662
  for (let i = 0; i < body.length; ) {
6629
6663
  const start = i, c = body[i];
6630
6664
  if (c === '"' || c === "'" || c === "`") {
@@ -6636,20 +6670,20 @@ function pointerExpression(body) {
6636
6670
  }
6637
6671
  if (body[i++] === c) break;
6638
6672
  }
6639
- text += body.slice(start, i);
6673
+ text2 += body.slice(start, i);
6640
6674
  operand = false;
6641
6675
  continue;
6642
6676
  }
6643
6677
  if (body.startsWith("//", i)) {
6644
6678
  i = body.indexOf("\n", i);
6645
6679
  if (i < 0) i = body.length;
6646
- text += body.slice(start, i);
6680
+ text2 += body.slice(start, i);
6647
6681
  continue;
6648
6682
  }
6649
6683
  if (body.startsWith("/*", i)) {
6650
6684
  const end = body.indexOf("*/", i + 2);
6651
6685
  i = end < 0 ? body.length : end + 2;
6652
- text += body.slice(start, i);
6686
+ text2 += body.slice(start, i);
6653
6687
  continue;
6654
6688
  }
6655
6689
  if (c === "/" && operand) {
@@ -6666,7 +6700,7 @@ function pointerExpression(body) {
6666
6700
  else if (current === "/" && !bracket) break;
6667
6701
  }
6668
6702
  while (/[a-z]/i.test(body[i] ?? "") && i < body.length) i++;
6669
- text += body.slice(start, i);
6703
+ text2 += body.slice(start, i);
6670
6704
  operand = false;
6671
6705
  continue;
6672
6706
  }
@@ -6674,7 +6708,7 @@ function pointerExpression(body) {
6674
6708
  if (slot) {
6675
6709
  const name = slot[1] ?? "";
6676
6710
  if (name.startsWith("?")) throw new SyntaxError("Optional slots are supported in pointer templates only");
6677
- text += `_pointerValues[${slots.length}]`;
6711
+ text2 += `_pointerValues[${slots.length}]`;
6678
6712
  slots.push(name);
6679
6713
  i += slot[0].length;
6680
6714
  operand = false;
@@ -6683,16 +6717,16 @@ function pointerExpression(body) {
6683
6717
  const word = body.slice(i).match(/^[A-Za-z_$][\w$]*/);
6684
6718
  if (word) {
6685
6719
  identifiers.add(word[0]);
6686
- text += word[0];
6720
+ text2 += word[0];
6687
6721
  i += word[0].length;
6688
6722
  operand = ["return", "typeof", "void", "delete", "new", "in", "instanceof", "yield", "await"].includes(word[0]);
6689
6723
  continue;
6690
6724
  }
6691
- text += c;
6725
+ text2 += c;
6692
6726
  i++;
6693
6727
  if (!/\s/.test(c)) operand = /[([{,:;=!?&|+*%~<>\/-]/.test(c);
6694
6728
  }
6695
- return { text, slots, identifiers };
6729
+ return { text: text2, slots, identifiers };
6696
6730
  }
6697
6731
  function resolvePointerItems(items, current, evaluate = () => null) {
6698
6732
  const values = /* @__PURE__ */ new Map(), active = [];
@@ -10181,8 +10215,8 @@ var Encoder = class _Encoder {
10181
10215
 
10182
10216
  // node_modules/@msgpack/msgpack/dist.esm/encode.mjs
10183
10217
  function encode(value, options) {
10184
- const encoder = new Encoder(options);
10185
- return encoder.encodeSharedRef(value);
10218
+ const encoder2 = new Encoder(options);
10219
+ return encoder2.encodeSharedRef(value);
10186
10220
  }
10187
10221
 
10188
10222
  // node_modules/@msgpack/msgpack/dist.esm/utils/prettyByte.mjs
@@ -14601,11 +14635,11 @@ var Bag = class _Bag {
14601
14635
  active.add(data);
14602
14636
  try {
14603
14637
  const width = Array.isArray(data) ? String(data.length).length + 1 : 0;
14604
- const entries = Array.isArray(data) ? Array.from(data, (value, i) => [`r_${String(i).padStart(width, "0")}`, value]) : Object.entries(data);
14638
+ const entries2 = Array.isArray(data) ? Array.from(data, (value, i) => [`r_${String(i).padStart(width, "0")}`, value]) : Object.entries(data);
14605
14639
  if (!Array.isArray(data) && Object.getOwnPropertySymbols(data).some((key) => Object.prototype.propertyIsEnumerable.call(data, key))) {
14606
14640
  throw new TypeError(`Bag labels must be strings at ${path}`);
14607
14641
  }
14608
- for (const [label, item] of entries) {
14642
+ for (const [label, item] of entries2) {
14609
14643
  let value = item;
14610
14644
  if (recursive && (isDictionary(value) || Array.isArray(value))) {
14611
14645
  value = this.createChildBag();
@@ -14961,9 +14995,9 @@ ${" ".repeat(depth)}</${tag2}>`;
14961
14995
  }
14962
14996
  return `<${tag2}${attrsStr}></${tag2}>`;
14963
14997
  }
14964
- const scalar = value instanceof Date && !Number.isNaN(value.getTime()) ? xmlDateText(value) : String(value);
14965
- const text = this._escapeXml(scalar);
14966
- return `<${tag2}${attrsStr}>${text}</${tag2}>`;
14998
+ const scalar2 = value instanceof Date && !Number.isNaN(value.getTime()) ? xmlDateText(value) : String(value);
14999
+ const text2 = this._escapeXml(scalar2);
15000
+ return `<${tag2}${attrsStr}>${text2}</${tag2}>`;
14967
15001
  }
14968
15002
  /**
14969
15003
  * Sanitize tag name for XML.
@@ -15075,19 +15109,19 @@ ${" ".repeat(depth)}</${tag2}>`;
15075
15109
  }
15076
15110
  const response = await fetch(url, fetchOptions);
15077
15111
  const contentType = response.headers.get("content-type") || "";
15078
- const text = await response.text();
15112
+ const text2 = await response.text();
15079
15113
  if (contentType.includes("json")) {
15080
- return _Bag.fromTytx(text);
15114
+ return _Bag.fromTytx(text2);
15081
15115
  }
15082
15116
  if (contentType.includes("xml")) {
15083
- return _Bag.fromXml(text);
15117
+ return _Bag.fromXml(text2);
15084
15118
  }
15085
- const trimmed = text.trim();
15119
+ const trimmed = text2.trim();
15086
15120
  if (trimmed.startsWith("<")) {
15087
- return _Bag.fromXml(text);
15121
+ return _Bag.fromXml(text2);
15088
15122
  }
15089
15123
  if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
15090
- return _Bag.fromTytx(text);
15124
+ return _Bag.fromTytx(text2);
15091
15125
  }
15092
15126
  throw new BagException(`Unsupported content-type: ${contentType}`);
15093
15127
  }
@@ -16367,9 +16401,9 @@ var RendererBase = class {
16367
16401
  }
16368
16402
  /** Compose string fragments and deliver the complete result. */
16369
16403
  finalize(result, target = null, _opts = {}) {
16370
- const text = this._composeStringFragments(result);
16404
+ const text2 = this._composeStringFragments(result);
16371
16405
  if (target === null || target === void 0) {
16372
- return text;
16406
+ return text2;
16373
16407
  }
16374
16408
  if (typeof target === "string") {
16375
16409
  throw new TypeError(
@@ -16377,15 +16411,15 @@ var RendererBase = class {
16377
16411
  );
16378
16412
  }
16379
16413
  if (typeof target.full === "function" && typeof target.write !== "function") {
16380
- target.full(text);
16414
+ target.full(text2);
16381
16415
  return null;
16382
16416
  }
16383
16417
  if (typeof target.write === "function") {
16384
- target.write(text);
16418
+ target.write(text2);
16385
16419
  return null;
16386
16420
  }
16387
16421
  if (typeof target === "function") {
16388
- target(text);
16422
+ target(text2);
16389
16423
  return null;
16390
16424
  }
16391
16425
  throw new TypeError(
@@ -16441,13 +16475,13 @@ var XmlRenderer = class extends RendererBase {
16441
16475
  return `${indent}<${tag2}${attrs}>${this._escapeText(item)}</${tag2}>${newline}`;
16442
16476
  }
16443
16477
  finalize(result, target = null, { docHeader = null } = {}) {
16444
- let text = this._composeStringFragments(result);
16478
+ let text2 = this._composeStringFragments(result);
16445
16479
  if (docHeader === true) {
16446
- text = `<?xml version='1.0' encoding='UTF-8'?>${text}`;
16480
+ text2 = `<?xml version='1.0' encoding='UTF-8'?>${text2}`;
16447
16481
  } else if (typeof docHeader === "string") {
16448
- text = docHeader + text;
16482
+ text2 = docHeader + text2;
16449
16483
  }
16450
- return super.finalize(text, target);
16484
+ return super.finalize(text2, target);
16451
16485
  }
16452
16486
  _formatAttrs(attrs) {
16453
16487
  return Object.entries(attrs || {}).map(([name, value]) => {
@@ -17210,14 +17244,14 @@ var BuilderBase = class _BuilderBase {
17210
17244
  * pointers find it through the ancestor climb. Built, rendered, dropped. */
17211
17245
  _expansionRoot(datapath = null) {
17212
17246
  const SourceClass = this.constructor._sourceClass;
17213
- const wrapper = new SourceClass(null, this);
17214
- wrapper.setBackref();
17215
- wrapper.setItem(
17247
+ const wrapper2 = new SourceClass(null, this);
17248
+ wrapper2.setBackref();
17249
+ wrapper2.setItem(
17216
17250
  SOURCE_ROOT,
17217
17251
  new SourceClass(null, this),
17218
17252
  datapath ? { datapath } : null
17219
17253
  );
17220
- return wrapper.getItem(SOURCE_ROOT);
17254
+ return wrapper2.getItem(SOURCE_ROOT);
17221
17255
  }
17222
17256
  /** Static lifecycle: setup → component declarations → main → logic. */
17223
17257
  create() {
@@ -17314,21 +17348,21 @@ function patternDate(value, pattern, locale, kind) {
17314
17348
  }).join("");
17315
17349
  }
17316
17350
  function formatDisplay(value, { format, mask, locale, dtype, places } = {}) {
17317
- let text = value == null ? "" : String(value);
17351
+ let text2 = value == null ? "" : String(value);
17318
17352
  if (value != null && value !== "" && (format != null && format !== "" || places != null)) {
17319
17353
  if (typeof value === "number" || isDecimal2(value)) {
17320
- text = formatNumber(value, { format, locale, places });
17354
+ text2 = formatNumber(value, { format, locale, places });
17321
17355
  } else {
17322
17356
  const kind = temporal(value, dtype);
17323
17357
  if (STYLES.has(format)) {
17324
17358
  const options = { timeZone: "UTC" };
17325
17359
  if (kind !== "H") options.dateStyle = format;
17326
17360
  if (kind !== "D") options.timeStyle = format;
17327
- text = new Intl.DateTimeFormat(locale || void 0, options).format(value);
17328
- } else text = patternDate(value, String(format), locale || void 0, kind);
17361
+ text2 = new Intl.DateTimeFormat(locale || void 0, options).format(value);
17362
+ } else text2 = patternDate(value, String(format), locale || void 0, kind);
17329
17363
  }
17330
17364
  }
17331
- return mask == null ? text : String(mask).replaceAll("%s", () => text);
17365
+ return mask == null ? text2 : String(mask).replaceAll("%s", () => text2);
17332
17366
  }
17333
17367
  function numericOptions({ format = "decimal", places } = {}) {
17334
17368
  const options = { maximumFractionDigits: 20 };
@@ -17454,10 +17488,10 @@ function parseStyle(value) {
17454
17488
  let escaped = false;
17455
17489
  let comment = false;
17456
17490
  let depth = 0;
17457
- const text = String(value);
17458
- for (let index = 0; index < text.length; index += 1) {
17459
- const char = text[index];
17460
- const next = text[index + 1];
17491
+ const text2 = String(value);
17492
+ for (let index = 0; index < text2.length; index += 1) {
17493
+ const char = text2[index];
17494
+ const next = text2[index + 1];
17461
17495
  if (comment) {
17462
17496
  if (char === "*" && next === "/") {
17463
17497
  comment = false;
@@ -17487,11 +17521,11 @@ function parseStyle(value) {
17487
17521
  } else if (")]}".includes(char) && depth > 0) {
17488
17522
  depth -= 1;
17489
17523
  } else if (char === ";" && depth === 0) {
17490
- declarations.push(text.slice(start, index));
17524
+ declarations.push(text2.slice(start, index));
17491
17525
  start = index + 1;
17492
17526
  }
17493
17527
  }
17494
- declarations.push(text.slice(start));
17528
+ declarations.push(text2.slice(start));
17495
17529
  for (const raw of declarations) {
17496
17530
  const entry = raw.trim();
17497
17531
  if (!entry) continue;
@@ -17547,8 +17581,8 @@ var HtmlRenderer = class extends RendererBase {
17547
17581
  return `${indent}<${tag2}${attrs}>${newline}${body}${indent}</${tag2}>${newline}`;
17548
17582
  }
17549
17583
  if (item === null || item === void 0) return `${indent}<${tag2}${attrs}></${tag2}>${newline}`;
17550
- const text = typeof item === "string" && item.endsWith("::HTML") ? item.slice(0, -6) : RAW_TEXT_TAGS.has(tag2) ? String(item) : this._escapeText(item);
17551
- return `${indent}<${tag2}${attrs}>${text}</${tag2}>${newline}`;
17584
+ const text2 = typeof item === "string" && item.endsWith("::HTML") ? item.slice(0, -6) : RAW_TEXT_TAGS.has(tag2) ? String(item) : this._escapeText(item);
17585
+ return `${indent}<${tag2}${attrs}>${text2}</${tag2}>${newline}`;
17552
17586
  }
17553
17587
  /** Resolve an inherited locale in the ancestor's own Data scope. */
17554
17588
  _displayLocale(node, locale) {
@@ -17627,8 +17661,8 @@ var HtmlRenderer = class extends RendererBase {
17627
17661
  return parts2.join("");
17628
17662
  }
17629
17663
  _htmlAttrValue(value) {
17630
- const text = value === true ? "true" : value === false ? "false" : String(value);
17631
- return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
17664
+ const text2 = value === true ? "true" : value === false ? "false" : String(value);
17665
+ return text2.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
17632
17666
  }
17633
17667
  _macro_rounded(value, subs, css) {
17634
17668
  const corners = value === void 0 ? {} : {
@@ -22147,8 +22181,8 @@ function freeze(value) {
22147
22181
  return Object.freeze(value);
22148
22182
  }
22149
22183
  function annotation2(parameter) {
22150
- if (typeof parameter.dtype !== "string" && !Array.isArray(parameter.dtype)) throw new TypeError("Component parameter requires dtype");
22151
- const alternatives = (Array.isArray(parameter.dtype) ? parameter.dtype : [parameter.dtype]).map((dtype) => ({ kind: "dtype", dtype }));
22184
+ if (!parameter.annotation && typeof parameter.dtype !== "string" && !Array.isArray(parameter.dtype)) throw new TypeError("Component parameter requires dtype");
22185
+ const alternatives = parameter.annotation ? [structuredClone(parameter.annotation)] : (Array.isArray(parameter.dtype) ? parameter.dtype : [parameter.dtype]).map((dtype) => ({ kind: "dtype", dtype }));
22152
22186
  if (parameter.nullable) alternatives.push({ kind: "dtype", dtype: "NN" });
22153
22187
  if (parameter.binding && parameter.dtype !== "T") alternatives.push({
22154
22188
  kind: "annotated",
@@ -22186,9 +22220,22 @@ function defineComponent({ name, tag: tag2, base, mixins = [], parameters: param
22186
22220
  implementation
22187
22221
  });
22188
22222
  }
22189
- var ComponentCollection = class {
22223
+ var ComponentCollection = class _ComponentCollection {
22190
22224
  #classes = /* @__PURE__ */ new WeakMap();
22191
- constructor({ name, components }) {
22225
+ constructor({ name, components, dependencies = [], css = [], assets = {}, registerCommands = () => {
22226
+ } }) {
22227
+ if (typeof name !== "string" || !name) throw new TypeError("Collection name must be nonempty");
22228
+ if (!Array.isArray(dependencies) || dependencies.some((item) => !(item instanceof _ComponentCollection))) {
22229
+ throw new TypeError("Collection dependencies must be collection objects");
22230
+ }
22231
+ if (!Array.isArray(css) || css.some((url) => !(url instanceof URL)) || !assets || typeof assets !== "object" || Array.isArray(assets) || Object.values(assets).some((url) => !(url instanceof URL))) {
22232
+ throw new TypeError("Collection css/assets require URL objects");
22233
+ }
22234
+ if (typeof registerCommands !== "function") throw new TypeError("registerCommands must be a function");
22235
+ this.dependencies = Object.freeze([...dependencies]);
22236
+ this.css = Object.freeze([...css]);
22237
+ this.assets = Object.freeze({ ...assets });
22238
+ this.registerCommands = registerCommands;
22192
22239
  this.name = name;
22193
22240
  this.components = Object.freeze([...components]);
22194
22241
  const names = /* @__PURE__ */ new Set(), tags = /* @__PURE__ */ new Set();
@@ -22299,7 +22346,7 @@ function controlElement(HTMLElement) {
22299
22346
  style.textContent = `:host{display:inline-block;font:inherit} *,*::before,*::after{box-sizing:border-box}
22300
22347
  input,textarea{font:inherit;max-width:100%} .control-box{min-width:0;color:var(--gramlot-ink,CanvasText)}
22301
22348
  input:not([type=checkbox]):not([type=radio]):not([type=range]):not([type=color]),textarea{
22302
- appearance:none;box-sizing:border-box;border:1px solid var(--gramlot-border-control,#7a8798);
22349
+ appearance:none;box-sizing:border-box;width:100%;border:1px solid var(--gramlot-border-control,#7a8798);
22303
22350
  border-radius:var(--gramlot-radius-sm,4px);background:var(--gramlot-field-background,Canvas);color:var(--gramlot-ink,CanvasText);
22304
22351
  min-height:var(--gramlot-field-height,28px);padding:var(--gramlot-field-padding,.25em .5em);font-size:var(--gramlot-field-font-size,1em);line-height:var(--gramlot-field-line-height,inherit)}
22305
22352
  input:read-only:not([type=checkbox]):not([type=radio]):not([type=range]):not([type=color]),textarea:read-only{
@@ -22433,9 +22480,9 @@ function ChoiceGroup(HTMLElement) {
22433
22480
  input.type = this.choiceType;
22434
22481
  input.name = "choice";
22435
22482
  input.value = code;
22436
- const text = this.ownerDocument.createElement("span");
22437
- label.append(input, text);
22438
- item = { label, input, text };
22483
+ const text2 = this.ownerDocument.createElement("span");
22484
+ label.append(input, text2);
22485
+ item = { label, input, text: text2 };
22439
22486
  this.#options.set(code, item);
22440
22487
  }
22441
22488
  item.text.textContent = caption;
@@ -22491,14 +22538,26 @@ ChoiceGroup.parameters = {
22491
22538
  // src/components/popup.js
22492
22539
  var VIEWPORT_MARGIN = 8;
22493
22540
  var ANCHOR_GAP = 3;
22494
- function positionPopup(popup, anchor, { align = "start", matchWidth = false, inset = 0 } = {}) {
22541
+ function positionPopup(popup, anchor, { align = "start", matchWidth = false, inset = 0, placement = "bottom", point = null } = {}) {
22495
22542
  const view = anchor.ownerDocument.defaultView;
22496
- const field = anchor.getBoundingClientRect();
22543
+ const field = point ? { left: point.x, right: point.x, top: point.y, bottom: point.y, width: 0 } : anchor.getBoundingClientRect();
22497
22544
  const availableWidth = Math.max(0, view.innerWidth - 2 * VIEWPORT_MARGIN);
22498
22545
  popup.style.setProperty("--gramlot-popup-available-width", `${availableWidth}px`);
22499
22546
  if (matchWidth) popup.style.width = `${Math.min(Math.max(0, field.width - 2 * inset), availableWidth)}px`;
22500
22547
  popup.style.removeProperty("--gramlot-popup-available-height");
22501
22548
  const natural = popup.getBoundingClientRect();
22549
+ if (placement === "side") {
22550
+ const right = Math.max(0, view.innerWidth - VIEWPORT_MARGIN - field.right - ANCHOR_GAP);
22551
+ const left2 = Math.max(0, field.left - VIEWPORT_MARGIN - ANCHOR_GAP);
22552
+ const opensLeft = natural.width > right && left2 > right;
22553
+ popup.style.setProperty("--gramlot-popup-available-width", `${opensLeft ? left2 : right}px`);
22554
+ popup.style.setProperty("--gramlot-popup-available-height", `${Math.max(0, view.innerHeight - 2 * VIEWPORT_MARGIN)}px`);
22555
+ const size2 = popup.getBoundingClientRect();
22556
+ const x = opensLeft ? field.left - size2.width - ANCHOR_GAP : field.right + ANCHOR_GAP;
22557
+ popup.style.left = `${Math.max(VIEWPORT_MARGIN, Math.min(x, view.innerWidth - size2.width - VIEWPORT_MARGIN))}px`;
22558
+ popup.style.top = `${Math.max(VIEWPORT_MARGIN, Math.min(field.top, view.innerHeight - size2.height - VIEWPORT_MARGIN))}px`;
22559
+ return;
22560
+ }
22502
22561
  const below = Math.max(0, view.innerHeight - VIEWPORT_MARGIN - field.bottom - ANCHOR_GAP);
22503
22562
  const above = Math.max(0, field.top - VIEWPORT_MARGIN - ANCHOR_GAP);
22504
22563
  const upwards = natural.height > below && above > below;
@@ -22510,439 +22569,109 @@ function positionPopup(popup, anchor, { align = "start", matchWidth = false, ins
22510
22569
  popup.style.top = `${Math.max(VIEWPORT_MARGIN, Math.min(top, view.innerHeight - size.height - VIEWPORT_MARGIN))}px`;
22511
22570
  }
22512
22571
 
22513
- // src/components/buttons.js
22514
- function Command(HTMLElement) {
22515
- return class extends controlElement(HTMLElement) {
22516
- constructor() {
22517
- super();
22518
- const doc = this.ownerDocument;
22519
- this.control = doc.createElement("button");
22520
- this.control.type = "button";
22521
- this.control.id = "control";
22522
- this.icon = doc.createElement("span");
22523
- this.icon.className = "icon";
22524
- this.icon.setAttribute("aria-hidden", "true");
22525
- this.caption = doc.createElement("slot");
22526
- this.control.append(this.icon, this.caption);
22527
- this.controlBox.append(this.control);
22528
- const style = doc.createElement("style");
22529
- style.textContent = `:host{vertical-align:middle} .control-box{display:flex;align-items:stretch}
22530
- button{display:inline-flex;align-items:center;justify-content:center;gap:var(--gramlot-button-gap,.35em);font:inherit;
22531
- color:var(--gramlot-ink,CanvasText);background:var(--gramlot-button-background,var(--gramlot-field-background,Canvas));
22532
- border:1px solid var(--gramlot-border-control,#888);border-radius:var(--gramlot-radius-sm,4px);
22533
- min-height:max(var(--gramlot-field-height,28px),var(--gramlot-touch-target,0px));
22534
- padding:var(--gramlot-button-padding,.25em .65em);cursor:pointer}
22535
- button:hover:not(:disabled){background:var(--gramlot-button-hover,var(--gramlot-field-readonly-background,#eee))}
22536
- :host(.button--quiet) button{background:transparent;color:var(--gramlot-action,CanvasText);border-color:transparent}
22537
- :host(.button--quiet) button:hover:not(:disabled){background:var(--gramlot-selected,Highlight);color:var(--gramlot-action-hover,CanvasText);border-color:transparent}
22538
- button:focus-visible{outline:2px solid var(--gramlot-focus-ring,Highlight);outline-offset:2px}
22539
- button:disabled{opacity:.55;cursor:not-allowed} .icon:empty{display:none}
22540
- .led{display:inline-block;width:.6em;height:.6em;border-radius:50%;background:var(--gramlot-button-led-off,#888)}
22541
- [aria-pressed=true] .led{background:var(--gramlot-button-led-on,#2b9a46)}
22542
- .arrow{border-start-start-radius:0;border-end-start-radius:0;border-inline-start:0}
22543
- .split{border-start-end-radius:0;border-end-end-radius:0}
22544
- .popup{position:fixed;inset:auto;margin:0;padding:var(--gramlot-popup-padding,4px);overflow:auto;
22545
- max-width:var(--gramlot-popup-available-width);max-height:var(--gramlot-popup-available-height);
22546
- border:1px solid var(--gramlot-border-control,#888);border-radius:var(--gramlot-radius-sm,4px);
22547
- color:var(--gramlot-ink,CanvasText);background:var(--gramlot-field-background,Canvas);box-shadow:0 3px 12px #0003}
22548
- :host([role=menuitem]){display:block} :host([role=menuitem]) button{width:100%;justify-content:start;border:0;background:transparent}
22549
- :host([role=separator]){display:block;border-top:1px solid var(--gramlot-border-control,#888);margin:.25em}
22550
- :host([role=separator]) button{display:none}`;
22551
- this.shadowRoot.append(style);
22552
- }
22553
- get disabled() {
22554
- return this.control.disabled;
22555
- }
22556
- set disabled(value) {
22557
- this.control.disabled = Boolean(value);
22558
- }
22559
- projectAttributes(attrs, adapt) {
22560
- const rest = super.projectAttributes(attrs, adapt);
22561
- this.control.disabled = Boolean(this.parameters.disabled);
22562
- this.control.readOnly = Boolean(this.parameters.readonly);
22563
- this.icon.textContent = this.parameters.icon ?? "";
22564
- if (attrs["aria-label"] != null) this.control.setAttribute("aria-label", attrs["aria-label"]);
22565
- else this.control.removeAttribute("aria-label");
22566
- return rest;
22567
- }
22568
- attachCommand() {
22569
- }
22570
- releaseCommand() {
22571
- }
22572
- commandTarget() {
22573
- return this;
22574
- }
22575
- prepareCommand() {
22576
- return !this.disabled;
22577
- }
22578
- };
22572
+ // src/format.js
22573
+ function validateMask(mask) {
22574
+ if (mask != null && (typeof mask !== "string" || /[{}]/.test(mask.replaceAll("{}", "")))) {
22575
+ throw new RangeError("This formatter mask supports only {} placeholders");
22576
+ }
22579
22577
  }
22580
- Command.parameters = {
22581
- disabled: { dtype: "B", default: false, binding: "read" },
22582
- icon: { dtype: "T", default: "", binding: "read" }
22583
- };
22584
- var Button = defineComponent({
22585
- name: "button",
22586
- tag: "gramlot-button",
22587
- base: Command,
22588
- command: true,
22589
- subTags: "*",
22590
- implementation: (Base) => class extends Base {
22578
+ function applyMask(text2, mask) {
22579
+ validateMask(mask);
22580
+ return mask == null ? text2 : mask.replaceAll("{}", () => text2);
22581
+ }
22582
+ function inferredType(value) {
22583
+ if (value instanceof Date) return getDateType(value);
22584
+ if (isDecimal2(value)) return "N";
22585
+ if (typeof value === "number") return Number.isInteger(value) ? "L" : "R";
22586
+ throw new TypeError("Formatting requires finite JavaScript numbers, TYTX Decimal values or valid Date objects");
22587
+ }
22588
+ function temporalText(value, dtype, { pattern = "short", locale, timeZone }) {
22589
+ if (!["short", "medium", "long", "full"].includes(pattern)) {
22590
+ throw new RangeError("Temporal formatting currently supports short, medium, long and full only");
22591
22591
  }
22592
- });
22593
- var ToggleButton = defineComponent({
22594
- name: "toggleButton",
22595
- tag: "gramlot-toggle-button",
22596
- base: Command,
22597
- command: true,
22598
- subTags: "*",
22599
- parameters: {
22600
- value: { dtype: "B", default: false, binding: "twoWay" },
22601
- readonly: { dtype: "B", default: false, binding: "read" }
22602
- },
22603
- implementation: (Base) => class extends Base {
22604
- #value = false;
22605
- constructor() {
22606
- super();
22607
- const led = this.ownerDocument.createElement("span");
22608
- led.className = "led";
22609
- led.setAttribute("aria-hidden", "true");
22610
- this.control.prepend(led);
22611
- this.writeControlValue(false);
22612
- }
22613
- get commitOnChange() {
22614
- return true;
22615
- }
22616
- readControlValue() {
22617
- return this.#value;
22618
- }
22619
- writeControlValue(value) {
22620
- this.#value = value;
22621
- this.control.setAttribute("aria-pressed", String(value));
22622
- }
22623
- prepareCommand(event) {
22624
- if (!super.prepareCommand(event) || this.control.readOnly) return false;
22625
- this.writeControlValue(!this.#value);
22626
- this.control.dispatchEvent(new this.ownerDocument.defaultView.Event("change"));
22627
- return true;
22628
- }
22592
+ if (dtype === "DHZ" && (typeof timeZone !== "string" || !timeZone)) {
22593
+ throw new TypeError("DHZ formatting currently requires an explicit timeZone");
22629
22594
  }
22630
- });
22631
- function MenuContainer(HTMLElement) {
22632
- return class extends HTMLElement {
22633
- constructor() {
22634
- super();
22635
- this.attachShadow({ mode: "open" }).append(this.ownerDocument.createElement("slot"));
22636
- }
22637
- connectedCallback() {
22638
- this.slot = "menu";
22639
- this.setAttribute("role", "menu");
22640
- }
22641
- projectAttributes(attrs) {
22642
- return projectParameters(this, attrs);
22595
+ const options = { timeZone: dtype === "DHZ" ? timeZone : "UTC" };
22596
+ if (dtype !== "H") options.dateStyle = pattern;
22597
+ if (dtype !== "D") options.timeStyle = pattern;
22598
+ return new Intl.DateTimeFormat(locale, options).format(value);
22599
+ }
22600
+ function numericSection(section) {
22601
+ const match = /^(-|\()?(#,##0|0+)(?:\.(0*#*))?(\))?$/.exec(section);
22602
+ if (!match || match[1] === "(" !== (match[4] === ")") || section.endsWith(".")) {
22603
+ throw new RangeError(`Unsupported numeric pattern section: ${section}`);
22604
+ }
22605
+ const fraction = match[3] ?? "";
22606
+ return {
22607
+ prefix: match[1] ?? "",
22608
+ suffix: match[4] ?? "",
22609
+ intl: {
22610
+ useGrouping: match[2].startsWith("#,##") ? "always" : false,
22611
+ minimumIntegerDigits: match[2].replace("#,##", "").length,
22612
+ minimumFractionDigits: fraction.replaceAll("#", "").length,
22613
+ maximumFractionDigits: fraction.length
22643
22614
  }
22644
22615
  };
22645
22616
  }
22646
- var Menu = defineComponent({
22647
- name: "menu",
22648
- tag: "gramlot-menu",
22649
- base: MenuContainer,
22650
- subTags: "menuline",
22651
- implementation: (Base) => class extends Base {
22617
+ function numericPattern(pattern) {
22618
+ const sections = pattern.split(";");
22619
+ if (sections.length > 3) throw new RangeError("Numeric patterns support at most three sections");
22620
+ const positive = numericSection(sections[0]);
22621
+ if (positive.prefix || positive.suffix) throw new RangeError("Positive-section affixes are not implemented");
22622
+ const zero = sections.length === 3 ? sections[1] : null;
22623
+ if (zero !== null && zero !== "" && zero !== "-") numericSection(zero);
22624
+ const negative = sections.length > 1 ? numericSection(sections.at(-1)) : null;
22625
+ return { positive, zero, negative };
22626
+ }
22627
+ function formatValue(value, options = {}, context = {}) {
22628
+ if (value === null) return "";
22629
+ if (typeof options === "string") options = { pattern: options };
22630
+ if (!options || typeof options !== "object" || Array.isArray(options)) {
22631
+ throw new TypeError("Format options must be a pattern string or an options object");
22652
22632
  }
22653
- });
22654
- var MenuLine = defineComponent({
22655
- name: "menuline",
22656
- tag: "gramlot-menu-line",
22657
- base: Command,
22658
- command: true,
22659
- subTags: "*",
22660
- parameters: { code: { dtype: "T", nullable: true } },
22661
- implementation: (Base) => class extends Base {
22662
- attachCommand() {
22663
- const separator = this.textContent.trim() === "-";
22664
- if (!separator && !this.parameters.code) throw new TypeError("menuline requires a stable code");
22665
- this.setAttribute("role", separator ? "separator" : "menuitem");
22666
- this.control.tabIndex = -1;
22667
- this.disabled ||= separator;
22668
- }
22669
- get disabled() {
22670
- return super.disabled || Boolean(this.closest("gramlot-drop-down-button")?.parameters.disabled);
22671
- }
22672
- set disabled(value) {
22673
- super.disabled = value;
22674
- }
22675
- prepareCommand(event) {
22676
- if (!super.prepareCommand(event)) return false;
22677
- this.closest("gramlot-drop-down-button").selectCommand(this, event.shiftKey);
22678
- return true;
22633
+ for (const key of Object.keys(options)) {
22634
+ if (!["pattern", "locale", "mask", "dtype", "timeZone"].includes(key)) throw new RangeError(`Unsupported format option: ${key}`);
22635
+ }
22636
+ options = { ...options, locale: options.locale ?? context.locale, timeZone: options.timeZone ?? context.timeZone };
22637
+ const dtype = options.dtype === void 0 ? inferredType(value) : options.dtype;
22638
+ const temporal2 = ["D", "H", "DHZ"].includes(dtype);
22639
+ if (!temporal2 && !["L", "R", "N"].includes(dtype)) throw new RangeError(`Unsupported format dtype: ${dtype}`);
22640
+ if (temporal2) {
22641
+ if (!(value instanceof Date) || !Number.isFinite(value.getTime())) throw new TypeError(`${dtype} requires a valid Date object`);
22642
+ } else if (!(typeof value === "number" && Number.isFinite(value)) && !(isDecimal2(value) && !["NaN", "Infinity", "-Infinity"].includes(value.toString()))) {
22643
+ throw new TypeError(`${dtype} formatting requires finite JavaScript numbers or TYTX Decimal values`);
22644
+ }
22645
+ if (dtype === "L" && !Number.isInteger(value)) throw new TypeError("L formatting requires an integer");
22646
+ const { pattern, locale, mask } = options;
22647
+ if (!temporal2 && typeof pattern !== "string") throw new TypeError("Numeric formatting currently requires an explicit pattern");
22648
+ if (typeof locale !== "string" || !locale) throw new TypeError("Formatting currently requires an explicit locale");
22649
+ const intl = temporal2 ? Intl.DateTimeFormat : Intl.NumberFormat;
22650
+ if (!intl.supportedLocalesOf([locale]).length) throw new RangeError(`Unsupported format locale: ${locale}`);
22651
+ validateMask(mask);
22652
+ if (temporal2) {
22653
+ const text3 = temporalText(value, dtype, options);
22654
+ return applyMask(text3, mask);
22655
+ }
22656
+ const { positive, zero, negative } = numericPattern(pattern);
22657
+ const decimal = isDecimal2(value);
22658
+ const zeroValue = decimal ? value.eq(0) : value === 0;
22659
+ const negativeValue = decimal ? value.lt(0) : value < 0;
22660
+ if (decimal && new Intl.NumberFormat("en", { useGrouping: false }).format("9007199254740993") !== "9007199254740993") throw new Error("This browser cannot format Decimal without precision loss");
22661
+ let text2;
22662
+ if (zeroValue && zero !== null) {
22663
+ if (zero === "") return "";
22664
+ if (zero === "-") text2 = "-";
22665
+ else {
22666
+ const section = numericSection(zero);
22667
+ text2 = section.prefix + new Intl.NumberFormat(locale, section.intl).format(0) + section.suffix;
22679
22668
  }
22669
+ } else {
22670
+ const affix = negativeValue && negative ? negative : positive;
22671
+ const number = decimal ? (negativeValue && negative ? value.abs() : value).toString() : negativeValue && negative ? -value : value === 0 ? 0 : value;
22672
+ text2 = affix.prefix + new Intl.NumberFormat(locale, positive.intl).format(number) + affix.suffix;
22680
22673
  }
22681
- });
22682
- var DropDownButton = defineComponent({
22683
- name: "dropDownButton",
22684
- tag: "gramlot-drop-down-button",
22685
- base: Command,
22686
- command: true,
22687
- subTags: "*",
22688
- parameters: { persist: { dtype: "B", default: false } },
22689
- implementation: (Base) => class extends Base {
22690
- #selected = null;
22691
- #observer = null;
22692
- #viewport = null;
22693
- #storageKey = null;
22694
- #popup;
22695
- #arrow;
22696
- #chosenCaption;
22697
- constructor() {
22698
- super();
22699
- const doc = this.ownerDocument;
22700
- this.control.classList.add("split");
22701
- this.#chosenCaption = doc.createElement("span");
22702
- this.#chosenCaption.hidden = true;
22703
- this.control.append(this.#chosenCaption);
22704
- this.#arrow = doc.createElement("button");
22705
- this.#arrow.type = "button";
22706
- this.#arrow.className = "arrow";
22707
- this.#arrow.textContent = "\u25BE";
22708
- this.#arrow.setAttribute("aria-label", "Open menu");
22709
- this.#arrow.setAttribute("aria-haspopup", "menu");
22710
- this.#arrow.setAttribute("aria-expanded", "false");
22711
- this.controlBox.append(this.#arrow);
22712
- this.#popup = doc.createElement("div");
22713
- this.#popup.className = "popup";
22714
- this.#popup.id = "menu";
22715
- this.#popup.setAttribute("popover", "auto");
22716
- this.#arrow.setAttribute("aria-controls", "menu");
22717
- const slot = doc.createElement("slot");
22718
- slot.name = "menu";
22719
- this.#popup.append(slot);
22720
- this.shadowRoot.append(this.#popup);
22721
- this.#arrow.addEventListener("click", (event) => {
22722
- event.stopPropagation();
22723
- if (this.#popup.matches(":popover-open")) this.closeMenu();
22724
- else this.openMenu();
22725
- });
22726
- this.#arrow.addEventListener("keydown", (event) => {
22727
- if (event.key === "ArrowDown" || event.key === "ArrowUp") {
22728
- event.preventDefault();
22729
- this.openMenu(event.key === "ArrowUp");
22730
- }
22731
- });
22732
- this.addEventListener("keydown", (event) => {
22733
- if (!this.#popup.matches(":popover-open")) return;
22734
- const items = this.menuItems.filter((item) => !item.disabled);
22735
- const index = items.indexOf(event.composedPath().find((item) => items.includes(item)));
22736
- let next;
22737
- if (event.key === "ArrowDown") next = (index + 1) % items.length;
22738
- if (event.key === "ArrowUp") next = (index - 1 + items.length) % items.length;
22739
- if (event.key === "Home") next = 0;
22740
- if (event.key === "End") next = items.length - 1;
22741
- if (next !== void 0) {
22742
- event.preventDefault();
22743
- items[next]?.focus();
22744
- }
22745
- if (event.key === "Escape" || event.key === "Tab") {
22746
- if (event.key === "Escape") event.preventDefault();
22747
- this.closeMenu();
22748
- }
22749
- });
22750
- this.#popup.addEventListener("toggle", () => {
22751
- const open = this.#popup.matches(":popover-open");
22752
- this.#arrow.setAttribute("aria-expanded", String(open));
22753
- if (!open) {
22754
- this.#viewport?.abort();
22755
- this.#viewport = null;
22756
- }
22757
- });
22758
- }
22759
- get menuItems() {
22760
- return [...this.querySelectorAll(":scope > gramlot-menu > gramlot-menu-line")];
22761
- }
22762
- projectAttributes(attrs, adapt) {
22763
- const rest = super.projectAttributes(attrs, adapt);
22764
- this.#arrow.disabled = this.disabled;
22765
- if (this.disabled && this.#popup.matches(":popover-open")) this.closeMenu();
22766
- this.#refreshCaption();
22767
- return rest;
22768
- }
22769
- attachCommand() {
22770
- if (this.parameters.persist) {
22771
- if (!this.id) throw new TypeError("dropDownButton persist requires an explicit id");
22772
- this.#storageKey = `gramlot:command:${this.ownerDocument.location.pathname}${this.ownerDocument.location.search}:${this.id}`;
22773
- try {
22774
- this.#selected = this.ownerDocument.defaultView.localStorage.getItem(this.#storageKey);
22775
- } catch {
22776
- }
22777
- }
22778
- this.#refreshCaption();
22779
- this.#observer = new this.ownerDocument.defaultView.MutationObserver(() => this.#refreshCaption());
22780
- this.#observer.observe(this, { childList: true, subtree: true, characterData: true });
22781
- }
22782
- releaseCommand() {
22783
- this.#observer?.disconnect();
22784
- this.#observer = null;
22785
- this.#viewport?.abort();
22786
- this.#viewport = null;
22787
- if (this.#popup.matches(":popover-open")) this.#popup.hidePopover();
22788
- }
22789
- commandTarget(event) {
22790
- if (event?.composedPath().includes(this.#popup)) return null;
22791
- return this.menuItems.find((item) => item.parameters.code === this.#selected) ?? this;
22792
- }
22793
- selectCommand(item, remember) {
22794
- if (remember) {
22795
- this.#selected = item.parameters.code;
22796
- if (this.#storageKey) {
22797
- try {
22798
- this.ownerDocument.defaultView.localStorage.setItem(this.#storageKey, this.#selected);
22799
- } catch {
22800
- }
22801
- }
22802
- this.#refreshCaption();
22803
- }
22804
- this.closeMenu();
22805
- }
22806
- #refreshCaption() {
22807
- const codes = this.menuItems.filter((item) => item.parameters.code).map((item) => item.parameters.code);
22808
- if (new Set(codes).size !== codes.length) throw new TypeError("Dropdown menu codes must be unique");
22809
- const target = this.commandTarget();
22810
- const selected = target !== this;
22811
- this.caption.hidden = selected;
22812
- this.#chosenCaption.hidden = !selected;
22813
- this.#chosenCaption.textContent = selected ? target.textContent : "";
22814
- this.icon.textContent = selected ? target.parameters.icon : this.parameters.icon;
22815
- }
22816
- openMenu(last = false) {
22817
- if (this.disabled) return;
22818
- const items = this.menuItems.filter((item) => !item.disabled);
22819
- if (!items.length) return;
22820
- this.#popup.showPopover();
22821
- this.#arrow.setAttribute("aria-expanded", "true");
22822
- const place = () => positionPopup(this.#popup, this.controlBox);
22823
- place();
22824
- this.#viewport?.abort();
22825
- this.#viewport = new this.ownerDocument.defaultView.AbortController();
22826
- const options = { signal: this.#viewport.signal, capture: true };
22827
- this.ownerDocument.defaultView.addEventListener("resize", place, options);
22828
- this.ownerDocument.addEventListener("scroll", place, options);
22829
- items[last ? items.length - 1 : 0].focus();
22830
- }
22831
- closeMenu() {
22832
- if (!this.#popup.matches(":popover-open")) return;
22833
- this.#popup.hidePopover();
22834
- this.#arrow.setAttribute("aria-expanded", "false");
22835
- this.#viewport?.abort();
22836
- this.#viewport = null;
22837
- this.#arrow.focus();
22838
- }
22839
- }
22840
- });
22841
- var buttons_default = defineCollection({ name: "buttons", components: [Button, ToggleButton, DropDownButton, Menu, MenuLine] });
22842
-
22843
- // src/format.js
22844
- function validateMask(mask) {
22845
- if (mask != null && (typeof mask !== "string" || /[{}]/.test(mask.replaceAll("{}", "")))) {
22846
- throw new RangeError("This formatter mask supports only {} placeholders");
22847
- }
22848
- }
22849
- function applyMask(text, mask) {
22850
- validateMask(mask);
22851
- return mask == null ? text : mask.replaceAll("{}", () => text);
22852
- }
22853
- function inferredType(value) {
22854
- if (value instanceof Date) return getDateType(value);
22855
- if (isDecimal2(value)) return "N";
22856
- if (typeof value === "number") return Number.isInteger(value) ? "L" : "R";
22857
- throw new TypeError("Formatting requires finite JavaScript numbers, TYTX Decimal values or valid Date objects");
22858
- }
22859
- function temporalText(value, dtype, { pattern = "short", locale, timeZone }) {
22860
- if (!["short", "medium", "long", "full"].includes(pattern)) {
22861
- throw new RangeError("Temporal formatting currently supports short, medium, long and full only");
22862
- }
22863
- if (dtype === "DHZ" && (typeof timeZone !== "string" || !timeZone)) {
22864
- throw new TypeError("DHZ formatting currently requires an explicit timeZone");
22865
- }
22866
- const options = { timeZone: dtype === "DHZ" ? timeZone : "UTC" };
22867
- if (dtype !== "H") options.dateStyle = pattern;
22868
- if (dtype !== "D") options.timeStyle = pattern;
22869
- return new Intl.DateTimeFormat(locale, options).format(value);
22870
- }
22871
- function numericSection(section) {
22872
- const match = /^(-|\()?(#,##0|0+)(?:\.(0*#*))?(\))?$/.exec(section);
22873
- if (!match || match[1] === "(" !== (match[4] === ")") || section.endsWith(".")) {
22874
- throw new RangeError(`Unsupported numeric pattern section: ${section}`);
22875
- }
22876
- const fraction = match[3] ?? "";
22877
- return {
22878
- prefix: match[1] ?? "",
22879
- suffix: match[4] ?? "",
22880
- intl: {
22881
- useGrouping: match[2].startsWith("#,##") ? "always" : false,
22882
- minimumIntegerDigits: match[2].replace("#,##", "").length,
22883
- minimumFractionDigits: fraction.replaceAll("#", "").length,
22884
- maximumFractionDigits: fraction.length
22885
- }
22886
- };
22887
- }
22888
- function numericPattern(pattern) {
22889
- const sections = pattern.split(";");
22890
- if (sections.length > 3) throw new RangeError("Numeric patterns support at most three sections");
22891
- const positive = numericSection(sections[0]);
22892
- if (positive.prefix || positive.suffix) throw new RangeError("Positive-section affixes are not implemented");
22893
- const zero = sections.length === 3 ? sections[1] : null;
22894
- if (zero !== null && zero !== "" && zero !== "-") numericSection(zero);
22895
- const negative = sections.length > 1 ? numericSection(sections.at(-1)) : null;
22896
- return { positive, zero, negative };
22897
- }
22898
- function formatValue(value, options = {}, context = {}) {
22899
- if (value === null) return "";
22900
- if (typeof options === "string") options = { pattern: options };
22901
- if (!options || typeof options !== "object" || Array.isArray(options)) {
22902
- throw new TypeError("Format options must be a pattern string or an options object");
22903
- }
22904
- for (const key of Object.keys(options)) {
22905
- if (!["pattern", "locale", "mask", "dtype", "timeZone"].includes(key)) throw new RangeError(`Unsupported format option: ${key}`);
22906
- }
22907
- options = { ...options, locale: options.locale ?? context.locale, timeZone: options.timeZone ?? context.timeZone };
22908
- const dtype = options.dtype === void 0 ? inferredType(value) : options.dtype;
22909
- const temporal2 = ["D", "H", "DHZ"].includes(dtype);
22910
- if (!temporal2 && !["L", "R", "N"].includes(dtype)) throw new RangeError(`Unsupported format dtype: ${dtype}`);
22911
- if (temporal2) {
22912
- if (!(value instanceof Date) || !Number.isFinite(value.getTime())) throw new TypeError(`${dtype} requires a valid Date object`);
22913
- } else if (!(typeof value === "number" && Number.isFinite(value)) && !(isDecimal2(value) && !["NaN", "Infinity", "-Infinity"].includes(value.toString()))) {
22914
- throw new TypeError(`${dtype} formatting requires finite JavaScript numbers or TYTX Decimal values`);
22915
- }
22916
- if (dtype === "L" && !Number.isInteger(value)) throw new TypeError("L formatting requires an integer");
22917
- const { pattern, locale, mask } = options;
22918
- if (!temporal2 && typeof pattern !== "string") throw new TypeError("Numeric formatting currently requires an explicit pattern");
22919
- if (typeof locale !== "string" || !locale) throw new TypeError("Formatting currently requires an explicit locale");
22920
- const intl = temporal2 ? Intl.DateTimeFormat : Intl.NumberFormat;
22921
- if (!intl.supportedLocalesOf([locale]).length) throw new RangeError(`Unsupported format locale: ${locale}`);
22922
- validateMask(mask);
22923
- if (temporal2) {
22924
- const text2 = temporalText(value, dtype, options);
22925
- return applyMask(text2, mask);
22926
- }
22927
- const { positive, zero, negative } = numericPattern(pattern);
22928
- const decimal = isDecimal2(value);
22929
- const zeroValue = decimal ? value.eq(0) : value === 0;
22930
- const negativeValue = decimal ? value.lt(0) : value < 0;
22931
- if (decimal && new Intl.NumberFormat("en", { useGrouping: false }).format("9007199254740993") !== "9007199254740993") throw new Error("This browser cannot format Decimal without precision loss");
22932
- let text;
22933
- if (zeroValue && zero !== null) {
22934
- if (zero === "") return "";
22935
- if (zero === "-") text = "-";
22936
- else {
22937
- const section = numericSection(zero);
22938
- text = section.prefix + new Intl.NumberFormat(locale, section.intl).format(0) + section.suffix;
22939
- }
22940
- } else {
22941
- const affix = negativeValue && negative ? negative : positive;
22942
- const number = decimal ? (negativeValue && negative ? value.abs() : value).toString() : negativeValue && negative ? -value : value === 0 ? 0 : value;
22943
- text = affix.prefix + new Intl.NumberFormat(locale, positive.intl).format(number) + affix.suffix;
22944
- }
22945
- return applyMask(text, mask);
22674
+ return applyMask(text2, mask);
22946
22675
  }
22947
22676
 
22948
22677
  // src/renderer/attributes.js
@@ -22995,7 +22724,7 @@ var NATIVE_ATTRIBUTES = {
22995
22724
  canvas: ["width", "height"]
22996
22725
  };
22997
22726
  var DISPLAY_ATTRIBUTES = ["format", "mask", "locale", "timeZone", "places", "dtype"];
22998
- var URL_ATTRIBUTES = /* @__PURE__ */ new Set(["href", "src", "formaction", "xlink:href", "xlink_href"]);
22727
+ var URL_ATTRIBUTES = /* @__PURE__ */ new Set(["href", "src", "action", "formaction", "xlink:href", "xlink_href"]);
22999
22728
  function withoutBindingAttributes(attrs) {
23000
22729
  return Object.fromEntries(Object.entries(attrs).filter(([name, value]) => !(value && typeof value === "object" && Object.hasOwn(value, "$gramlotRef")) && !BINDING_ATTRIBUTES.has(name) && !BINDING_ATTRIBUTE_PREFIXES.some((prefix) => name.startsWith(prefix))));
23001
22730
  }
@@ -23006,95 +22735,1096 @@ function requireStyleClassAttributes(node, attrs, prefixes = []) {
23006
22735
  if (["style", "class", "_class"].includes(bare) && value != null && typeof value !== "string") {
23007
22736
  throw new TypeError(`${node.nodeTag} '${node.label}': '${name}' must be a string or null`);
23008
22737
  }
23009
- }
23010
- }
23011
- function requireNoScriptAttributes(node, attrs, prefixes = []) {
23012
- if (attrs.onClose != null && !node.parentNode?._getMeta("gramlot_component")?.childParameters?.onClose) {
23013
- throw new Error("onClose is only supported on a tab/stack panel");
23014
- }
23015
- for (const [name, value] of Object.entries(withoutNullValues(withoutBindingAttributes(attrs)))) {
23016
- const prefix = prefixes.find((candidate) => name.startsWith(candidate));
23017
- const bare = prefix ? name.slice(prefix.length) : name;
23018
- if (/^on./i.test(bare)) {
23019
- throw new Error(`${node.nodeTag} '${node.label}': '${name}' has the form of a native event handler, run by the browser outside Gramlot; write connect_${bare} for an event, or rename the attribute`);
22738
+ }
22739
+ }
22740
+ function requireNoScriptAttributes(node, attrs, prefixes = []) {
22741
+ if (node.nodeTag === "script") {
22742
+ const executable = [["", node.staticValue], ...sourceAttributeItems(node.getAttr()).filter(([name]) => ["src", "href", "xlink:href", "xlink_href", "_text"].includes(name.slice((prefixes.find((prefix) => name.startsWith(prefix)) ?? "").length).toLowerCase()))];
22743
+ for (const [name, value] of executable) {
22744
+ if (node.pointerType(value) || isExpression(value)) {
22745
+ throw new Error(`script '${node.label}': '${name}' must be literal Source; script code and URLs cannot come from Data`);
22746
+ }
22747
+ }
22748
+ }
22749
+ if (attrs.onClose != null && !node.parentNode?._getMeta("gramlot_component")?.childParameters?.onClose) {
22750
+ throw new Error("onClose is only supported on a tab/stack panel");
22751
+ }
22752
+ for (const [name, value] of Object.entries(withoutNullValues(withoutBindingAttributes(attrs)))) {
22753
+ const prefix = prefixes.find((candidate) => name.startsWith(candidate));
22754
+ const bare = prefix ? name.slice(prefix.length) : name;
22755
+ if (/^on./i.test(bare)) {
22756
+ throw new Error(`${node.nodeTag} '${node.label}': '${name}' has the form of a native event handler, run by the browser outside Gramlot; write connect_${bare} for an event, or rename the attribute`);
22757
+ }
22758
+ if (URL_ATTRIBUTES.has(bare.toLowerCase()) && isJavascriptUrl(value)) {
22759
+ throw new Error(`${node.nodeTag} '${node.label}': '${name}' holds a javascript: URL, run by the browser as code; write connect_onclick or the action of a button instead`);
22760
+ }
22761
+ }
22762
+ }
22763
+ function isJavascriptUrl(value) {
22764
+ return typeof value === "string" && /^javascript:/i.test(value.replace(/[\t\n\r]/g, "").replace(/^[\u0000-\u0020]+/, ""));
22765
+ }
22766
+ function withDataSrcdocSandbox(node, attrs, prefixes = []) {
22767
+ if (node.nodeTag !== "iframe") return attrs;
22768
+ const bare = (name) => {
22769
+ const prefix = prefixes.find((candidate) => name.startsWith(candidate)) ?? "";
22770
+ return [prefix, name.slice(prefix.length).toLowerCase()];
22771
+ };
22772
+ const declared = Object.fromEntries(sourceAttributeItems(node.getAttr()));
22773
+ const srcdoc = [...Object.keys(declared), ...Object.keys(attrs)].find((name) => bare(name)[1] === "srcdoc");
22774
+ if (srcdoc === void 0 || Object.keys(declared).some((name) => bare(name)[1] === "sandbox")) return attrs;
22775
+ if (node.pointerType(node.value) === null && !(Object.hasOwn(declared, srcdoc) && (node.pointerType(declared[srcdoc]) !== null || isExpression(declared[srcdoc])))) return attrs;
22776
+ const rest = Object.fromEntries(Object.entries(attrs).filter(([name]) => bare(name)[1] !== "sandbox"));
22777
+ return { [`${bare(srcdoc)[0]}sandbox`]: "", ...rest };
22778
+ }
22779
+ function withoutNullValues(attrs) {
22780
+ return Object.fromEntries(Object.entries(attrs).filter(([, value]) => value != null));
22781
+ }
22782
+ function domNames(attrs) {
22783
+ return Object.fromEntries(Object.entries(attrs).map(([name, value]) => {
22784
+ if (name.startsWith("xmlns_")) return [`xmlns:${name.slice(6)}`, value];
22785
+ if (name.startsWith("data_") || name.startsWith("aria_")) return [name.replaceAll("_", "-"), value];
22786
+ return [name, value];
22787
+ }));
22788
+ }
22789
+ function boundaryAttributes(attrs) {
22790
+ const { _meta, ...rest } = attrs;
22791
+ return domNames(withoutNullValues(withoutBindingAttributes(rest)));
22792
+ }
22793
+ function splitNativeAttributes(tag2, attrs) {
22794
+ const names = NATIVE_ATTRIBUTES[String(tag2).toLowerCase()] ?? [];
22795
+ const rest = {};
22796
+ const native = {};
22797
+ for (const [name, value] of Object.entries(attrs)) {
22798
+ if (names.includes(name)) native[name] = value;
22799
+ else rest[name] = value;
22800
+ }
22801
+ return [rest, native];
22802
+ }
22803
+ function textValue(value) {
22804
+ return String(value);
22805
+ }
22806
+ function displayItem(item, attrs, format = null) {
22807
+ const rest = { ...attrs };
22808
+ const { mask, format: pattern, locale, timeZone, dtype, places } = rest;
22809
+ for (const name of DISPLAY_ATTRIBUTES) delete rest[name];
22810
+ const display = (value) => {
22811
+ if (format && pattern != null) {
22812
+ if (places != null) throw new RangeError("places is not implemented; specify precision in format");
22813
+ return format(value, {
22814
+ pattern,
22815
+ mask,
22816
+ ...locale == null ? {} : { locale },
22817
+ ...timeZone == null ? {} : { timeZone },
22818
+ ...dtype == null ? {} : { dtype }
22819
+ });
22820
+ }
22821
+ if (typeof value === "boolean") value = textValue(value);
22822
+ if (mask == null) return value;
22823
+ const text2 = value == null ? "" : textValue(value);
22824
+ return text2 === "" ? text2 : applyMask(text2, mask);
22825
+ };
22826
+ if (Array.isArray(item)) {
22827
+ if (Object.hasOwn(rest, "_text")) rest._text = display(rest._text);
22828
+ return [item, rest];
22829
+ }
22830
+ return [display(item), rest];
22831
+ }
22832
+ function isExpression(value) {
22833
+ return typeof value === "string" && value.startsWith("==");
22834
+ }
22835
+
22836
+ // src/components/toolbar-overflow.js
22837
+ var ToolbarOverflow = class {
22838
+ #menu;
22839
+ #viewport;
22840
+ #panel;
22841
+ #button;
22842
+ #resize;
22843
+ #events;
22844
+ #openEvents;
22845
+ #frame = null;
22846
+ #opened = false;
22847
+ #units = [];
22848
+ #overflow = /* @__PURE__ */ new Set();
22849
+ constructor(menu, slot) {
22850
+ this.#menu = menu;
22851
+ const doc = menu.ownerDocument;
22852
+ this.#viewport = doc.createElement("div");
22853
+ this.#viewport.className = "toolbar-viewport";
22854
+ this.#viewport.append(slot);
22855
+ this.#button = doc.createElement("button");
22856
+ this.#button.type = "button";
22857
+ this.#button.className = "toolbar-more";
22858
+ this.#button.hidden = true;
22859
+ this.#button.title = "More commands";
22860
+ const icon = doc.createElementNS(SVG_NS, "svg");
22861
+ icon.setAttribute("viewBox", "0 0 24 24");
22862
+ icon.setAttribute("aria-hidden", "true");
22863
+ icon.setAttribute("focusable", "false");
22864
+ const path = doc.createElementNS(SVG_NS, "path");
22865
+ path.setAttribute("d", "m5 6 6 6-6 6m8-12 6 6-6 6");
22866
+ path.setAttribute("fill", "none");
22867
+ path.setAttribute("stroke", "currentColor");
22868
+ path.setAttribute("stroke-width", "1.8");
22869
+ path.setAttribute("stroke-linecap", "round");
22870
+ path.setAttribute("stroke-linejoin", "round");
22871
+ icon.append(path);
22872
+ this.#button.append(icon);
22873
+ this.#button.setAttribute("aria-label", "More commands");
22874
+ this.#button.setAttribute("aria-haspopup", "menu");
22875
+ this.#button.setAttribute("aria-expanded", "false");
22876
+ this.#panel = doc.createElement("div");
22877
+ this.#panel.className = "toolbar-overflow";
22878
+ this.#panel.setAttribute("popover", "manual");
22879
+ this.#panel.setAttribute("role", "menu");
22880
+ this.#panel.tabIndex = -1;
22881
+ const overflowSlot = doc.createElement("slot");
22882
+ overflowSlot.name = "overflow";
22883
+ this.#panel.append(overflowSlot);
22884
+ this.#button.addEventListener("click", () => this.#opened ? this.close() : this.open());
22885
+ this.#button.addEventListener("keydown", (event) => {
22886
+ if (["ArrowDown", "ArrowRight"].includes(event.key)) {
22887
+ event.preventDefault();
22888
+ event.stopPropagation();
22889
+ this.open();
22890
+ }
22891
+ });
22892
+ this.#panel.addEventListener("keydown", (event) => {
22893
+ if (event.key === "Escape" && !event.composedPath().some((node) => node.localName === "gramlot-menu" && node !== menu)) {
22894
+ event.preventDefault();
22895
+ event.stopPropagation();
22896
+ this.close();
22897
+ }
22898
+ });
22899
+ const style = doc.createElement("style");
22900
+ style.textContent = `
22901
+ :host([role=toolbar]){min-width:0;min-height:0;max-width:100%;width:100%;flex-shrink:1;gap:0}
22902
+ :host([role=toolbar][aria-orientation=vertical]){width:auto;height:100%;max-height:100%}
22903
+ .toolbar-viewport{display:contents}
22904
+ :host([role=toolbar]) .toolbar-viewport{display:flex;align-items:center;gap:var(--gramlot-toolbar-gap,4px);flex:1 1 0%;min-width:0;min-height:0;overflow-x:auto;overflow-y:hidden}
22905
+ :host([role=toolbar][aria-orientation=vertical]) .toolbar-viewport{flex-direction:column;align-items:stretch;overflow-x:hidden;overflow-y:auto;width:100%}
22906
+ :host([role=toolbar]) ::slotted(*){flex-shrink:0}
22907
+ .toolbar-more{flex:0 0 auto;width:max(var(--gramlot-field-height,32px),var(--gramlot-touch-target,0px));height:max(var(--gramlot-field-height,32px),var(--gramlot-touch-target,0px));padding:0;border:0;border-radius:4px;background:transparent;color:inherit;font:inherit;display:grid;place-items:center}
22908
+ .toolbar-more svg{display:block;width:18px;height:18px;pointer-events:none}
22909
+ .toolbar-more:hover,.toolbar-more:focus-visible{background:var(--gramlot-selected,Highlight)}
22910
+ :host([role=toolbar][aria-orientation=vertical]) .toolbar-more{width:100%}
22911
+ .toolbar-more[hidden]{display:none}
22912
+ .toolbar-overflow{position:fixed;inset:auto;margin:0;padding:5px;box-sizing:border-box;min-width:min(16rem,var(--gramlot-popup-available-width));width:max-content;
22913
+ max-width:var(--gramlot-popup-available-width);max-height:var(--gramlot-popup-available-height);overflow:auto;
22914
+ background:var(--gramlot-field-background,Canvas);color:var(--gramlot-ink,CanvasText);border:1px solid var(--gramlot-border-control,#888);border-radius:var(--gramlot-radius-lg,9px);box-shadow:0 8px 28px #0004}
22915
+ .toolbar-overflow ::slotted([role=separator]){margin:5px 7px;border-top:1px solid var(--gramlot-border-control,#888)}
22916
+ `;
22917
+ menu.shadowRoot.append(style, this.#viewport, this.#button, this.#panel);
22918
+ }
22919
+ get opened() {
22920
+ return this.#opened;
22921
+ }
22922
+ get button() {
22923
+ return this.#button;
22924
+ }
22925
+ get panel() {
22926
+ return this.#panel;
22927
+ }
22928
+ contains(item) {
22929
+ let unit = item;
22930
+ while (unit && unit.parentElement !== this.#menu) unit = unit.parentElement;
22931
+ return this.#overflow.has(unit);
22932
+ }
22933
+ connect() {
22934
+ if (!this.#menu.permanent || this.#resize) return;
22935
+ const win = this.#menu.ownerDocument.defaultView;
22936
+ this.#events = new win.AbortController();
22937
+ this.#resize = new win.ResizeObserver(() => this.schedule());
22938
+ this.#resize.observe(this.#menu);
22939
+ this.#menu.ownerDocument.fonts.addEventListener("loadingdone", () => this.schedule(), { signal: this.#events.signal });
22940
+ this.schedule();
22941
+ }
22942
+ disconnect() {
22943
+ this.close(false);
22944
+ this.#resize?.disconnect();
22945
+ this.#resize = null;
22946
+ this.#events?.abort();
22947
+ if (this.#frame !== null) this.#menu.ownerDocument.defaultView.cancelAnimationFrame(this.#frame);
22948
+ this.#frame = null;
22949
+ this.#units = [];
22950
+ }
22951
+ schedule() {
22952
+ if (!this.#menu.isConnected) return;
22953
+ if (!this.#menu.permanent) {
22954
+ this.disconnect();
22955
+ for (const unit of this.#menu.children) {
22956
+ unit.removeAttribute("slot");
22957
+ unit.removeAttribute("data-menu-overflow");
22958
+ }
22959
+ this.#overflow.clear();
22960
+ this.#button.hidden = true;
22961
+ return;
22962
+ }
22963
+ if (!this.#resize) this.connect();
22964
+ if (this.#frame !== null) return;
22965
+ this.#frame = this.#menu.ownerDocument.defaultView.requestAnimationFrame(() => {
22966
+ this.#frame = null;
22967
+ this.layout();
22968
+ });
22969
+ }
22970
+ layout() {
22971
+ const menu = this.#menu, win = menu.ownerDocument.defaultView;
22972
+ if (!menu.permanent || !menu.isConnected) return;
22973
+ const vertical = menu.parameters.orientation === "vertical", axis = vertical ? "height" : "width";
22974
+ const style = win.getComputedStyle(menu);
22975
+ const available = (vertical ? menu.clientHeight : menu.clientWidth) - parseFloat(style[vertical ? "paddingTop" : "paddingLeft"] || 0) - parseFloat(style[vertical ? "paddingBottom" : "paddingRight"] || 0);
22976
+ if (available <= 0) return;
22977
+ let active = menu.ownerDocument.activeElement;
22978
+ while (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement;
22979
+ const units = [...menu.children].filter((unit) => !unit.hidden && (unit.localName !== "gramlot-menu" || unit.permanent));
22980
+ for (const unit of this.#units) if (!units.includes(unit)) {
22981
+ this.#resize.unobserve(unit);
22982
+ unit.removeAttribute("slot");
22983
+ unit.removeAttribute("data-menu-overflow");
22984
+ }
22985
+ for (const unit of units) if (!this.#units.includes(unit)) this.#resize.observe(unit);
22986
+ this.#units = units;
22987
+ for (const unit of units) {
22988
+ unit.removeAttribute("slot");
22989
+ unit.removeAttribute("data-menu-overflow");
22990
+ }
22991
+ this.#overflow.clear();
22992
+ menu.refreshItems();
22993
+ for (const item of menu.items) item.refreshAvailability();
22994
+ const gap = parseFloat(win.getComputedStyle(this.#viewport).gap) || 0;
22995
+ const lengths = new Map(units.map((unit) => {
22996
+ const css = win.getComputedStyle(unit);
22997
+ const length = unit.localName === "gramlot-spacer" ? unit.parameters.size ?? 0 : unit.getBoundingClientRect()[axis];
22998
+ return [unit, length + (parseFloat(css[vertical ? "marginTop" : "marginLeft"]) || 0) + (parseFloat(css[vertical ? "marginBottom" : "marginRight"]) || 0)];
22999
+ }));
23000
+ const separator = (unit) => unit.getAttribute("role") === "separator";
23001
+ const tidy = (list) => list.filter((unit, index) => !separator(unit) || list.slice(0, index).some((item) => item.localName !== "gramlot-spacer" && !separator(item)) && list.slice(index + 1).find((item) => item.localName !== "gramlot-spacer") && !separator(list.slice(index + 1).find((item) => item.localName !== "gramlot-spacer")));
23002
+ const required = (remaining2) => remaining2.reduce((sum2, unit) => sum2 + lengths.get(unit), 0) + Math.max(0, remaining2.length - 1) * gap;
23003
+ let remaining = tidy(units);
23004
+ if (required(remaining) > available) {
23005
+ const candidates = units.map((unit, index) => ({ unit, index })).filter(({ unit }) => unit.localName === "gramlot-menu-line" && !separator(unit) && unit.parameters.overflowable).sort((a, b) => a.unit.parameters.priority - b.unit.parameters.priority || b.index - a.index);
23006
+ for (const { unit } of candidates) {
23007
+ if (required(remaining) <= available - 32) break;
23008
+ this.#overflow.add(unit);
23009
+ remaining = tidy(remaining.filter((item) => item !== unit));
23010
+ }
23011
+ }
23012
+ const overflowRows = tidy(units.filter((unit) => this.#overflow.has(unit) || separator(unit) && !remaining.includes(unit)));
23013
+ for (const unit of overflowRows) this.#overflow.add(unit);
23014
+ for (const unit of units) if (separator(unit) && !remaining.includes(unit) && !this.#overflow.has(unit)) unit.slot = "suppressed";
23015
+ for (const unit of this.#overflow) {
23016
+ unit.slot = "overflow";
23017
+ unit.setAttribute("data-menu-overflow", "");
23018
+ }
23019
+ this.#button.hidden = this.#overflow.size === 0;
23020
+ for (const item of menu.items) item.refreshAvailability();
23021
+ menu.refreshItems();
23022
+ const activeUnit = units.find((unit) => {
23023
+ let node = active;
23024
+ while (node) {
23025
+ if (node === unit) return true;
23026
+ node = node.parentNode ?? node.host;
23027
+ }
23028
+ return false;
23029
+ });
23030
+ if (this.#overflow.size === 0) this.close(false);
23031
+ else if (activeUnit && this.#overflow.has(activeUnit)) this.open(false);
23032
+ else if (this.#opened) this.#place();
23033
+ if (activeUnit && active?.isConnected) active.focus({ preventScroll: true });
23034
+ menu.refreshItems();
23035
+ }
23036
+ #place() {
23037
+ positionPopup(this.#panel, this.#button, { placement: this.#menu.parameters.orientation === "vertical" ? "side" : "bottom" });
23038
+ }
23039
+ open(focus = true) {
23040
+ if (!this.#overflow.size) return;
23041
+ if (!this.#opened) {
23042
+ this.#panel.showPopover();
23043
+ this.#opened = true;
23044
+ this.#button.setAttribute("aria-expanded", "true");
23045
+ this.#openEvents = new this.#menu.ownerDocument.defaultView.AbortController();
23046
+ const options = { signal: this.#openEvents.signal };
23047
+ this.#menu.ownerDocument.addEventListener("pointerdown", (event) => {
23048
+ if (!event.composedPath().includes(this.#panel) && !event.composedPath().includes(this.#button)) this.close(false);
23049
+ }, options);
23050
+ this.#menu.ownerDocument.addEventListener("scroll", () => this.#place(), { ...options, capture: true });
23051
+ }
23052
+ this.#menu.refreshItems();
23053
+ this.#place();
23054
+ if (focus) {
23055
+ const focusable = (element) => {
23056
+ if (element.hidden || element.disabled) return null;
23057
+ if (element.localName === "gramlot-menu-line" && !element.parameters.group) return element.getAttribute("role") === "separator" ? null : element;
23058
+ if (element.matches('input:not([type=hidden]),textarea,select,button,[tabindex="0"]')) return element;
23059
+ for (const child of element.children) {
23060
+ const found = focusable(child);
23061
+ if (found) return found;
23062
+ }
23063
+ return null;
23064
+ };
23065
+ const target = [...this.#menu.children].filter((unit) => this.#overflow.has(unit)).map(focusable).find(Boolean);
23066
+ (target ?? this.#panel).focus();
23067
+ }
23068
+ }
23069
+ close(restore = true) {
23070
+ if (!this.#opened) return;
23071
+ for (const unit of this.#overflow) for (const child of unit.querySelectorAll("gramlot-menu")) if (!child.permanent) child.close(false);
23072
+ this.#panel.hidePopover();
23073
+ this.#opened = false;
23074
+ this.#openEvents?.abort();
23075
+ this.#button.setAttribute("aria-expanded", "false");
23076
+ if (restore && !this.#button.hidden) this.#button.focus();
23077
+ }
23078
+ };
23079
+
23080
+ // src/components/menus.js
23081
+ function MenuContainer(HTMLElement) {
23082
+ return class extends HTMLElement {
23083
+ #events;
23084
+ #observer;
23085
+ #active = null;
23086
+ #previous = [];
23087
+ #opener = null;
23088
+ #overflow;
23089
+ #message;
23090
+ #retry;
23091
+ #slot;
23092
+ #opened = false;
23093
+ #attachment;
23094
+ #attachmentEvents;
23095
+ constructor() {
23096
+ super();
23097
+ const doc = this.ownerDocument, shadow = this.attachShadow({ mode: "open" });
23098
+ const style = doc.createElement("style");
23099
+ style.textContent = `:host{box-sizing:border-box;color:var(--gramlot-ink,CanvasText)}
23100
+ :host([role=menu]){position:fixed;inset:auto;margin:0;padding:5px;min-width:min(16rem,var(--gramlot-popup-available-width));width:max-content;font:inherit;
23101
+ max-width:min(28rem,var(--gramlot-popup-available-width));max-height:var(--gramlot-popup-available-height);overflow:auto;
23102
+ background:var(--gramlot-field-background,Canvas);border:1px solid var(--gramlot-border-control,#888);border-radius:var(--gramlot-radius-lg,9px);box-shadow:0 8px 28px #0004}
23103
+ :host([role=toolbar][aria-orientation=vertical]){flex-direction:column;align-items:stretch}
23104
+ :host([role=toolbar]){display:flex;gap:var(--gramlot-toolbar-gap,4px);align-items:center}
23105
+ :host([role=menu]) ::slotted([role=separator]){margin:5px 7px 5px 2.5rem;border-top:1px solid var(--gramlot-border-control,#888)}
23106
+ :host([role=toolbar][aria-orientation=horizontal]) ::slotted([role=separator]){border-top:0;border-left:1px solid var(--gramlot-border-control,#888);align-self:stretch;margin:4px}
23107
+ :host([hidden]){display:none!important} slot{display:contents} .status{padding:.4em;opacity:.75}
23108
+ .status:empty{display:none} button{font:inherit}`;
23109
+ this.#slot = doc.createElement("slot");
23110
+ this.#message = doc.createElement("span");
23111
+ this.#message.className = "status";
23112
+ this.#message.setAttribute("role", "status");
23113
+ this.#retry = doc.createElement("button");
23114
+ this.#retry.textContent = "Riprova";
23115
+ this.#retry.hidden = true;
23116
+ this.#retry.addEventListener("click", (event) => {
23117
+ event.stopPropagation();
23118
+ this.menuBinding.load(true);
23119
+ });
23120
+ shadow.append(style, this.#slot, this.#message, this.#retry);
23121
+ this.#overflow = new ToolbarOverflow(this, this.#slot);
23122
+ this.addEventListener("keydown", (event) => this.#key(event));
23123
+ this.addEventListener("focusin", (event) => {
23124
+ const item = event.composedPath().find((node) => this.items.includes(node));
23125
+ if (item) {
23126
+ this.#active = item;
23127
+ this.refreshItems();
23128
+ }
23129
+ });
23130
+ }
23131
+ get permanent() {
23132
+ return this.parameters.presentation === "bar";
23133
+ }
23134
+ get opened() {
23135
+ return this.permanent || this.#opened;
23136
+ }
23137
+ get items() {
23138
+ return [...this.querySelectorAll("gramlot-menu-line")].filter((item) => item.menuOwner === this && !item.parameters.group);
23139
+ }
23140
+ get overflow() {
23141
+ return this.#overflow;
23142
+ }
23143
+ isOverflowed(item) {
23144
+ return this.#overflow.contains(item);
23145
+ }
23146
+ get usableItems() {
23147
+ return this.items.filter((item) => item.slot !== "suppressed" && !item.disabled && !item.hidden && !item.closest("[hidden]") && item.getAttribute("role") !== "separator");
23148
+ }
23149
+ get parentMenu() {
23150
+ return this.parentElement?.closest("gramlot-menu") ?? null;
23151
+ }
23152
+ connectedCallback() {
23153
+ this.#observer = new this.ownerDocument.defaultView.MutationObserver(() => {
23154
+ this.refreshItems();
23155
+ this.#overflow.schedule();
23156
+ });
23157
+ this.#observer.observe(this, { childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: ["hidden", "disabled"] });
23158
+ this.refreshItems();
23159
+ this.#attachOpening();
23160
+ this.#overflow.connect();
23161
+ if (this.permanent) this.menuBinding?.load();
23162
+ }
23163
+ disconnectedCallback() {
23164
+ this.#overflow.disconnect();
23165
+ this.#observer?.disconnect();
23166
+ this.#events?.abort();
23167
+ this.#attachmentEvents?.abort();
23168
+ this.#attachment = null;
23169
+ this.#opened = false;
23170
+ }
23171
+ projectAttributes(attrs) {
23172
+ const rest = projectParameters(this, attrs);
23173
+ this.#modifierKeys();
23174
+ if (!Number.isFinite(this.parameters.iconSize) || this.parameters.iconSize <= 0) throw new TypeError("menu iconSize must be positive");
23175
+ this.setAttribute("role", this.permanent ? "toolbar" : "menu");
23176
+ this.setAttribute("aria-orientation", this.permanent ? this.parameters.orientation : "vertical");
23177
+ this.tabIndex = -1;
23178
+ if (this.permanent) this.removeAttribute("popover");
23179
+ else this.setAttribute("popover", "manual");
23180
+ this.refreshItems();
23181
+ this.#overflow.schedule();
23182
+ return rest;
23183
+ }
23184
+ #modifierKeys() {
23185
+ const value = this.parameters.modifiers;
23186
+ if (value == null) return null;
23187
+ if (value === "*") return [];
23188
+ const keys = value.trim().toLowerCase().split(/[,\s]+/);
23189
+ if (!keys.length || keys.some((key) => !["shift", "ctrl", "alt", "meta"].includes(key)) || new Set(keys).size !== keys.length) {
23190
+ throw new TypeError("Menu modifiers require *, or a combination of Shift, Ctrl, Alt and Meta");
23191
+ }
23192
+ return keys;
23193
+ }
23194
+ #attachOpening() {
23195
+ const owner = this.parentElement;
23196
+ if (this.permanent || !owner) return;
23197
+ if (["gramlot-menu-line", "gramlot-drop-down-button"].includes(owner.localName)) {
23198
+ this.slot = "menu";
23199
+ return;
23200
+ }
23201
+ this.removeAttribute("slot");
23202
+ if (owner.localName === "gramlot-menu") return;
23203
+ this.#attachment = owner;
23204
+ this.#attachmentEvents = new this.ownerDocument.defaultView.AbortController();
23205
+ const options = { signal: this.#attachmentEvents.signal };
23206
+ const outsideMenus = (event) => !event.composedPath().some((node) => node.localName === "gramlot-menu");
23207
+ const open = (event) => {
23208
+ if (this.hidden || this.permanent || !outsideMenus(event)) return;
23209
+ if (event.composedPath().some((node) => node instanceof this.ownerDocument.defaultView.Element && (node.disabled === true || node.getAttribute("aria-disabled") === "true"))) return;
23210
+ const keys = this.#modifierKeys();
23211
+ if (event.type === "click") {
23212
+ if (keys === null || event.button !== 0 || ["shift", "ctrl", "alt", "meta"].some((key) => Boolean(event[key + "Key"]) !== keys.includes(key))) return;
23213
+ } else if (keys !== null) return;
23214
+ event.preventDefault();
23215
+ event.stopPropagation();
23216
+ const keyboard = event.type === "keydown";
23217
+ const rect = keyboard ? owner.getBoundingClientRect() : null;
23218
+ this.open(owner, false, keyboard ? { x: rect.left + 8, y: rect.top + 8 } : { x: event.clientX, y: event.clientY });
23219
+ };
23220
+ owner.addEventListener("click", open, options);
23221
+ owner.addEventListener("contextmenu", open, options);
23222
+ owner.addEventListener("keydown", (event) => {
23223
+ if (event.key === "ContextMenu" || event.key === "F10" && event.shiftKey && !event.ctrlKey && !event.altKey && !event.metaKey) open(event);
23224
+ }, options);
23225
+ }
23226
+ setStatus(status) {
23227
+ this.status = status;
23228
+ this.#message.textContent = { loading: "Caricamento\u2026", empty: "Nessuna voce", error: "Impossibile caricare" }[status] ?? "";
23229
+ this.#retry.hidden = status !== "error";
23230
+ this.setAttribute("aria-busy", String(status === "loading"));
23231
+ for (const item of this.items) item.refreshAvailability();
23232
+ this.refreshItems();
23233
+ }
23234
+ refreshItems() {
23235
+ for (const group of this.querySelectorAll("gramlot-menu-line")) if (group.menuOwner === this && group.parameters.group) group.refreshAvailability();
23236
+ for (const item of this.items) item.refreshAvailability();
23237
+ const usable = this.usableItems;
23238
+ if (this.#active && !usable.includes(this.#active)) {
23239
+ const index = this.#previous.indexOf(this.#active);
23240
+ const next = this.#previous.slice(index + 1).find((item) => usable.includes(item)) ?? this.#previous.slice(0, index).reverse().find((item) => usable.includes(item));
23241
+ this.#active = next ?? null;
23242
+ if (this.opened && this.status !== "loading") {
23243
+ if (next) next.focus();
23244
+ else if (this.permanent) this.focus();
23245
+ else this.close();
23246
+ }
23247
+ }
23248
+ const visible = usable.filter((item) => !this.isOverflowed(item));
23249
+ for (const item of this.items) item.control.tabIndex = this.permanent && item === (visible.includes(this.#active) ? this.#active : visible[0]) ? 0 : -1;
23250
+ this.#previous = this.items;
23251
+ }
23252
+ open(opener, last = false, point = null) {
23253
+ if (this.permanent) return;
23254
+ this.#opener = opener;
23255
+ if (!this.#opened) {
23256
+ this.showPopover();
23257
+ this.#opened = true;
23258
+ }
23259
+ opener.setAttribute("aria-expanded", "true");
23260
+ this.#events?.abort();
23261
+ this.#events = new this.ownerDocument.defaultView.AbortController();
23262
+ const options = { signal: this.#events.signal };
23263
+ const place = () => positionPopup(this, opener, { point, placement: this.parentMenu && (!this.parentMenu.permanent || this.parentMenu.parameters.orientation === "vertical" || this.parentMenu.isOverflowed(this.parentElement)) ? "side" : "bottom" });
23264
+ place();
23265
+ this.ownerDocument.defaultView.addEventListener("resize", place, options);
23266
+ this.ownerDocument.addEventListener("scroll", place, { ...options, capture: true });
23267
+ this.ownerDocument.addEventListener("pointerdown", (event) => {
23268
+ if (!event.composedPath().includes(this) && (opener === this.#attachment || !event.composedPath().includes(opener))) this.closeChain(false);
23269
+ }, options);
23270
+ this.menuBinding?.load().then(() => {
23271
+ if (this.#opened && (this.ownerDocument.activeElement === this || !this.contains(this.ownerDocument.activeElement))) this.focusEntry(last);
23272
+ if (this.#opened) place();
23273
+ });
23274
+ this.focusEntry(last);
23275
+ }
23276
+ focusEntry(last = false) {
23277
+ const usable = this.usableItems;
23278
+ const target = usable[last ? usable.length - 1 : 0];
23279
+ if (target) {
23280
+ this.#active = target;
23281
+ target.focus();
23282
+ } else this.focus();
23283
+ }
23284
+ close(restore = true) {
23285
+ for (const child of this.querySelectorAll("gramlot-menu")) if (!child.permanent) child.close(false);
23286
+ if (this.permanent) {
23287
+ this.#overflow.close(restore);
23288
+ return;
23289
+ }
23290
+ if (!this.#opened) return;
23291
+ this.hidePopover();
23292
+ this.#opened = false;
23293
+ this.#events?.abort();
23294
+ this.#opener?.setAttribute("aria-expanded", "false");
23295
+ if (restore && this.#opener?.isConnected) this.#opener.focus();
23296
+ }
23297
+ closeChain(restore = true) {
23298
+ const parent = this.parentMenu;
23299
+ this.close(restore && !parent);
23300
+ if (parent && !parent.permanent) parent.closeChain(restore);
23301
+ else if (parent?.isOverflowed(this.parentElement)) parent.overflow.close(restore);
23302
+ else if (restore && this.#opener?.isConnected) this.#opener.focus();
23303
+ }
23304
+ #key(event) {
23305
+ if (event.defaultPrevented || event.composedPath().find((node) => node.localName === "gramlot-menu") !== this) return;
23306
+ const item = event.composedPath().find((node) => this.items.includes(node));
23307
+ if (!item && event.target !== this) return;
23308
+ const inOverflow = item && this.isOverflowed(item);
23309
+ const items = this.usableItems.filter((entry) => this.isOverflowed(entry) === Boolean(inOverflow)), index = items.indexOf(item);
23310
+ const nextKey = this.permanent && !inOverflow && this.parameters.orientation === "horizontal" ? "ArrowRight" : "ArrowDown";
23311
+ const prevKey = this.permanent && !inOverflow && this.parameters.orientation === "horizontal" ? "ArrowLeft" : "ArrowUp";
23312
+ let next;
23313
+ if (event.key === nextKey) next = Math.min(items.length - 1, index + 1);
23314
+ if (event.key === prevKey) next = Math.max(0, index - 1);
23315
+ if (event.key === "Home") next = 0;
23316
+ if (event.key === "End") next = items.length - 1;
23317
+ if (next !== void 0) {
23318
+ event.preventDefault();
23319
+ event.stopPropagation();
23320
+ items[next]?.focus();
23321
+ return;
23322
+ }
23323
+ if ((!this.permanent || inOverflow) && event.key === "ArrowRight" && item?.submenu) {
23324
+ event.preventDefault();
23325
+ event.stopPropagation();
23326
+ item.openSubmenu();
23327
+ } else if (event.key === "Escape" && (!this.permanent || this.overflow.opened || this.items.some((entry) => entry.submenu?.opened)) || !this.permanent && event.key === "ArrowLeft" && this.parentMenu) {
23328
+ event.preventDefault();
23329
+ event.stopPropagation();
23330
+ this.close();
23331
+ } else if (event.key === "Tab") this.closeChain(false);
23332
+ }
23333
+ };
23334
+ }
23335
+ function menuLine(Base) {
23336
+ return class extends Base {
23337
+ #accessibleLabel;
23338
+ #group;
23339
+ #caption;
23340
+ #check;
23341
+ #arrow;
23342
+ #hover;
23343
+ #registry = null;
23344
+ #authoredDisabled = false;
23345
+ constructor() {
23346
+ super();
23347
+ const doc = this.ownerDocument;
23348
+ this.#caption = doc.createElement("span");
23349
+ this.#check = doc.createElement("span");
23350
+ this.#caption.className = "menu-caption";
23351
+ this.#check.className = "menu-check";
23352
+ this.#arrow = doc.createElement("span");
23353
+ this.#arrow.className = "menu-arrow";
23354
+ this.#arrow.setAttribute("aria-hidden", "true");
23355
+ this.#check.setAttribute("aria-hidden", "true");
23356
+ this.control.prepend(this.#check);
23357
+ this.control.append(this.#caption, this.#arrow);
23358
+ const style = doc.createElement("style");
23359
+ style.textContent = `:host{color:var(--gramlot-ink,CanvasText)} .control-box{color:inherit;height:100%} :host button{color:inherit}
23360
+ .menu-check:empty,.menu-arrow:empty{display:none}
23361
+ button.menu-row{display:grid;grid-template-columns:1em 1.15em minmax(0,1fr) .7em;column-gap:.5em;
23362
+ align-items:center;width:100%;min-height:max(min(var(--gramlot-field-height,28px),28px),var(--gramlot-touch-target,0px));padding:var(--gramlot-button-padding,3px 8px);
23363
+ line-height:1.3;text-align:left;border:0;border-radius:var(--gramlot-radius-sm,5px);background:transparent;cursor:default}
23364
+ .menu-row .menu-check,.menu-row .icon,.menu-row .menu-arrow{display:flex;align-items:center;justify-content:center;min-width:0}
23365
+ .menu-row .menu-check{grid-column:1}.menu-row .icon{grid-column:2}
23366
+ .menu-row .menu-caption{grid-column:3;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
23367
+ .menu-row .menu-arrow{grid-column:4;font-size:1.2em;line-height:1}
23368
+ button.menu-row:hover:not(:disabled),button.menu-row:focus-visible,button.menu-row[aria-expanded=true]{
23369
+ background:var(--gramlot-selected,Highlight);color:var(--gramlot-action-hover,HighlightText);outline:none}
23370
+ button.menu-row:disabled{opacity:.45;cursor:default}
23371
+ :host button.toolbar-button{position:relative;display:inline-flex;align-items:center;justify-content:center;gap:var(--gramlot-button-gap,6px);
23372
+ box-sizing:border-box;width:100%;height:100%;min-width:max(var(--gramlot-field-height,38px),var(--gramlot-touch-target,0px));min-height:max(var(--gramlot-field-height,38px),var(--gramlot-touch-target,0px));padding:var(--gramlot-button-padding,6px 5px);border:1px solid transparent;border-radius:var(--gramlot-radius-sm,8px);
23373
+ background:transparent;cursor:pointer;line-height:1.2;white-space:nowrap}
23374
+ :host button.toolbar-button .icon{display:inline-flex;align-items:center;justify-content:center;
23375
+ width:var(--gramlot-toolbar-icon-size);height:var(--gramlot-toolbar-icon-size);font-size:var(--gramlot-toolbar-icon-size);line-height:1}
23376
+ :host button.toolbar-button .icon:empty{display:none}
23377
+ :host button.toolbar-button:hover:not(:disabled){background:color-mix(in srgb,currentColor 10%,transparent)}
23378
+ :host button.toolbar-button:focus-visible{outline:2px solid var(--gramlot-focus-ring,Highlight);outline-offset:-2px}
23379
+ :host button.toolbar-button[aria-checked=true],:host button.toolbar-button[aria-expanded=true]{background:var(--gramlot-selected,color-mix(in srgb,currentColor 14%,transparent))}
23380
+ :host button.toolbar-button:disabled{opacity:.45;cursor:default}
23381
+ :host button.toolbar-below{flex-direction:column;gap:3px;min-width:54px}
23382
+ :host button.toolbar-below .menu-caption{font-size:11px;line-height:1.2}
23383
+ :host button.toolbar-tooltip .menu-caption{display:none}
23384
+ :host button.toolbar-button .menu-check{display:none}
23385
+ :host button.toolbar-tooltip .menu-arrow{position:absolute;right:3px;top:50%;transform:translateY(-50%);font-size:12px}
23386
+ :host button.toolbar-below .menu-arrow{position:absolute;inset:4px 3px auto auto;font-size:12px}`;
23387
+ style.textContent += `
23388
+ :host([role=group]){display:block;min-width:0}
23389
+ :host([role=group]) .control-box{display:none}
23390
+ .menu-group{display:flex;align-items:center;gap:var(--gramlot-toolbar-gap,4px);flex-wrap:nowrap}
23391
+ .menu-group ::slotted(*){flex-shrink:0}
23392
+ .menu-group[hidden]{display:none}
23393
+ :host([data-menu-overflow]) .menu-group,:host([data-menu-group-rows]) .menu-group{flex-direction:column;align-items:stretch;padding:3px 0}
23394
+ :host([data-menu-overflow][role=group]){border-block-end:1px solid var(--gramlot-border-control,#888);margin-block-end:4px}
23395
+ :host([role=group][aria-disabled=true]) .menu-group{opacity:.45;pointer-events:none}
23396
+ :host([hidden]){display:none!important}`;
23397
+ this.caption.name = "command-caption";
23398
+ this.#group = doc.createElement("div");
23399
+ this.#group.className = "menu-group";
23400
+ this.#group.append(doc.createElement("slot"));
23401
+ this.#group.hidden = true;
23402
+ this.shadowRoot.append(style, this.#group);
23403
+ const slot = doc.createElement("slot");
23404
+ slot.name = "menu";
23405
+ this.shadowRoot.append(slot);
23406
+ this.addEventListener("pointerenter", () => {
23407
+ if (this.menuOwner && (!this.menuOwner.permanent || this.menuOwner.isOverflowed(this)) && !this.disabled) {
23408
+ clearTimeout(this.#hover);
23409
+ this.#hover = setTimeout(() => {
23410
+ if (!this.isConnected || this.disabled || !this.menuOwner.opened) return;
23411
+ this.control.focus({ preventScroll: true });
23412
+ if (this.submenu) this.openSubmenu();
23413
+ else for (const sibling of this.menuOwner.items) sibling.submenu?.close(false);
23414
+ }, 180);
23415
+ }
23416
+ });
23417
+ this.addEventListener("pointerleave", () => clearTimeout(this.#hover));
23418
+ }
23419
+ get menuOwner() {
23420
+ return this.parentElement?.closest("gramlot-menu") ?? null;
23421
+ }
23422
+ get submenu() {
23423
+ return [...this.children].find((child) => child.localName === "gramlot-menu") ?? null;
23424
+ }
23425
+ get entryCaption() {
23426
+ return this.parameters.caption ?? this.#registry?.label ?? "";
23427
+ }
23428
+ get entryIcon() {
23429
+ return this.parameters.icon || this.parameters.iconSrc ? this.parameters.icon : this.#registry?.icon;
23430
+ }
23431
+ get entryIconSrc() {
23432
+ return this.parameters.icon || this.parameters.iconSrc ? this.parameters.iconSrc : this.#registry?.iconSrc;
23433
+ }
23434
+ get occurrence() {
23435
+ return this.parameters.code ?? this.sourceLabel;
23436
+ }
23437
+ setCommandDefinition(definition, sourceLabel) {
23438
+ this.#registry = definition;
23439
+ this.sourceLabel = sourceLabel;
23440
+ this.#render();
23441
+ }
23442
+ projectAttributes(attrs, adapt) {
23443
+ const rest = super.projectAttributes(attrs, adapt);
23444
+ this.#accessibleLabel = attrs["aria-label"];
23445
+ if (this.parameters.iconSize != null && (!Number.isFinite(this.parameters.iconSize) || this.parameters.iconSize <= 0)) throw new TypeError("menuline iconSize must be positive");
23446
+ if (!Number.isFinite(this.parameters.priority)) throw new TypeError("menuline priority must be finite");
23447
+ this.#authoredDisabled = Boolean(this.parameters.disabled);
23448
+ this.#render();
23449
+ this.menuOwner?.overflow.schedule();
23450
+ return rest;
23451
+ }
23452
+ #render() {
23453
+ const separator = [...this.childNodes].filter((node) => node.nodeType === 3).map((node) => node.textContent).join("").trim() === "-" && !this.parameters.command;
23454
+ this.setAttribute("role", this.parameters.group ? "group" : separator ? "separator" : this.parameters.checked == null ? "menuitem" : "menuitemcheckbox");
23455
+ this.#group.hidden = !this.parameters.group;
23456
+ this.setAttribute("aria-disabled", String(this.#authoredDisabled));
23457
+ if (this.parameters.checked != null) {
23458
+ this.setAttribute("aria-checked", String(this.parameters.checked));
23459
+ this.control.setAttribute("aria-checked", String(this.parameters.checked));
23460
+ } else {
23461
+ this.removeAttribute("aria-checked");
23462
+ this.control.removeAttribute("aria-checked");
23463
+ }
23464
+ this.#check.textContent = this.parameters.checked ? "\u2713" : "";
23465
+ this.#caption.textContent = this.parameters.command && !this.#registry ? "???" : this.entryCaption;
23466
+ this.caption.hidden = true;
23467
+ this.renderIcon(this.entryIcon, this.entryIconSrc);
23468
+ const tooltip = this.parameters.tooltip ?? this.#registry?.tooltip ?? this.entryCaption;
23469
+ this.control.title = tooltip;
23470
+ this.control.setAttribute("aria-label", this.#accessibleLabel ?? (this.entryCaption || tooltip));
23471
+ if (this.submenu) this.control.setAttribute("aria-haspopup", "menu");
23472
+ else this.control.removeAttribute("aria-haspopup");
23473
+ this.refreshAvailability();
23474
+ }
23475
+ refreshAvailability() {
23476
+ const owner = this.menuOwner;
23477
+ const popup = owner && (!owner.permanent || owner.isOverflowed(this));
23478
+ const inherited = (name) => {
23479
+ for (let node = this; node && node !== owner; node = node.parentElement) {
23480
+ if (node.localName === "gramlot-menu-line" && node.parameters[name] != null) return node.parameters[name];
23481
+ }
23482
+ return owner?.parameters[name];
23483
+ };
23484
+ const toolbar = Boolean(owner?.permanent && !popup);
23485
+ const labelPosition = inherited("labelPosition");
23486
+ this.control.classList.toggle("toolbar-button", toolbar);
23487
+ this.control.classList.toggle("toolbar-below", toolbar && labelPosition === "below");
23488
+ this.control.classList.toggle("toolbar-tooltip", toolbar && labelPosition === "tooltip");
23489
+ if (toolbar) this.control.style.setProperty("--gramlot-toolbar-icon-size", `${inherited("iconSize")}px`);
23490
+ else this.control.style.removeProperty("--gramlot-toolbar-icon-size");
23491
+ this.toggleAttribute("data-menu-group-rows", Boolean(popup || owner?.parameters.orientation === "vertical"));
23492
+ this.control.classList.toggle("menu-row", popup);
23493
+ this.#arrow.textContent = this.submenu ? popup || owner?.parameters.orientation === "vertical" ? "\u203A" : "\u25BE" : "";
23494
+ const disabled = this.#authoredDisabled || this.getAttribute("role") === "separator" || Boolean(this.parameters.command && !this.#registry) || ["loading", "error"].includes(owner?.status) || Boolean(this.closest("gramlot-drop-down-button")?.parameters.disabled);
23495
+ if (this.control.disabled !== disabled) this.control.disabled = disabled;
23496
+ }
23497
+ get disabled() {
23498
+ for (let p = this.parentElement; p && p !== this.menuOwner; p = p.parentElement) if (p.localName === "gramlot-menu-line" && p.parameters.disabled) return true;
23499
+ return this.control.disabled || Boolean(this.closest("gramlot-drop-down-button")?.parameters.disabled);
23500
+ }
23501
+ set disabled(value) {
23502
+ this.control.disabled = Boolean(value);
23503
+ }
23504
+ attachCommand() {
23505
+ this.#render();
23506
+ }
23507
+ releaseCommand() {
23508
+ clearTimeout(this.#hover);
23509
+ this.submenu?.close(false);
23510
+ }
23511
+ openSubmenu() {
23512
+ if (this.disabled || !this.submenu) return;
23513
+ for (const sibling of this.menuOwner.items) if (sibling !== this) sibling.submenu?.close(false);
23514
+ this.submenu.open(this.control);
23515
+ }
23516
+ prepareCommand(event) {
23517
+ if (this.parameters.group || this.disabled || this.hidden) return false;
23518
+ if (this.submenu) {
23519
+ event.stopPropagation();
23520
+ if (this.submenu.opened) this.submenu.close();
23521
+ else this.openSubmenu();
23522
+ return false;
23523
+ }
23524
+ const drop = this.menuOwner?.parentElement;
23525
+ if (drop?.localName === "gramlot-drop-down-button") drop.selectCommand(this, event.shiftKey);
23526
+ else this.menuOwner.closeChain();
23527
+ return true;
23528
+ }
23529
+ };
23530
+ }
23531
+
23532
+ // src/components/buttons.js
23533
+ function Command(HTMLElement) {
23534
+ return class extends controlElement(HTMLElement) {
23535
+ constructor() {
23536
+ super();
23537
+ const doc = this.ownerDocument;
23538
+ this.control = doc.createElement("button");
23539
+ this.control.type = "button";
23540
+ this.control.id = "control";
23541
+ this.icon = doc.createElement("span");
23542
+ this.icon.className = "icon";
23543
+ this.icon.setAttribute("aria-hidden", "true");
23544
+ this.caption = doc.createElement("slot");
23545
+ this.control.append(this.icon, this.caption);
23546
+ this.controlBox.append(this.control);
23547
+ const style = doc.createElement("style");
23548
+ style.textContent = `:host{vertical-align:middle} .control-box{display:flex;align-items:stretch}
23549
+ button{display:inline-flex;align-items:center;justify-content:center;gap:var(--gramlot-button-gap,.35em);font:inherit;
23550
+ color:var(--gramlot-ink,CanvasText);background:var(--gramlot-button-background,var(--gramlot-field-background,Canvas));
23551
+ border:1px solid var(--gramlot-border-control,#888);border-radius:var(--gramlot-radius-sm,4px);
23552
+ min-height:max(var(--gramlot-field-height,28px),var(--gramlot-touch-target,0px));
23553
+ padding:var(--gramlot-button-padding,.25em .65em);cursor:pointer}
23554
+ button:hover:not(:disabled){background:var(--gramlot-button-hover,var(--gramlot-field-readonly-background,#eee))}
23555
+ :host(.button--quiet) button{background:transparent;color:var(--gramlot-action,CanvasText);border-color:transparent}
23556
+ :host(.button--quiet) button:hover:not(:disabled){background:var(--gramlot-selected,Highlight);color:var(--gramlot-action-hover,CanvasText);border-color:transparent}
23557
+ button:focus-visible{outline:2px solid var(--gramlot-focus-ring,Highlight);outline-offset:2px}
23558
+ button:disabled{opacity:.55;cursor:not-allowed} .icon:empty{display:none} .icon img{display:block;width:100%;height:100%;object-fit:contain} .icon:has(img){width:1em;height:1em}
23559
+ .led{display:inline-block;width:.6em;height:.6em;border-radius:50%;background:var(--gramlot-button-led-off,#888)}
23560
+ [aria-pressed=true] .led{background:var(--gramlot-button-led-on,#2b9a46)}
23561
+ .arrow{border-start-start-radius:0;border-end-start-radius:0;border-inline-start:0}
23562
+ .split{border-start-end-radius:0;border-end-end-radius:0}
23563
+ .popup{position:fixed;inset:auto;margin:0;padding:var(--gramlot-popup-padding,4px);overflow:auto;
23564
+ max-width:var(--gramlot-popup-available-width);max-height:var(--gramlot-popup-available-height);
23565
+ border:1px solid var(--gramlot-border-control,#888);border-radius:var(--gramlot-radius-sm,4px);
23566
+ color:var(--gramlot-ink,CanvasText);background:var(--gramlot-field-background,Canvas);box-shadow:0 3px 12px #0003}
23567
+ :host(:is([role=menuitem],[role=menuitemcheckbox])){display:block} :host(:is([role=menuitem],[role=menuitemcheckbox])) button{width:100%;justify-content:start;border:0;background:transparent}
23568
+ :host([role=separator]){display:block;border-top:1px solid var(--gramlot-border-control,#888);margin:.25em}
23569
+ :host([role=separator]) button{display:none}`;
23570
+ this.shadowRoot.append(style);
23571
+ }
23572
+ get disabled() {
23573
+ return this.control.disabled;
23574
+ }
23575
+ set disabled(value) {
23576
+ this.control.disabled = Boolean(value);
23577
+ }
23578
+ projectAttributes(attrs, adapt) {
23579
+ const rest = super.projectAttributes(attrs, adapt);
23580
+ this.control.disabled = Boolean(this.parameters.disabled);
23581
+ this.control.readOnly = Boolean(this.parameters.readonly);
23582
+ this.renderIcon(this.parameters.icon, this.parameters.iconSrc);
23583
+ if (attrs["aria-label"] != null) this.control.setAttribute("aria-label", attrs["aria-label"]);
23584
+ else this.control.removeAttribute("aria-label");
23585
+ return rest;
23586
+ }
23587
+ renderIcon(icon, iconSrc) {
23588
+ if (!iconSrc) {
23589
+ this.icon.textContent = icon ?? "";
23590
+ return;
23591
+ }
23592
+ let image = this.icon.firstElementChild;
23593
+ if (!image) {
23594
+ image = this.ownerDocument.createElement("img");
23595
+ image.alt = "";
23596
+ image.draggable = false;
23597
+ this.icon.replaceChildren(image);
23598
+ }
23599
+ if (image.getAttribute("src") !== iconSrc) image.setAttribute("src", iconSrc);
23600
+ }
23601
+ get entryIcon() {
23602
+ return this.parameters.icon;
23603
+ }
23604
+ get entryIconSrc() {
23605
+ return this.parameters.iconSrc;
23606
+ }
23607
+ attachCommand() {
23608
+ }
23609
+ releaseCommand() {
23610
+ }
23611
+ commandTarget() {
23612
+ return this;
23613
+ }
23614
+ prepareCommand() {
23615
+ return !this.disabled;
23616
+ }
23617
+ };
23618
+ }
23619
+ Command.parameters = {
23620
+ disabled: { dtype: "B", default: false, binding: "read" },
23621
+ icon: { dtype: "T", default: "", binding: "read" },
23622
+ iconSrc: { dtype: "T", default: "", binding: "read" }
23623
+ };
23624
+ var Button = defineComponent({
23625
+ name: "button",
23626
+ tag: "gramlot-button",
23627
+ base: Command,
23628
+ command: true,
23629
+ subTags: "*",
23630
+ implementation: (Base) => class extends Base {
23631
+ }
23632
+ });
23633
+ var ToggleButton = defineComponent({
23634
+ name: "toggleButton",
23635
+ tag: "gramlot-toggle-button",
23636
+ base: Command,
23637
+ command: true,
23638
+ subTags: "*",
23639
+ parameters: {
23640
+ value: { dtype: "B", default: false, binding: "twoWay" },
23641
+ readonly: { dtype: "B", default: false, binding: "read" }
23642
+ },
23643
+ implementation: (Base) => class extends Base {
23644
+ #value = false;
23645
+ constructor() {
23646
+ super();
23647
+ const led = this.ownerDocument.createElement("span");
23648
+ led.className = "led";
23649
+ led.setAttribute("aria-hidden", "true");
23650
+ this.control.prepend(led);
23651
+ this.writeControlValue(false);
23652
+ }
23653
+ get commitOnChange() {
23654
+ return true;
23655
+ }
23656
+ readControlValue() {
23657
+ return this.#value;
23658
+ }
23659
+ writeControlValue(value) {
23660
+ this.#value = value;
23661
+ this.control.setAttribute("aria-pressed", String(value));
23662
+ }
23663
+ prepareCommand(event) {
23664
+ if (!super.prepareCommand(event) || this.control.readOnly) return false;
23665
+ this.writeControlValue(!this.#value);
23666
+ this.control.dispatchEvent(new this.ownerDocument.defaultView.Event("change"));
23667
+ return true;
23668
+ }
23669
+ }
23670
+ });
23671
+ var Menu = defineComponent({
23672
+ name: "menu",
23673
+ tag: "gramlot-menu",
23674
+ base: MenuContainer,
23675
+ subTags: "menuline,spacer,contentPane",
23676
+ parameters: {
23677
+ presentation: { dtype: "T", default: "popup", enum: ["popup", "bar"] },
23678
+ orientation: { dtype: "T", default: "horizontal", enum: ["horizontal", "vertical"] },
23679
+ modifiers: { dtype: "T", nullable: true },
23680
+ labelPosition: { dtype: "T", binding: "read", default: "beside", enum: ["beside", "below", "tooltip"] },
23681
+ iconSize: { dtype: "R", binding: "read", default: 24 },
23682
+ resolver: { dtype: "T", nullable: true },
23683
+ cacheTime: { dtype: "R", default: -1 },
23684
+ sync: { dtype: "B", default: false }
23685
+ },
23686
+ implementation: (Base) => class extends Base {
23687
+ }
23688
+ });
23689
+ var MenuLine = defineComponent({
23690
+ name: "menuline",
23691
+ tag: "gramlot-menu-line",
23692
+ base: Command,
23693
+ command: true,
23694
+ subTags: "*",
23695
+ parameters: {
23696
+ command: { dtype: "T", nullable: true },
23697
+ caption: { dtype: "T", nullable: true },
23698
+ code: { dtype: "T", nullable: true },
23699
+ checked: { dtype: "B", nullable: true, binding: "read" },
23700
+ tooltip: { dtype: "T", nullable: true },
23701
+ labelPosition: { dtype: "T", binding: "read", nullable: true, enum: ["beside", "below", "tooltip"] },
23702
+ iconSize: { dtype: "R", binding: "read", nullable: true },
23703
+ group: { dtype: "B", default: false },
23704
+ priority: { dtype: "R", default: 0 },
23705
+ overflowable: { dtype: "B", default: true },
23706
+ parameters: { annotation: { kind: "type", module: "builtins", name: "dict" }, nullable: true },
23707
+ favorite: { dtype: "B", default: false }
23708
+ },
23709
+ implementation: menuLine
23710
+ });
23711
+ var Spacer = defineComponent({ name: "spacer", tag: "gramlot-spacer", base: (HTMLElement) => class extends HTMLElement {
23712
+ projectAttributes(attrs) {
23713
+ const rest = projectParameters(this, attrs), { size, flex } = this.parameters;
23714
+ if (size != null && flex != null) throw new TypeError("spacer accepts size or flex, not both");
23715
+ if (size != null && (!Number.isFinite(size) || size < 0) || flex != null && (!Number.isFinite(flex) || flex <= 0)) throw new TypeError("Invalid spacer size/flex");
23716
+ this.style.flex = flex != null ? `${flex} 1 0px` : `0 0 ${size ?? 0}px`;
23717
+ this.setAttribute("aria-hidden", "true");
23718
+ return rest;
23719
+ }
23720
+ }, parameters: { size: { dtype: "R", nullable: true }, flex: { dtype: "R", nullable: true } }, implementation: (Base) => class extends Base {
23721
+ } });
23722
+ var DropDownButton = defineComponent({
23723
+ name: "dropDownButton",
23724
+ tag: "gramlot-drop-down-button",
23725
+ base: Command,
23726
+ command: true,
23727
+ subTags: "*",
23728
+ parameters: { persist: { dtype: "B", default: false } },
23729
+ implementation: (Base) => class extends Base {
23730
+ #selected = null;
23731
+ #observer;
23732
+ #storageKey = null;
23733
+ #arrow;
23734
+ #chosenCaption;
23735
+ constructor() {
23736
+ super();
23737
+ const doc = this.ownerDocument;
23738
+ this.control.classList.add("split");
23739
+ this.#chosenCaption = doc.createElement("span");
23740
+ this.#chosenCaption.hidden = true;
23741
+ this.control.append(this.#chosenCaption);
23742
+ this.#arrow = doc.createElement("button");
23743
+ this.#arrow.type = "button";
23744
+ this.#arrow.className = "arrow";
23745
+ this.#arrow.textContent = "\u25BE";
23746
+ this.#arrow.setAttribute("aria-label", "Open menu");
23747
+ this.#arrow.setAttribute("aria-haspopup", "menu");
23748
+ this.#arrow.setAttribute("aria-expanded", "false");
23749
+ this.controlBox.append(this.#arrow);
23750
+ const slot = doc.createElement("slot");
23751
+ slot.name = "menu";
23752
+ this.shadowRoot.append(slot);
23753
+ this.#arrow.addEventListener("click", (event) => {
23754
+ event.stopPropagation();
23755
+ if (this.menu.opened) this.closeMenu();
23756
+ else this.openMenu();
23757
+ });
23758
+ this.#arrow.addEventListener("keydown", (event) => {
23759
+ if (["ArrowDown", "ArrowUp"].includes(event.key)) {
23760
+ event.preventDefault();
23761
+ this.openMenu(event.key === "ArrowUp");
23762
+ }
23763
+ });
23764
+ }
23765
+ get menu() {
23766
+ return [...this.children].find((child) => child.localName === "gramlot-menu");
23767
+ }
23768
+ get menuItems() {
23769
+ return this.menu?.items ?? [];
23770
+ }
23771
+ projectAttributes(attrs, adapt) {
23772
+ const rest = super.projectAttributes(attrs, adapt);
23773
+ this.#arrow.disabled = this.disabled;
23774
+ if (this.disabled) this.menu?.close(false);
23775
+ this.#refreshCaption();
23776
+ return rest;
23777
+ }
23778
+ attachCommand() {
23779
+ if (this.parameters.persist) {
23780
+ if (!this.id) throw new TypeError("dropDownButton persist requires an explicit id");
23781
+ this.#storageKey = `gramlot:command:${this.ownerDocument.location.pathname}${this.ownerDocument.location.search}:${this.id}`;
23782
+ try {
23783
+ this.#selected = this.ownerDocument.defaultView.localStorage.getItem(this.#storageKey);
23784
+ } catch {
23785
+ }
23786
+ }
23787
+ this.#refreshCaption();
23788
+ this.#observer = new this.ownerDocument.defaultView.MutationObserver(() => this.#refreshCaption());
23789
+ this.#observer.observe(this, { childList: true, subtree: true, characterData: true });
23790
+ }
23791
+ releaseCommand() {
23792
+ this.#observer?.disconnect();
23793
+ this.menu?.close(false);
23020
23794
  }
23021
- if (URL_ATTRIBUTES.has(bare.toLowerCase()) && isJavascriptUrl(value)) {
23022
- throw new Error(`${node.nodeTag} '${node.label}': '${name}' holds a javascript: URL, run by the browser as code; write connect_onclick or the action of a button instead`);
23795
+ commandTarget(event) {
23796
+ if (event?.composedPath().includes(this.menu)) return null;
23797
+ return this.menuItems.find((item) => item.occurrence === this.#selected) ?? this;
23023
23798
  }
23024
- }
23025
- }
23026
- function isJavascriptUrl(value) {
23027
- return typeof value === "string" && /^javascript:/i.test(value.replace(/[\t\n\r]/g, "").replace(/^[\u0000-\u0020]+/, ""));
23028
- }
23029
- function withDataSrcdocSandbox(node, attrs, prefixes = []) {
23030
- if (node.nodeTag !== "iframe") return attrs;
23031
- const bare = (name) => {
23032
- const prefix = prefixes.find((candidate) => name.startsWith(candidate)) ?? "";
23033
- return [prefix, name.slice(prefix.length).toLowerCase()];
23034
- };
23035
- const declared = Object.fromEntries(sourceAttributeItems(node.getAttr()));
23036
- const srcdoc = [...Object.keys(declared), ...Object.keys(attrs)].find((name) => bare(name)[1] === "srcdoc");
23037
- if (srcdoc === void 0 || Object.keys(declared).some((name) => bare(name)[1] === "sandbox")) return attrs;
23038
- if (node.pointerType(node.value) === null && !(Object.hasOwn(declared, srcdoc) && (node.pointerType(declared[srcdoc]) !== null || isExpression(declared[srcdoc])))) return attrs;
23039
- const rest = Object.fromEntries(Object.entries(attrs).filter(([name]) => bare(name)[1] !== "sandbox"));
23040
- return { [`${bare(srcdoc)[0]}sandbox`]: "", ...rest };
23041
- }
23042
- function withoutNullValues(attrs) {
23043
- return Object.fromEntries(Object.entries(attrs).filter(([, value]) => value != null));
23044
- }
23045
- function domNames(attrs) {
23046
- return Object.fromEntries(Object.entries(attrs).map(([name, value]) => {
23047
- if (name.startsWith("xmlns_")) return [`xmlns:${name.slice(6)}`, value];
23048
- if (name.startsWith("data_") || name.startsWith("aria_")) return [name.replaceAll("_", "-"), value];
23049
- return [name, value];
23050
- }));
23051
- }
23052
- function boundaryAttributes(attrs) {
23053
- const { _meta, ...rest } = attrs;
23054
- return domNames(withoutNullValues(withoutBindingAttributes(rest)));
23055
- }
23056
- function splitNativeAttributes(tag2, attrs) {
23057
- const names = NATIVE_ATTRIBUTES[String(tag2).toLowerCase()] ?? [];
23058
- const rest = {};
23059
- const native = {};
23060
- for (const [name, value] of Object.entries(attrs)) {
23061
- if (names.includes(name)) native[name] = value;
23062
- else rest[name] = value;
23063
- }
23064
- return [rest, native];
23065
- }
23066
- function textValue(value) {
23067
- return String(value);
23068
- }
23069
- function displayItem(item, attrs, format = null) {
23070
- const rest = { ...attrs };
23071
- const { mask, format: pattern, locale, timeZone, dtype, places } = rest;
23072
- for (const name of DISPLAY_ATTRIBUTES) delete rest[name];
23073
- const display = (value) => {
23074
- if (format && pattern != null) {
23075
- if (places != null) throw new RangeError("places is not implemented; specify precision in format");
23076
- return format(value, {
23077
- pattern,
23078
- mask,
23079
- ...locale == null ? {} : { locale },
23080
- ...timeZone == null ? {} : { timeZone },
23081
- ...dtype == null ? {} : { dtype }
23082
- });
23799
+ selectCommand(item, remember) {
23800
+ if (remember) {
23801
+ this.#selected = item.occurrence;
23802
+ if (this.#storageKey) try {
23803
+ this.ownerDocument.defaultView.localStorage.setItem(this.#storageKey, this.#selected);
23804
+ } catch {
23805
+ }
23806
+ this.#refreshCaption();
23807
+ }
23808
+ this.closeMenu();
23809
+ }
23810
+ #refreshCaption() {
23811
+ const codes = this.menuItems.map((item) => item.occurrence).filter(Boolean);
23812
+ if (new Set(codes).size !== codes.length) throw new TypeError("Dropdown menu codes must be unique");
23813
+ const target = this.commandTarget(), selected = target !== this;
23814
+ this.caption.hidden = selected;
23815
+ this.#chosenCaption.hidden = !selected;
23816
+ this.#chosenCaption.textContent = selected ? target.entryCaption : "";
23817
+ this.renderIcon(target.entryIcon, target.entryIconSrc);
23818
+ }
23819
+ openMenu(last = false) {
23820
+ if (!this.disabled) this.menu?.open(this.#arrow, last);
23821
+ }
23822
+ closeMenu() {
23823
+ this.menu?.close();
23083
23824
  }
23084
- if (typeof value === "boolean") value = textValue(value);
23085
- if (mask == null) return value;
23086
- const text = value == null ? "" : textValue(value);
23087
- return text === "" ? text : applyMask(text, mask);
23088
- };
23089
- if (Array.isArray(item)) {
23090
- if (Object.hasOwn(rest, "_text")) rest._text = display(rest._text);
23091
- return [item, rest];
23092
23825
  }
23093
- return [display(item), rest];
23094
- }
23095
- function isExpression(value) {
23096
- return typeof value === "string" && value.startsWith("==");
23097
- }
23826
+ });
23827
+ var buttons_default = defineCollection({ name: "buttons", components: [Button, ToggleButton, DropDownButton, Menu, MenuLine, Spacer] });
23098
23828
 
23099
23829
  // src/binding/pointer.js
23100
23830
  function attributeReader(node, items, context = node) {
@@ -23201,16 +23931,16 @@ var NodeRequests = class {
23201
23931
  */
23202
23932
  submit(method, params, perform) {
23203
23933
  try {
23204
- const text = toTytx(params);
23934
+ const text2 = toTytx(params);
23205
23935
  if (this.#inflight) {
23206
23936
  if (this.#pending) return Promise.resolve(void 0);
23207
23937
  return new Promise((resolve, reject) => {
23208
- this.#pending = { method, text, perform, resolve, reject };
23938
+ this.#pending = { method, text: text2, perform, resolve, reject };
23209
23939
  });
23210
23940
  }
23211
23941
  this.#pending?.resolve(void 0);
23212
23942
  this.#pending = null;
23213
- return this.#start(method, params, text, perform);
23943
+ return this.#start(method, params, text2, perform);
23214
23944
  } catch (error) {
23215
23945
  return Promise.reject(error);
23216
23946
  }
@@ -23240,16 +23970,16 @@ var NodeRequests = class {
23240
23970
  }
23241
23971
  result.then(pending.resolve, pending.reject);
23242
23972
  }
23243
- #start(method, params, text, perform) {
23973
+ #start(method, params, text2, perform) {
23244
23974
  if (!this.#nameSyntax.matches(method)) {
23245
23975
  return Promise.reject(new TypeError(`Method name must match ${this.#nameSyntax.pattern}, not ${JSON.stringify(method)}`));
23246
23976
  }
23247
23977
  const controller = new AbortController();
23248
- const record2 = { method, params, text, controller, ignored: false };
23978
+ const record2 = { method, params, text: text2, controller, ignored: false };
23249
23979
  record2.view = Object.freeze({
23250
23980
  method,
23251
23981
  get params() {
23252
- return fromTytx(text);
23982
+ return fromTytx(text2);
23253
23983
  },
23254
23984
  sentAt: Date.now(),
23255
23985
  cancel: () => this.#cancel(record2)
@@ -23281,6 +24011,42 @@ function isExpression2(value) {
23281
24011
  return typeof value === "string" && value.startsWith("==");
23282
24012
  }
23283
24013
  var GramlotBuilderBagNode = class extends SourceBagNode {
24014
+ get frame() {
24015
+ if (!["dialog", "floatingPane"].includes(this.nodeTag)) throw new TypeError("frame accessor requires a window");
24016
+ const children = this.value instanceof SourceBag ? this.value.getNodes() : [];
24017
+ if (children.length) {
24018
+ if (children.length !== 1 || children[0].nodeTag !== "framePane") throw new TypeError("A window requires exactly one framePane");
24019
+ return this.builder.wrapSource(children[0]);
24020
+ }
24021
+ return this.builder.wrapSource(this.builder.commandOnNode(this, "framePane", null, { node_label: "frame" }));
24022
+ }
24023
+ requestClose(reason = "application") {
24024
+ if (!["dialog", "floatingPane"].includes(this.nodeTag)) throw new TypeError("requestClose requires a window");
24025
+ return this.rootBuilder.binding.gramlot.dom.getDomNode(this).requestClose(reason);
24026
+ }
24027
+ get top() {
24028
+ return this.frameRegion("top");
24029
+ }
24030
+ get bottom() {
24031
+ return this.frameRegion("bottom");
24032
+ }
24033
+ get left() {
24034
+ return this.frameRegion("left");
24035
+ }
24036
+ get right() {
24037
+ return this.frameRegion("right");
24038
+ }
24039
+ get center() {
24040
+ return this.frameRegion("center");
24041
+ }
24042
+ frameRegion(region) {
24043
+ if (this.nodeTag !== "framePane") throw new TypeError("Region accessors require framePane");
24044
+ const existing = this.value instanceof SourceBag ? this.value.getNodes().find((child) => child.getAttr("region") === region) : null;
24045
+ if (existing) return this.builder.wrapSource(existing);
24046
+ const attrs = { region, node_label: region };
24047
+ if (region !== "center") Object.assign(attrs, { display: "flex", flex_direction: ["top", "bottom"].includes(region) ? "column" : "row" });
24048
+ return this.builder.wrapSource(this.builder.commandOnNode(this, "contentPane", null, attrs));
24049
+ }
23284
24050
  // Attributes ending in `_path` whose pointer symbol was already reported.
23285
24051
  #reportedPathPointers = /* @__PURE__ */ new Set();
23286
24052
  // The texts of the inline code received with the Source, by the name InlineCompiler uses; null before activation.
@@ -23295,7 +24061,8 @@ var GramlotBuilderBagNode = class extends SourceBagNode {
23295
24061
  * `formula` of a dataFormula, `script` of a dataController, `_if`/`_else` of the four providers, the
23296
24062
  * `_onCalling`/`_onResult`/`_onError` of a dataRpc and the `_onCalling` of a dataRemote, `action` of a
23297
24063
  * button, `_if`/`_else`/`_onRemote`/`_onCalling` of a node whose `remote` is a string, every `connect_on<event>`,
23298
- * every `==` attribute (canonical name) and a `==` node value (`''`).
24064
+ * every `==` attribute (canonical name) and a `==` node value (`''`). Script elements also retain
24065
+ * their literal executable text and URLs here for the live renderer's activation check.
23299
24066
  */
23300
24067
  codeAttributes() {
23301
24068
  const own2 = [
@@ -23318,8 +24085,12 @@ var GramlotBuilderBagNode = class extends SourceBagNode {
23318
24085
  }
23319
24086
  for (const [name, value] of sourceAttributeItems(this.getAttr())) {
23320
24087
  if (isExpression2(value)) items.push([name, value]);
24088
+ if (this.nodeTag === "script" && typeof value === "string") {
24089
+ const prefix = this.builder.constructor.dialectPrefixes.find((prefix2) => name.startsWith(prefix2)) ?? "";
24090
+ if (["src", "href", "xlink:href", "xlink_href", "_text"].includes(name.slice(prefix.length).toLowerCase())) items.push([name, value]);
24091
+ }
23321
24092
  }
23322
- if (isExpression2(this.staticValue)) items.push(["", this.staticValue]);
24093
+ if (isExpression2(this.staticValue) || this.nodeTag === "script" && typeof this.staticValue === "string") items.push(["", this.staticValue]);
23323
24094
  return items;
23324
24095
  }
23325
24096
  /**
@@ -23330,14 +24101,14 @@ var GramlotBuilderBagNode = class extends SourceBagNode {
23330
24101
  */
23331
24102
  activateCode() {
23332
24103
  const code = /* @__PURE__ */ new Map();
23333
- for (const [name, text] of this.codeAttributes()) {
23334
- if (this.pointerType(text)) {
23335
- throw new Error(`${this.nodeTag} '${this.label}': '${name}' is inline code and cannot be the pointer '${text}'; inline code is never read from Data`);
24104
+ for (const [name, text2] of this.codeAttributes()) {
24105
+ if (this.pointerType(text2)) {
24106
+ throw new Error(`${this.nodeTag} '${this.label}': '${name}' is inline code and cannot be the pointer '${text2}'; inline code is never read from Data`);
23336
24107
  }
23337
- code.set(name, text);
24108
+ code.set(name, text2);
23338
24109
  }
23339
- for (const [name, text] of [...sourceAttributeItems(this.getAttr()), ["datapath", this.getAttr("datapath")]]) {
23340
- if (pointerTransform(text)?.expression) code.set(name, text);
24110
+ for (const [name, text2] of [...sourceAttributeItems(this.getAttr()), ["datapath", this.getAttr("datapath")]]) {
24111
+ if (pointerTransform(text2)?.expression) code.set(name, text2);
23341
24112
  }
23342
24113
  this.#activatedCode = code;
23343
24114
  }
@@ -23371,13 +24142,13 @@ var GramlotBuilderBagNode = class extends SourceBagNode {
23371
24142
  }
23372
24143
  /** Publish to this node's selfsubscribe topics, as in the legacy Source API. */
23373
24144
  publish(topic, payload = {}) {
23374
- return this.builder.binding.subscriptions.publishNode(this, topic, payload);
24145
+ return this.rootBuilder.binding.subscriptions.publishNode(this, topic, payload);
23375
24146
  }
23376
24147
  /** Builder's `^` pointers, except the attributes ending in `_path`, which hold a bare path. */
23377
24148
  pointers() {
23378
24149
  const datapath = this.getAttr("datapath");
23379
24150
  const dependencies = pointerTransform(datapath) ? pointerDependencies(this, datapath) : /* @__PURE__ */ new Set();
23380
- const result = super.pointers().filter(([name, pointer]) => !dependencies.has(name) && !this.#isPathAttribute(name, pointer)).map(([name, pointer]) => [name, pointerTransform(pointer)?.pointer ?? pointer]);
24151
+ const result = super.pointers().filter(([name, pointer]) => !(this.nodeTag === "menuline" && ["caption", "icon", "tooltip", "command"].includes(name)) && !dependencies.has(name) && !this.#isPathAttribute(name, pointer)).map(([name, pointer]) => [name, pointerTransform(pointer)?.pointer ?? pointer]);
23381
24152
  for (const name of dependencies) {
23382
24153
  const value = this.getAttr(name);
23383
24154
  if (this.pointerType(value) === "^") result.push(["datapath", pointerTransform(value)?.pointer ?? value]);
@@ -23392,6 +24163,10 @@ var GramlotBuilderBagNode = class extends SourceBagNode {
23392
24163
  runtimeToEvaluate() {
23393
24164
  const items = super.runtimeToEvaluate();
23394
24165
  for (const [name, value] of items) {
24166
+ if (this.nodeTag === "menuline" && ["caption", "icon", "tooltip", "command"].includes(name)) {
24167
+ items.set(name, new BagCbResolver(() => value));
24168
+ continue;
24169
+ }
23395
24170
  if (!this.pointerType(value)) continue;
23396
24171
  if (pointerTransform(value)) {
23397
24172
  if (typeof name !== "string") throw new Error(`${this.nodeTag} '${this.label}': pointer suffixes belong to attributes; use format/mask for node text`);
@@ -23770,6 +24545,7 @@ var GramlotHtmlRenderer = class extends HtmlRenderer {
23770
24545
  const evaluate = (attr, expr) => compiler ? compiler.compileExpression(node, attr, expr)(runtimeAttrs) : null;
23771
24546
  const attrs = { ...runtimeAttrs };
23772
24547
  for (const [name, raw] of sourceAttributeItems(node.getAttr())) {
24548
+ if (node.nodeTag === "menuline" && ["caption", "icon", "tooltip", "command"].includes(name)) continue;
23773
24549
  if (isExpression(raw) && Object.hasOwn(attrs, name)) attrs[name] = evaluate(name, raw);
23774
24550
  }
23775
24551
  if (isExpression(node.value)) this.#expressionValues.set(node, evaluate("", node.value));
@@ -23819,10 +24595,10 @@ var GramlotHtmlRenderer = class extends HtmlRenderer {
23819
24595
  /** Builder's finalize; `doctype` prepends `<!doctype html>` and wraps the output in `<html>` when the root is not `html`. */
23820
24596
  finalize(result, target = null, opts = {}) {
23821
24597
  if (!opts.doctype) return super.finalize(result, target, opts);
23822
- let text = this._composeStringFragments(result);
24598
+ let text2 = this._composeStringFragments(result);
23823
24599
  const roots = this.builder.source.getNodes().filter((node) => !node._getMeta("data_element"));
23824
- if (!(roots.length === 1 && roots[0].nodeTag === "html")) text = `<html>${text}</html>`;
23825
- return super.finalize(`<!doctype html>${text}`, target, opts);
24600
+ if (!(roots.length === 1 && roots[0].nodeTag === "html")) text2 = `<html>${text2}</html>`;
24601
+ return super.finalize(`<!doctype html>${text2}`, target, opts);
23826
24602
  }
23827
24603
  };
23828
24604
 
@@ -24240,6 +25016,31 @@ var binding_default = {
24240
25016
  _meta: {
24241
25017
  render_tag: "button"
24242
25018
  }
25019
+ },
25020
+ html_dialog: {
25021
+ doc: "Native HTML dialog, distinct from the layout window component.",
25022
+ sub_tags: "a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",
25023
+ parent_tags: null,
25024
+ inherits_from: null,
25025
+ ns: null,
25026
+ attributes: {
25027
+ parameters: [
25028
+ {
25029
+ name: "kwargs",
25030
+ kind: "var_keyword",
25031
+ role: "attribute",
25032
+ annotation: null,
25033
+ has_default: false
25034
+ }
25035
+ ],
25036
+ accepts_var_keyword: true,
25037
+ accepts_var_positional: false
25038
+ },
25039
+ node_label: null,
25040
+ collection_key: null,
25041
+ _meta: {
25042
+ render_tag: "dialog"
25043
+ }
24243
25044
  }
24244
25045
  }
24245
25046
  };
@@ -24431,11 +25232,23 @@ var GramlotBuilder = class _GramlotBuilder extends HtmlBuilder {
24431
25232
  }
24432
25233
  /** Builder's element call from the Proxy on a Source Bag. */
24433
25234
  bagCall(bag, tag2, value, attrs) {
24434
- return super.bagCall(bag, this.#authoredTag(tag2), value, attrs);
25235
+ tag2 = this.#authoredTag(tag2);
25236
+ [value, attrs] = this.menuArguments(tag2, value, attrs);
25237
+ return super.bagCall(bag, tag2, value, attrs);
24435
25238
  }
24436
25239
  /** Builder's element call from the Proxy on a Source node. */
24437
25240
  commandOnNode(node, tag2, value, attrs) {
24438
- return super.commandOnNode(node, this.#authoredTag(tag2), value, attrs);
25241
+ tag2 = this.#authoredTag(tag2);
25242
+ [value, attrs] = this.menuArguments(tag2, value, attrs);
25243
+ return super.commandOnNode(node, tag2, value, attrs);
25244
+ }
25245
+ menuArguments(tag2, value, attrs = {}) {
25246
+ if (tag2 === "menu" && value == null) return [new GramlotBuilderBag(null, this), attrs];
25247
+ if (tag2 === "menuline" && value != null && value !== "-") {
25248
+ if (Object.hasOwn(attrs, "command")) throw new TypeError("menuline command must be declared once");
25249
+ return [null, { ...attrs, command: value }];
25250
+ }
25251
+ return [value, attrs];
24439
25252
  }
24440
25253
  /** Builder's value check, plus the excluded attributes (authoring names the tag). */
24441
25254
  validateNodeValues(tag2, value, attrs = {}) {
@@ -24466,7 +25279,7 @@ var GramlotBuilder = class _GramlotBuilder extends HtmlBuilder {
24466
25279
  return super._validateChildren(
24467
25280
  parentTag,
24468
25281
  info,
24469
- tags.map((tag2) => tag2 === "html_button" ? "button" : tag2),
25282
+ tags.map((tag2) => tag2 === "html_button" ? "button" : tag2 === "html_dialog" ? "dialog" : tag2),
24470
25283
  includeMinimum
24471
25284
  );
24472
25285
  }
@@ -25081,6 +25894,14 @@ function componentContext(adapter) {
25081
25894
  format: (value, options) => app.format(value, options),
25082
25895
  invoke,
25083
25896
  remote: (method, keywords, signal) => app.rpc.call("data", method, keywords, { signal }),
25897
+ selectionOutputs: ({ selectedCaption, selectedRecord, fields }, row) => {
25898
+ if (binding.closed) return;
25899
+ if (selectedCaption) node.setRelativeData(selectedCaption, row?.caption ?? null);
25900
+ if (selectedRecord) node.setRelativeData(selectedRecord, row ? new Bag(row.record) : null);
25901
+ for (const [name, path] of Object.entries(fields)) {
25902
+ node.setRelativeData(path, row?.record[name.slice(9)] ?? null);
25903
+ }
25904
+ },
25084
25905
  validationCurrent: () => {
25085
25906
  const pointer = node.getAttr("value");
25086
25907
  const path = node.pointerType(pointer) ? node.absDatapath(pointer) : null;
@@ -25186,12 +26007,13 @@ var HtmlElement = class {
25186
26007
  }
25187
26008
  validate(node, builder = node.builder) {
25188
26009
  const branch = node.value instanceof SourceBag;
25189
- const text = branch ? node.getAttr("_text") : node.value;
25190
- if (text != null && !["string", "number", "boolean"].includes(typeof text)) {
26010
+ const text2 = branch ? node.getAttr("_text") : node.value;
26011
+ if (text2 != null && !["string", "number", "boolean"].includes(typeof text2)) {
25191
26012
  throw new TypeError("HTML text must be scalar");
25192
26013
  }
25193
26014
  for (const [key, value] of Object.entries(node.attr)) {
25194
26015
  if (key === "value" && this.definition(node).meta.gramlot_component) continue;
26016
+ if (node.nodeTag === "menuline" && key === "parameters") continue;
25195
26017
  if (this.metadataAttributes.has(key) || ["ask", "_ask"].includes(key) || value && typeof value === "object" && Object.hasOwn(value, "$gramlotRef")) continue;
25196
26018
  if (value != null && !["string", "number", "boolean"].includes(typeof value)) {
25197
26019
  throw new TypeError(`HTML attribute ${key} must be scalar`);
@@ -25199,7 +26021,7 @@ var HtmlElement = class {
25199
26021
  }
25200
26022
  const declaredAttrs = Object.fromEntries(Object.entries(node.attr).filter(([key]) => !this.metadataAttributes.has(key)));
25201
26023
  const childTags = branch ? node.value.getNodes().map((child) => child.nodeTag).filter(Boolean) : [];
25202
- builder.validateNode(node, { value: text, attrs: declaredAttrs, childTags });
26024
+ builder.validateNode(node, { value: text2, attrs: declaredAttrs, childTags });
25203
26025
  }
25204
26026
  create(node, document, tag2 = null, attrs = node.attr, visible = null) {
25205
26027
  const { tag: defaultTag, namespace, meta } = this.definition(node);
@@ -25221,9 +26043,9 @@ var HtmlElement = class {
25221
26043
  callLogic: (name, keywords) => this.callLogic(node, name, keywords)
25222
26044
  });
25223
26045
  }
25224
- const text = document.createTextNode(this.text(node));
25225
- if (namespace !== XHTML_NS || !meta.void) element.append(text);
25226
- const record2 = { element, text, tag: tag2 };
26046
+ const text2 = document.createTextNode(this.text(node));
26047
+ if (namespace !== XHTML_NS || !meta.void) element.append(text2);
26048
+ const record2 = { element, text: text2, tag: tag2 };
25227
26049
  this.update(record2, node, attrs, DEFAULT_TEXT, visible);
25228
26050
  return record2;
25229
26051
  }
@@ -25244,8 +26066,8 @@ var HtmlElement = class {
25244
26066
  node.setRelativeData(pointer.slice(1), value);
25245
26067
  }
25246
26068
  }
25247
- compose(record2, text, children) {
25248
- record2.text.data = text ?? "";
26069
+ compose(record2, text2, children) {
26070
+ record2.text.data = text2 ?? "";
25249
26071
  for (const child of children) record2.element.append(child);
25250
26072
  }
25251
26073
  /**
@@ -25255,7 +26077,14 @@ var HtmlElement = class {
25255
26077
  * control belongs to its ControlAdapter: neither the attribute nor the property is written here.
25256
26078
  */
25257
26079
  update(record2, node, attrs = node.attr, textValue2 = DEFAULT_TEXT, visible = null) {
25258
- const { element, text } = record2;
26080
+ if (node.nodeTag === "script") {
26081
+ for (const [name, code] of node.codeAttributes()) {
26082
+ if (node.activatedCode(name) !== code) {
26083
+ throw new Error(`script '${node.label}': '${name}' runs only as received with the Source`);
26084
+ }
26085
+ }
26086
+ }
26087
+ const { element, text: text2 } = record2;
25259
26088
  const isHtml = element.namespaceURI === XHTML_NS;
25260
26089
  const renderAttributes = this.definition(node).meta.render_attributes ?? {};
25261
26090
  const previous = record2.attrs ?? {};
@@ -25286,7 +26115,7 @@ var HtmlElement = class {
25286
26115
  const controlled = ControlAdapter.classFor(element, attrs) !== null;
25287
26116
  if (textValue2 === DEFAULT_TEXT) textValue2 = this.text(node);
25288
26117
  const nextText = textValue2 == null ? "" : String(textValue2);
25289
- if (text.data !== nextText) text.data = nextText;
26118
+ if (text2.data !== nextText) text2.data = nextText;
25290
26119
  const keys = [.../* @__PURE__ */ new Set([...Object.keys(previous), ...Object.keys(attrs)])];
25291
26120
  keys.sort((a, b) => (b === "sandbox") - (a === "sandbox"));
25292
26121
  for (const key of keys) {
@@ -25326,12 +26155,72 @@ var HtmlElement = class {
25326
26155
  }
25327
26156
  };
25328
26157
 
26158
+ // src/view/menu-command.js
26159
+ function commandFrame(node) {
26160
+ for (let parent = node.parentNode; parent; parent = parent.parentNode) if (parent.nodeTag === "framePane") return parent;
26161
+ return null;
26162
+ }
26163
+ function frameRecipient(frame) {
26164
+ if (!frame || !(frame.value instanceof SourceBag)) return null;
26165
+ const center = frame.value.getNodes().find((node) => node.getAttr("region") === "center");
26166
+ const targets = [];
26167
+ function visit(node) {
26168
+ if (node.nodeTag === "framePane") return;
26169
+ if (node.getAttr("frameTarget") === true) targets.push(node);
26170
+ if (node.value instanceof SourceBag) for (const child of node.value.getNodes()) visit(child);
26171
+ }
26172
+ if (center) visit(center);
26173
+ return targets.length === 1 ? targets[0] : null;
26174
+ }
26175
+ function eligible(binding) {
26176
+ if (binding.closed || !binding.runtime.renderer.attached(binding.node)) return false;
26177
+ for (let node = binding.node; node; node = node.parentNode) {
26178
+ const [, attrs] = node.rootBuilder.runtimeValues(node);
26179
+ if (attrs.hidden === true || attrs.disabled === true) return false;
26180
+ }
26181
+ return true;
26182
+ }
26183
+ function freeze2(value) {
26184
+ if (value && typeof value === "object") {
26185
+ for (const item of Object.values(value)) freeze2(item);
26186
+ Object.freeze(value);
26187
+ }
26188
+ return value;
26189
+ }
26190
+ function captureCommand(binding, event) {
26191
+ const sender = binding.node, command = sender.getAttr("command");
26192
+ const definition = binding.runtime.gramlot.commands.get(command);
26193
+ const frame = commandFrame(sender), target = frameRecipient(frame);
26194
+ if (!definition || !target) {
26195
+ console.warn(`Cannot dispatch command '${command}' at '${sender.label}': missing or duplicate frame recipient`);
26196
+ return null;
26197
+ }
26198
+ const raw = sender.getAttr("parameters") ?? {};
26199
+ if (typeof raw !== "object" || Array.isArray(raw)) throw new TypeError("Command parameters require a mapping");
26200
+ const values = Object.fromEntries(Object.entries(raw).map(([key, value]) => [key, sender.pointerType(value) ? sender.getRelativeData(value) : value]));
26201
+ const parameters2 = freeze2(fromTytx(toTytx(values)));
26202
+ const modifiers = Object.freeze(Object.fromEntries(["shift", "ctrl", "alt", "meta"].map((key) => [key, Boolean(event[`${key}Key`])])));
26203
+ const message = Object.freeze({ sender, target, command, parameters: parameters2, modifiers });
26204
+ let cancelled = false;
26205
+ const release = binding.runtime.bindingFor(target).track(() => {
26206
+ cancelled = true;
26207
+ });
26208
+ const current = () => !cancelled && eligible(binding) && frameRecipient(frame) === target && binding.runtime.renderer.attached(target) && sender.getAttr("command") === command;
26209
+ return { message, current, release, cancel() {
26210
+ cancelled = true;
26211
+ }, deliver() {
26212
+ if (current()) target.publish(definition.publish, message);
26213
+ } };
26214
+ }
26215
+
25329
26216
  // src/view/button.js
25330
26217
  var ButtonBinding = class _ButtonBinding {
25331
26218
  #binding;
25332
26219
  #record;
25333
26220
  #cancelDelay = null;
25334
26221
  #pendingCount = 0;
26222
+ #activations = /* @__PURE__ */ new Set();
26223
+ #warnedCommand = null;
25335
26224
  /** The binding of a Gramlot button; html_button remains native despite its DOM tag. */
25336
26225
  static for(binding, record2) {
25337
26226
  const element = record2.element;
@@ -25371,7 +26260,14 @@ var ButtonBinding = class _ButtonBinding {
25371
26260
  const found = [];
25372
26261
  if (controllers.length) found.push("controller");
25373
26262
  if (attrs.action != null) found.push("action");
26263
+ if (node.nodeTag === "menuline" && attrs.command != null) found.push("registered");
25374
26264
  if (fireAttributes(attrs).length) found.push("fire");
26265
+ if (node.nodeTag === "menuline" && node.value instanceof SourceBag && node.value.getNodes().some((child) => child.nodeTag === "menu") && found.length) {
26266
+ throw new Error(`menuline '${node.label}': a submenu cannot also execute a command`);
26267
+ }
26268
+ if (node.nodeTag === "menuline" && attrs.group && found.length) {
26269
+ throw new Error(`menuline '${node.label}': a group cannot execute a command`);
26270
+ }
25375
26271
  if (found.length > 1) {
25376
26272
  throw new Error(`${node.nodeTag} '${node.label}': ${found.join(" and ")} together; a button has one click mechanism`);
25377
26273
  }
@@ -25389,6 +26285,16 @@ var ButtonBinding = class _ButtonBinding {
25389
26285
  * again, so an ambiguity raises now, and a button that gained a mechanism gets `type="button"`.
25390
26286
  */
25391
26287
  refresh() {
26288
+ if (this.node.nodeTag === "menuline") {
26289
+ const command = this.node.getAttr("command");
26290
+ const definition = command ? this.binding.runtime.gramlot.commands.get(command) : null;
26291
+ this.element.setCommandDefinition(definition, this.node.label);
26292
+ if (command && !definition && this.#warnedCommand !== command) {
26293
+ console.warn(`Unknown command '${command}' in menu '${this.node.parentNode?.label}', entry '${this.node.label}'`);
26294
+ this.#warnedCommand = command;
26295
+ }
26296
+ }
26297
+ for (const activation of this.#activations) if (!activation.current()) activation.cancel();
25392
26298
  const mechanism = this.mechanism;
25393
26299
  if (mechanism && this.node.getAttr("type") == null && this.element.getAttribute("type") !== "button") {
25394
26300
  this.element.setAttribute("type", "button");
@@ -25399,6 +26305,11 @@ var ButtonBinding = class _ButtonBinding {
25399
26305
  this.element.releaseCommand();
25400
26306
  delete this.element.activateCommand;
25401
26307
  this.#cancelDelay?.();
26308
+ for (const activation of this.#activations) {
26309
+ activation.cancel();
26310
+ activation.release();
26311
+ }
26312
+ this.#activations.clear();
25402
26313
  }
25403
26314
  handleEvent(event) {
25404
26315
  this.onClick(event);
@@ -25421,6 +26332,9 @@ var ButtonBinding = class _ButtonBinding {
25421
26332
  if (!mechanism) return;
25422
26333
  event.stopPropagation();
25423
26334
  if (this.element.disabled) return;
26335
+ const activation = mechanism === "registered" ? captureCommand(this.binding, event) : null;
26336
+ if (mechanism === "registered" && !activation) return;
26337
+ if (activation) this.#activations.add(activation);
25424
26338
  const counter = this.binding.countClick();
25425
26339
  let owner = this.node;
25426
26340
  while (owner && owner.getAttr("_delay") == null) owner = owner.parentNode;
@@ -25433,11 +26347,16 @@ var ButtonBinding = class _ButtonBinding {
25433
26347
  release();
25434
26348
  this.#cancelDelay = null;
25435
26349
  this.#pendingCount = 0;
25436
- this.#execute(event, count);
26350
+ this.#execute(event, count, activation);
25437
26351
  }, delay);
25438
26352
  const release = this.binding.track(() => this.#cancelDelay?.());
25439
26353
  this.#cancelDelay = () => {
25440
26354
  clearTimeout(timer);
26355
+ if (activation) {
26356
+ activation.cancel();
26357
+ activation.release();
26358
+ this.#activations.delete(activation);
26359
+ }
25441
26360
  release();
25442
26361
  this.#cancelDelay = null;
25443
26362
  this.#pendingCount = 0;
@@ -25445,10 +26364,26 @@ var ButtonBinding = class _ButtonBinding {
25445
26364
  return;
25446
26365
  }
25447
26366
  this.#cancelDelay?.();
25448
- return this.#execute(event, counter);
26367
+ return this.#execute(event, counter, activation);
26368
+ }
26369
+ async #executeRegistered(activation) {
26370
+ try {
26371
+ if (!activation.current()) return;
26372
+ const ask = this.node.getAttr("ask"), dialog = this.binding.runtime.askDialog;
26373
+ const keywords = { ...activation.message.parameters };
26374
+ if (ask && dialog.required(this.binding, ask, keywords, "ask")) {
26375
+ const result = await dialog.show(this.binding, ask, keywords);
26376
+ if (result === null) return;
26377
+ }
26378
+ activation.deliver();
26379
+ } finally {
26380
+ activation.release();
26381
+ this.#activations.delete(activation);
26382
+ }
25449
26383
  }
25450
26384
  /** Deliver the last event once; arguments are read when the mechanism executes. */
25451
- #execute(event, counter) {
26385
+ #execute(event, counter, activation = null) {
26386
+ if (activation) return this.#executeRegistered(activation);
25452
26387
  if (this.binding.closed || this.element.disabled) return;
25453
26388
  const mechanism = this.mechanism;
25454
26389
  if (!mechanism) return;
@@ -25489,12 +26424,230 @@ var ButtonBinding = class _ButtonBinding {
25489
26424
  }
25490
26425
  }
25491
26426
  };
25492
- function fireAttributes(attrs) {
25493
- return Object.entries(attrs ?? {}).filter(([name, value]) => value != null && (name === "fire" || name.startsWith("fire_")));
26427
+ function fireAttributes(attrs) {
26428
+ return Object.entries(attrs ?? {}).filter(([name, value]) => value != null && (name === "fire" || name.startsWith("fire_")));
26429
+ }
26430
+ function eventToString(event) {
26431
+ return ["shift", "ctrl", "alt", "meta"].filter((key) => event[`${key}Key`]).map((key) => key[0].toUpperCase() + key.slice(1)).join("");
26432
+ }
26433
+
26434
+ // src/binding/remote-resolver.js
26435
+ var RemoteResolver = class extends BagResolver {
26436
+ static classKwargs = { ...BagResolver.classKwargs, asBag: false };
26437
+ constructor({ cacheTime, onError }) {
26438
+ super({ cacheTime: cacheTime ?? -1 });
26439
+ this.onError = onError;
26440
+ this.loading = null;
26441
+ this.loaded = false;
26442
+ this.writing = false;
26443
+ }
26444
+ resolve({ static: isStatic = false } = {}) {
26445
+ if (!isStatic && !this.closed && !this.loading && !this.writing && this.expired) this.refresh();
26446
+ return this.cachedValue;
26447
+ }
26448
+ refresh() {
26449
+ if (this.closed) return null;
26450
+ const loading = this.startLoad((request) => this.#load(request));
26451
+ if (loading === null) return null;
26452
+ const settle = () => {
26453
+ if (this.loading === loading) this.loading = null;
26454
+ };
26455
+ loading.then(settle, settle);
26456
+ this.loading = loading;
26457
+ loading.catch((error) => {
26458
+ if (error?.name !== "AbortError") this.onError(error);
26459
+ });
26460
+ return loading;
26461
+ }
26462
+ resolveSync(options) {
26463
+ return super.resolve(options);
26464
+ }
26465
+ prepareValue(value) {
26466
+ return value;
26467
+ }
26468
+ #fingerprint() {
26469
+ const kwargs = { ...this._kw };
26470
+ for (const [name, value] of Object.entries(this.node?.attr ?? {})) {
26471
+ if (!this.constructor.internalParams.has(name)) kwargs[name] = value;
26472
+ }
26473
+ return this._computeEffectiveFingerprint(kwargs);
26474
+ }
26475
+ async #load(request) {
26476
+ if (this.closed) return void 0;
26477
+ const fingerprint = this.#fingerprint();
26478
+ const received = await this.loadAsync(request);
26479
+ if (this.closed || request.ignored) return void 0;
26480
+ const value = this.prepareValue(received);
26481
+ this._lastUpdate = Date.now();
26482
+ this._lastEffectiveFingerprint = fingerprint;
26483
+ this.loaded = true;
26484
+ this.writing = true;
26485
+ try {
26486
+ if (this.node) this.node.setValue(value, this.cacheTime !== 0);
26487
+ else this.cachedValue = value;
26488
+ } finally {
26489
+ this.writing = false;
26490
+ }
26491
+ return value;
26492
+ }
26493
+ };
26494
+
26495
+ // src/binding/rpc-resolver.js
26496
+ var RpcResolver = class extends RemoteResolver {
26497
+ static internalParams = /* @__PURE__ */ new Set([...RemoteResolver.internalParams, "binding", "method", "params", "onCalling", "onError", "sync"]);
26498
+ constructor({ binding, method, params, cacheTime, onCalling = null, onError, sync = false }) {
26499
+ super({ cacheTime, onError });
26500
+ this.binding = binding;
26501
+ this.sync = sync;
26502
+ this.method = method;
26503
+ this.params = params;
26504
+ this.onCalling = onCalling;
26505
+ }
26506
+ get closed() {
26507
+ return this.binding.closed;
26508
+ }
26509
+ resolve(options = {}) {
26510
+ if (!this.sync) return super.resolve(options);
26511
+ if (options.static || this.loading || this.writing) return this.cachedValue;
26512
+ if (this.expired && !this.binding.node.requests.calling(this.onCalling)) return this.cachedValue;
26513
+ return super.resolveSync(options);
26514
+ }
26515
+ load() {
26516
+ let value;
26517
+ try {
26518
+ value = this.binding.callSync("data", this.method, this.params);
26519
+ } catch (error) {
26520
+ this.onError(error);
26521
+ }
26522
+ this.loaded = true;
26523
+ return value;
26524
+ }
26525
+ startLoad(perform) {
26526
+ const requests = this.binding.node.requests;
26527
+ if (!requests.calling(this.onCalling)) return null;
26528
+ return requests.submit(this.method, this.params, perform);
26529
+ }
26530
+ loadAsync(request) {
26531
+ return this.binding.call("data", request);
26532
+ }
26533
+ };
26534
+
26535
+ // src/view/menu.js
26536
+ var ENTRY_FIELDS = /* @__PURE__ */ new Set(["kind", "command", "caption", "icon", "iconSrc", "tooltip", "disabled", "hidden", "checked", "favorite", "parameters", "resolver", "cacheTime", "sync"]);
26537
+ function entries(bag, ancestors = /* @__PURE__ */ new Set()) {
26538
+ if (!(bag instanceof Bag) || ancestors.has(bag)) throw new TypeError("Menu resolver must return an acyclic Bag");
26539
+ const parents2 = /* @__PURE__ */ new Set([...ancestors, bag]);
26540
+ return bag.getNodes().map((node) => {
26541
+ const a = node.attr, kind = a.kind, value = node.staticValue;
26542
+ if (Object.keys(a).some((key) => !ENTRY_FIELDS.has(key) && !key.startsWith("resolver_"))) throw new TypeError(`Unsupported menu record field: ${node.label}`);
26543
+ if (!["command", "separator", "submenu"].includes(kind)) throw new TypeError(`Invalid menu kind: ${node.label}`);
26544
+ for (const name of ["disabled", "hidden", "checked"]) if (a[name] != null && typeof a[name] !== "boolean" && !(typeof a[name] === "string" && a[name].startsWith("^"))) throw new TypeError(`Invalid menu ${name}`);
26545
+ if (a.favorite != null && typeof a.favorite !== "boolean") throw new TypeError("favorite must be boolean");
26546
+ if (a.caption != null && typeof a.caption !== "string") throw new TypeError("Menu caption must be text");
26547
+ if (a.parameters != null && (typeof a.parameters !== "object" || Array.isArray(a.parameters))) throw new TypeError("Menu parameters must be a mapping");
26548
+ if (kind === "command" && (typeof a.command !== "string" || !a.command || value != null || a.resolver != null)) throw new TypeError("Command record requires a command and no children/resolver");
26549
+ if (kind === "separator" && (value != null || Object.keys(a).length !== 1)) throw new TypeError("Separator record accepts kind only");
26550
+ if (kind === "submenu" && (typeof a.caption !== "string" || a.command != null || value instanceof Bag === (a.resolver != null) || !(value instanceof Bag) && value != null)) throw new TypeError("Submenu requires caption and exactly one content source");
26551
+ const children = value instanceof Bag ? entries(value, parents2) : null;
26552
+ return { label: node.label, attrs: { ...a }, children };
26553
+ });
25494
26554
  }
25495
- function eventToString(event) {
25496
- return ["shift", "ctrl", "alt", "meta"].filter((key) => event[`${key}Key`]).map((key) => key[0].toUpperCase() + key.slice(1)).join("");
26555
+ function project(menu, records) {
26556
+ const handle = menu.builder.wrapSource(menu);
26557
+ const old = menu.value instanceof SourceBag ? menu.value.getNodes() : [];
26558
+ const keys = new Set(records.map((item) => item.label));
26559
+ for (const node of old) if (!keys.has(node.label)) menu.value.popNode(node.label);
26560
+ for (const [index, item] of records.entries()) {
26561
+ const { kind, ...attrs } = item.attrs;
26562
+ const resolver = Object.fromEntries(Object.entries(attrs).filter(([key]) => key === "resolver" || key === "cacheTime" || key === "sync" || key.startsWith("resolver_")));
26563
+ for (const key of Object.keys(resolver)) delete attrs[key];
26564
+ const value = kind === "separator" ? "-" : null;
26565
+ let node = menu.value instanceof SourceBag ? menu.value.getNodes().find((node2) => node2.label === item.label) : null;
26566
+ const wasSubmenu = node?.value instanceof SourceBag;
26567
+ if (node && (wasSubmenu !== (kind === "submenu") || node.value === "-" !== (kind === "separator"))) {
26568
+ menu.value.popNode(node.label);
26569
+ node = null;
26570
+ }
26571
+ if (!node) node = sourceTarget(handle.menuline(value, { ...attrs, node_label: item.label }));
26572
+ else {
26573
+ const previous = Object.keys(node.attr).filter((key) => ENTRY_FIELDS.has(key) && !Object.hasOwn(attrs, key));
26574
+ node.setAttr({ ...Object.fromEntries(previous.map((key) => [key, null])), ...attrs });
26575
+ }
26576
+ if (kind === "submenu") {
26577
+ let child = node.value instanceof SourceBag ? node.value.getNodes().find((n) => n.nodeTag === "menu") : null;
26578
+ if (!child) child = sourceTarget(node.builder.wrapSource(node).menu({ ...resolver, node_label: "menu" }));
26579
+ else child.setAttr({ ...Object.fromEntries(Object.keys(child.attr).filter((key) => key === "resolver" || key === "cacheTime" || key === "sync" || key.startsWith("resolver_")).map((key) => [key, null])), ...resolver });
26580
+ if (item.children) project(child, item.children);
26581
+ }
26582
+ const order = menu.value.getNodes().indexOf(node);
26583
+ if (order !== index) menu.value.move(order, index);
26584
+ }
25497
26585
  }
26586
+ var MenuBinding = class {
26587
+ #key = null;
26588
+ #resolver = null;
26589
+ #generation = 0;
26590
+ #closed = false;
26591
+ #projection = null;
26592
+ constructor(binding, element) {
26593
+ this.binding = binding;
26594
+ this.element = element;
26595
+ }
26596
+ get node() {
26597
+ return this.binding.node;
26598
+ }
26599
+ attach() {
26600
+ this.element.menuBinding = this;
26601
+ this.refresh();
26602
+ }
26603
+ detach() {
26604
+ this.#closed = true;
26605
+ this.#generation++;
26606
+ this.node.requests.inflight?.cancel();
26607
+ delete this.element.menuBinding;
26608
+ this.element.close(false);
26609
+ }
26610
+ refresh() {
26611
+ const [, attrs] = this.node.rootBuilder.runtimeValues(this.node);
26612
+ const params = Object.fromEntries(Object.entries(attrs).filter(([key2]) => key2.startsWith("resolver_")).map(([key2, value]) => [key2.slice(9), value]));
26613
+ const key = toTytx([attrs.resolver, params, attrs.cacheTime, attrs.sync]);
26614
+ if (key === this.#key) return;
26615
+ this.#key = key;
26616
+ this.#generation++;
26617
+ this.#projection = null;
26618
+ this.#resolver = attrs.resolver ? new RpcResolver({ binding: this.binding, method: attrs.resolver, params, cacheTime: attrs.cacheTime ?? -1, sync: attrs.sync ?? false, onError: () => {
26619
+ } }) : null;
26620
+ if (this.#resolver) {
26621
+ this.element.setStatus("loading");
26622
+ if (this.element.opened && this.element.isConnected) this.load();
26623
+ } else this.element.setStatus(null);
26624
+ }
26625
+ async load(force = false) {
26626
+ if (this.#closed || !this.#resolver) return;
26627
+ const resolver = this.#resolver, generation = this.#generation;
26628
+ try {
26629
+ if (force) resolver.refresh();
26630
+ else resolver.resolve();
26631
+ if (resolver.loading) {
26632
+ this.element.setStatus("loading");
26633
+ await resolver.loading;
26634
+ }
26635
+ if (this.#closed || generation !== this.#generation) return;
26636
+ const result = resolver.cachedValue;
26637
+ const records = entries(result);
26638
+ const fingerprint = toTytx(result);
26639
+ if (this.#projection !== fingerprint) {
26640
+ project(this.node, records);
26641
+ this.#projection = fingerprint;
26642
+ }
26643
+ this.element.setStatus(records.length ? null : "empty");
26644
+ } catch (error) {
26645
+ if (this.#closed || generation !== this.#generation) return;
26646
+ this.element.setStatus("error");
26647
+ console.warn(`Menu '${this.node.label}' failed to load`, error);
26648
+ }
26649
+ }
26650
+ };
25498
26651
 
25499
26652
  // src/view/events.js
25500
26653
  var PREFIX = "connect_on";
@@ -25820,19 +26973,18 @@ var DataInstaller = class {
25820
26973
  * Steps 2-3 of §5.1 on `branch` (a SourceBagNode or a SourceBag): the installation rules of
25821
26974
  * `requireInstallable` are checked first (a candidate of `mountMainSource` or `remoteSource` was
25822
26975
  * already checked at step 1; a branch inserted by a Source event is checked here, before any
25823
- * write), then every `dataSetter` in document order, each with its NodeBinding opened and stamped
25824
- * `installed`, then the defaults of the visual nodes. A `dataSetter` whose NodeBinding is already
25825
- * stamped is not installed again.
26976
+ * write), then every `dataSetter` in document order, then the defaults of the visual nodes.
26977
+ * A processed setter is consumed: close its binding and remove it from Source immediately
26978
+ * after the Data write. The renderer ignores this deletion.
25826
26979
  */
25827
26980
  install(branch) {
25828
26981
  const nodes = branchNodes(branch);
25829
26982
  const setters = this.setterNodes(branch);
25830
26983
  requireInstallable(branch);
25831
26984
  for (const node of setters) {
25832
- const binding = this.runtime.openBinding(node);
25833
- if (binding.hasStamp("installed")) continue;
25834
26985
  this.applySetter(node);
25835
- binding.stamp("installed");
26986
+ this.runtime.closeBranch(node);
26987
+ if (node.parentBag) node.parentBag.popNode(node.label);
25836
26988
  }
25837
26989
  this.applyDefaults(nodes.filter((node) => node.nodeTag && !node._getMeta("data_element")));
25838
26990
  }
@@ -25984,107 +27136,6 @@ function branchNodes(branch) {
25984
27136
  return nodes;
25985
27137
  }
25986
27138
 
25987
- // src/binding/remote-resolver.js
25988
- var RemoteResolver = class extends BagResolver {
25989
- static classKwargs = { ...BagResolver.classKwargs, asBag: false };
25990
- constructor({ cacheTime, onError }) {
25991
- super({ cacheTime: cacheTime ?? -1 });
25992
- this.onError = onError;
25993
- this.loading = null;
25994
- this.loaded = false;
25995
- this.writing = false;
25996
- }
25997
- resolve({ static: isStatic = false } = {}) {
25998
- if (!isStatic && !this.closed && !this.loading && !this.writing && this.expired) this.refresh();
25999
- return this.cachedValue;
26000
- }
26001
- refresh() {
26002
- if (this.closed) return null;
26003
- const loading = this.startLoad((request) => this.#load(request));
26004
- if (loading === null) return null;
26005
- const settle = () => {
26006
- if (this.loading === loading) this.loading = null;
26007
- };
26008
- loading.then(settle, settle);
26009
- this.loading = loading;
26010
- loading.catch((error) => {
26011
- if (error?.name !== "AbortError") this.onError(error);
26012
- });
26013
- return loading;
26014
- }
26015
- resolveSync(options) {
26016
- return super.resolve(options);
26017
- }
26018
- prepareValue(value) {
26019
- return value;
26020
- }
26021
- #fingerprint() {
26022
- const kwargs = { ...this._kw };
26023
- for (const [name, value] of Object.entries(this.node?.attr ?? {})) {
26024
- if (!this.constructor.internalParams.has(name)) kwargs[name] = value;
26025
- }
26026
- return this._computeEffectiveFingerprint(kwargs);
26027
- }
26028
- async #load(request) {
26029
- if (this.closed) return void 0;
26030
- const fingerprint = this.#fingerprint();
26031
- const received = await this.loadAsync(request);
26032
- if (this.closed || request.ignored) return void 0;
26033
- const value = this.prepareValue(received);
26034
- this._lastUpdate = Date.now();
26035
- this._lastEffectiveFingerprint = fingerprint;
26036
- this.loaded = true;
26037
- this.writing = true;
26038
- try {
26039
- if (this.node) this.node.setValue(value, this.cacheTime !== 0);
26040
- else this.cachedValue = value;
26041
- } finally {
26042
- this.writing = false;
26043
- }
26044
- return value;
26045
- }
26046
- };
26047
-
26048
- // src/binding/rpc-resolver.js
26049
- var RpcResolver = class extends RemoteResolver {
26050
- static internalParams = /* @__PURE__ */ new Set([...RemoteResolver.internalParams, "binding", "method", "params", "onCalling", "onError", "sync"]);
26051
- constructor({ binding, method, params, cacheTime, onCalling = null, onError, sync = false }) {
26052
- super({ cacheTime, onError });
26053
- this.binding = binding;
26054
- this.sync = sync;
26055
- this.method = method;
26056
- this.params = params;
26057
- this.onCalling = onCalling;
26058
- }
26059
- get closed() {
26060
- return this.binding.closed;
26061
- }
26062
- resolve(options = {}) {
26063
- if (!this.sync) return super.resolve(options);
26064
- if (options.static || this.loading || this.writing) return this.cachedValue;
26065
- if (this.expired && !this.binding.node.requests.calling(this.onCalling)) return this.cachedValue;
26066
- return super.resolveSync(options);
26067
- }
26068
- load() {
26069
- let value;
26070
- try {
26071
- value = this.binding.callSync("data", this.method, this.params);
26072
- } catch (error) {
26073
- this.onError(error);
26074
- }
26075
- this.loaded = true;
26076
- return value;
26077
- }
26078
- startLoad(perform) {
26079
- const requests = this.binding.node.requests;
26080
- if (!requests.calling(this.onCalling)) return null;
26081
- return requests.submit(this.method, this.params, perform);
26082
- }
26083
- loadAsync(request) {
26084
- return this.binding.call("data", request);
26085
- }
26086
- };
26087
-
26088
27139
  // src/binding/providers.js
26089
27140
  var CONTROL_ATTRIBUTES = /* @__PURE__ */ new Set([
26090
27141
  "destination_path",
@@ -26563,21 +27614,21 @@ var InlineCompiler = class {
26563
27614
  }
26564
27615
  /** Number of compiled declarations. */
26565
27616
  get size() {
26566
- return [...this.#cache.values()].reduce((total, entries) => total + entries.size, 0);
27617
+ return [...this.#cache.values()].reduce((total, entries2) => total + entries2.size, 0);
26567
27618
  }
26568
27619
  /**
26569
27620
  * The legacy macros of `source` translated to the node methods, `$n` to `arguments[n-1]`, as in
26570
27621
  * `gnrlang.js`. A translated declaration gets one deprecation warning; `PUBLISH` is an error.
26571
27622
  */
26572
27623
  preprocess(node, attr, source) {
26573
- const text = source.trim();
26574
- if (PUBLISH.test(text)) throw new Error(`${declaration2(node, attr)}: the PUBLISH macro is excluded from Gramlot`);
26575
- let result = text.replace(/\$(\d+)/g, (_token, n) => `arguments[${parseInt(n, 10) - 1}]`);
27624
+ const text2 = source.trim();
27625
+ if (PUBLISH.test(text2)) throw new Error(`${declaration2(node, attr)}: the PUBLISH macro is excluded from Gramlot`);
27626
+ let result = text2.replace(/\$(\d+)/g, (_token, n) => `arguments[${parseInt(n, 10) - 1}]`);
26576
27627
  for (const [separator, macro, target] of MACROS) {
26577
27628
  if (separator) result = result.replace(separator, `; ${separator.source.slice(1)}`);
26578
27629
  result = result.replace(macro, target);
26579
27630
  }
26580
- if (result !== text) {
27631
+ if (result !== text2) {
26581
27632
  console.warn(`${declaration2(node, attr)}: legacy macros are deprecated; write this.GET(path), this.SET(path, value), this.PUT(path, value), this.FIRE(path, value), this.FIRE_AFTER(path, value) and arguments[n] in place of GET, SET, PUT, FIRE, FIRE_AFTER and $n`);
26582
27633
  }
26583
27634
  return result;
@@ -26596,16 +27647,16 @@ var InlineCompiler = class {
26596
27647
  if (node.activatedCode(attr) !== code) {
26597
27648
  throw new Error(`${declaration2(node, attr)}: inline code runs only as received with the Source (main or a remote Source); a text written later is not run: use named logic`);
26598
27649
  }
26599
- let entries = this.#cache.get(node);
26600
- if (!entries) {
26601
- entries = /* @__PURE__ */ new Map();
26602
- this.#cache.set(node, entries);
27650
+ let entries2 = this.#cache.get(node);
27651
+ if (!entries2) {
27652
+ entries2 = /* @__PURE__ */ new Map();
27653
+ this.#cache.set(node, entries2);
26603
27654
  this.runtime.bindingFor(node).track(() => this.release(node));
26604
27655
  }
26605
- let entry = entries.get(attr);
27656
+ let entry = entries2.get(attr);
26606
27657
  if (entry?.source !== source) {
26607
27658
  entry = { source, text: this.preprocess(node, attr, source), key: null, run: null };
26608
- entries.set(attr, entry);
27659
+ entries2.set(attr, entry);
26609
27660
  }
26610
27661
  const params = argNames.filter(isIdentifier);
26611
27662
  const key = params.join(",");
@@ -26656,11 +27707,11 @@ var InlineCompiler = class {
26656
27707
  this.#cache.delete(node);
26657
27708
  return;
26658
27709
  }
26659
- const entries = this.#cache.get(node);
26660
- if (!entries) return;
27710
+ const entries2 = this.#cache.get(node);
27711
+ if (!entries2) return;
26661
27712
  for (const name of names) {
26662
- entries.delete(name);
26663
- for (const [resolved2] of sourceAttributeItems({ [name]: null })) entries.delete(resolved2);
27713
+ entries2.delete(name);
27714
+ for (const [resolved2] of sourceAttributeItems({ [name]: null })) entries2.delete(resolved2);
26664
27715
  }
26665
27716
  }
26666
27717
  };
@@ -26670,18 +27721,18 @@ function isIdentifier(name) {
26670
27721
  function declaration2(node, attr) {
26671
27722
  return `${node.nodeTag} '${node.label}' ${attr ? `'${attr}'` : "node value"}`;
26672
27723
  }
26673
- function create(node, attr, text, params) {
27724
+ function create(node, attr, text2, params) {
26674
27725
  try {
26675
- if (text.startsWith("function")) return new Function(`return (${text}
27726
+ if (text2.startsWith("function")) return new Function(`return (${text2}
26676
27727
  )`)();
26677
- return new Function(...params, `${text}
27728
+ return new Function(...params, `${text2}
26678
27729
  `);
26679
27730
  } catch (error) {
26680
27731
  if (error instanceof EvalError) {
26681
27732
  throw new EvalError(`${declaration2(node, attr)}: inline code blocked by the Content Security Policy of the page (no 'unsafe-eval'); move the code to named logic (a method of the page's class Logic) or serve the page with the permissive CSP profile, which allows 'unsafe-eval'`, { cause: error });
26682
27733
  }
26683
27734
  throw new SyntaxError(`${declaration2(node, attr)}: ${error.message} in the inline code:
26684
- ${text}`, { cause: error });
27735
+ ${text2}`, { cause: error });
26685
27736
  }
26686
27737
  }
26687
27738
 
@@ -26689,6 +27740,7 @@ ${text}`, { cause: error });
26689
27740
  var RemoteBinding = class {
26690
27741
  #binding;
26691
27742
  #timers;
27743
+ #closed = false;
26692
27744
  // The name and TYTX parameters of the fragment mounted last on the node, whoever requested it.
26693
27745
  #lastName = null;
26694
27746
  #lastParams = null;
@@ -26703,7 +27755,12 @@ var RemoteBinding = class {
26703
27755
  return this.binding.node;
26704
27756
  }
26705
27757
  get closed() {
26706
- return this.binding.closed;
27758
+ return this.#closed || this.binding.closed;
27759
+ }
27760
+ /** Removing the declaration releases scheduled calls; an in-flight fragment keeps the node request contract. */
27761
+ close() {
27762
+ this.#closed = true;
27763
+ this.#timers.cancel();
26707
27764
  }
26708
27765
  /** Start `_timing` again from its current value: called at every registration of the node's pointers. */
26709
27766
  register() {
@@ -26743,8 +27800,8 @@ var RemoteBinding = class {
26743
27800
  }
26744
27801
  let mounted;
26745
27802
  try {
26746
- const text = toTytx(params);
26747
- if (attrs._cachedRemote && this.#cached(name, text)) return;
27803
+ const text2 = toTytx(params);
27804
+ if (attrs._cachedRemote && this.#cached(name, text2)) return;
26748
27805
  const onCalling = node.getAttr("_onCalling");
26749
27806
  if (!node.requests.calling(onCalling ? () => this.#inline("_onCalling", onCalling, onCalling, params) : null)) return;
26750
27807
  mounted = await this.binding.runtime.gramlot.src.remoteSource(node, name, params);
@@ -26752,21 +27809,21 @@ var RemoteBinding = class {
26752
27809
  throw new Error(`${node.nodeTag} '${node.label}': remote '${name}' failed: ${error.message}`, { cause: error });
26753
27810
  }
26754
27811
  const onRemote = node.getAttr("_onRemote");
26755
- if (mounted && onRemote) this.#inline("_onRemote", onRemote, onRemote, params);
27812
+ if (!this.closed && mounted && onRemote) this.#inline("_onRemote", onRemote, onRemote, params);
26756
27813
  }
26757
27814
  /**
26758
27815
  * Record the fragment `remoteSource` mounted on the node, with its method and the TYTX of its parameters:
26759
27816
  * `_cachedRemote` compares with it. A fragment requested from code replaces the record too.
26760
27817
  */
26761
- fragmentMounted(method, text) {
27818
+ fragmentMounted(method, text2) {
26762
27819
  this.#lastName = method;
26763
- this.#lastParams = text;
27820
+ this.#lastParams = text2;
26764
27821
  }
26765
27822
  /** Whether `name` and `text` equal the request in flight, or the fragment mounted last when none is in flight. */
26766
- #cached(name, text) {
27823
+ #cached(name, text2) {
26767
27824
  const inflight = this.node.requests.inflight;
26768
- if (inflight) return inflight.method === name && toTytx(inflight.params) === text;
26769
- return name === this.#lastName && text === this.#lastParams;
27825
+ if (inflight) return inflight.method === name && toTytx(inflight.params) === text2;
27826
+ return name === this.#lastName && text2 === this.#lastParams;
26770
27827
  }
26771
27828
  /** The current value of a control attribute: a pointer is read from Data. */
26772
27829
  #control(name) {
@@ -26858,7 +27915,7 @@ var AskDialog = class {
26858
27915
  release = binding.track(() => finish(false));
26859
27916
  try {
26860
27917
  const builder = new GramlotBuilder();
26861
- const dialog = builder.root.dialog({
27918
+ const dialog = builder.root.html_dialog({
26862
27919
  nodeId: id,
26863
27920
  datapath: id,
26864
27921
  request: id,
@@ -27144,8 +28201,8 @@ var BindingRuntime = class {
27144
28201
  /**
27145
28202
  * Steps 2-4 of §5.1 on `branch` (a SourceBagNode or a new SourceBag value). The `nodeId` map is
27146
28203
  * complete, and a duplicate refused, before the first write or registration, so a `#<nodeId>`
27147
- * of the branch translates; then the installation (`dataSetter`s and defaults), then one
27148
- * NodeBinding per node and the registrations, providers included. On an error the NodeBindings
28204
+ * of the branch translates; one NodeBinding per node owns expression cleanup before installation
28205
+ * (`dataSetter`s and defaults), followed by registrations, providers included. On an error the NodeBindings
27149
28206
  * opened here are closed and the map entries they brought are removed; the Data is not rolled
27150
28207
  * back. Then `_init` (step 5), once per node: its error propagates and the NodeBindings stay
27151
28208
  * open (P12, no rollback).
@@ -27165,9 +28222,11 @@ var BindingRuntime = class {
27165
28222
  }
27166
28223
  for (const [nodeId, node] of entering) this.nodeIds.set(nodeId, node);
27167
28224
  try {
27168
- this.installer.install(branch);
27169
28225
  for (const node of nodes) this.openBinding(node);
27170
- for (const node of nodes) this.bindingFor(node).registerPointers();
28226
+ this.installer.install(branch);
28227
+ for (const node of nodes) {
28228
+ if (this.renderer.attached(node)) this.bindingFor(node).registerPointers();
28229
+ }
27171
28230
  } catch (error) {
27172
28231
  const errors = [error];
27173
28232
  for (const node of nodes.filter((node2) => !known.has(node2)).reverse()) {
@@ -27310,7 +28369,7 @@ var NodeBinding = class {
27310
28369
  countClick() {
27311
28370
  return ++this.#clickCount;
27312
28371
  }
27313
- /** Whether the lifecycle step `name` ('installed', 'init', 'built', 'start') ran for the node. */
28372
+ /** Whether the lifecycle step `name` ('init', 'built', 'start') ran for the node. */
27314
28373
  hasStamp(name) {
27315
28374
  return this.#stamps.has(name);
27316
28375
  }
@@ -27335,6 +28394,10 @@ var NodeBinding = class {
27335
28394
  const dataElement = node._getMeta("data_element");
27336
28395
  if (dataElement && !PROVIDERS[node.nodeTag]) return;
27337
28396
  if (!dataElement && typeof node.getAttr("remote") === "string") this.#remote ??= new RemoteBinding(this);
28397
+ else if (this.#remote) {
28398
+ this.#remote.close();
28399
+ this.#remote = null;
28400
+ }
27338
28401
  const remoteDependencies = /* @__PURE__ */ new Set();
27339
28402
  if (node._getMeta("gramlot_component")?.bagStore) {
27340
28403
  const storepath = node.getAttr("storepath");
@@ -27448,6 +28511,7 @@ var NodeBinding = class {
27448
28511
  close() {
27449
28512
  if (this.closed) return;
27450
28513
  this.#closed = true;
28514
+ this.#remote?.close();
27451
28515
  if (this.node._getMeta("data_element")) this.runtime.renderer.references.remove(this.node);
27452
28516
  this.#closeRegistrations();
27453
28517
  const errors = [];
@@ -27971,7 +29035,7 @@ var GramlotRenderer = class extends GramlotHtmlRenderer {
27971
29035
  }
27972
29036
  attrs = this.componentAttributes(node, attrs);
27973
29037
  const children = Array.isArray(item) ? item : [];
27974
- const text = Array.isArray(item) ? attrs._text : item;
29038
+ const text2 = Array.isArray(item) ? attrs._text : item;
27975
29039
  const resolved2 = this.#resolvedAttributes.get(node);
27976
29040
  const record2 = {
27977
29041
  node,
@@ -27983,7 +29047,7 @@ var GramlotRenderer = class extends GramlotHtmlRenderer {
27983
29047
  resolved: resolved2,
27984
29048
  ...this.html.create(node, document, tag2, attrs, resolved2.visible ?? null)
27985
29049
  };
27986
- this.html.compose(record2, text, children);
29050
+ this.html.compose(record2, text2, children);
27987
29051
  record2.shape = ControlAdapter.shape(record2.element, resolved2);
27988
29052
  this.records.set(node, record2);
27989
29053
  this.elements.set(record2.element, record2);
@@ -28000,6 +29064,11 @@ var GramlotRenderer = class extends GramlotHtmlRenderer {
28000
29064
  button.attach();
28001
29065
  record2.cleanup.push(() => button.detach());
28002
29066
  }
29067
+ if (node.nodeTag === "menu") {
29068
+ record2.menu = new MenuBinding(record2.binding, record2.element);
29069
+ record2.menu.attach();
29070
+ record2.cleanup.push(() => record2.menu.detach());
29071
+ }
28003
29072
  this.#connectEvents(record2);
28004
29073
  this.references?.register(node, record2.element);
28005
29074
  for (const element of children) {
@@ -28098,7 +29167,8 @@ var GramlotRenderer = class extends GramlotHtmlRenderer {
28098
29167
  }
28099
29168
  /**
28100
29169
  * Source event intake (§5.2): an event on a node under construction is ignored
28101
- * on arrival; every other event is queued and processed in arrival order.
29170
+ * on arrival, as is the deletion of a consumed dataSetter (already closed by the installer).
29171
+ * Every other event is queued and processed in arrival order.
28102
29172
  * Semantic work runs for every event, also under freeze; structural work only
28103
29173
  * outside frozen branches. A failing disposer does not block the rest: the
28104
29174
  * closing errors of the semantic work and the cleanup errors of the removals
@@ -28106,11 +29176,12 @@ var GramlotRenderer = class extends GramlotHtmlRenderer {
28106
29176
  */
28107
29177
  receive(event) {
28108
29178
  if (this.disposed) return;
29179
+ const ignored = (node) => this.#constructing.has(node) || event.evt === "del" && node.nodeTag === "dataSetter";
28109
29180
  if (Array.isArray(event.node)) {
28110
- const nodes = event.node.filter((node) => !this.#constructing.has(node));
29181
+ const nodes = event.node.filter((node) => !ignored(node));
28111
29182
  if (!nodes.length) return;
28112
29183
  event = { ...event, node: nodes };
28113
- } else if (this.#constructing.has(event.node)) return;
29184
+ } else if (ignored(event.node)) return;
28114
29185
  this.pending.push(event);
28115
29186
  if (this.building) return;
28116
29187
  this.building = true;
@@ -28307,20 +29378,21 @@ var GramlotRenderer = class extends GramlotHtmlRenderer {
28307
29378
  record2.resolved = resolved2;
28308
29379
  let attrs = node._getMeta("subbuilder") ? resolvedAttrs : renderer.adaptAttrs(resolvedAttrs);
28309
29380
  const branch = node.value instanceof SourceBag;
28310
- let text = branch ? [] : this.expressionValue(node, value);
29381
+ let text2 = branch ? [] : this.expressionValue(node, value);
28311
29382
  if (renderer === this) {
28312
29383
  attrs = this.restoreNativeAttributes(node, attrs);
28313
- if (!node._getMeta("gramlot_component")) [text, attrs] = displayItem(
28314
- text,
29384
+ if (!node._getMeta("gramlot_component")) [text2, attrs] = displayItem(
29385
+ text2,
28315
29386
  attrs,
28316
29387
  (value2, options) => this._binding.gramlot.format(value2, options)
28317
29388
  );
28318
29389
  }
28319
29390
  attrs = this.componentAttributes(node, attrs);
28320
- this.html.update(record2, node, attrs, branch ? attrs._text : text, resolved2.visible ?? null);
29391
+ this.html.update(record2, node, attrs, branch ? attrs._text : text2, resolved2.visible ?? null);
28321
29392
  this.#projectControl(record2, node, attrs, change);
28322
29393
  record2.control?.refresh();
28323
29394
  record2.button?.refresh();
29395
+ record2.menu?.refresh();
28324
29396
  this.#connectEvents(record2);
28325
29397
  const defaults = this.#presentationDefaults.get(node);
28326
29398
  if (defaults) {
@@ -28661,9 +29733,9 @@ var LogicRegistry = class {
28661
29733
  * Check the Logic classes of a page before its Gramlot instance exists (§4.12 step 2bis, Q12.2):
28662
29734
  * the rules of `register` over all the entries, `[{logicClass, group, resource}]`, together.
28663
29735
  */
28664
- static check(entries) {
29736
+ static check(entries2) {
28665
29737
  const children = /* @__PURE__ */ new Map();
28666
- for (const { group, resource } of entries) {
29738
+ for (const { group, resource } of entries2) {
28667
29739
  const segments = groupSegments(group, resource);
28668
29740
  for (let index = 0; index < segments.length; index++) {
28669
29741
  const parent = segments.slice(0, index).join("/");
@@ -28671,7 +29743,7 @@ var LogicRegistry = class {
28671
29743
  children.get(parent).add(segments[index]);
28672
29744
  }
28673
29745
  }
28674
- for (const { logicClass, group, resource } of entries) {
29746
+ for (const { logicClass, group, resource } of entries2) {
28675
29747
  const names = children.get(group ?? "") ?? /* @__PURE__ */ new Set();
28676
29748
  for (const [name] of logicMethods(logicClass, resource)) {
28677
29749
  if (names.has(name)) {
@@ -28765,9 +29837,17 @@ var SourceHandler = class extends Handler {
28765
29837
  * new one; the Data is not rolled back. A later error (`_init`, DOM) keeps `main` and its
28766
29838
  * NodeBindings (P12, no rollback).
28767
29839
  */
28768
- mountMainSource(wire) {
29840
+ mountMainSource(wire, initialData = null) {
28769
29841
  const source = this.prepareSource(wire);
28770
29842
  this.renderer.validateCandidate(source);
29843
+ if (initialData !== null) {
29844
+ if (!(initialData instanceof Bag) || initialData instanceof SourceBag) {
29845
+ throw new TypeError("Initial page data must be a Data Bag");
29846
+ }
29847
+ for (const node of initialData.getNodes()) {
29848
+ this.builder.data.setItem([node.label], node.getValue(), node.attr, ">", false, false);
29849
+ }
29850
+ }
28771
29851
  try {
28772
29852
  this.source.setItem("main", source);
28773
29853
  } catch (error) {
@@ -28881,11 +29961,15 @@ var RpcHandler = class extends Handler {
28881
29961
  if (response.error) throw new RpcError(response.error);
28882
29962
  return response.value;
28883
29963
  }
28884
- async call(contentType, name, params = {}, { signal = null } = {}) {
29964
+ async call(contentType, name, params = {}, options = {}) {
29965
+ return (await this.callEnvelope(contentType, name, params, options)).value;
29966
+ }
29967
+ /** Return the checked response envelope, including optional initial-main Data. */
29968
+ async callEnvelope(contentType, name, params = {}, { signal = null } = {}) {
28885
29969
  if (!this.transport?.call) throw new Error(`rpc '${name}' is unavailable without a server transport`);
28886
29970
  assertTransportData(params);
28887
29971
  const id = randomId();
28888
- const text = toTytx({ id, pageId: this.gramlot.pageId, contentType, name, params });
29972
+ const text2 = toTytx({ id, pageId: this.gramlot.pageId, contentType, name, params });
28889
29973
  const sources = signal ? [this.gramlot.abort.signal, signal] : [this.gramlot.abort.signal];
28890
29974
  const before = sources.find((source) => source.aborted);
28891
29975
  if (before) throw before.reason;
@@ -28900,10 +29984,10 @@ var RpcHandler = class extends Handler {
28900
29984
  });
28901
29985
  this.remoteRequests.set(id, controller);
28902
29986
  try {
28903
- const response = fromTytx(await Promise.race([this.transport.call(text, controller.signal), aborted]));
29987
+ const response = fromTytx(await Promise.race([this.transport.call(text2, controller.signal), aborted]));
28904
29988
  if (response.id !== id) throw new Error("rpc response id mismatch");
28905
29989
  if (response.error) throw new RpcError(response.error);
28906
- return response.value;
29990
+ return response;
28907
29991
  } finally {
28908
29992
  this.remoteRequests.delete(id);
28909
29993
  for (const source of sources) source.removeEventListener("abort", forward);
@@ -29211,8 +30295,8 @@ var SubscriptionsHandler = class extends Handler {
29211
30295
  var MAILTO_LIMIT = 2e3;
29212
30296
  function leafText(value) {
29213
30297
  if (!(value instanceof Date)) return String(value ?? "");
29214
- const text = value.toISOString();
29215
- return text.endsWith("T00:00:00.000Z") ? text.slice(0, 10) : text;
30298
+ const text2 = value.toISOString();
30299
+ return text2.endsWith("T00:00:00.000Z") ? text2.slice(0, 10) : text2;
29216
30300
  }
29217
30301
  var InOut = class {
29218
30302
  constructor(gramlot, document) {
@@ -29307,9 +30391,9 @@ var InOut = class {
29307
30391
  }
29308
30392
  }
29309
30393
  /** Hand text to the browser as a file named filename. */
29310
- saveText(text, filename, type) {
30394
+ saveText(text2, filename, type) {
29311
30395
  const window2 = this.document.defaultView;
29312
- const url = window2.URL.createObjectURL(new window2.Blob([text], { type }));
30396
+ const url = window2.URL.createObjectURL(new window2.Blob([text2], { type }));
29313
30397
  this.open(url, filename);
29314
30398
  window2.setTimeout(() => window2.URL.revokeObjectURL(url), 1e3);
29315
30399
  }
@@ -29352,6 +30436,7 @@ var Gramlot = class {
29352
30436
  for (const collection of collections) {
29353
30437
  if (collection instanceof ComponentCollection) collection.register(document.defaultView);
29354
30438
  }
30439
+ this.commands = new CommandRegistry();
29355
30440
  this.pageId = pageId;
29356
30441
  const browserContext = locale == null || timeZone == null ? document.defaultView.Intl.DateTimeFormat().resolvedOptions() : null;
29357
30442
  this.devices = Object.freeze([...devices]);
@@ -29407,7 +30492,7 @@ var Gramlot = class {
29407
30492
  async loadMain() {
29408
30493
  let wire;
29409
30494
  try {
29410
- wire = await this.rpc.call("source", "main");
30495
+ wire = await this.rpc.callEnvelope("source", "main");
29411
30496
  } catch (error) {
29412
30497
  if (this.state === "disposed") throw new Error("Gramlot was disposed during main", { cause: error });
29413
30498
  this.state = "failed";
@@ -29415,7 +30500,7 @@ var Gramlot = class {
29415
30500
  }
29416
30501
  if (this.state === "disposed") throw new Error("Gramlot was disposed during main");
29417
30502
  try {
29418
- return this.src.mountMainSource(wire);
30503
+ return this.src.mountMainSource(wire.value, wire.data);
29419
30504
  } catch (error) {
29420
30505
  if (this.state !== "disposed") this.state = "failed";
29421
30506
  throw error;
@@ -29461,56 +30546,95 @@ var PageBootstrap = class {
29461
30546
  const { config: config2, resources, document } = this;
29462
30547
  const window2 = document.defaultView;
29463
30548
  if (resources.serverAdapter !== void 0) this.serverAdapter = await this.loadServerAdapter(resources.serverAdapter);
29464
- for (const url of resources.css) {
29465
- const link = document.createElement("link");
29466
- link.rel = "stylesheet";
29467
- link.href = url;
29468
- document.head.append(link);
29469
- }
29470
- let closed = false;
30549
+ let closed = false, resolveClosed, app;
30550
+ const styleCleanup = [];
30551
+ const closing = new Promise((resolve) => {
30552
+ resolveClosed = resolve;
30553
+ });
29471
30554
  const pagehide = (event) => {
29472
30555
  if (event.persisted || closed) return;
29473
30556
  closed = true;
29474
30557
  this.closePage();
30558
+ resolveClosed(null);
29475
30559
  };
29476
30560
  window2.addEventListener("pagehide", pagehide);
29477
- let entries, collections;
29478
30561
  try {
29479
- const settled = await Promise.allSettled(resources.js.map(({ url }) => import(new URL(url, document.baseURI).href)));
29480
- if (closed) return null;
29481
- entries = resources.js.map(({ url, group }, index) => {
29482
- const outcome = settled[index];
29483
- if (outcome.status === "rejected") {
29484
- throw new Error(`${url}: import failed: ${outcome.reason?.message ?? outcome.reason}`, { cause: outcome.reason });
30562
+ const styles = resources.css.map((url) => new Promise((resolve, reject) => {
30563
+ const link = document.createElement("link");
30564
+ link.rel = "stylesheet";
30565
+ link.href = url;
30566
+ const cleanup = () => {
30567
+ link.removeEventListener("load", loaded);
30568
+ link.removeEventListener("error", failed);
30569
+ };
30570
+ styleCleanup.push(cleanup);
30571
+ const loaded = () => {
30572
+ cleanup();
30573
+ resolve();
30574
+ };
30575
+ const failed = () => {
30576
+ cleanup();
30577
+ reject(new Error(`${url}: stylesheet load failed`));
30578
+ };
30579
+ link.addEventListener("load", loaded);
30580
+ link.addEventListener("error", failed);
30581
+ document.head.append(link);
30582
+ }));
30583
+ const logic = resources.js.map(async ({ url, group }) => {
30584
+ try {
30585
+ const module = await import(new URL(url, document.baseURI).href);
30586
+ return { logicClass: module.Logic, group, resource: url };
30587
+ } catch (error) {
30588
+ throw new Error(`${url}: import failed: ${error.message}`, { cause: error });
29485
30589
  }
29486
- return { logicClass: outcome.value.Logic, group, resource: url };
29487
30590
  });
29488
- LogicRegistry.check(entries);
29489
- collections = await Promise.all((resources.collections ?? []).map(async (url) => {
30591
+ const names = /* @__PURE__ */ new Set();
30592
+ const collectionImports = (resources.collections ?? []).map(async (record2) => {
30593
+ if (!record2 || typeof record2 !== "object" || Object.keys(record2).sort().join(",") !== "buildId,name,url" || typeof record2.name !== "string" || typeof record2.url !== "string" || typeof record2.buildId !== "string" || !/^sha256:[0-9a-f]{64}$/.test(record2.buildId) || names.has(record2.name)) {
30594
+ throw new TypeError("Invalid or duplicate collection bootstrap record");
30595
+ }
30596
+ names.add(record2.name);
30597
+ const { name, url, buildId } = record2;
30598
+ let module;
29490
30599
  try {
29491
- return (await import(new URL(url, document.baseURI).href)).default;
30600
+ module = await import(new URL(url, document.baseURI).href);
29492
30601
  } catch (error) {
29493
- throw new Error(`${url}: collection import failed: ${error.message}`, { cause: error });
30602
+ throw new Error(`${name}: collection import failed: ${error.message}`, { cause: error });
29494
30603
  }
29495
- }));
30604
+ if (module.default?.name !== name || module.buildId !== buildId) {
30605
+ throw new Error(`${name}: collection identity mismatch; expected ${buildId}, received ${module.buildId}`);
30606
+ }
30607
+ return module.default;
30608
+ });
30609
+ const result = await Promise.race([Promise.all([
30610
+ Promise.all(styles),
30611
+ Promise.all(logic),
30612
+ Promise.all(collectionImports)
30613
+ ]), closing]);
29496
30614
  if (closed) return null;
30615
+ const [, entries2, collections] = result;
30616
+ LogicRegistry.check(entries2);
29497
30617
  for (const collection of collections) collection.register(window2);
30618
+ app = new Gramlot({
30619
+ ...config2,
30620
+ document,
30621
+ serverAdapter: this.serverAdapter,
30622
+ collections: [...config2.collections ?? [], ...collections.map((c) => c.toDocument())]
30623
+ });
30624
+ window2.removeEventListener("pagehide", pagehide);
30625
+ for (const collection of collections) collection.registerCommands(app);
30626
+ for (const { logicClass, group, resource } of entries2) app.src.logicRegistry.register(logicClass, { group, resource });
30627
+ window2.gramlot = app;
30628
+ await app.start();
30629
+ return app;
29498
30630
  } catch (error) {
29499
- this.closePage();
30631
+ if (app) app.dispose();
30632
+ else if (!closed) this.closePage();
29500
30633
  throw error;
29501
30634
  } finally {
30635
+ for (const cleanup of styleCleanup) cleanup();
29502
30636
  window2.removeEventListener("pagehide", pagehide);
29503
30637
  }
29504
- const app = new Gramlot({
29505
- ...config2,
29506
- document,
29507
- serverAdapter: this.serverAdapter,
29508
- collections: [...config2.collections ?? [], ...collections.map((collection) => collection.toDocument())]
29509
- });
29510
- for (const { logicClass, group, resource } of entries) app.src.logicRegistry.register(logicClass, { group, resource });
29511
- window2.gramlot = app;
29512
- await app.start();
29513
- return app;
29514
30638
  }
29515
30639
  /**
29516
30640
  * The ServerAdapter the server names in `resources.serverAdapter`: an instance of the default export of the
@@ -29572,6 +30696,7 @@ var Exposed = class {
29572
30696
  }
29573
30697
  };
29574
30698
  var Page = class extends Exposed {
30699
+ static gramlots = [];
29575
30700
  static title = "Gramlot";
29576
30701
  static devices = [];
29577
30702
  static locale = null;
@@ -29692,7 +30817,7 @@ function mountIndexPage(renderer, root, onSelection = () => {
29692
30817
  if (!(navigation instanceof Bag)) throw new TypeError("IndexPage navigation must be a Bag");
29693
30818
  const tabs = root.value.getNode("frame.center.tabs");
29694
30819
  const builder = root.builder;
29695
- const entries = /* @__PURE__ */ new Map();
30820
+ const entries2 = /* @__PURE__ */ new Map();
29696
30821
  let disposed = false, selecting = false, sequence = 0, requested = null;
29697
30822
  const opened = state.getItem("opened");
29698
30823
  for (const record2 of opened.getNodes()) {
@@ -29700,7 +30825,7 @@ function mountIndexPage(renderer, root, onSelection = () => {
29700
30825
  const pane = tabs.value.getNode(record2.label);
29701
30826
  const entry = { url, path, title, pane, node: navigation.getNode(path), loading: false };
29702
30827
  prepareEntry(entry);
29703
- entries.set(url, entry);
30828
+ entries2.set(url, entry);
29704
30829
  sequence++;
29705
30830
  }
29706
30831
  const activate = (entry) => {
@@ -29709,7 +30834,7 @@ function mountIndexPage(renderer, root, onSelection = () => {
29709
30834
  try {
29710
30835
  state.setItem("active", entry.url);
29711
30836
  state.setItem("navigationSelection", entry.path);
29712
- onSelection(entries, entry.url);
30837
+ onSelection(entries2, entry.url);
29713
30838
  } finally {
29714
30839
  selecting = false;
29715
30840
  }
@@ -29721,7 +30846,7 @@ function mountIndexPage(renderer, root, onSelection = () => {
29721
30846
  if (url == null) return;
29722
30847
  if (typeof url !== "string" || !url) throw new TypeError("IndexPage URL must be nonempty text");
29723
30848
  requested = url;
29724
- let entry = entries.get(url);
30849
+ let entry = entries2.get(url);
29725
30850
  if (entry) {
29726
30851
  entry.path = path;
29727
30852
  activate(entry);
@@ -29736,7 +30861,7 @@ function mountIndexPage(renderer, root, onSelection = () => {
29736
30861
  }));
29737
30862
  const previous = state.getItem("active");
29738
30863
  entry = { url, path, node, pane, title: node.attr.title ?? node.label, loading: true };
29739
- entries.set(url, entry);
30864
+ entries2.set(url, entry);
29740
30865
  try {
29741
30866
  activate(entry);
29742
30867
  onLoad(url, "loading");
@@ -29756,12 +30881,12 @@ function mountIndexPage(renderer, root, onSelection = () => {
29756
30881
  activate(entry);
29757
30882
  }
29758
30883
  } catch (error) {
29759
- entries.delete(url);
30884
+ entries2.delete(url);
29760
30885
  if (opened.getNode(pane.label)) opened.popNode(pane.label);
29761
30886
  if (pane.parentBag) pane.parentBag.popNode(pane.label);
29762
30887
  if (!disposed && requested === url) {
29763
30888
  onLoad(url, "error", error);
29764
- const restored = entries.get(previous);
30889
+ const restored = entries2.get(previous);
29765
30890
  requested = restored?.url ?? null;
29766
30891
  if (restored) activate(restored);
29767
30892
  else {
@@ -29769,7 +30894,7 @@ function mountIndexPage(renderer, root, onSelection = () => {
29769
30894
  try {
29770
30895
  state.setItem("active", null);
29771
30896
  state.setItem("navigationSelection", null);
29772
- onSelection(entries, null);
30897
+ onSelection(entries2, null);
29773
30898
  } finally {
29774
30899
  selecting = false;
29775
30900
  }
@@ -29784,7 +30909,7 @@ function mountIndexPage(renderer, root, onSelection = () => {
29784
30909
  const path = state.getItem("navigationSelection");
29785
30910
  if (path !== null) void select(path);
29786
30911
  } else if (event.node === state.getNode("active")) {
29787
- const entry = entries.get(state.getItem("active"));
30912
+ const entry = entries2.get(state.getItem("active"));
29788
30913
  if (entry) {
29789
30914
  requested = entry.url;
29790
30915
  activate(entry);
@@ -29795,15 +30920,15 @@ function mountIndexPage(renderer, root, onSelection = () => {
29795
30920
  if (disposed) return;
29796
30921
  disposed = true;
29797
30922
  state.unsubscribe(subscription, { any: true });
29798
- for (const entry of entries.values()) if (entry.loading && entry.pane.parentBag) {
30923
+ for (const entry of entries2.values()) if (entry.loading && entry.pane.parentBag) {
29799
30924
  entry.pane.parentBag.popNode(entry.pane.label);
29800
30925
  }
29801
30926
  };
29802
30927
  renderer.onDispose(root, dispose);
29803
- const active = entries.get(state.getItem("active"));
30928
+ const active = entries2.get(state.getItem("active"));
29804
30929
  if (active) activate(active);
29805
30930
  else if (state.getItem("navigationSelection") !== null) void select(state.getItem("navigationSelection"));
29806
- return { entries, dispose };
30931
+ return { entries: entries2, dispose };
29807
30932
  }
29808
30933
  var IndexLogic = class {
29809
30934
  indexMount(node, { shell_id }) {
@@ -30895,43 +32020,43 @@ var unrecognized = (code = "UNRECOGNIZED_EXPRESSION", message = "Text is not a s
30895
32020
  throw Object.assign(new SyntaxError(message), { code });
30896
32021
  };
30897
32022
  var own = (object, key) => Object.hasOwn(object, key);
30898
- function decodeYear(text, context) {
30899
- if (text.length === 4) return Number(text);
32023
+ function decodeYear(text2, context) {
32024
+ if (text2.length === 4) return Number(text2);
30900
32025
  const lowest = context.year + context.twoDigitYearAhead - 100;
30901
- return lowest + ((Number(text) - lowest) % 100 + 100) % 100;
32026
+ return lowest + ((Number(text2) - lowest) % 100 + 100) % 100;
30902
32027
  }
30903
- function boundTexts(text, context) {
30904
- if (text.includes(";")) {
30905
- const bounds = text.split(";").map((part) => part.trim());
32028
+ function boundTexts(text2, context) {
32029
+ if (text2.includes(";")) {
32030
+ const bounds = text2.split(";").map((part) => part.trim());
30906
32031
  if (bounds.length !== 2) return unrecognized("INVALID_RANGE", "A range must have exactly two endpoints.");
30907
32032
  return { bounds, range: true };
30908
32033
  }
30909
- if (context.phrases("no_period").includes(text)) return { bounds: ["", ""], range: true };
32034
+ if (context.phrases("no_period").includes(text2)) return { bounds: ["", ""], range: true };
30910
32035
  const to = context.phrases("to"), from = context.phrases("from");
30911
32036
  for (const word of to) {
30912
- if (text.startsWith(`${word} `)) return { bounds: ["", text.slice(word.length + 1).trim()], range: true };
32037
+ if (text2.startsWith(`${word} `)) return { bounds: ["", text2.slice(word.length + 1).trim()], range: true };
30913
32038
  }
30914
32039
  for (const word of to) {
30915
32040
  const separator = ` ${word} `;
30916
- if (!text.includes(separator)) continue;
32041
+ if (!text2.includes(separator)) continue;
30917
32042
  for (const prefix of from) {
30918
- if (text.startsWith(`${prefix} `)) {
30919
- text = text.slice(prefix.length + 1);
32043
+ if (text2.startsWith(`${prefix} `)) {
32044
+ text2 = text2.slice(prefix.length + 1);
30920
32045
  break;
30921
32046
  }
30922
32047
  }
30923
- const bounds = text.split(separator).map((part) => part.trim());
32048
+ const bounds = text2.split(separator).map((part) => part.trim());
30924
32049
  if (bounds.length !== 2) return unrecognized("INVALID_RANGE", "A range must have exactly two endpoints.");
30925
32050
  return { bounds, range: true };
30926
32051
  }
30927
32052
  for (const word of from) {
30928
- if (text.startsWith(`${word} `)) return { bounds: [text.slice(word.length + 1).trim(), ""], range: true };
32053
+ if (text2.startsWith(`${word} `)) return { bounds: [text2.slice(word.length + 1).trim(), ""], range: true };
30929
32054
  }
30930
- return { bounds: [text, text], range: false };
32055
+ return { bounds: [text2, text2], range: false };
30931
32056
  }
30932
- function keywordDate(text, context, isEnd) {
30933
- const candidates = [[text, 0]];
30934
- const offset = /^(.+?)\s*([+-])\s*(\d+)$/.exec(text);
32057
+ function keywordDate(text2, context, isEnd) {
32058
+ const candidates = [[text2, 0]];
32059
+ const offset = /^(.+?)\s*([+-])\s*(\d+)$/.exec(text2);
30935
32060
  if (offset) candidates.push([offset[1], Number(offset[2] + offset[3])]);
30936
32061
  const shifts = {
30937
32062
  today: 0,
@@ -30957,15 +32082,15 @@ function keywordDate(text, context, isEnd) {
30957
32082
  }
30958
32083
  return null;
30959
32084
  }
30960
- function quarter(text, context, isEnd) {
30961
- const entries = Object.entries(context.dictionary.quarters).sort((a, b) => b[0].length - a[0].length);
30962
- for (const [name, number] of entries) {
32085
+ function quarter(text2, context, isEnd) {
32086
+ const entries2 = Object.entries(context.dictionary.quarters).sort((a, b) => b[0].length - a[0].length);
32087
+ for (const [name, number] of entries2) {
30963
32088
  let year;
30964
- if (text === name) year = null;
30965
- else if (text.startsWith(name) && yearPattern.test(text.slice(name.length).trim())) {
30966
- year = decodeYear(text.slice(name.length).trim(), context);
30967
- } else if (text.endsWith(name) && yearPattern.test(text.slice(0, -name.length).trim())) {
30968
- year = decodeYear(text.slice(0, -name.length).trim(), context);
32089
+ if (text2 === name) year = null;
32090
+ else if (text2.startsWith(name) && yearPattern.test(text2.slice(name.length).trim())) {
32091
+ year = decodeYear(text2.slice(name.length).trim(), context);
32092
+ } else if (text2.endsWith(name) && yearPattern.test(text2.slice(0, -name.length).trim())) {
32093
+ year = decodeYear(text2.slice(0, -name.length).trim(), context);
30969
32094
  } else continue;
30970
32095
  return { year, month: isEnd ? number * 3 : number * 3 - 2 };
30971
32096
  }
@@ -30976,8 +32101,8 @@ function monthNumber(token, dictionary) {
30976
32101
  const match = /^m(\d{1,2})$/.exec(token);
30977
32102
  return match && Number(match[1]) >= 1 && Number(match[1]) <= 12 ? Number(match[1]) : null;
30978
32103
  }
30979
- function namedMonth(text, context) {
30980
- const tokens = text.split(/\s+/);
32104
+ function namedMonth(text2, context) {
32105
+ const tokens = text2.split(/\s+/);
30981
32106
  const positions = tokens.map((token, i) => monthNumber(token, context.dictionary) ? i : -1).filter((i) => i >= 0);
30982
32107
  if (!positions.length) return null;
30983
32108
  if (positions.length !== 1) return unrecognized();
@@ -31000,20 +32125,20 @@ function namedMonth(text, context) {
31000
32125
  }
31001
32126
  return unrecognized();
31002
32127
  }
31003
- function numericDate(text, context) {
31004
- const iso = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text);
32128
+ function numericDate(text2, context) {
32129
+ const iso = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text2);
31005
32130
  if (iso) return civil(...iso.slice(1).map(Number));
31006
- const numeric = /^(\d{1,4})[/\-. ]+(\d{1,4})[/\-. ]+(\d{1,4})$/.exec(text);
32131
+ const numeric = /^(\d{1,4})[/\-. ]+(\d{1,4})[/\-. ]+(\d{1,4})$/.exec(text2);
31007
32132
  const values = {};
31008
32133
  if (numeric) context.order.split("").forEach((letter, i) => {
31009
32134
  values[letter] = numeric[i + 1];
31010
32135
  });
31011
- else if (/^(?:\d{6}|\d{8})$/.test(text)) {
31012
- const yearWidth = text.length === 8 ? 4 : 2;
32136
+ else if (/^(?:\d{6}|\d{8})$/.test(text2)) {
32137
+ const yearWidth = text2.length === 8 ? 4 : 2;
31013
32138
  for (const letter of context.order) {
31014
32139
  const width = letter === "Y" ? yearWidth : 2;
31015
- values[letter] = text.slice(0, width);
31016
- text = text.slice(width);
32140
+ values[letter] = text2.slice(0, width);
32141
+ text2 = text2.slice(width);
31017
32142
  }
31018
32143
  } else return null;
31019
32144
  if (!yearPattern.test(values.Y) || values.D.length > 2 || values.M.length > 2) return unrecognized();
@@ -31021,16 +32146,16 @@ function numericDate(text, context) {
31021
32146
  if (numeric && month > 12 && day <= 12) [day, month] = [month, day];
31022
32147
  return civil(decodeYear(values.Y, context), month, day);
31023
32148
  }
31024
- function getBound(text, context, isEnd) {
31025
- if (!text) return null;
32149
+ function getBound(text2, context, isEnd) {
32150
+ if (!text2) return null;
31026
32151
  const articles = context.phrases("articles");
31027
- text = text.split(/\s+/).filter((token) => !articles.includes(token)).join(" ");
31028
- if (!text) return unrecognized();
31029
- if (yearPattern.test(text)) return civil(decodeYear(text, context), isEnd ? 12 : 1, isEnd ? 31 : 1);
31030
- const value = keywordDate(text, context, isEnd) ?? quarter(text, context, isEnd) ?? namedMonth(text, context);
32152
+ text2 = text2.split(/\s+/).filter((token) => !articles.includes(token)).join(" ");
32153
+ if (!text2) return unrecognized();
32154
+ if (yearPattern.test(text2)) return civil(decodeYear(text2, context), isEnd ? 12 : 1, isEnd ? 31 : 1);
32155
+ const value = keywordDate(text2, context, isEnd) ?? quarter(text2, context, isEnd) ?? namedMonth(text2, context);
31031
32156
  if (value !== null) return value;
31032
- if (own(context.dictionary.weekdays, text)) return addDays(monday(context.workdate), context.dictionary.weekdays[text]);
31033
- return numericDate(text, context) ?? unrecognized();
32157
+ if (own(context.dictionary.weekdays, text2)) return addDays(monday(context.workdate), context.dictionary.weekdays[text2]);
32158
+ return numericDate(text2, context) ?? unrecognized();
31034
32159
  }
31035
32160
  function startDate(start, end, context) {
31036
32161
  if (start === null || typeof start === "string") return start;
@@ -31053,7 +32178,7 @@ function endDate(end, start, context) {
31053
32178
  }
31054
32179
  return civil(year, end.month, daysInMonth(year, end.month));
31055
32180
  }
31056
- function parseDateExpression(text, options = {}) {
32181
+ function parseDateExpression(text2, options = {}) {
31057
32182
  if (!options || typeof options !== "object" || Array.isArray(options)) return fail2("INVALID_CONTEXT", "Options must provide a civil workdate and supported locale.");
31058
32183
  let context;
31059
32184
  try {
@@ -31064,9 +32189,9 @@ function parseDateExpression(text, options = {}) {
31064
32189
  } catch (error) {
31065
32190
  return fail2("INVALID_CONTEXT", error.message);
31066
32191
  }
31067
- if (typeof text !== "string") return fail2("INVALID_INPUT", "Expression must be a string.");
32192
+ if (typeof text2 !== "string") return fail2("INVALID_INPUT", "Expression must be a string.");
31068
32193
  try {
31069
- const expression = text.toLowerCase().trim().replaceAll(",", "");
32194
+ const expression = text2.toLowerCase().trim().replaceAll(",", "");
31070
32195
  const { bounds, range } = boundTexts(expression, context);
31071
32196
  const right = getBound(bounds[1], context, true), left = getBound(bounds[0], context, false);
31072
32197
  const start = startDate(left, right, context), end = endDate(right, start, context);
@@ -31078,12 +32203,501 @@ function parseDateExpression(text, options = {}) {
31078
32203
  throw error;
31079
32204
  }
31080
32205
  }
32206
+
32207
+ // src/components/labelbox.js
32208
+ var POSITIONS = ["TL", "TC", "TR", "L", "R", "BL", "BC", "BR"];
32209
+ function project2(element, attrs, adapt, previous) {
32210
+ const next = adapt(attrs);
32211
+ for (const key of /* @__PURE__ */ new Set([...Object.keys(previous), ...Object.keys(next)])) {
32212
+ if (next[key] == null) element.removeAttribute(key);
32213
+ else element.setAttribute(key, String(next[key]));
32214
+ }
32215
+ return next;
32216
+ }
32217
+ function Labelbox(Base) {
32218
+ return class extends Base {
32219
+ #previous = { box: {}, label: {}, labelBox: {}, controlBox: {} };
32220
+ constructor() {
32221
+ super();
32222
+ this.box = this.ownerDocument.createElement("div");
32223
+ this.box.className = "labelbox";
32224
+ this.labelBox = this.ownerDocument.createElement("div");
32225
+ this.labelBox.className = "label-box";
32226
+ this.fieldLabel = this.ownerDocument.createElement("label");
32227
+ this.fieldLabel.id = "field-label";
32228
+ this.fieldLabel.htmlFor = "control";
32229
+ this.labelBox.append(this.fieldLabel);
32230
+ this.box.append(this.labelBox, this.controlBox);
32231
+ const style = this.ownerDocument.createElement("style");
32232
+ style.textContent = `.labelbox{--gramlot-label-width:initial;--gramlot-formlet-label-width:initial;display:grid;gap:var(--gramlot-label-gap,.25em);grid-template-areas:'label' 'control'}
32233
+ .label-box{grid-area:label;color:var(--gramlot-label-color,var(--gramlot-text-secondary,inherit));font-size:var(--gramlot-label-size,1em)} .control-box{grid-area:control}
32234
+ .labelbox[data-position='L']{grid-template-areas:'label control';align-items:center}
32235
+ .labelbox[data-position='R']{grid-template-areas:'control label';align-items:center}
32236
+ .labelbox[data-position^='B']{grid-template-areas:'control' 'label'}
32237
+ .labelbox[data-position$='C']>.label-box{text-align:center}
32238
+ .labelbox[data-position$='R']>.label-box{text-align:right}
32239
+ .label-box[hidden]{display:none} .label-box label{display:block}
32240
+ .labelbox[data-position='L']>.label-box{text-align:right;padding-right:2px}
32241
+ .labelbox[data-formlet-aligned]>.label-box>label{width:max-content;margin-left:auto}
32242
+ .labelbox[data-position='L']{grid-template-columns:var(--gramlot-label-width,var(--gramlot-formlet-label-width,max-content)) minmax(0,1fr)}`;
32243
+ this.shadowRoot.append(style, this.box);
32244
+ }
32245
+ projectAttributes(attrs, adapt) {
32246
+ const rest = super.projectAttributes(attrs, adapt);
32247
+ const { lbl, lbl_position = "TL" } = this.parameters;
32248
+ if (!POSITIONS.includes(lbl_position)) throw new TypeError(`Invalid lbl_position: ${lbl_position}`);
32249
+ const groups = { box: {}, label: {}, labelBox: {}, controlBox: {} };
32250
+ const prefixes = [["box_l_", "labelBox"], ["box_c_", "controlBox"], ["lbl_", "label"], ["box_", "box"]];
32251
+ for (const [name, value] of Object.entries(rest)) {
32252
+ const match = prefixes.find(([prefix]) => name.startsWith(prefix));
32253
+ if (match) {
32254
+ groups[match[1]][name.slice(match[0].length)] = value;
32255
+ delete rest[name];
32256
+ }
32257
+ }
32258
+ const elements = { box: this.box, label: this.fieldLabel, labelBox: this.labelBox, controlBox: this.controlBox };
32259
+ for (const [name, element] of Object.entries(elements)) {
32260
+ this.#previous[name] = project2(element, groups[name], adapt, this.#previous[name]);
32261
+ }
32262
+ if (attrs.lbl_width == null) this.box.style.removeProperty("--gramlot-label-width");
32263
+ else this.box.style.setProperty("--gramlot-label-width", attrs.lbl_width);
32264
+ this.box.classList.add("labelbox");
32265
+ this.labelBox.classList.add("label-box");
32266
+ this.controlBox.classList.add("control-box");
32267
+ this.box.dataset.position = lbl_position;
32268
+ this.fieldLabel.textContent = lbl ?? "";
32269
+ this.labelBox.hidden = lbl == null || lbl === "";
32270
+ if (this.control.localName !== "input") {
32271
+ if (this.labelBox.hidden) this.control.removeAttribute("aria-labelledby");
32272
+ else this.control.setAttribute("aria-labelledby", "field-label");
32273
+ }
32274
+ this.dispatchEvent(new this.ownerDocument.defaultView.Event("gramlot-label-layout", { bubbles: true }));
32275
+ return rest;
32276
+ }
32277
+ };
32278
+ }
32279
+ Labelbox.parameters = {
32280
+ lbl: { dtype: "T", qualification: "intl_str", nullable: true, binding: "read" },
32281
+ lbl_position: { dtype: "T", default: "TL", binding: "read", enum: POSITIONS }
32282
+ };
32283
+
32284
+ // src/components/validation.js
32285
+ var validationRules = ["select", "notnull", "empty", "case", "len", "min", "max", "email", "regex", "call", "remote"];
32286
+ var deferredRules = ["nodup", "exist", "gridnodup"];
32287
+ var empty = (value) => value == null || value === "";
32288
+ var then = (value, next) => value instanceof Promise ? value.then(next) : next(value);
32289
+ function validateInput(value, parameters2, context = {}) {
32290
+ const result = { value, modified: false, error: null, warnings: [], issues: [], datachanges: [] };
32291
+ const validations = Object.fromEntries(Object.entries(parameters2).map(([key, val]) => [key.slice(9), val]));
32292
+ const configured = (name) => Object.hasOwn(parameters2, `validate_${name}`) && parameters2[`validate_${name}`] != null;
32293
+ for (const name of deferredRules) if (configured(name)) throw new Error(`validate_${name} requires the DB/grid integration.`);
32294
+ const invoke = (name, current, expression = false) => context.invoke(name, parameters2[name], {
32295
+ ...validations,
32296
+ value: current,
32297
+ result,
32298
+ validations,
32299
+ userChange: true,
32300
+ signal: context.signal
32301
+ }, expression);
32302
+ const consume = (rule, output) => {
32303
+ if (output == null || output === true) return;
32304
+ if (typeof output !== "boolean" && typeof output !== "string" && (typeof output !== "object" || Array.isArray(output))) throw new TypeError("A validator returns true, false, null, an error code, or a result object/Bag.");
32305
+ const prefix = `validate_${rule}`;
32306
+ const response = output instanceof Bag ? Object.fromEntries(output.getNodes().map((node) => [node.label, node.value])) : typeof output === "object" ? output : { errorcode: output === false ? "error" : output };
32307
+ if (Object.hasOwn(response, "value")) {
32308
+ result.modified ||= !Object.is(result.value, response.value);
32309
+ result.value = response.value;
32310
+ }
32311
+ if (response.data != null) {
32312
+ context.checkDataPatch(response.data);
32313
+ result.datachanges.push(response.data);
32314
+ }
32315
+ if (!response.errorcode) return;
32316
+ const warning = parameters2[`${prefix}_iswarning`] ?? response.iswarning ?? Boolean(parameters2[`${prefix}_warning`] && !parameters2[`${prefix}_error`]);
32317
+ const message = parameters2[`${prefix}_${response.errorcode}`] || parameters2[`${prefix}_${warning ? "warning" : "error"}`] || response.message || parameters2[`${prefix}_${warning ? "error" : "warning"}`] || String(response.errorcode);
32318
+ const renderedMessage = pointerTemplate(message, (name) => name ? { ...validations, ...response, value: result.value }[name] : result.value);
32319
+ if (renderedMessage == null) throw new Error("A validation message references a missing value.");
32320
+ const issue = { rule, code: response.errorcode, severity: warning ? "warning" : "error", message: renderedMessage };
32321
+ result.issues.push(issue);
32322
+ if (warning) result.warnings.push(renderedMessage);
32323
+ else {
32324
+ result.error = renderedMessage;
32325
+ result.required = Boolean(response.required);
32326
+ }
32327
+ };
32328
+ const step = (index) => {
32329
+ if (context.signal?.aborted) throw context.signal.reason;
32330
+ if (result.error || index === validationRules.length) return result;
32331
+ const rule = validationRules[index], prefix = `validate_${rule}`, param = parameters2[prefix];
32332
+ if (!configured(rule) || param === false && rule !== "empty") return step(index + 1);
32333
+ const run = (allowed) => {
32334
+ if (!allowed) return step(index + 1);
32335
+ let output;
32336
+ if (rule === "remote" && result.value == null) return step(index + 1);
32337
+ if (rule === "call") output = invoke(prefix, result.value);
32338
+ else if (rule === "remote") output = context.remote(param, { ...remoteArguments(parameters2), value: result.value }, context.signal);
32339
+ else output = localRule(rule, param, result.value, context);
32340
+ return then(output, (answer) => {
32341
+ if (context.signal?.aborted) throw context.signal.reason;
32342
+ const complete = () => {
32343
+ consume(rule, answer);
32344
+ return step(index + 1);
32345
+ };
32346
+ if (rule === "remote" && parameters2.validate__onResult) return then(context.invoke(
32347
+ "validate__onResult",
32348
+ parameters2.validate__onResult,
32349
+ { result: answer, value: result.value, validations, signal: context.signal }
32350
+ ), complete);
32351
+ return complete();
32352
+ });
32353
+ };
32354
+ const condition = parameters2[`${prefix}_if`];
32355
+ return then(condition == null ? true : typeof condition === "boolean" ? condition : invoke(`${prefix}_if`, result.value, true), run);
32356
+ };
32357
+ return step(0);
32358
+ }
32359
+ function remoteArguments(parameters2) {
32360
+ const excluded = /* @__PURE__ */ new Set(["if", "error", "warning", "iswarning"]);
32361
+ return Object.fromEntries(Object.entries(parameters2).filter(([key]) => key.startsWith("validate_remote_") && !excluded.has(key.slice(16))).map(([key, value]) => [key.slice(16), value]));
32362
+ }
32363
+ function fail3(errorcode, message, extra = {}) {
32364
+ return { errorcode, message, ...extra };
32365
+ }
32366
+ function localRule(rule, param, value, context) {
32367
+ if (rule === "select") return context.selection(value);
32368
+ if (rule === "notnull") return empty(value) && param ? fail3("notnull", "A value is required.", { required: true }) : null;
32369
+ if (rule === "empty") return empty(value) ? { value: param } : null;
32370
+ if (rule === "len") {
32371
+ if (typeof param !== "string" || !/^(?:\d+|\d+:\d*|:\d+)$/.test(param)) throw new Error("Invalid validate_len: use a length or min:max.");
32372
+ const [low, high] = param.split(":");
32373
+ const min2 = Number(low || 0), max2 = high === void 0 ? min2 : high === "" ? Infinity : Number(high);
32374
+ if (min2 > max2) throw new Error("Invalid validate_len: minimum exceeds maximum.");
32375
+ if (empty(value)) return;
32376
+ if (typeof value !== "string") throw new TypeError("validate_len requires a text value.");
32377
+ if (value.length < min2 || value.length > max2) return fail3(
32378
+ min2 === max2 ? "wrong length" : value.length < min2 ? "too short" : "too long",
32379
+ min2 === max2 ? `Enter exactly ${min2} characters.` : max2 === Infinity ? `Enter at least ${min2} characters.` : min2 === 0 ? `Enter no more than ${max2} characters.` : `Enter between ${min2} and ${max2} characters.`
32380
+ );
32381
+ return;
32382
+ }
32383
+ if (empty(value)) return;
32384
+ if (rule === "case") {
32385
+ if (typeof value !== "string") throw new TypeError("validate_case requires a text value.");
32386
+ switch (param) {
32387
+ case "upper":
32388
+ case "u":
32389
+ return { value: value.toUpperCase() };
32390
+ case "lower":
32391
+ case "l":
32392
+ return { value: value.toLowerCase() };
32393
+ case "title":
32394
+ case "t":
32395
+ return { value: value.replace(/\p{L}[\p{L}\p{M}]*/gu, (word) => word[0].toUpperCase() + word.slice(1).toLowerCase()) };
32396
+ case "capitalize":
32397
+ case "c":
32398
+ return { value: value[0].toUpperCase() + value.slice(1).toLowerCase() };
32399
+ default:
32400
+ throw new Error("Invalid validate_case: use upper, lower, title or capitalize.");
32401
+ }
32402
+ }
32403
+ if (rule === "min" || rule === "max") {
32404
+ let comparison;
32405
+ if (context.isDecimal?.(value)) comparison = value.comparedTo(param);
32406
+ else if (value instanceof Date && param instanceof Date) comparison = value.getTime() - param.getTime();
32407
+ else if (typeof value === "number" && Number.isFinite(value) && typeof param === "number" && Number.isFinite(param)) comparison = value - param;
32408
+ else throw new TypeError(`validate_${rule} requires matching numeric or date/time values.`);
32409
+ if (rule === "min" ? comparison < 0 : comparison > 0) return fail3(rule, `Value must be ${rule === "min" ? "at least" : "at most"} ${param}.`);
32410
+ return;
32411
+ }
32412
+ if (rule === "email") {
32413
+ if (typeof value !== "string") throw new TypeError("validate_email requires a text value.");
32414
+ return /^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(value) ? null : fail3("email", "Check email format.", { iswarning: true });
32415
+ }
32416
+ if (rule === "regex") {
32417
+ if (typeof value !== "string" || typeof param !== "string") throw new TypeError("validate_regex requires text.");
32418
+ const pattern = param.trim(), negative = pattern.startsWith("!");
32419
+ return new RegExp(negative ? pattern.slice(1) : pattern, "u").test(value) !== negative ? null : fail3("regex", "The value does not match the required pattern.");
32420
+ }
32421
+ }
32422
+ var text = { dtype: "T", nullable: true, binding: "read" };
32423
+ var boolean = { dtype: "B", nullable: true, binding: "read" };
32424
+ var scalar = { dtype: ["T", "L", "N", "R", "B", "D", "H", "DH", "DHZ"], nullable: true, binding: "read" };
32425
+ var validationParameters = {
32426
+ validate_select: boolean,
32427
+ validate_notnull: { ...boolean, default: false },
32428
+ validate_empty: scalar,
32429
+ validate_case: { ...text, enum: ["upper", "lower", "title", "capitalize", "u", "l", "t", "c"] },
32430
+ validate_len: text,
32431
+ validate_min: scalar,
32432
+ validate_max: scalar,
32433
+ validate_email: boolean,
32434
+ validate_regex: text,
32435
+ validate_call: { dtype: "T", nullable: true },
32436
+ validate_remote: text,
32437
+ validate_onAccept: { dtype: "T", nullable: true },
32438
+ validate_onReject: { dtype: "T", nullable: true },
32439
+ validate__onResult: { dtype: "T", nullable: true },
32440
+ validate_timeout: { dtype: "L", nullable: true, binding: "read" },
32441
+ ...Object.fromEntries(validationRules.flatMap((rule) => [
32442
+ [`validate_${rule}_if`, { dtype: ["T", "B"], nullable: true }],
32443
+ [`validate_${rule}_iswarning`, boolean],
32444
+ ...["error", "warning"].map((suffix) => [`validate_${rule}_${suffix}`, { ...text, qualification: "intl_str" }])
32445
+ ]))
32446
+ };
32447
+
32448
+ // src/components/field-state.js
32449
+ var MESSAGE_DURATION = 1800;
32450
+ var MESSAGE_FADE_DURATION = 200;
32451
+ function FieldState(Base) {
32452
+ return class extends Base {
32453
+ #rejected = false;
32454
+ #projected;
32455
+ #messageTimer;
32456
+ #messageEvents;
32457
+ #validation;
32458
+ #validationEpoch = 0;
32459
+ #validationCurrent;
32460
+ #rules = {};
32461
+ validationResult = null;
32462
+ constructor() {
32463
+ super();
32464
+ this.message = this.ownerDocument.createElement("small");
32465
+ this.message.id = "field-message";
32466
+ this.message.hidden = true;
32467
+ this.message.setAttribute("aria-live", "polite");
32468
+ this.message.setAttribute("popover", "manual");
32469
+ this.message.setAttribute("role", "tooltip");
32470
+ const style = this.ownerDocument.createElement("style");
32471
+ style.textContent = `#control[aria-invalid="true"]{background:var(--gramlot-error-background,#fff1f0)}
32472
+ input#control[aria-invalid="true"],textarea#control[aria-invalid="true"]{color:var(--gramlot-error,#8c1d18)}
32473
+ #field-message{position:fixed;inset:auto;margin:0;padding:.4em .65em;border:1px solid var(--gramlot-error,#b3261e);border-radius:var(--gramlot-radius-sm,4px);
32474
+ color:var(--gramlot-error,#8c1d18);background:var(--gramlot-error-background,#fff1f0);font:inherit;font-size:.85em;box-shadow:var(--gramlot-shadow,0 2px 8px #0003);
32475
+ max-width:min(28em,var(--gramlot-popup-available-width,100vw));max-height:var(--gramlot-popup-available-height,100vh);overflow:auto;overflow-wrap:anywhere;opacity:1;transition:opacity ${MESSAGE_FADE_DURATION}ms ease-out}
32476
+ #field-message[data-severity="warning"]{color:var(--gramlot-warning,#805600);border-color:var(--gramlot-warning,#805600);background:var(--gramlot-warning-background,#fff8df)}
32477
+ #field-message[data-fading]{opacity:0}
32478
+ @media(prefers-reduced-motion:reduce){#field-message{transition:none}}`;
32479
+ this.shadowRoot.append(style);
32480
+ this.control.setAttribute("aria-describedby", this.message.id);
32481
+ this.controlBox.append(this.message);
32482
+ this.control.addEventListener("input", () => this.cancelValidation());
32483
+ this.control.addEventListener("compositionstart", () => this.cancelValidation());
32484
+ this.control.addEventListener("focusin", () => this.#showMessage());
32485
+ this.control.addEventListener("mouseenter", () => this.#showMessage());
32486
+ this.control.addEventListener("keydown", (event) => {
32487
+ if (event.key === "Escape") {
32488
+ this.cancelValidation();
32489
+ this.#hideMessage();
32490
+ }
32491
+ });
32492
+ }
32493
+ #hideMessage() {
32494
+ this.ownerDocument.defaultView.clearTimeout(this.#messageTimer);
32495
+ this.#messageEvents?.abort();
32496
+ this.#messageEvents = null;
32497
+ if (!this.message.hidden) this.message.hidePopover();
32498
+ this.message.hidden = true;
32499
+ this.message.removeAttribute("data-fading");
32500
+ }
32501
+ #showMessage() {
32502
+ if (!this.message.textContent || !this.isConnected) return;
32503
+ this.#hideMessage();
32504
+ const view = this.ownerDocument.defaultView;
32505
+ this.message.hidden = false;
32506
+ this.message.showPopover();
32507
+ positionPopup(this.message, this.control);
32508
+ this.#messageTimer = view.setTimeout(() => {
32509
+ if (this.message.hidden) return;
32510
+ this.message.setAttribute("data-fading", "");
32511
+ this.#messageTimer = view.setTimeout(() => this.#hideMessage(), MESSAGE_FADE_DURATION);
32512
+ }, MESSAGE_DURATION);
32513
+ this.#messageEvents = new view.AbortController();
32514
+ const options = { capture: true, signal: this.#messageEvents.signal };
32515
+ view.addEventListener("scroll", () => this.#hideMessage(), options);
32516
+ view.addEventListener("resize", () => this.#hideMessage(), options);
32517
+ }
32518
+ releaseControl() {
32519
+ this.cancelValidation();
32520
+ this.#hideMessage();
32521
+ super.releaseControl();
32522
+ }
32523
+ disconnectedCallback() {
32524
+ this.releaseControl();
32525
+ }
32526
+ setFieldState({ invalid = false, pending = false } = {}) {
32527
+ this.control.setAttribute("aria-invalid", String(invalid));
32528
+ this.control.setAttribute("aria-busy", String(pending));
32529
+ }
32530
+ error(message) {
32531
+ this.#rejected = false;
32532
+ if (["input", "textarea"].includes(this.control.localName)) this.control.setCustomValidity(message);
32533
+ this.control.setAttribute("aria-invalid", String(Boolean(message)));
32534
+ this.message.textContent = message;
32535
+ if (message) this.#showMessage();
32536
+ else this.#hideMessage();
32537
+ }
32538
+ cancelValidation() {
32539
+ this.#validationEpoch++;
32540
+ this.#validation?.abort();
32541
+ this.#validation = null;
32542
+ this.#validationCurrent = null;
32543
+ this.control.setAttribute("aria-busy", "false");
32544
+ }
32545
+ validateCandidate(value, accept) {
32546
+ this.cancelValidation();
32547
+ const controller = new AbortController();
32548
+ this.#validation = controller;
32549
+ const epoch = this.#validationEpoch;
32550
+ const rules = this.#rules;
32551
+ const current = this.pageContext.validationCurrent();
32552
+ this.#validationCurrent = current;
32553
+ const valid = () => this.#validationEpoch === epoch && !controller.signal.aborted && current();
32554
+ const failure = (error) => ({ value, modified: false, error: error.message, warnings: [], issues: [], datachanges: [] });
32555
+ const finish = (result2) => {
32556
+ if (!valid()) {
32557
+ if (this.#validation === controller) this.cancelValidation();
32558
+ return { ok: false };
32559
+ }
32560
+ this.#validation = null;
32561
+ this.#validationCurrent = null;
32562
+ this.control.setAttribute("aria-busy", "false");
32563
+ try {
32564
+ if (!result2.error) accept(result2.value);
32565
+ } catch (error) {
32566
+ result2 = failure(error);
32567
+ }
32568
+ this.validationResult = result2;
32569
+ this.error(result2.error || "");
32570
+ this.message.dataset.severity = result2.error ? "error" : "warning";
32571
+ this.#rejected = Boolean(result2.error);
32572
+ if (!result2.error && result2.warnings.length) {
32573
+ this.message.textContent = result2.warnings.join("\n");
32574
+ this.#showMessage();
32575
+ }
32576
+ const outcome = { ok: !result2.error, value: result2.value, result: result2, rules, isCurrent: valid };
32577
+ if (!outcome.ok) this.finishValidation(outcome);
32578
+ return outcome;
32579
+ };
32580
+ let result;
32581
+ try {
32582
+ if (rules.validate_timeout != null && (!Number.isInteger(rules.validate_timeout) || rules.validate_timeout <= 0)) throw new TypeError("validate_timeout must be a positive integer in milliseconds.");
32583
+ result = validateInput(value, rules, { ...this.pageContext, signal: controller.signal, selection: (value2) => this.validateSelection(value2) });
32584
+ } catch (error) {
32585
+ return finish(failure(error));
32586
+ }
32587
+ if (!(result instanceof Promise)) return finish(result);
32588
+ this.control.setAttribute("aria-busy", "true");
32589
+ return new Promise((resolve) => {
32590
+ let timer;
32591
+ const abort = () => {
32592
+ clearTimeout(timer);
32593
+ resolve({ ok: false });
32594
+ };
32595
+ controller.signal.addEventListener("abort", abort, { once: true });
32596
+ const settle = (answer) => {
32597
+ clearTimeout(timer);
32598
+ controller.signal.removeEventListener("abort", abort);
32599
+ resolve(finish(answer));
32600
+ };
32601
+ if (rules.validate_timeout != null) timer = setTimeout(() => {
32602
+ settle(failure(new Error("Validation timed out.")));
32603
+ controller.abort();
32604
+ }, rules.validate_timeout);
32605
+ result.then(settle, (error) => settle(failure(error)));
32606
+ });
32607
+ }
32608
+ finishValidation(outcome) {
32609
+ if (!outcome.result) return;
32610
+ this.pageContext.finishValidation(outcome);
32611
+ }
32612
+ shouldProjectControlValue(value) {
32613
+ if (this.#validationCurrent && !this.#validationCurrent()) this.cancelValidation();
32614
+ const same = this.sameControlValue(value, this.#projected);
32615
+ if (same && this.#rejected) return false;
32616
+ if (!same) this.cancelValidation();
32617
+ this.#projected = value;
32618
+ if (!same && this.#rejected) this.error("");
32619
+ return true;
32620
+ }
32621
+ projectAttributes(attrs, adapt) {
32622
+ const rest = super.projectAttributes(attrs, adapt);
32623
+ const rules = Object.fromEntries(Object.entries(attrs).filter(([name]) => name.startsWith("validate_")));
32624
+ const keys = /* @__PURE__ */ new Set([...Object.keys(rules), ...Object.keys(this.#rules)]);
32625
+ if ([...keys].some((key) => !Object.is(rules[key], this.#rules[key])) || attrs.disabled || attrs.readonly) this.cancelValidation();
32626
+ this.#rules = rules;
32627
+ for (const key of Object.keys(rules)) delete rest[key];
32628
+ const required = Boolean(this.parameters.validate_notnull);
32629
+ this.control.setAttribute("aria-required", String(required));
32630
+ if (this.control.localName === "textarea" || this.control.localName === "input" && ["text", "password"].includes(this.control.type)) {
32631
+ this.control.required = required;
32632
+ }
32633
+ return rest;
32634
+ }
32635
+ };
32636
+ }
32637
+ FieldState.parameters = validationParameters;
32638
+
32639
+ // src/collection-artifact.js
32640
+ var encoder = new TextEncoder();
32641
+ var wrapper = (id) => `export {default} from "./collection.js";
32642
+ export const buildId = "${id}";
32643
+ `;
32644
+ var pathValid = (value) => typeof value === "string" && value.length > 0 && !/[\\\x00-\x1f:?#%]/.test(value) && !value.split("/").some((part) => !part || part === "." || part === "..");
32645
+ function validate(metadata, files) {
32646
+ if (!metadata || typeof metadata.name !== "string" || !metadata.name || !["grammar", "commands", "module"].every((key) => pathValid(metadata[key])) || !Array.isArray(metadata.css) || !metadata.css.every(pathValid) || !Array.isArray(metadata.dependencies) || !metadata.dependencies.every((name) => typeof name === "string" && name.length > 0) || !Array.isArray(metadata.files) || !metadata.files.every(pathValid) || new Set(metadata.files).size !== metadata.files.length || !(files instanceof Map) || files.size !== metadata.files.length || metadata.files.some((path) => !(files.get(path) instanceof Uint8Array)) || [metadata.grammar, metadata.commands, metadata.module, ...metadata.css].some((path) => !files.has(path))) {
32647
+ throw new TypeError("Invalid collection artifact metadata or file inventory");
32648
+ }
32649
+ }
32650
+ async function collectionBuildId(metadata, files) {
32651
+ validate(metadata, files);
32652
+ const chunks = [encoder.encode("gramlot-build-v1\0")];
32653
+ const record2 = (tag2, value) => {
32654
+ const bytes = typeof value === "string" ? encoder.encode(value) : value;
32655
+ chunks.push(encoder.encode(`${tag2}\0${bytes.length}\0`), bytes);
32656
+ };
32657
+ for (const key of ["name", "grammar", "commands", "module"]) record2(key, metadata[key]);
32658
+ for (const value of metadata.css) record2("css", value);
32659
+ for (const value of metadata.dependencies) record2("dependency", value);
32660
+ const compare = (a, b) => {
32661
+ const left = encoder.encode(a), right = encoder.encode(b);
32662
+ for (let i = 0; i < Math.min(left.length, right.length); i++) if (left[i] !== right[i]) return left[i] - right[i];
32663
+ return left.length - right.length;
32664
+ };
32665
+ for (const path of [...metadata.files].sort(compare)) {
32666
+ record2("path", path);
32667
+ record2("content", path === metadata.module ? wrapper("__GRAMLOT_BUILD_ID__") : files.get(path));
32668
+ }
32669
+ const input = new Uint8Array(chunks.reduce((total, chunk) => total + chunk.length, 0));
32670
+ let offset = 0;
32671
+ for (const chunk of chunks) {
32672
+ input.set(chunk, offset);
32673
+ offset += chunk.length;
32674
+ }
32675
+ const hash = await crypto.subtle.digest("SHA-256", input);
32676
+ return "sha256:" + [...new Uint8Array(hash)].map((value) => value.toString(16).padStart(2, "0")).join("");
32677
+ }
32678
+ async function verifyCollectionArtifact(metadata, files) {
32679
+ validate(metadata, files);
32680
+ if (typeof metadata.buildId !== "string" || !/^sha256:[a-f0-9]{64}$/.test(metadata.buildId)) {
32681
+ throw new TypeError("Invalid collection buildId");
32682
+ }
32683
+ const expected = encoder.encode(wrapper(metadata.buildId)), actual = files.get(metadata.module);
32684
+ if (actual.length !== expected.length || actual.some((byte, index) => byte !== expected[index])) {
32685
+ throw new Error("Invalid collection wrapper");
32686
+ }
32687
+ if (await collectionBuildId(metadata, files) !== metadata.buildId) {
32688
+ throw new Error(`Collection fingerprint mismatch: ${metadata.name}`);
32689
+ }
32690
+ }
31081
32691
  export {
31082
32692
  Bag,
31083
32693
  BagNode,
32694
+ ChoiceGroup,
32695
+ CommandRegistry,
32696
+ ComponentCollection,
31084
32697
  DirectoryResolver,
31085
32698
  DomHandler,
31086
32699
  Exposed,
32700
+ FieldState,
31087
32701
  FileSystemController,
31088
32702
  FileSystemLogic,
31089
32703
  FramePage,
@@ -31098,6 +32712,8 @@ export {
31098
32712
  InOut,
31099
32713
  IndexLogic,
31100
32714
  IndexPage,
32715
+ Labelbox,
32716
+ NativeControl,
31101
32717
  NavigationResolver,
31102
32718
  Page,
31103
32719
  PageBootstrap,
@@ -31108,8 +32724,12 @@ export {
31108
32724
  SourceHandler,
31109
32725
  UtilitiesHandler,
31110
32726
  codeMirrorWithOptions,
32727
+ collectionBuildId,
31111
32728
  createDecimal,
32729
+ defineCollection,
32730
+ defineComponent,
31112
32731
  fileSystemTree,
31113
32732
  mountIndexPage,
31114
- parseDateExpression
32733
+ parseDateExpression,
32734
+ verifyCollectionArtifact
31115
32735
  };