@gramlot/gramlot 0.2.19 → 0.3.0

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 (66) hide show
  1. package/dist/gramlot.js +2145 -224
  2. package/dist/gramlot.min.js +363 -21
  3. package/package.json +6 -3
  4. package/src/binding/ask-dialog.js +2 -2
  5. package/src/binding/inline.js +11 -12
  6. package/src/binding/installation.js +4 -1
  7. package/src/binding/pointer.js +63 -0
  8. package/src/binding/providers.js +8 -4
  9. package/src/binding/runtime.js +11 -5
  10. package/src/bootstrap.d.ts +2 -0
  11. package/src/bootstrap.js +9 -2
  12. package/src/builder/gramlot-builder.js +24 -3
  13. package/src/builder/source.js +33 -9
  14. package/src/components/bases.js +182 -0
  15. package/src/components/buttons.js +254 -0
  16. package/src/components/choice-editor.js +221 -0
  17. package/src/components/choices.js +13 -0
  18. package/src/components/date-calendar.js +139 -0
  19. package/src/components/field-state.js +166 -0
  20. package/src/components/formlet-labels.js +80 -0
  21. package/src/components/index.js +5 -0
  22. package/src/components/inputs.js +196 -0
  23. package/src/components/labelbox.js +74 -0
  24. package/src/components/layout.js +190 -0
  25. package/src/components/parameters.js +6 -0
  26. package/src/components/popup.js +22 -0
  27. package/src/components/registry.js +83 -0
  28. package/src/components/typed-editor.js +260 -0
  29. package/src/components/validation.js +138 -0
  30. package/src/date-parser/civil.js +61 -0
  31. package/src/date-parser/index.d.ts +18 -0
  32. package/src/date-parser/index.js +196 -0
  33. package/src/date-parser/locales.js +257 -0
  34. package/src/format.js +128 -0
  35. package/src/gramlot.d.ts +25 -0
  36. package/src/gramlot.js +15 -1
  37. package/src/handlers/dom-handler.d.ts +1 -0
  38. package/src/handlers/dom-handler.js +7 -0
  39. package/src/index-page-runtime.js +78 -30
  40. package/src/index-page-styles.js +2 -2
  41. package/src/index-theme.js +1 -1
  42. package/src/index.d.ts +4 -1
  43. package/src/index.js +2 -0
  44. package/src/renderer/attributes.js +25 -50
  45. package/src/renderer/gramlot-html-renderer.js +4 -3
  46. package/src/renderer/gramlot-renderer.js +63 -3
  47. package/src/server/gramlot-server.d.ts +5 -0
  48. package/src/server/gramlot-server.js +14 -5
  49. package/src/server/index-page.d.ts +1 -0
  50. package/src/server/index-page.js +8 -3
  51. package/src/server/page-base.js +3 -0
  52. package/src/server/page.d.ts +3 -0
  53. package/src/server/resources.d.ts +2 -0
  54. package/src/view/button.js +17 -13
  55. package/src/view/controls.js +152 -4
  56. package/src/view/html.js +18 -0
  57. package/themes/gramlot-base/README.md +6 -0
  58. package/themes/gramlot-base/theme.css +34 -6
  59. package/themes/gramlot-compact/README.md +6 -0
  60. package/themes/gramlot-compact/theme.css +8 -4
  61. package/themes/joanna/README.md +23 -0
  62. package/themes/joanna/theme.css +89 -0
  63. package/themes/mimi/README.md +23 -0
  64. package/themes/mimi/theme.css +89 -0
  65. package/tools/gramlot-tools-inspector.js +42 -18
  66. package/tools/inspector-agent.js +8 -4
package/dist/gramlot.js CHANGED
@@ -60,7 +60,7 @@ var require_conventions = __commonJS({
60
60
  }
61
61
  }
62
62
  }
63
- function freeze(object, oc) {
63
+ function freeze2(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 = freeze({
86
+ var HTML_BOOLEAN_ATTRIBUTES = freeze2({
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 = freeze({
115
+ var HTML_VOID_ELEMENTS = freeze2({
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 = freeze({
134
+ var HTML_RAW_TEXT_ELEMENTS = freeze2({
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 = freeze({
154
+ var MIME_TYPE = freeze2({
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 = freeze({
207
+ var NAMESPACE = freeze2({
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 = freeze;
235
+ exports.freeze = freeze2;
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;
@@ -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 freeze = require_conventions().freeze;
3290
- exports.XML_ENTITIES = freeze({
3289
+ var freeze2 = require_conventions().freeze;
3290
+ exports.XML_ENTITIES = freeze2({
3291
3291
  amp: "&",
3292
3292
  apos: "'",
3293
3293
  gt: ">",
3294
3294
  lt: "<",
3295
3295
  quot: '"'
3296
3296
  });
3297
- exports.HTML_ENTITIES = freeze({
3297
+ exports.HTML_ENTITIES = freeze2({
3298
3298
  Aacute: "\xC1",
3299
3299
  aacute: "\xE1",
3300
3300
  Abreve: "\u0102",
@@ -6565,6 +6565,160 @@ var HttpTransport = class {
6565
6565
  }
6566
6566
  };
6567
6567
 
6568
+ // node_modules/@genrojs/builders/src/pointers.js
6569
+ function pointerTransform(value) {
6570
+ if (typeof value !== "string" || !["^", "="].includes(value[0]) || value.startsWith("==")) return null;
6571
+ const index = value.indexOf(":");
6572
+ if (index < 0) return null;
6573
+ const expression = value[index + 1] === "=";
6574
+ return { pointer: value.slice(0, index), expression, body: value.slice(index + (expression ? 2 : 1)) };
6575
+ }
6576
+ var SLOT = /^\{(\??[A-Za-z_][A-Za-z0-9_]*|\?)?\}/;
6577
+ function pointerTemplate(body, read) {
6578
+ let result = "", blocked = false;
6579
+ for (let i = 0; i < body.length; ) {
6580
+ if (body[i] !== "{" && body[i] !== "}") {
6581
+ result += body[i++];
6582
+ continue;
6583
+ }
6584
+ const match = body.slice(i).match(SLOT);
6585
+ if (!match) throw new SyntaxError("Invalid pointer template placeholder");
6586
+ const slot = match[1] ?? "";
6587
+ const optional = slot.startsWith("?");
6588
+ const value = read(optional ? slot.slice(1) : slot);
6589
+ if (value == null || value === "" && !optional) blocked = true;
6590
+ else result += String(value);
6591
+ i += match[0].length;
6592
+ }
6593
+ return blocked ? null : result;
6594
+ }
6595
+ function pointerExpression(body) {
6596
+ const slots = [], identifiers = /* @__PURE__ */ new Set();
6597
+ let text = "", operand = true;
6598
+ for (let i = 0; i < body.length; ) {
6599
+ const start = i, c = body[i];
6600
+ if (c === '"' || c === "'" || c === "`") {
6601
+ i++;
6602
+ while (i < body.length) {
6603
+ if (body[i] === "\\") {
6604
+ i += 2;
6605
+ continue;
6606
+ }
6607
+ if (body[i++] === c) break;
6608
+ }
6609
+ text += body.slice(start, i);
6610
+ operand = false;
6611
+ continue;
6612
+ }
6613
+ if (body.startsWith("//", i)) {
6614
+ i = body.indexOf("\n", i);
6615
+ if (i < 0) i = body.length;
6616
+ text += body.slice(start, i);
6617
+ continue;
6618
+ }
6619
+ if (body.startsWith("/*", i)) {
6620
+ const end = body.indexOf("*/", i + 2);
6621
+ i = end < 0 ? body.length : end + 2;
6622
+ text += body.slice(start, i);
6623
+ continue;
6624
+ }
6625
+ if (c === "/" && operand) {
6626
+ let bracket = false;
6627
+ i++;
6628
+ while (i < body.length) {
6629
+ const current = body[i++];
6630
+ if (current === "\\") {
6631
+ i++;
6632
+ continue;
6633
+ }
6634
+ if (current === "[") bracket = true;
6635
+ else if (current === "]") bracket = false;
6636
+ else if (current === "/" && !bracket) break;
6637
+ }
6638
+ while (/[a-z]/i.test(body[i] ?? "") && i < body.length) i++;
6639
+ text += body.slice(start, i);
6640
+ operand = false;
6641
+ continue;
6642
+ }
6643
+ const slot = c === "{" ? body.slice(i).match(SLOT) : null;
6644
+ if (slot) {
6645
+ const name = slot[1] ?? "";
6646
+ if (name.startsWith("?")) throw new SyntaxError("Optional slots are supported in pointer templates only");
6647
+ text += `_pointerValues[${slots.length}]`;
6648
+ slots.push(name);
6649
+ i += slot[0].length;
6650
+ operand = false;
6651
+ continue;
6652
+ }
6653
+ const word = body.slice(i).match(/^[A-Za-z_$][\w$]*/);
6654
+ if (word) {
6655
+ identifiers.add(word[0]);
6656
+ text += word[0];
6657
+ i += word[0].length;
6658
+ operand = ["return", "typeof", "void", "delete", "new", "in", "instanceof", "yield", "await"].includes(word[0]);
6659
+ continue;
6660
+ }
6661
+ text += c;
6662
+ i++;
6663
+ if (!/\s/.test(c)) operand = /[([{,:;=!?&|+*%~<>\/-]/.test(c);
6664
+ }
6665
+ return { text, slots, identifiers };
6666
+ }
6667
+ function resolvePointerItems(items, current, evaluate = () => null) {
6668
+ const values = /* @__PURE__ */ new Map(), active = [];
6669
+ const resolve = (name) => {
6670
+ if (values.has(name)) return values.get(name);
6671
+ if (!items.has(name)) throw new Error(`Referenced Source attribute '${name}' does not exist`);
6672
+ if (active.includes(name)) throw new Error(`Cyclic attribute dependency: ${[...active, name].join(" -> ")}`);
6673
+ active.push(name);
6674
+ try {
6675
+ const raw = items.get(name);
6676
+ const transform = typeof name === "string" ? pointerTransform(raw) : null;
6677
+ let result = current.get(name);
6678
+ if (transform) {
6679
+ const read = (key) => key ? resolve(key) : current.get(name);
6680
+ if (transform.expression) {
6681
+ const expression = pointerExpression(transform.body);
6682
+ result = evaluate(name, raw, expression, expression.slots.map(read));
6683
+ } else {
6684
+ result = pointerTemplate(transform.body, read);
6685
+ if (current.get(name) == null) result = null;
6686
+ }
6687
+ }
6688
+ values.set(name, result);
6689
+ return result;
6690
+ } finally {
6691
+ active.pop();
6692
+ }
6693
+ };
6694
+ return new Map([...items.keys()].map((name) => [name, resolve(name)]));
6695
+ }
6696
+ function pointerDependencies(node, raw) {
6697
+ const items = new Map([...Object.entries(node.getAttr()), ...node.fixedAttrItems()]);
6698
+ const seen = /* @__PURE__ */ new Set(), active = [];
6699
+ const visit = (value) => {
6700
+ const transform = pointerTransform(value);
6701
+ if (!transform) return;
6702
+ const names = [];
6703
+ if (transform.expression) names.push(...pointerExpression(transform.body).slots);
6704
+ else pointerTemplate(transform.body, (key) => {
6705
+ names.push(key);
6706
+ return "";
6707
+ });
6708
+ for (const name of names.filter(Boolean)) {
6709
+ if (!items.has(name)) throw new Error(`Referenced Source attribute '${name}' does not exist`);
6710
+ if (active.includes(name)) throw new Error(`Cyclic attribute dependency: ${[...active, name].join(" -> ")}`);
6711
+ if (seen.has(name)) continue;
6712
+ active.push(name);
6713
+ visit(items.get(name));
6714
+ active.pop();
6715
+ seen.add(name);
6716
+ }
6717
+ };
6718
+ visit(raw);
6719
+ return seen;
6720
+ }
6721
+
6568
6722
  // node_modules/decimal.js/decimal.mjs
6569
6723
  /*!
6570
6724
  * decimal.js v10.6.0
@@ -11159,16 +11313,16 @@ function toQs(value) {
11159
11313
  return value.map((item) => String(item)).join("&");
11160
11314
  }
11161
11315
  if (value !== null && typeof value === "object") {
11162
- const parts = [];
11316
+ const parts2 = [];
11163
11317
  for (const [k, v] of Object.entries(value)) {
11164
11318
  const [encoded, result] = rawEncode(v, true);
11165
11319
  if (encoded) {
11166
- parts.push(`${k}=${result}`);
11320
+ parts2.push(`${k}=${result}`);
11167
11321
  } else {
11168
- parts.push(`${k}=${v}`);
11322
+ parts2.push(`${k}=${v}`);
11169
11323
  }
11170
11324
  }
11171
- return parts.join("&");
11325
+ return parts2.join("&");
11172
11326
  }
11173
11327
  throw new TypeError(`toQs expects object or array, got ${typeof value}`);
11174
11328
  }
@@ -11176,18 +11330,18 @@ function fromQs(data) {
11176
11330
  if (!data) {
11177
11331
  return [];
11178
11332
  }
11179
- const parts = data.split("&");
11180
- const hasEq = parts.map((p) => p.includes("="));
11333
+ const parts2 = data.split("&");
11334
+ const hasEq = parts2.map((p) => p.includes("="));
11181
11335
  const allWithEq = hasEq.every(Boolean);
11182
11336
  const noneWithEq = !hasEq.some(Boolean);
11183
11337
  if (!allWithEq && !noneWithEq) {
11184
11338
  throw new Error("QS format error: mixed items with and without '='");
11185
11339
  }
11186
11340
  if (noneWithEq) {
11187
- return parts.map((p) => fromTytx(p));
11341
+ return parts2.map((p) => fromTytx(p));
11188
11342
  }
11189
11343
  const result = {};
11190
- for (const part of parts) {
11344
+ for (const part of parts2) {
11191
11345
  const eqIndex = part.indexOf("=");
11192
11346
  const key = part.slice(0, eqIndex);
11193
11347
  const value = part.slice(eqIndex + 1);
@@ -11199,6 +11353,9 @@ function fromQs(data) {
11199
11353
  // node_modules/@genrojs/tytx/js/src/registry.js
11200
11354
  var DecimalClass = DecimalJS || BigJS || Number;
11201
11355
  var decimalLibrary = DecimalJS ? "decimal.js" : BigJS ? "big.js" : "number";
11356
+ function getDecimalLibrary() {
11357
+ return decimalLibrary;
11358
+ }
11202
11359
  function createDecimal(value) {
11203
11360
  return new DecimalClass(value);
11204
11361
  }
@@ -12983,15 +13140,15 @@ var Bag = class _Bag {
12983
13140
  * @returns {string|null} The relative path, or null if not a descendant.
12984
13141
  */
12985
13142
  relativePath(node) {
12986
- const parts = [];
13143
+ const parts2 = [];
12987
13144
  let current = node;
12988
13145
  while (current !== null) {
12989
13146
  if (current.parentBag === this) {
12990
- parts.push(current.label);
12991
- parts.reverse();
12992
- return parts.join(".");
13147
+ parts2.push(current.label);
13148
+ parts2.reverse();
13149
+ return parts2.join(".");
12993
13150
  }
12994
- parts.push(current.label);
13151
+ parts2.push(current.label);
12995
13152
  current = current.parentNode;
12996
13153
  }
12997
13154
  return null;
@@ -14723,11 +14880,11 @@ ${content}`;
14723
14880
  * @private
14724
14881
  */
14725
14882
  _bagToXml(selfClosedTags = null, pretty = false, depth = 0) {
14726
- const parts = [];
14883
+ const parts2 = [];
14727
14884
  for (const node of this._nodes) {
14728
- parts.push((pretty ? " ".repeat(depth) : "") + this._nodeToXml(node, selfClosedTags, pretty, depth));
14885
+ parts2.push((pretty ? " ".repeat(depth) : "") + this._nodeToXml(node, selfClosedTags, pretty, depth));
14729
14886
  }
14730
- return parts.join(pretty ? "\n" : "");
14887
+ return parts2.join(pretty ? "\n" : "");
14731
14888
  }
14732
14889
  /**
14733
14890
  * Convert a BagNode to XML string (internal).
@@ -15059,8 +15216,8 @@ ${" ".repeat(depth)}</${tag2}>`;
15059
15216
  let attrStr = "";
15060
15217
  const attrs = node.attr;
15061
15218
  if (attrs && Object.keys(attrs).length > 0) {
15062
- const parts = Object.entries(attrs).map(([k, v]) => `${k}=${JSON.stringify(v)}`);
15063
- attrStr = ` [${parts.join(", ")}]`;
15219
+ const parts2 = Object.entries(attrs).map(([k, v]) => `${k}=${JSON.stringify(v)}`);
15220
+ attrStr = ` [${parts2.join(", ")}]`;
15064
15221
  }
15065
15222
  const branch = isLast ? "\u2514\u2500\u2500 " : "\u251C\u2500\u2500 ";
15066
15223
  const childPrefix = _prefix + (isLast ? " " : "\u2502 ");
@@ -15209,7 +15366,7 @@ var SourceBagNode = class extends BagNode {
15209
15366
  }
15210
15367
  /** Return "^" (reactive), "=" (passive) or null. */
15211
15368
  pointerType(v) {
15212
- if (typeof v === "string" && (v[0] === "^" || v[0] === "=")) {
15369
+ if (typeof v === "string" && (v[0] === "^" || v[0] === "=") && !v.startsWith("==")) {
15213
15370
  return v[0];
15214
15371
  }
15215
15372
  return null;
@@ -15221,11 +15378,11 @@ var SourceBagNode = class extends BagNode {
15221
15378
  const result = [];
15222
15379
  for (const [attrname, v] of Object.entries(this.getAttr() || {})) {
15223
15380
  if (this.pointerType(v) === "^") {
15224
- result.push([attrname, v]);
15381
+ result.push([attrname, v.split(":", 1)[0]]);
15225
15382
  }
15226
15383
  }
15227
15384
  if (this.pointerType(this.value) === "^") {
15228
- result.push(["", this.value]);
15385
+ result.push(["", this.value.split(":", 1)[0]]);
15229
15386
  }
15230
15387
  return result;
15231
15388
  }
@@ -15244,14 +15401,14 @@ var SourceBagNode = class extends BagNode {
15244
15401
  absDatapath(path) {
15245
15402
  const raw = path;
15246
15403
  if (this.pointerType(path)) {
15247
- path = path.slice(1);
15404
+ path = (pointerTransform(path)?.pointer ?? path).slice(1);
15248
15405
  }
15249
15406
  let attr = null;
15250
15407
  if (path.includes("?")) {
15251
15408
  [path, attr] = path.split("?", 2);
15252
15409
  }
15253
15410
  if (path.startsWith("#")) {
15254
- return this._resolveSymbolicDatapath(path, raw);
15411
+ return this._finalizeAbsPath(this._resolveSymbolicDatapath(path, raw), attr);
15255
15412
  }
15256
15413
  if (path.startsWith(".")) {
15257
15414
  path = this._composeRelativeDatapath(path, raw);
@@ -15570,13 +15727,31 @@ function pythonRegexPattern(pattern, flags) {
15570
15727
  }
15571
15728
  function annotation(desc, path, nested = false, customTypes = null) {
15572
15729
  if (desc === null) return null;
15573
- exactKeys(desc, ["kind", "module", "name", "origin", "arguments", "items", "values", "base", "metadata", "pattern", "flags", "ge", "le", "gt", "lt", "value"], ["kind"], path);
15730
+ exactKeys(desc, ["kind", "dtype", "module", "name", "origin", "arguments", "items", "values", "base", "metadata", "pattern", "flags", "ge", "le", "gt", "lt", "value"], ["kind"], path);
15574
15731
  switch (desc.kind) {
15575
15732
  case "custom": {
15576
15733
  exactKeys(desc, ["kind", "name"], ["kind", "name"], path);
15577
15734
  if (!customTypes) fail(path, "custom references require a catalog; nested catalog references are unsupported");
15578
15735
  return customTypes.resolve(desc.name, path);
15579
15736
  }
15737
+ case "dtype": {
15738
+ exactKeys(desc, ["kind", "dtype"], ["kind", "dtype"], path);
15739
+ const code = desc.dtype;
15740
+ if (typeof code !== "string") fail(path, "dtype must be a string");
15741
+ const Type = getRegisteredType(code);
15742
+ if (!Type && code !== "NN") fail(path, `unknown dtype '${code}'`);
15743
+ const test = (value) => {
15744
+ if (code === "NN") return value === null;
15745
+ if (code === "N") return isDecimal2(value) && !["NaN", "Infinity", "-Infinity"].includes(value.toString());
15746
+ if (Type === Number) return typeof value === "number" && Number.isFinite(value) && (code !== "L" || Number.isInteger(value));
15747
+ if (Type === String) return typeof value === "string";
15748
+ if (Type === Boolean) return typeof value === "boolean";
15749
+ if (Type === Date) return value instanceof Date && Number.isFinite(value.getTime());
15750
+ if (Type === Object) return plainObject(value) && [Object.prototype, null].includes(Object.getPrototypeOf(value));
15751
+ return value instanceof Type;
15752
+ };
15753
+ return { ...desc, test };
15754
+ }
15580
15755
  case "any":
15581
15756
  return { ...desc, test: (_v) => true };
15582
15757
  case "type": {
@@ -15745,13 +15920,13 @@ function declaration(value, path, isElement, customTypes) {
15745
15920
  function parents(value) {
15746
15921
  return value ? value.split(",").map((x) => x.trim()).filter(Boolean) : [];
15747
15922
  }
15748
- function inherit(base, own) {
15749
- const out = { ...own };
15923
+ function inherit(base, own2) {
15924
+ const out = { ...own2 };
15750
15925
  for (const [key, value] of Object.entries(base)) {
15751
15926
  if (key === "inherits_from" || key.startsWith("_")) continue;
15752
15927
  if (!out[key]) out[key] = value;
15753
15928
  }
15754
- out._meta = { ...base._meta || {}, ...own._meta || {} };
15929
+ out._meta = { ...base._meta || {}, ...own2._meta || {} };
15755
15930
  return out;
15756
15931
  }
15757
15932
  function compileDeclaration(value) {
@@ -15778,9 +15953,9 @@ function resolveGrammarDeclarations({ abstracts: rawAbstracts = {}, elements: ra
15778
15953
  const state = /* @__PURE__ */ new Map();
15779
15954
  for (const name of Object.keys(abstracts)) resolveAbstract(name, abstracts, state, `abstracts.${name}.inherits_from`);
15780
15955
  const elements = {};
15781
- for (const [name, own] of Object.entries(rawElements)) {
15782
- let out = { ...own };
15783
- for (const parent of parents(own.inherits_from)) {
15956
+ for (const [name, own2] of Object.entries(rawElements)) {
15957
+ let out = { ...own2 };
15958
+ for (const parent of parents(own2.inherits_from)) {
15784
15959
  const base = abstracts[parent];
15785
15960
  if (!base) fail(`elements.${name}.inherits_from`, `unknown abstract '${parent}'`);
15786
15961
  out = inherit(base, out);
@@ -16823,41 +16998,47 @@ var BuilderBase = class _BuilderBase {
16823
16998
  /** Resolve the pointers/values a node carries → [runtimeValue, runtimeAttrs]. */
16824
16999
  runtimeValues(node) {
16825
17000
  node.builder.validateCustomTypes(node);
16826
- const resolved2 = /* @__PURE__ */ new Map();
17001
+ const current = /* @__PURE__ */ new Map();
16827
17002
  const carried = {};
17003
+ const items = node.runtimeToEvaluate();
17004
+ const projected = new Set(items.keys());
17005
+ const sourceAttrs = new Map([...Object.entries(node.getAttr()), ...node.fixedAttrItems()]);
17006
+ for (const [key, raw] of [...items]) {
17007
+ if (typeof key !== "string" || !pointerTransform(raw)) continue;
17008
+ for (const name of pointerDependencies(node, raw)) {
17009
+ if (!items.has(name)) items.set(name, sourceAttrs.get(name));
17010
+ }
17011
+ }
16828
17012
  const isDataElement = node._getMeta("data_element");
16829
- for (const [k, v] of node.runtimeToEvaluate()) {
17013
+ for (const [k, v] of items) {
16830
17014
  if (v instanceof BagResolver) {
16831
- resolved2.set(k, v.resolve());
17015
+ current.set(k, v.resolve());
16832
17016
  continue;
16833
17017
  }
16834
- if (!node.pointerType(v)) {
16835
- resolved2.set(k, v);
17018
+ const pointer = typeof k === "string" ? pointerTransform(v)?.pointer ?? v : v;
17019
+ if (!node.pointerType(pointer)) {
17020
+ current.set(k, typeof k === "string" && typeof v === "string" && v.startsWith("==") ? null : v);
16836
17021
  continue;
16837
17022
  }
16838
- const absPath = node.absDatapath(v);
16839
- resolved2.set(k, this.data.getItem(absPath));
17023
+ const absPath = node.absDatapath(pointer);
17024
+ current.set(k, this.data.getItem(absPath));
16840
17025
  if (!isDataElement && !absPath.includes("?") && k === VALUE) {
16841
17026
  const dataNode = this.data.getNode(absPath);
16842
17027
  if (dataNode) Object.assign(carried, dataNode.getAttr("_wdg"));
16843
17028
  }
16844
17029
  }
16845
- const consumed = /* @__PURE__ */ new Set();
16846
- for (const [k, v] of resolved2) {
16847
- if (isDataElement || k === VALUE || typeof v !== "string") continue;
16848
- resolved2.set(k, v.replace(/(\\)?\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g, (token, escaped, name) => {
16849
- if (escaped) return token.slice(1);
16850
- if (!resolved2.has(name)) throw new Error(`Unknown template parameter '${name}'`);
16851
- consumed.add(name);
16852
- const value = resolved2.get(name);
16853
- return value === null ? "" : String(value);
16854
- }));
16855
- }
17030
+ const resolved2 = resolvePointerItems(items, current, (name, raw, expression, inputs) => this.evaluatePointerExpression(node, name, raw, expression, inputs));
16856
17031
  const runtimeValue = resolved2.get(VALUE);
16857
17032
  resolved2.delete(VALUE);
16858
- for (const name of consumed) resolved2.delete(name);
17033
+ for (const name of resolved2.keys()) if (!projected.has(name)) resolved2.delete(name);
16859
17034
  return [runtimeValue, { ...Object.fromEntries(resolved2), ...carried }];
16860
17035
  }
17036
+ /** Consumer hook for := expressions. Static builders intentionally return null.
17037
+ * Override using the runtime's compiler/CSP policy. inputs are typed slot values;
17038
+ * expression.text refers to them through _pointerValues, never textual injection. */
17039
+ evaluatePointerExpression(node, name, raw, expression, inputs) {
17040
+ return null;
17041
+ }
16861
17042
  /** Stable per-document identity assigned when a renderer requests it. */
16862
17043
  targetId(node) {
16863
17044
  if (node._targetId) {
@@ -17066,8 +17247,8 @@ function temporal(value, dtype) {
17066
17247
  return kind;
17067
17248
  }
17068
17249
  function patternDate(value, pattern, locale, kind) {
17069
- const parts = pattern.match(TOKENS) || [];
17070
- if (parts.join("") !== pattern) throw new RangeError("Unclosed format literal");
17250
+ const parts2 = pattern.match(TOKENS) || [];
17251
+ if (parts2.join("") !== pattern) throw new RangeError("Unclosed format literal");
17071
17252
  const pad = (v, n = 2) => String(v).padStart(n, "0");
17072
17253
  const name = (options) => new Intl.DateTimeFormat(locale, { timeZone: "UTC", ...options }).format(value);
17073
17254
  const date = {
@@ -17095,7 +17276,7 @@ function patternDate(value, pattern, locale, kind) {
17095
17276
  a: () => new Intl.DateTimeFormat(locale, { hour: "numeric", hour12: true, timeZone: "UTC" }).formatToParts(value).find((p) => p.type === "dayPeriod").value
17096
17277
  };
17097
17278
  const tokens = { ...kind === "H" ? {} : date, ...kind === "D" ? {} : time };
17098
- return parts.map((part) => {
17279
+ return parts2.map((part) => {
17099
17280
  if (part.startsWith("'")) return part === "''" ? "'" : part.slice(1, -1).replaceAll("''", "'");
17100
17281
  if (!/^[a-zA-Z]/.test(part)) return part;
17101
17282
  if (!tokens[part]) throw new RangeError(`Unsupported date format token: ${part}`);
@@ -17405,15 +17586,15 @@ var HtmlRenderer = class extends RendererBase {
17405
17586
  return [...css].map(([key, value]) => `${key}: ${value}`).join("; ");
17406
17587
  }
17407
17588
  _formatAttrs(attrs) {
17408
- const parts = [];
17589
+ const parts2 = [];
17409
17590
  for (const [name, value] of Object.entries(attrs || {})) {
17410
17591
  if (BOOLEAN_ATTRS.has(name)) {
17411
- if (value) parts.push(` ${name}`);
17592
+ if (value) parts2.push(` ${name}`);
17412
17593
  } else {
17413
- parts.push(` ${name}="${this._htmlAttrValue(value)}"`);
17594
+ parts2.push(` ${name}="${this._htmlAttrValue(value)}"`);
17414
17595
  }
17415
17596
  }
17416
- return parts.join("");
17597
+ return parts2.join("");
17417
17598
  }
17418
17599
  _htmlAttrValue(value) {
17419
17600
  const text = value === true ? "true" : value === false ? "false" : String(value);
@@ -17442,27 +17623,27 @@ var HtmlRenderer = class extends RendererBase {
17442
17623
  }
17443
17624
  }
17444
17625
  _macro_transform(value, subs, css) {
17445
- const parts = value === void 0 ? [] : [String(value)];
17626
+ const parts2 = value === void 0 ? [] : [String(value)];
17446
17627
  for (const [name, subValue] of Object.entries(subs)) {
17447
- if (name === "rotate") parts.push(`rotate(${subValue}deg)`);
17448
- else if (name === "scale" || name === "translate") parts.push(`${name}(${subValue})`);
17449
- else if (name === "translate_x") parts.push(`translateX(${px(subValue)})`);
17450
- else if (name === "translate_y") parts.push(`translateY(${px(subValue)})`);
17451
- else if (name === "skew_x") parts.push(`skewX(${subValue}deg)`);
17452
- else if (name === "skew_y") parts.push(`skewY(${subValue}deg)`);
17453
- else parts.push(`${name.replaceAll("_", "-")}(${subValue})`);
17628
+ if (name === "rotate") parts2.push(`rotate(${subValue}deg)`);
17629
+ else if (name === "scale" || name === "translate") parts2.push(`${name}(${subValue})`);
17630
+ else if (name === "translate_x") parts2.push(`translateX(${px(subValue)})`);
17631
+ else if (name === "translate_y") parts2.push(`translateY(${px(subValue)})`);
17632
+ else if (name === "skew_x") parts2.push(`skewX(${subValue}deg)`);
17633
+ else if (name === "skew_y") parts2.push(`skewY(${subValue}deg)`);
17634
+ else parts2.push(`${name.replaceAll("_", "-")}(${subValue})`);
17454
17635
  }
17455
- if (parts.length) css.set("transform", parts.join(" "));
17636
+ if (parts2.length) css.set("transform", parts2.join(" "));
17456
17637
  }
17457
17638
  _macro_filter(value, subs, css) {
17458
- const parts = value === void 0 ? [] : [String(value)];
17639
+ const parts2 = value === void 0 ? [] : [String(value)];
17459
17640
  for (const [name, subValue] of Object.entries(subs)) {
17460
- if (name === "rotate") parts.push(`hue-rotate(${subValue}deg)`);
17461
- else if (name === "blur") parts.push(`blur(${px(subValue)})`);
17462
- else if (name === "drop_shadow") parts.push(`drop-shadow(${subValue})`);
17463
- else parts.push(`${name.replaceAll("_", "-")}(${subValue})`);
17641
+ if (name === "rotate") parts2.push(`hue-rotate(${subValue}deg)`);
17642
+ else if (name === "blur") parts2.push(`blur(${px(subValue)})`);
17643
+ else if (name === "drop_shadow") parts2.push(`drop-shadow(${subValue})`);
17644
+ else parts2.push(`${name.replaceAll("_", "-")}(${subValue})`);
17464
17645
  }
17465
- if (parts.length) css.set("filter", parts.join(" "));
17646
+ if (parts2.length) css.set("filter", parts2.join(" "));
17466
17647
  }
17467
17648
  _macro_transition(value, subs, css) {
17468
17649
  if (value !== void 0) css.set("transition", String(value));
@@ -21878,13 +22059,776 @@ var Handler = class {
21878
22059
  }
21879
22060
  };
21880
22061
 
22062
+ // src/webcomponent.js
22063
+ var NAME2 = /^[a-z][.0-9_a-z\-\u00B7\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u037D\u037F-\u1FFF\u200C-\u200D\u203F-\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}]*$/u;
22064
+ var RESERVED = /* @__PURE__ */ new Set([
22065
+ "annotation-xml",
22066
+ "color-profile",
22067
+ "font-face",
22068
+ "font-face-src",
22069
+ "font-face-uri",
22070
+ "font-face-format",
22071
+ "font-face-name",
22072
+ "missing-glyph"
22073
+ ]);
22074
+ function webcomponentCode(attrs) {
22075
+ const code = attrs.code;
22076
+ if (typeof code !== "string" || NAME2.exec(code)?.[0] !== code || !code.includes("-") || RESERVED.has(code)) {
22077
+ throw new TypeError("webcomponent: code must be a literal custom-element name");
22078
+ }
22079
+ return code;
22080
+ }
22081
+
22082
+ // src/components/registry.js
22083
+ function freeze(value) {
22084
+ for (const child of Object.values(value)) if (child && typeof child === "object") freeze(child);
22085
+ return Object.freeze(value);
22086
+ }
22087
+ function annotation2(parameter) {
22088
+ if (typeof parameter.dtype !== "string" && !Array.isArray(parameter.dtype)) throw new TypeError("Component parameter requires dtype");
22089
+ const alternatives = (Array.isArray(parameter.dtype) ? parameter.dtype : [parameter.dtype]).map((dtype) => ({ kind: "dtype", dtype }));
22090
+ if (parameter.nullable) alternatives.push({ kind: "dtype", dtype: "NN" });
22091
+ if (parameter.binding && parameter.dtype !== "T") alternatives.push({
22092
+ kind: "annotated",
22093
+ base: { kind: "dtype", dtype: "T" },
22094
+ metadata: [{ kind: "regex", pattern: "^[\\^=].+", flags: 0 }]
22095
+ });
22096
+ return alternatives.length === 1 ? alternatives[0] : { kind: "union", items: alternatives };
22097
+ }
22098
+ function defineComponent({ name, tag: tag2, base, mixins = [], parameters: parameters2 = {}, subTags = "", presentationDefaults = [], dataScope = false, command = false, implementation }) {
22099
+ webcomponentCode({ code: tag2 });
22100
+ if (!/^[a-zA-Z][a-zA-Z0-9]*$/.test(name)) throw new TypeError("Invalid component authoring name");
22101
+ const effective = { ...base.parameters };
22102
+ for (const mixin of mixins) {
22103
+ for (const [key, spec] of Object.entries(mixin.parameters)) {
22104
+ if (Object.hasOwn(effective, key)) throw new Error(`Duplicate mixin parameter: ${key}`);
22105
+ effective[key] = spec;
22106
+ }
22107
+ }
22108
+ Object.assign(effective, parameters2);
22109
+ for (const spec of Object.values(effective)) annotation2(spec);
22110
+ return Object.freeze({
22111
+ name,
22112
+ tag: tag2,
22113
+ base,
22114
+ subTags,
22115
+ presentationDefaults: Object.freeze([...presentationDefaults]),
22116
+ dataScope,
22117
+ command,
22118
+ mixins: Object.freeze([...mixins]),
22119
+ parameters: freeze(structuredClone(effective)),
22120
+ implementation
22121
+ });
22122
+ }
22123
+ var ComponentCollection = class {
22124
+ #classes = /* @__PURE__ */ new WeakMap();
22125
+ constructor({ name, components }) {
22126
+ this.name = name;
22127
+ this.components = Object.freeze([...components]);
22128
+ const names = /* @__PURE__ */ new Set(), tags = /* @__PURE__ */ new Set();
22129
+ for (const component of components) {
22130
+ if (names.has(component.name.toLowerCase()) || tags.has(component.tag)) {
22131
+ throw new Error(`Duplicate component: ${component.name}`);
22132
+ }
22133
+ names.add(component.name.toLowerCase());
22134
+ tags.add(component.tag);
22135
+ }
22136
+ }
22137
+ /** Same JSON consumed by Python and JavaScript Builders. */
22138
+ toDocument() {
22139
+ return {
22140
+ document_format: { name: "builder_grammar", version: "1.1" },
22141
+ grammar: { name: this.name, version: null, title: this.name, description: null },
22142
+ abstracts: {},
22143
+ elements: Object.fromEntries(this.components.map((component) => [component.name, {
22144
+ doc: null,
22145
+ sub_tags: component.subTags,
22146
+ parent_tags: null,
22147
+ inherits_from: null,
22148
+ ns: null,
22149
+ node_label: null,
22150
+ collection_key: null,
22151
+ attributes: {
22152
+ parameters: [
22153
+ ...Object.entries(component.parameters).map(([name, spec]) => ({
22154
+ name,
22155
+ kind: "keyword_only",
22156
+ role: "attribute",
22157
+ annotation: annotation2(spec),
22158
+ has_default: true,
22159
+ default: spec.default ?? null
22160
+ })),
22161
+ {
22162
+ name: "attr",
22163
+ kind: "var_keyword",
22164
+ role: "attribute",
22165
+ annotation: { kind: "any" },
22166
+ has_default: false
22167
+ }
22168
+ ],
22169
+ accepts_var_keyword: true,
22170
+ accepts_var_positional: false
22171
+ },
22172
+ _meta: { render_tag: component.tag, gramlot_component: {
22173
+ parameters: structuredClone(component.parameters),
22174
+ presentationDefaults: [...component.presentationDefaults],
22175
+ dataScope: component.dataScope,
22176
+ command: component.command
22177
+ } }
22178
+ }]))
22179
+ };
22180
+ }
22181
+ /** Register once per document realm, only when the collection is activated. */
22182
+ register(window2) {
22183
+ if (this.#classes.has(window2)) return;
22184
+ const classes2 = [];
22185
+ for (const component of this.components) {
22186
+ if (window2.customElements.get(component.tag)) throw new Error(`Custom element already registered: ${component.tag}`);
22187
+ let Base = component.base(window2.HTMLElement);
22188
+ for (const mixin of component.mixins) Base = mixin(Base);
22189
+ const Class = component.implementation(Base);
22190
+ Object.defineProperty(Class, "gramlotComponent", { value: component });
22191
+ classes2.push([component.tag, Class]);
22192
+ }
22193
+ for (const [tag2, Class] of classes2) window2.customElements.define(tag2, Class);
22194
+ this.#classes.set(window2, classes2);
22195
+ }
22196
+ };
22197
+ function defineCollection(options) {
22198
+ return new ComponentCollection(options);
22199
+ }
22200
+
22201
+ // src/components/parameters.js
22202
+ function projectParameters(element, attrs) {
22203
+ element.parameters = Object.fromEntries(Object.entries(element.constructor.gramlotComponent.parameters).map(([name, spec]) => [name, Object.hasOwn(attrs, name) ? attrs[name] : spec.default]));
22204
+ return Object.fromEntries(Object.entries(attrs).filter(([name]) => !Object.hasOwn(element.parameters, name)));
22205
+ }
22206
+
22207
+ // src/components/choices.js
22208
+ function parseChoices(values) {
22209
+ if (values === "") return [];
22210
+ const ids = /* @__PURE__ */ new Set();
22211
+ return values.split(",").map((item) => {
22212
+ const colon = item.indexOf(":");
22213
+ const id = colon < 0 ? item : item.slice(0, colon);
22214
+ const caption = colon < 0 ? item : item.slice(colon + 1);
22215
+ if (!id || ids.has(id)) throw new Error("Invalid or duplicate choice code");
22216
+ ids.add(id);
22217
+ return { id, caption };
22218
+ });
22219
+ }
22220
+
22221
+ // src/components/bases.js
22222
+ function controlElement(HTMLElement) {
22223
+ return class extends HTMLElement {
22224
+ constructor() {
22225
+ super();
22226
+ const shadow = this.attachShadow({ mode: "open" });
22227
+ const style = this.ownerDocument.createElement("style");
22228
+ style.textContent = `:host{display:inline-block;font:inherit} *,*::before,*::after{box-sizing:border-box}
22229
+ input,textarea{font:inherit;max-width:100%} .control-box{min-width:0;color:var(--gramlot-ink,CanvasText)}
22230
+ input:not([type=checkbox]):not([type=radio]):not([type=range]):not([type=color]),textarea{
22231
+ appearance:none;box-sizing:border-box;border:1px solid var(--gramlot-border-control,#7a8798);
22232
+ border-radius:var(--gramlot-radius-sm,4px);background:var(--gramlot-field-background,Canvas);color:var(--gramlot-ink,CanvasText);
22233
+ 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)}
22234
+ input:read-only:not([type=checkbox]):not([type=radio]):not([type=range]):not([type=color]),textarea:read-only{
22235
+ background:var(--gramlot-field-readonly-background,Canvas)}
22236
+ input:disabled,textarea:disabled{opacity:.6;cursor:not-allowed}
22237
+ input::placeholder,textarea::placeholder{color:var(--gramlot-text-secondary,GrayText)}
22238
+ input:focus-visible,textarea:focus-visible,button:focus-visible{outline:2px solid var(--gramlot-focus-ring,Highlight);outline-offset:1px}
22239
+ input[type=checkbox],input[type=radio],input[type=range]{accent-color:var(--gramlot-brand-blue,Highlight)}
22240
+ input[type=range],input[type=color],button{min-width:var(--gramlot-touch-target,0px);min-height:var(--gramlot-touch-target,0px)}
22241
+ input[type=checkbox],input[type=radio]{min-width:calc(var(--gramlot-touch-target,0px) / 2);min-height:calc(var(--gramlot-touch-target,0px) / 2)}
22242
+ .options{display:grid;gap:.3em .8em} .option{display:flex;align-items:center;gap:.35em;min-width:var(--gramlot-touch-target,0px);min-height:var(--gramlot-touch-target,0px)}
22243
+ .caption:empty{display:none}`;
22244
+ this.controlBox = this.ownerDocument.createElement("div");
22245
+ this.controlBox.className = "control-box";
22246
+ shadow.append(style, this.controlBox);
22247
+ }
22248
+ projectAttributes(attrs) {
22249
+ return projectParameters(this, attrs);
22250
+ }
22251
+ setPageContext(context) {
22252
+ this.pageContext = context;
22253
+ }
22254
+ releaseControl() {
22255
+ }
22256
+ validateCandidate(value, accept) {
22257
+ accept(value);
22258
+ return { ok: true, value, isCurrent: () => this.pageContext.isActive() };
22259
+ }
22260
+ finishValidation() {
22261
+ }
22262
+ validateSelection() {
22263
+ throw new TypeError("validate_select requires a constrained choice editor.");
22264
+ }
22265
+ shouldProjectControlValue() {
22266
+ return true;
22267
+ }
22268
+ acceptControlValue() {
22269
+ const value = this.readControlValue();
22270
+ return this.validateCandidate(value, (accepted) => {
22271
+ if (accepted == null && !this.constructor.gramlotComponent.parameters.value.nullable) throw new TypeError("This component requires a non-null value.");
22272
+ if (accepted != null && value != null && typeof accepted !== typeof value) throw new TypeError("Validation must preserve the component value type.");
22273
+ if (!this.sameControlValue(value, accepted)) this.writeControlValue(accepted);
22274
+ });
22275
+ }
22276
+ sameControlValue(a, b) {
22277
+ return Object.is(a, b);
22278
+ }
22279
+ focus(options) {
22280
+ this.control.focus(options);
22281
+ }
22282
+ };
22283
+ }
22284
+ function NativeControl(HTMLElement) {
22285
+ return class extends controlElement(HTMLElement) {
22286
+ constructor() {
22287
+ super();
22288
+ this.control = this.createControl();
22289
+ if (this.control.localName === "textarea" || this.control.localName === "input" && ["text", "password"].includes(this.control.type)) {
22290
+ this.control.setAttribute("autocomplete", "off");
22291
+ this.control.setAttribute("autocorrect", "off");
22292
+ this.control.setAttribute("autocapitalize", "off");
22293
+ this.control.setAttribute("spellcheck", "false");
22294
+ }
22295
+ this.control.id = "control";
22296
+ const option = this.ownerDocument.createElement("label");
22297
+ option.className = "option";
22298
+ this.optionCaption = this.ownerDocument.createElement("span");
22299
+ this.optionCaption.className = "caption";
22300
+ option.append(this.control, this.optionCaption);
22301
+ this.controlBox.append(option);
22302
+ }
22303
+ projectAttributes(attrs, adapt) {
22304
+ const rest = super.projectAttributes(attrs, adapt);
22305
+ const { disabled, readonly } = this.parameters;
22306
+ this.control.disabled = Boolean(disabled);
22307
+ this.control.readOnly = Boolean(readonly);
22308
+ for (const [name, spec] of Object.entries(this.constructor.gramlotComponent.parameters)) {
22309
+ if (spec.target === "control") {
22310
+ const value = this.parameters[name] ?? "";
22311
+ if (String(this.control[name]) !== String(value)) this.control[name] = value;
22312
+ }
22313
+ if (spec.target === "optionCaption") this.optionCaption.textContent = this.parameters[name] ?? "";
22314
+ }
22315
+ return rest;
22316
+ }
22317
+ };
22318
+ }
22319
+ NativeControl.parameters = {
22320
+ disabled: { dtype: "B", default: false, binding: "read" },
22321
+ readonly: { dtype: "B", default: false, binding: "read" },
22322
+ live: { dtype: "B", default: false, binding: "read" }
22323
+ };
22324
+ function ChoiceGroup(HTMLElement) {
22325
+ return class extends controlElement(HTMLElement) {
22326
+ #options = /* @__PURE__ */ new Map();
22327
+ #values;
22328
+ #value = null;
22329
+ constructor() {
22330
+ super();
22331
+ this.control = this.ownerDocument.createElement("div");
22332
+ this.control.className = "options";
22333
+ this.control.id = "control";
22334
+ this.control.setAttribute("role", this.multiple ? "group" : "radiogroup");
22335
+ this.controlBox.append(this.control);
22336
+ this.control.addEventListener("keydown", (event) => {
22337
+ if (!this.multiple || !["ArrowDown", "ArrowUp", "ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)) return;
22338
+ const items = [...this.control.querySelectorAll("input:not(:disabled)")];
22339
+ const index = items.indexOf(event.target);
22340
+ if (index < 0) return;
22341
+ event.preventDefault();
22342
+ const next = event.key === "Home" ? 0 : event.key === "End" ? items.length - 1 : Math.max(0, Math.min(items.length - 1, index + (["ArrowDown", "ArrowRight"].includes(event.key) ? 1 : -1)));
22343
+ items[next].focus();
22344
+ });
22345
+ }
22346
+ projectAttributes(attrs, adapt) {
22347
+ const rest = super.projectAttributes(attrs, adapt);
22348
+ const values = this.parameters.values ?? "";
22349
+ if (values !== this.#values) {
22350
+ const options = parseChoices(values);
22351
+ const retained = /* @__PURE__ */ new Set();
22352
+ let previous = null;
22353
+ for (const { id: code, caption } of options) {
22354
+ let item = this.#options.get(code);
22355
+ if (!item) {
22356
+ const label = this.ownerDocument.createElement("label");
22357
+ label.className = "option";
22358
+ const input = this.ownerDocument.createElement("input");
22359
+ input.type = this.choiceType;
22360
+ input.name = "choice";
22361
+ input.value = code;
22362
+ const text = this.ownerDocument.createElement("span");
22363
+ label.append(input, text);
22364
+ item = { label, input, text };
22365
+ this.#options.set(code, item);
22366
+ }
22367
+ item.text.textContent = caption;
22368
+ const expected = previous ? previous.nextSibling : this.control.firstChild;
22369
+ if (expected !== item.label) this.control.insertBefore(item.label, expected);
22370
+ previous = item.label;
22371
+ retained.add(code);
22372
+ }
22373
+ for (const [code, item] of this.#options) if (!retained.has(code)) {
22374
+ item.label.remove();
22375
+ this.#options.delete(code);
22376
+ }
22377
+ this.#values = values;
22378
+ }
22379
+ const cols = this.parameters.cols;
22380
+ if (!Number.isInteger(cols) || cols < 1) throw new TypeError("cols must be a positive integer");
22381
+ this.control.style.gridTemplateColumns = `repeat(${cols}, minmax(0, 1fr))`;
22382
+ this.control.disabled = Boolean(this.parameters.disabled);
22383
+ this.control.readOnly = Boolean(this.parameters.readonly);
22384
+ for (const { input } of this.#options.values()) input.disabled = this.control.disabled || this.control.readOnly;
22385
+ return rest;
22386
+ }
22387
+ readControlValue() {
22388
+ if (this.multiple) {
22389
+ const codes = this.#value ? this.#value.split(",") : [];
22390
+ const selected = codes.filter((code) => !this.#options.has(code) || this.#options.get(code).input.checked);
22391
+ for (const [code, { input }] of this.#options) if (input.checked && !selected.includes(code)) selected.push(code);
22392
+ return selected.join(",") || null;
22393
+ }
22394
+ for (const [code, { input }] of this.#options) if (input.checked) return code;
22395
+ return null;
22396
+ }
22397
+ writeControlValue(value) {
22398
+ this.#value = value;
22399
+ const selected = this.multiple ? new Set(value ? value.split(",") : []) : null;
22400
+ for (const [code, { input }] of this.#options) input.checked = this.multiple ? selected.has(code) : code === value;
22401
+ }
22402
+ acceptControlValue() {
22403
+ const value = this.readControlValue();
22404
+ return this.validateCandidate(value, (accepted) => this.writeControlValue(accepted));
22405
+ }
22406
+ focus(options) {
22407
+ const items = [...this.#options.values()];
22408
+ (items.find(({ input }) => input.checked && !input.disabled) ?? items.find(({ input }) => !input.disabled))?.input.focus(options);
22409
+ }
22410
+ };
22411
+ }
22412
+ ChoiceGroup.parameters = {
22413
+ disabled: { dtype: "B", default: false, binding: "read" },
22414
+ readonly: { dtype: "B", default: false, binding: "read" }
22415
+ };
22416
+
22417
+ // src/components/popup.js
22418
+ var VIEWPORT_MARGIN = 8;
22419
+ var ANCHOR_GAP = 3;
22420
+ function positionPopup(popup, anchor, { align = "start", matchWidth = false } = {}) {
22421
+ const view = anchor.ownerDocument.defaultView;
22422
+ const field = anchor.getBoundingClientRect();
22423
+ const availableWidth = Math.max(0, view.innerWidth - 2 * VIEWPORT_MARGIN);
22424
+ popup.style.setProperty("--gramlot-popup-available-width", `${availableWidth}px`);
22425
+ if (matchWidth) popup.style.width = `${Math.min(field.width, availableWidth)}px`;
22426
+ popup.style.removeProperty("--gramlot-popup-available-height");
22427
+ const natural = popup.getBoundingClientRect();
22428
+ const below = Math.max(0, view.innerHeight - VIEWPORT_MARGIN - field.bottom - ANCHOR_GAP);
22429
+ const above = Math.max(0, field.top - VIEWPORT_MARGIN - ANCHOR_GAP);
22430
+ const upwards = natural.height > below && above > below;
22431
+ popup.style.setProperty("--gramlot-popup-available-height", `${upwards ? above : below}px`);
22432
+ const size = popup.getBoundingClientRect();
22433
+ const left = align === "end" ? field.right - size.width : field.left;
22434
+ const top = upwards ? field.top - size.height - ANCHOR_GAP : field.bottom + ANCHOR_GAP;
22435
+ popup.style.left = `${Math.max(VIEWPORT_MARGIN, Math.min(left, view.innerWidth - size.width - VIEWPORT_MARGIN))}px`;
22436
+ popup.style.top = `${Math.max(VIEWPORT_MARGIN, Math.min(top, view.innerHeight - size.height - VIEWPORT_MARGIN))}px`;
22437
+ }
22438
+
22439
+ // src/components/buttons.js
22440
+ function Command(HTMLElement) {
22441
+ return class extends controlElement(HTMLElement) {
22442
+ constructor() {
22443
+ super();
22444
+ const doc = this.ownerDocument;
22445
+ this.control = doc.createElement("button");
22446
+ this.control.type = "button";
22447
+ this.control.id = "control";
22448
+ this.icon = doc.createElement("span");
22449
+ this.icon.className = "icon";
22450
+ this.icon.setAttribute("aria-hidden", "true");
22451
+ this.caption = doc.createElement("slot");
22452
+ this.control.append(this.icon, this.caption);
22453
+ this.controlBox.append(this.control);
22454
+ const style = doc.createElement("style");
22455
+ style.textContent = `:host{vertical-align:middle} .control-box{display:flex;align-items:stretch}
22456
+ button{display:inline-flex;align-items:center;justify-content:center;gap:var(--gramlot-button-gap,.35em);font:inherit;
22457
+ color:var(--gramlot-ink,CanvasText);background:var(--gramlot-button-background,var(--gramlot-field-background,Canvas));
22458
+ border:1px solid var(--gramlot-border-control,#888);border-radius:var(--gramlot-radius-sm,4px);
22459
+ min-height:max(var(--gramlot-field-height,28px),var(--gramlot-touch-target,0px));
22460
+ padding:var(--gramlot-button-padding,.25em .65em);cursor:pointer}
22461
+ button:hover:not(:disabled){background:var(--gramlot-button-hover,var(--gramlot-field-readonly-background,#eee))}
22462
+ button:disabled{opacity:.55;cursor:not-allowed} .icon:empty{display:none}
22463
+ .led{display:inline-block;width:.6em;height:.6em;border-radius:50%;background:var(--gramlot-button-led-off,#888)}
22464
+ [aria-pressed=true] .led{background:var(--gramlot-button-led-on,#2b9a46)}
22465
+ .arrow{border-start-start-radius:0;border-end-start-radius:0;border-inline-start:0}
22466
+ .split{border-start-end-radius:0;border-end-end-radius:0}
22467
+ .popup{position:fixed;inset:auto;margin:0;padding:var(--gramlot-popup-padding,4px);overflow:auto;
22468
+ max-width:var(--gramlot-popup-available-width);max-height:var(--gramlot-popup-available-height);
22469
+ border:1px solid var(--gramlot-border-control,#888);border-radius:var(--gramlot-radius-sm,4px);
22470
+ color:var(--gramlot-ink,CanvasText);background:var(--gramlot-field-background,Canvas);box-shadow:0 3px 12px #0003}
22471
+ :host([role=menuitem]){display:block} :host([role=menuitem]) button{width:100%;justify-content:start;border:0;background:transparent}
22472
+ :host([role=separator]){display:block;border-top:1px solid var(--gramlot-border-control,#888);margin:.25em}
22473
+ :host([role=separator]) button{display:none}`;
22474
+ this.shadowRoot.append(style);
22475
+ }
22476
+ get disabled() {
22477
+ return this.control.disabled;
22478
+ }
22479
+ set disabled(value) {
22480
+ this.control.disabled = Boolean(value);
22481
+ }
22482
+ projectAttributes(attrs, adapt) {
22483
+ const rest = super.projectAttributes(attrs, adapt);
22484
+ this.control.disabled = Boolean(this.parameters.disabled);
22485
+ this.control.readOnly = Boolean(this.parameters.readonly);
22486
+ this.icon.textContent = this.parameters.icon ?? "";
22487
+ if (attrs["aria-label"] != null) this.control.setAttribute("aria-label", attrs["aria-label"]);
22488
+ else this.control.removeAttribute("aria-label");
22489
+ return rest;
22490
+ }
22491
+ attachCommand() {
22492
+ }
22493
+ releaseCommand() {
22494
+ }
22495
+ commandTarget() {
22496
+ return this;
22497
+ }
22498
+ prepareCommand() {
22499
+ return !this.disabled;
22500
+ }
22501
+ };
22502
+ }
22503
+ Command.parameters = {
22504
+ disabled: { dtype: "B", default: false, binding: "read" },
22505
+ icon: { dtype: "T", default: "", binding: "read" }
22506
+ };
22507
+ var Button = defineComponent({
22508
+ name: "button",
22509
+ tag: "gramlot-button",
22510
+ base: Command,
22511
+ command: true,
22512
+ subTags: "*",
22513
+ implementation: (Base) => class extends Base {
22514
+ }
22515
+ });
22516
+ var ToggleButton = defineComponent({
22517
+ name: "toggleButton",
22518
+ tag: "gramlot-toggle-button",
22519
+ base: Command,
22520
+ command: true,
22521
+ subTags: "*",
22522
+ parameters: {
22523
+ value: { dtype: "B", default: false, binding: "twoWay" },
22524
+ readonly: { dtype: "B", default: false, binding: "read" }
22525
+ },
22526
+ implementation: (Base) => class extends Base {
22527
+ #value = false;
22528
+ constructor() {
22529
+ super();
22530
+ const led = this.ownerDocument.createElement("span");
22531
+ led.className = "led";
22532
+ led.setAttribute("aria-hidden", "true");
22533
+ this.control.prepend(led);
22534
+ this.writeControlValue(false);
22535
+ }
22536
+ get commitOnChange() {
22537
+ return true;
22538
+ }
22539
+ readControlValue() {
22540
+ return this.#value;
22541
+ }
22542
+ writeControlValue(value) {
22543
+ this.#value = value;
22544
+ this.control.setAttribute("aria-pressed", String(value));
22545
+ }
22546
+ prepareCommand(event) {
22547
+ if (!super.prepareCommand(event) || this.control.readOnly) return false;
22548
+ this.writeControlValue(!this.#value);
22549
+ this.control.dispatchEvent(new this.ownerDocument.defaultView.Event("change"));
22550
+ return true;
22551
+ }
22552
+ }
22553
+ });
22554
+ function MenuContainer(HTMLElement) {
22555
+ return class extends HTMLElement {
22556
+ constructor() {
22557
+ super();
22558
+ this.attachShadow({ mode: "open" }).append(this.ownerDocument.createElement("slot"));
22559
+ }
22560
+ connectedCallback() {
22561
+ this.slot = "menu";
22562
+ this.setAttribute("role", "menu");
22563
+ }
22564
+ projectAttributes(attrs) {
22565
+ return projectParameters(this, attrs);
22566
+ }
22567
+ };
22568
+ }
22569
+ var Menu = defineComponent({
22570
+ name: "menu",
22571
+ tag: "gramlot-menu",
22572
+ base: MenuContainer,
22573
+ subTags: "menuline",
22574
+ implementation: (Base) => class extends Base {
22575
+ }
22576
+ });
22577
+ var MenuLine = defineComponent({
22578
+ name: "menuline",
22579
+ tag: "gramlot-menu-line",
22580
+ base: Command,
22581
+ command: true,
22582
+ subTags: "*",
22583
+ parameters: { code: { dtype: "T", nullable: true } },
22584
+ implementation: (Base) => class extends Base {
22585
+ attachCommand() {
22586
+ const separator = this.textContent.trim() === "-";
22587
+ if (!separator && !this.parameters.code) throw new TypeError("menuline requires a stable code");
22588
+ this.setAttribute("role", separator ? "separator" : "menuitem");
22589
+ this.control.tabIndex = -1;
22590
+ this.disabled ||= separator;
22591
+ }
22592
+ get disabled() {
22593
+ return super.disabled || Boolean(this.closest("gramlot-drop-down-button")?.parameters.disabled);
22594
+ }
22595
+ set disabled(value) {
22596
+ super.disabled = value;
22597
+ }
22598
+ prepareCommand(event) {
22599
+ if (!super.prepareCommand(event)) return false;
22600
+ this.closest("gramlot-drop-down-button").selectCommand(this, event.shiftKey);
22601
+ return true;
22602
+ }
22603
+ }
22604
+ });
22605
+ var DropDownButton = defineComponent({
22606
+ name: "dropDownButton",
22607
+ tag: "gramlot-drop-down-button",
22608
+ base: Command,
22609
+ command: true,
22610
+ subTags: "*",
22611
+ parameters: { persist: { dtype: "B", default: false } },
22612
+ implementation: (Base) => class extends Base {
22613
+ #selected = null;
22614
+ #observer = null;
22615
+ #viewport = null;
22616
+ #storageKey = null;
22617
+ #popup;
22618
+ #arrow;
22619
+ #chosenCaption;
22620
+ constructor() {
22621
+ super();
22622
+ const doc = this.ownerDocument;
22623
+ this.control.classList.add("split");
22624
+ this.#chosenCaption = doc.createElement("span");
22625
+ this.#chosenCaption.hidden = true;
22626
+ this.control.append(this.#chosenCaption);
22627
+ this.#arrow = doc.createElement("button");
22628
+ this.#arrow.type = "button";
22629
+ this.#arrow.className = "arrow";
22630
+ this.#arrow.textContent = "\u25BE";
22631
+ this.#arrow.setAttribute("aria-label", "Open menu");
22632
+ this.#arrow.setAttribute("aria-haspopup", "menu");
22633
+ this.#arrow.setAttribute("aria-expanded", "false");
22634
+ this.controlBox.append(this.#arrow);
22635
+ this.#popup = doc.createElement("div");
22636
+ this.#popup.className = "popup";
22637
+ this.#popup.id = "menu";
22638
+ this.#popup.setAttribute("popover", "auto");
22639
+ this.#arrow.setAttribute("aria-controls", "menu");
22640
+ const slot = doc.createElement("slot");
22641
+ slot.name = "menu";
22642
+ this.#popup.append(slot);
22643
+ this.shadowRoot.append(this.#popup);
22644
+ this.#arrow.addEventListener("click", (event) => {
22645
+ event.stopPropagation();
22646
+ if (this.#popup.matches(":popover-open")) this.closeMenu();
22647
+ else this.openMenu();
22648
+ });
22649
+ this.#arrow.addEventListener("keydown", (event) => {
22650
+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {
22651
+ event.preventDefault();
22652
+ this.openMenu(event.key === "ArrowUp");
22653
+ }
22654
+ });
22655
+ this.addEventListener("keydown", (event) => {
22656
+ if (!this.#popup.matches(":popover-open")) return;
22657
+ const items = this.menuItems.filter((item) => !item.disabled);
22658
+ const index = items.indexOf(event.composedPath().find((item) => items.includes(item)));
22659
+ let next;
22660
+ if (event.key === "ArrowDown") next = (index + 1) % items.length;
22661
+ if (event.key === "ArrowUp") next = (index - 1 + items.length) % items.length;
22662
+ if (event.key === "Home") next = 0;
22663
+ if (event.key === "End") next = items.length - 1;
22664
+ if (next !== void 0) {
22665
+ event.preventDefault();
22666
+ items[next]?.focus();
22667
+ }
22668
+ if (event.key === "Escape" || event.key === "Tab") {
22669
+ if (event.key === "Escape") event.preventDefault();
22670
+ this.closeMenu();
22671
+ }
22672
+ });
22673
+ this.#popup.addEventListener("toggle", () => {
22674
+ const open = this.#popup.matches(":popover-open");
22675
+ this.#arrow.setAttribute("aria-expanded", String(open));
22676
+ if (!open) {
22677
+ this.#viewport?.abort();
22678
+ this.#viewport = null;
22679
+ }
22680
+ });
22681
+ }
22682
+ get menuItems() {
22683
+ return [...this.querySelectorAll(":scope > gramlot-menu > gramlot-menu-line")];
22684
+ }
22685
+ projectAttributes(attrs, adapt) {
22686
+ const rest = super.projectAttributes(attrs, adapt);
22687
+ this.#arrow.disabled = this.disabled;
22688
+ if (this.disabled && this.#popup.matches(":popover-open")) this.closeMenu();
22689
+ this.#refreshCaption();
22690
+ return rest;
22691
+ }
22692
+ attachCommand() {
22693
+ if (this.parameters.persist) {
22694
+ if (!this.id) throw new TypeError("dropDownButton persist requires an explicit id");
22695
+ this.#storageKey = `gramlot:command:${this.ownerDocument.location.pathname}${this.ownerDocument.location.search}:${this.id}`;
22696
+ try {
22697
+ this.#selected = this.ownerDocument.defaultView.localStorage.getItem(this.#storageKey);
22698
+ } catch {
22699
+ }
22700
+ }
22701
+ this.#refreshCaption();
22702
+ this.#observer = new this.ownerDocument.defaultView.MutationObserver(() => this.#refreshCaption());
22703
+ this.#observer.observe(this, { childList: true, subtree: true, characterData: true });
22704
+ }
22705
+ releaseCommand() {
22706
+ this.#observer?.disconnect();
22707
+ this.#observer = null;
22708
+ this.#viewport?.abort();
22709
+ this.#viewport = null;
22710
+ if (this.#popup.matches(":popover-open")) this.#popup.hidePopover();
22711
+ }
22712
+ commandTarget(event) {
22713
+ if (event?.composedPath().includes(this.#popup)) return null;
22714
+ return this.menuItems.find((item) => item.parameters.code === this.#selected) ?? this;
22715
+ }
22716
+ selectCommand(item, remember) {
22717
+ if (remember) {
22718
+ this.#selected = item.parameters.code;
22719
+ if (this.#storageKey) {
22720
+ try {
22721
+ this.ownerDocument.defaultView.localStorage.setItem(this.#storageKey, this.#selected);
22722
+ } catch {
22723
+ }
22724
+ }
22725
+ this.#refreshCaption();
22726
+ }
22727
+ this.closeMenu();
22728
+ }
22729
+ #refreshCaption() {
22730
+ const codes = this.menuItems.filter((item) => item.parameters.code).map((item) => item.parameters.code);
22731
+ if (new Set(codes).size !== codes.length) throw new TypeError("Dropdown menu codes must be unique");
22732
+ const target = this.commandTarget();
22733
+ const selected = target !== this;
22734
+ this.caption.hidden = selected;
22735
+ this.#chosenCaption.hidden = !selected;
22736
+ this.#chosenCaption.textContent = selected ? target.textContent : "";
22737
+ this.icon.textContent = selected ? target.parameters.icon : this.parameters.icon;
22738
+ }
22739
+ openMenu(last = false) {
22740
+ if (this.disabled) return;
22741
+ const items = this.menuItems.filter((item) => !item.disabled);
22742
+ if (!items.length) return;
22743
+ this.#popup.showPopover();
22744
+ this.#arrow.setAttribute("aria-expanded", "true");
22745
+ const place = () => positionPopup(this.#popup, this.controlBox);
22746
+ place();
22747
+ this.#viewport?.abort();
22748
+ this.#viewport = new this.ownerDocument.defaultView.AbortController();
22749
+ const options = { signal: this.#viewport.signal, capture: true };
22750
+ this.ownerDocument.defaultView.addEventListener("resize", place, options);
22751
+ this.ownerDocument.addEventListener("scroll", place, options);
22752
+ items[last ? items.length - 1 : 0].focus();
22753
+ }
22754
+ closeMenu() {
22755
+ if (!this.#popup.matches(":popover-open")) return;
22756
+ this.#popup.hidePopover();
22757
+ this.#arrow.setAttribute("aria-expanded", "false");
22758
+ this.#viewport?.abort();
22759
+ this.#viewport = null;
22760
+ this.#arrow.focus();
22761
+ }
22762
+ }
22763
+ });
22764
+ var buttons_default = defineCollection({ name: "buttons", components: [Button, ToggleButton, DropDownButton, Menu, MenuLine] });
22765
+
22766
+ // src/binding/pointer.js
22767
+ function attributeReader(node, items, context = node) {
22768
+ const values = /* @__PURE__ */ new Map(), active = /* @__PURE__ */ new Set();
22769
+ const compiler = node.rootBuilder.binding?.inlineCompiler;
22770
+ const current = /* @__PURE__ */ new Map();
22771
+ for (const [name, raw] of items) {
22772
+ if (typeof name !== "string") continue;
22773
+ const pointer = pointerTransform(raw)?.pointer ?? raw;
22774
+ current.set(name, pointer instanceof BagResolver ? pointer.resolve() : node.pointerType(pointer) ? context.getRelativeData(pointer) : pointer);
22775
+ }
22776
+ const resolve = (name) => {
22777
+ if (values.has(name)) return values.get(name);
22778
+ if (!items.has(name)) throw new Error(`Source attribute '${name}' does not exist`);
22779
+ if (active.has(name)) throw new Error(`cyclic attribute dependency: ${[...active, name].join(" -> ")}`);
22780
+ active.add(name);
22781
+ const raw = items.get(name), transform = pointerTransform(raw);
22782
+ const leading = transform ? current.get(name) : null;
22783
+ let result;
22784
+ const read = (key) => {
22785
+ if (!key) return leading;
22786
+ return resolve(key);
22787
+ };
22788
+ try {
22789
+ if (transform) {
22790
+ if (transform.expression) {
22791
+ const expression = pointerExpression(transform.body);
22792
+ const inputs = expression.slots.map(read);
22793
+ result = node.rootBuilder.evaluatePointerExpression(node, name, raw, expression, inputs);
22794
+ } else {
22795
+ result = pointerTemplate(transform.body, read);
22796
+ if (leading == null) result = null;
22797
+ }
22798
+ } else if (typeof raw === "string" && raw.startsWith("==")) {
22799
+ const names = pointerExpression(raw.slice(2)).identifiers;
22800
+ const args = {};
22801
+ for (const key of names) if (key !== name && key !== "_F" && items.has(key)) args[key] = resolve(key);
22802
+ result = compiler ? compiler.compile(
22803
+ node,
22804
+ name,
22805
+ raw,
22806
+ [...Object.keys(args), "_F"],
22807
+ `return (${raw.slice(2)}
22808
+ )`
22809
+ )({ ...args, _F: (value, options) => node.rootBuilder.binding.gramlot.format(value, options) }) : null;
22810
+ } else {
22811
+ result = current.get(name);
22812
+ }
22813
+ values.set(name, result);
22814
+ return result;
22815
+ } finally {
22816
+ active.delete(name);
22817
+ }
22818
+ };
22819
+ return { resolve };
22820
+ }
22821
+ function resolvePointerAttribute(node, name, context = node) {
22822
+ const items = new Map([...Object.entries(node.getAttr()), ...sourceAttributeItems(node.getAttr())]);
22823
+ return attributeReader(node, items, context).resolve(name);
22824
+ }
22825
+
21881
22826
  // src/builder/source.js
21882
22827
  var CODE_ATTRIBUTES = {
21883
22828
  dataFormula: ["formula", "_if", "_else", "_ask_if", "_ask_onCancel"],
21884
22829
  dataController: ["script", "_if", "_else", "_ask_if", "_ask_onCancel"],
21885
22830
  dataRpc: ["_ask_if", "_ask_onCancel", "_if", "_else", "_onCalling", "_onResult", "_onError"],
21886
- dataRemote: ["_if", "_else"],
21887
- button: ["action", "_ask_if"]
22831
+ dataRemote: ["_if", "_else"]
21888
22832
  };
21889
22833
  var REMOTE_CONTROLS = ["_cachedRemote", "_if", "_else", "_onRemote"];
21890
22834
  var REMOTE_CODE_ATTRIBUTES = ["_if", "_else", "_onRemote"];
@@ -21905,13 +22849,14 @@ var GramlotBuilderBagNode = class extends SourceBagNode {
21905
22849
  * every `==` attribute (canonical name) and a `==` node value (`''`).
21906
22850
  */
21907
22851
  codeAttributes() {
21908
- const own = [
22852
+ const own2 = [
21909
22853
  ...CODE_ATTRIBUTES[this.nodeTag] ?? [],
22854
+ ...this._getMeta("gramlot_component")?.command ? ["action", "_ask_if"] : [],
21910
22855
  ...typeof this.getAttr("remote") === "string" ? REMOTE_CODE_ATTRIBUTES : []
21911
22856
  ];
21912
22857
  const items = [];
21913
22858
  for (const [name, value] of Object.entries(this.getAttr() ?? {})) {
21914
- if (typeof value === "string" && (own.includes(name) || name.startsWith("connect_on") || name.startsWith("subscribe_") || name.startsWith("selfsubscribe_"))) items.push([name, value]);
22859
+ if (typeof value === "string" && (own2.includes(name) || name === "validate_call" || name === "validate__onResult" || name === "validate_onAccept" || name === "validate_onReject" || /^validate_\w+_if$/.test(name) || name.startsWith("connect_on") || name.startsWith("subscribe_") || name.startsWith("selfsubscribe_"))) items.push([name, value]);
21915
22860
  }
21916
22861
  for (const attribute of ["ask", "_ask"]) {
21917
22862
  const spec = this.getAttr(attribute);
@@ -21941,6 +22886,9 @@ var GramlotBuilderBagNode = class extends SourceBagNode {
21941
22886
  }
21942
22887
  code.set(name, text);
21943
22888
  }
22889
+ for (const [name, text] of [...sourceAttributeItems(this.getAttr()), ["datapath", this.getAttr("datapath")]]) {
22890
+ if (pointerTransform(text)?.expression) code.set(name, text);
22891
+ }
21944
22892
  this.#activatedCode = code;
21945
22893
  }
21946
22894
  /** The text of the inline code `name` received with the Source, or null when it was not received. */
@@ -21972,14 +22920,16 @@ var GramlotBuilderBagNode = class extends SourceBagNode {
21972
22920
  publish(topic, payload = {}) {
21973
22921
  return this.builder.binding.gramlot._subscriptions.publishNode(this, topic, payload);
21974
22922
  }
21975
- /** Builder's pointerType, except that a string starting with `==` is not a pointer. */
21976
- pointerType(v) {
21977
- if (typeof v === "string" && v.startsWith("==")) return null;
21978
- return super.pointerType(v);
21979
- }
21980
22923
  /** Builder's `^` pointers, except the attributes ending in `_path`, which hold a bare path. */
21981
22924
  pointers() {
21982
- return super.pointers().filter(([name, pointer]) => !this.#isPathAttribute(name, pointer));
22925
+ const datapath = this.getAttr("datapath");
22926
+ const dependencies = pointerTransform(datapath) ? pointerDependencies(this, datapath) : /* @__PURE__ */ new Set();
22927
+ const result = super.pointers().filter(([name, pointer]) => !dependencies.has(name) && !this.#isPathAttribute(name, pointer)).map(([name, pointer]) => [name, pointerTransform(pointer)?.pointer ?? pointer]);
22928
+ for (const name of dependencies) {
22929
+ const value = this.getAttr(name);
22930
+ if (this.pointerType(value) === "^") result.push(["datapath", pointerTransform(value)?.pointer ?? value]);
22931
+ }
22932
+ return result;
21983
22933
  }
21984
22934
  /**
21985
22935
  * Builder's items to resolve, with the Gramlot rules applied before Builder's runtimeValues:
@@ -21990,6 +22940,13 @@ var GramlotBuilderBagNode = class extends SourceBagNode {
21990
22940
  const items = super.runtimeToEvaluate();
21991
22941
  for (const [name, value] of items) {
21992
22942
  if (!this.pointerType(value)) continue;
22943
+ if (pointerTransform(value)) {
22944
+ if (typeof name !== "string") throw new Error(`${this.nodeTag} '${this.label}': pointer suffixes belong to attributes; use format/mask for node text`);
22945
+ if (this.absDatapath(value) === null) {
22946
+ items.set(name, new BagCbResolver(() => resolvePointerAttribute(this, name)));
22947
+ }
22948
+ continue;
22949
+ }
21993
22950
  if (this.#isPathAttribute(name, value)) items.set(name, value.slice(1));
21994
22951
  else if (this.absDatapath(value) === null) items.set(name, null);
21995
22952
  }
@@ -22002,6 +22959,7 @@ var GramlotBuilderBagNode = class extends SourceBagNode {
22002
22959
  */
22003
22960
  pathAttribute(name) {
22004
22961
  const value = this.getAttr(name);
22962
+ if (pointerTransform(value)) return resolvePointerAttribute(this, name);
22005
22963
  return this.pointerType(value) && this.#isPathAttribute(name, value) ? value.slice(1) : value;
22006
22964
  }
22007
22965
  /** Builder's read; null on a null path (Q7). */
@@ -22080,6 +23038,7 @@ var GramlotBuilderBagNode = class extends SourceBagNode {
22080
23038
  }
22081
23039
  /** Builder's absDatapath, keeping `?attr` on symbolic paths. */
22082
23040
  absDatapath(path) {
23041
+ path = pointerTransform(path)?.pointer ?? path;
22083
23042
  const bare = this.pointerType(path) ? path.slice(1) : path;
22084
23043
  if (bare.startsWith("#") && bare.includes("?")) {
22085
23044
  const [target, attr] = bare.split("?", 2);
@@ -22132,6 +23091,10 @@ var GramlotBuilderBagNode = class extends SourceBagNode {
22132
23091
  * the context of the carrier's parent; the value counts as if written in place of the pointer.
22133
23092
  */
22134
23093
  #variableDatapath(carrier, pointer) {
23094
+ if (pointerTransform(pointer)) {
23095
+ const value2 = resolvePointerAttribute(carrier, "datapath", carrier.parentNode);
23096
+ return value2 == null || value2 === "" ? null : value2;
23097
+ }
22135
23098
  const path = carrier.parentNode.absDatapath(pointer);
22136
23099
  if (path === null) return null;
22137
23100
  const value = this.data.getItem(path);
@@ -22139,6 +23102,7 @@ var GramlotBuilderBagNode = class extends SourceBagNode {
22139
23102
  }
22140
23103
  /** Whether `name` ends in `_path`; a pointer there loses its symbol, with one warning per attribute. */
22141
23104
  #isPathAttribute(name, value) {
23105
+ if (pointerTransform(value)) return false;
22142
23106
  if (typeof name !== "string" || !name.endsWith("_path")) return false;
22143
23107
  if (!this.#reportedPathPointers.has(name)) {
22144
23108
  this.#reportedPathPointers.add(name);
@@ -22208,6 +23172,117 @@ if ((getSubtypeDict(GramlotBuilderBag.tytxSuffix).GramlotBuilderBag ?? GramlotBu
22208
23172
  }
22209
23173
  setSubtypeDict(GramlotBuilderBag.tytxSuffix, { ...getSubtypeDict(GramlotBuilderBag.tytxSuffix), GramlotBuilderBag });
22210
23174
 
23175
+ // src/format.js
23176
+ function validateMask(mask) {
23177
+ if (mask != null && (typeof mask !== "string" || /[{}]/.test(mask.replaceAll("{}", "")))) {
23178
+ throw new RangeError("This formatter mask supports only {} placeholders");
23179
+ }
23180
+ }
23181
+ function applyMask(text, mask) {
23182
+ validateMask(mask);
23183
+ return mask == null ? text : mask.replaceAll("{}", () => text);
23184
+ }
23185
+ function inferredType(value) {
23186
+ if (value instanceof Date) {
23187
+ const epochDay = value.getUTCFullYear() === 1970 && value.getUTCMonth() === 0 && value.getUTCDate() === 1;
23188
+ const midnight = value.getUTCHours() === 0 && value.getUTCMinutes() === 0 && value.getUTCSeconds() === 0 && value.getUTCMilliseconds() === 0;
23189
+ if (epochDay && !midnight) return "H";
23190
+ if (midnight && !epochDay) return "D";
23191
+ return "DHZ";
23192
+ }
23193
+ if (isDecimal2(value)) return "N";
23194
+ if (typeof value === "number") return Number.isInteger(value) ? "L" : "R";
23195
+ throw new TypeError("Formatting requires finite JavaScript numbers, TYTX Decimal values or valid Date objects");
23196
+ }
23197
+ function temporalText(value, dtype, { pattern = "short", locale, timeZone }) {
23198
+ if (!["short", "medium", "long", "full"].includes(pattern)) {
23199
+ throw new RangeError("Temporal formatting currently supports short, medium, long and full only");
23200
+ }
23201
+ if (dtype === "DHZ" && (typeof timeZone !== "string" || !timeZone)) {
23202
+ throw new TypeError("DHZ formatting currently requires an explicit timeZone");
23203
+ }
23204
+ const options = { timeZone: dtype === "DHZ" ? timeZone : "UTC" };
23205
+ if (dtype !== "H") options.dateStyle = pattern;
23206
+ if (dtype !== "D") options.timeStyle = pattern;
23207
+ return new Intl.DateTimeFormat(locale, options).format(value);
23208
+ }
23209
+ function numericSection(section) {
23210
+ const match = /^(-|\()?(#,##0|0+)(?:\.(0*#*))?(\))?$/.exec(section);
23211
+ if (!match || match[1] === "(" !== (match[4] === ")") || section.endsWith(".")) {
23212
+ throw new RangeError(`Unsupported numeric pattern section: ${section}`);
23213
+ }
23214
+ const fraction = match[3] ?? "";
23215
+ return {
23216
+ prefix: match[1] ?? "",
23217
+ suffix: match[4] ?? "",
23218
+ intl: {
23219
+ useGrouping: match[2].startsWith("#,##") ? "always" : false,
23220
+ minimumIntegerDigits: match[2].replace("#,##", "").length,
23221
+ minimumFractionDigits: fraction.replaceAll("#", "").length,
23222
+ maximumFractionDigits: fraction.length
23223
+ }
23224
+ };
23225
+ }
23226
+ function numericPattern(pattern) {
23227
+ const sections = pattern.split(";");
23228
+ if (sections.length > 3) throw new RangeError("Numeric patterns support at most three sections");
23229
+ const positive = numericSection(sections[0]);
23230
+ if (positive.prefix || positive.suffix) throw new RangeError("Positive-section affixes are not implemented");
23231
+ const zero = sections.length === 3 ? sections[1] : null;
23232
+ if (zero !== null && zero !== "" && zero !== "-") numericSection(zero);
23233
+ const negative = sections.length > 1 ? numericSection(sections.at(-1)) : null;
23234
+ return { positive, zero, negative };
23235
+ }
23236
+ function formatValue(value, options = {}, context = {}) {
23237
+ if (value === null) return "";
23238
+ if (typeof options === "string") options = { pattern: options };
23239
+ if (!options || typeof options !== "object" || Array.isArray(options)) {
23240
+ throw new TypeError("Format options must be a pattern string or an options object");
23241
+ }
23242
+ for (const key of Object.keys(options)) {
23243
+ if (!["pattern", "locale", "mask", "dtype", "timeZone"].includes(key)) throw new RangeError(`Unsupported format option: ${key}`);
23244
+ }
23245
+ options = { ...options, locale: options.locale ?? context.locale, timeZone: options.timeZone ?? context.timeZone };
23246
+ const dtype = options.dtype === void 0 ? inferredType(value) : options.dtype;
23247
+ const temporal2 = ["D", "H", "DHZ"].includes(dtype);
23248
+ if (!temporal2 && !["L", "R", "N"].includes(dtype)) throw new RangeError(`Unsupported format dtype: ${dtype}`);
23249
+ if (temporal2) {
23250
+ if (!(value instanceof Date) || !Number.isFinite(value.getTime())) throw new TypeError(`${dtype} requires a valid Date object`);
23251
+ } else if (!(typeof value === "number" && Number.isFinite(value)) && !(isDecimal2(value) && !["NaN", "Infinity", "-Infinity"].includes(value.toString()))) {
23252
+ throw new TypeError(`${dtype} formatting requires finite JavaScript numbers or TYTX Decimal values`);
23253
+ }
23254
+ if (dtype === "L" && !Number.isInteger(value)) throw new TypeError("L formatting requires an integer");
23255
+ const { pattern, locale, mask } = options;
23256
+ if (!temporal2 && typeof pattern !== "string") throw new TypeError("Numeric formatting currently requires an explicit pattern");
23257
+ if (typeof locale !== "string" || !locale) throw new TypeError("Formatting currently requires an explicit locale");
23258
+ const intl = temporal2 ? Intl.DateTimeFormat : Intl.NumberFormat;
23259
+ if (!intl.supportedLocalesOf([locale]).length) throw new RangeError(`Unsupported format locale: ${locale}`);
23260
+ validateMask(mask);
23261
+ if (temporal2) {
23262
+ const text2 = temporalText(value, dtype, options);
23263
+ return applyMask(text2, mask);
23264
+ }
23265
+ const { positive, zero, negative } = numericPattern(pattern);
23266
+ const decimal = isDecimal2(value);
23267
+ const zeroValue = decimal ? value.eq(0) : value === 0;
23268
+ const negativeValue = decimal ? value.lt(0) : value < 0;
23269
+ if (decimal && new Intl.NumberFormat("en", { useGrouping: false }).format("9007199254740993") !== "9007199254740993") throw new Error("This browser cannot format Decimal without precision loss");
23270
+ let text;
23271
+ if (zeroValue && zero !== null) {
23272
+ if (zero === "") return "";
23273
+ if (zero === "-") text = "-";
23274
+ else {
23275
+ const section = numericSection(zero);
23276
+ text = section.prefix + new Intl.NumberFormat(locale, section.intl).format(0) + section.suffix;
23277
+ }
23278
+ } else {
23279
+ const affix = negativeValue && negative ? negative : positive;
23280
+ const number = decimal ? (negativeValue && negative ? value.abs() : value).toString() : negativeValue && negative ? -value : value === 0 ? 0 : value;
23281
+ text = affix.prefix + new Intl.NumberFormat(locale, positive.intl).format(number) + affix.suffix;
23282
+ }
23283
+ return applyMask(text, mask);
23284
+ }
23285
+
22211
23286
  // src/renderer/attributes.js
22212
23287
  var XHTML_NS = "http://www.w3.org/1999/xhtml";
22213
23288
  var SVG_NS = "http://www.w3.org/2000/svg";
@@ -22244,8 +23319,7 @@ var NATIVE_ATTRIBUTES = {
22244
23319
  img: ["width", "height"],
22245
23320
  canvas: ["width", "height"]
22246
23321
  };
22247
- var TEMPLATE_REFERENCE = /(?<!\\)\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;
22248
- var DISPLAY_ATTRIBUTES = ["format", "mask", "locale", "places", "dtype"];
23322
+ var DISPLAY_ATTRIBUTES = ["format", "mask", "locale", "timeZone", "places", "dtype"];
22249
23323
  var URL_ATTRIBUTES = /* @__PURE__ */ new Set(["href", "src", "formaction", "xlink:href", "xlink_href"]);
22250
23324
  function withoutBindingAttributes(attrs) {
22251
23325
  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))));
@@ -22283,14 +23357,7 @@ function withDataSrcdocSandbox(node, attrs, prefixes = []) {
22283
23357
  const declared = Object.fromEntries(sourceAttributeItems(node.getAttr()));
22284
23358
  const srcdoc = [...Object.keys(declared), ...Object.keys(attrs)].find((name) => bare(name)[1] === "srcdoc");
22285
23359
  if (srcdoc === void 0 || Object.keys(declared).some((name) => bare(name)[1] === "sandbox")) return attrs;
22286
- const fromData = (name, seen) => {
22287
- const raw = declared[name];
22288
- seen.add(name);
22289
- return node.pointerType(raw) !== null || isExpression2(raw) || templateParameters(raw).some((param) => Object.hasOwn(declared, param) && !seen.has(param) && fromData(param, seen));
22290
- };
22291
- if (node.pointerType(node.value) === null && !(Object.hasOwn(declared, srcdoc) && fromData(srcdoc, /* @__PURE__ */ new Set()))) {
22292
- return attrs;
22293
- }
23360
+ if (node.pointerType(node.value) === null && !(Object.hasOwn(declared, srcdoc) && (node.pointerType(declared[srcdoc]) !== null || isExpression2(declared[srcdoc])))) return attrs;
22294
23361
  const rest = Object.fromEntries(Object.entries(attrs).filter(([name]) => bare(name)[1] !== "sandbox"));
22295
23362
  return { [`${bare(srcdoc)[0]}sandbox`]: "", ...rest };
22296
23363
  }
@@ -22321,38 +23388,35 @@ function splitNativeAttributes(tag2, attrs) {
22321
23388
  function textValue(value) {
22322
23389
  return String(value);
22323
23390
  }
22324
- function displayItem(item, attrs) {
23391
+ function displayItem(item, attrs, format = null) {
22325
23392
  const rest = { ...attrs };
22326
- const mask = rest.mask;
23393
+ const { mask, format: pattern, locale, timeZone, dtype, places } = rest;
22327
23394
  for (const name of DISPLAY_ATTRIBUTES) delete rest[name];
22328
- if (Array.isArray(item)) return [item, rest];
22329
- if (typeof item === "boolean") item = textValue(item);
22330
- if (mask == null) return [item, rest];
22331
- const text = item == null ? "" : textValue(item);
22332
- return [text === "" ? text : String(mask).replaceAll("%s", () => text), rest];
22333
- }
22334
- function templateParameters(value) {
22335
- return typeof value === "string" ? [...value.matchAll(TEMPLATE_REFERENCE)].map(([, name]) => name) : [];
23395
+ const display = (value) => {
23396
+ if (format && pattern != null) {
23397
+ if (places != null) throw new RangeError("places is not implemented; specify precision in format");
23398
+ return format(value, {
23399
+ pattern,
23400
+ mask,
23401
+ ...locale == null ? {} : { locale },
23402
+ ...timeZone == null ? {} : { timeZone },
23403
+ ...dtype == null ? {} : { dtype }
23404
+ });
23405
+ }
23406
+ if (typeof value === "boolean") value = textValue(value);
23407
+ if (mask == null) return value;
23408
+ const text = value == null ? "" : textValue(value);
23409
+ return text === "" ? text : applyMask(text, mask);
23410
+ };
23411
+ if (Array.isArray(item)) {
23412
+ if (Object.hasOwn(rest, "_text")) rest._text = display(rest._text);
23413
+ return [item, rest];
23414
+ }
23415
+ return [display(item), rest];
22336
23416
  }
22337
23417
  function isExpression2(value) {
22338
23418
  return typeof value === "string" && value.startsWith("==");
22339
23419
  }
22340
- function requireNoExpressionTemplate(node) {
22341
- if (isExpression2(node.value) && templateParameters(node.value).length) {
22342
- throw new Error(`${node.nodeTag} '${node.label}': the == node value contains a \${\u2026} template, not accepted in a == expression`);
22343
- }
22344
- const attrs = Object.fromEntries(sourceAttributeItems(node.getAttr()));
22345
- for (const [name, raw] of Object.entries(attrs)) {
22346
- if (isExpression2(raw) && templateParameters(raw).length) {
22347
- throw new Error(`${node.nodeTag} '${node.label}': '${name}' contains a \${\u2026} template, not accepted in a == expression`);
22348
- }
22349
- for (const param of templateParameters(raw)) {
22350
- if (isExpression2(attrs[param])) {
22351
- throw new Error(`${node.nodeTag} '${node.label}': the template of '${name}' uses '${param}', a == expression`);
22352
- }
22353
- }
22354
- }
22355
- }
22356
23420
 
22357
23421
  // src/renderer/gramlot-svg-renderer.js
22358
23422
  var SVG_VOID_TAGS = /* @__PURE__ */ new Set([
@@ -22429,26 +23493,6 @@ var GramlotSvgRenderer = class extends SvgRenderer {
22429
23493
  }
22430
23494
  };
22431
23495
 
22432
- // src/webcomponent.js
22433
- var NAME2 = /^[a-z][.0-9_a-z\-\u00B7\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u037D\u037F-\u1FFF\u200C-\u200D\u203F-\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}]*$/u;
22434
- var RESERVED = /* @__PURE__ */ new Set([
22435
- "annotation-xml",
22436
- "color-profile",
22437
- "font-face",
22438
- "font-face-src",
22439
- "font-face-uri",
22440
- "font-face-format",
22441
- "font-face-name",
22442
- "missing-glyph"
22443
- ]);
22444
- function webcomponentCode(attrs) {
22445
- const code = attrs.code;
22446
- if (typeof code !== "string" || NAME2.exec(code)?.[0] !== code || !code.includes("-") || RESERVED.has(code)) {
22447
- throw new TypeError("webcomponent: code must be a literal custom-element name");
22448
- }
22449
- return code;
22450
- }
22451
-
22452
23496
  // src/renderer/gramlot-html-renderer.js
22453
23497
  var GramlotHtmlRenderer = class extends HtmlRenderer {
22454
23498
  // noConvertStyle attributes taken out in _handleMeta, put back after adaptAttrs.
@@ -22462,6 +23506,7 @@ var GramlotHtmlRenderer = class extends HtmlRenderer {
22462
23506
  /** HTML nodes (GramlotBuilder, HtmlBuilder) → this renderer; SVG nodes → one GramlotSvgRenderer owned by it. */
22463
23507
  getRender(builder) {
22464
23508
  if (!this.renders.has(builder)) {
23509
+ builder.evaluatePointerExpression = this.builder.evaluatePointerExpression.bind(this.builder);
22465
23510
  if (builder instanceof HtmlBuilder) this.addRender(builder, this);
22466
23511
  else if (builder instanceof SvgBuilder) this.addRender(builder, new GramlotSvgRenderer(builder, this));
22467
23512
  }
@@ -22501,10 +23546,9 @@ var GramlotHtmlRenderer = class extends HtmlRenderer {
22501
23546
  /**
22502
23547
  * Step 3 of Q11.2 on the attributes of `node` resolved by runtimeValues, for HTML and SVG nodes: every
22503
23548
  * `==` attribute, and a `==` node value, evaluated by the page's InlineCompiler (§4.10); without a
22504
- * compiler they are null and nothing is written. A template using a `==` attribute is an error.
23549
+ * compiler they are null and nothing is written.
22505
23550
  */
22506
23551
  evaluateExpressions(node, runtimeAttrs) {
22507
- requireNoExpressionTemplate(node);
22508
23552
  const compiler = this.inlineCompiler;
22509
23553
  const evaluate = (attr, expr) => compiler ? compiler.compileExpression(node, attr, expr)(runtimeAttrs) : null;
22510
23554
  const attrs = { ...runtimeAttrs };
@@ -22531,14 +23575,14 @@ var GramlotHtmlRenderer = class extends HtmlRenderer {
22531
23575
  */
22532
23576
  adaptAttrs(attrs) {
22533
23577
  const { _meta, ...rest } = attrs;
22534
- const own = `${this.builder.constructor._name}_`;
23578
+ const own2 = `${this.builder.constructor._name}_`;
22535
23579
  const prefixes = this.builder.constructor.dialectPrefixes;
22536
23580
  const literal = {};
22537
23581
  const styled = {};
22538
23582
  for (const [name, value] of Object.entries(withoutBindingAttributes(rest))) {
22539
23583
  if (value == null) continue;
22540
- if (name.startsWith(own)) {
22541
- throw new Error(`${name}: the attribute prefix '${own}' is not accepted; use the prefix '${prefixes[0]}'`);
23584
+ if (name.startsWith(own2)) {
23585
+ throw new Error(`${name}: the attribute prefix '${own2}' is not accepted; use the prefix '${prefixes[0]}'`);
22542
23586
  }
22543
23587
  const prefix = prefixes.find((candidate) => name.startsWith(candidate));
22544
23588
  if (prefix) literal[name.slice(prefix.length)] = value;
@@ -23037,10 +24081,13 @@ var DATA_PATH_ATTRIBUTES = {
23037
24081
  };
23038
24082
  var DATA_INLINE_ATTRIBUTES = { dataFormula: "formula", dataController: "script" };
23039
24083
  function dataElementError(tag2, attrs) {
24084
+ if (["input", "textarea", "select", "webcomponent"].includes(tag2) && pointerTransform(attrs.value)) {
24085
+ return "'value' does not accept pointer suffixes; use an ordinary value pointer";
24086
+ }
23040
24087
  if (tag2 === "html_button" && Object.keys(attrs).some((name) => ["action", "ask", "_delay", "fire"].includes(name) || name.startsWith("fire_"))) {
23041
24088
  return "plain HTML button: use button for action, ask, fire or _delay";
23042
24089
  }
23043
- if (Object.hasOwn(attrs, "ask") && tag2 !== "button") return "'ask' is supported on buttons";
24090
+ if (Object.hasOwn(attrs, "ask") && !["button", "toggleButton", "dropDownButton", "menuline"].includes(tag2)) return "'ask' is supported on buttons";
23044
24091
  if (Object.hasOwn(attrs, "_ask") && !["dataController", "dataFormula", "dataRpc"].includes(tag2)) return "'_ask' requires a controller, formula or RPC";
23045
24092
  if (["dataSetter", "dataRemote"].includes(tag2) && Object.keys(attrs).some((name) => name.startsWith("subscribe_") || name.startsWith("selfsubscribe_"))) {
23046
24093
  return "topic subscriptions are supported on controllers, formulas, RPCs and rendered elements";
@@ -23070,6 +24117,9 @@ var GramlotBuilder = class _GramlotBuilder extends HtmlBuilder {
23070
24117
  static {
23071
24118
  this.defineGrammar(webcomponent_default);
23072
24119
  }
24120
+ static {
24121
+ this.defineGrammar(buttons_default.toDocument());
24122
+ }
23073
24123
  /** Tag prefixes of the parent dialects, from the `_name` of the classes above GramlotBuilder. */
23074
24124
  static get dialectPrefixes() {
23075
24125
  const prefixes = [];
@@ -23097,6 +24147,10 @@ var GramlotBuilder = class _GramlotBuilder extends HtmlBuilder {
23097
24147
  set binding(runtime) {
23098
24148
  this._binding = runtime;
23099
24149
  }
24150
+ /** Builder supplies typed slots; Gramlot owns activation, CSP and page-local _F. */
24151
+ evaluatePointerExpression(node, name, raw, expression, inputs) {
24152
+ return this.binding ? this.binding.inlineCompiler.compilePointerExpression(node, name, raw, expression.text)(inputs) : null;
24153
+ }
23100
24154
  /** Builder's nodeById; inside a Gramlot page it reads the node_id map of the BindingRuntime (R06). */
23101
24155
  nodeById(nodeId) {
23102
24156
  if (!this.binding) return super.nodeById(nodeId);
@@ -23105,7 +24159,7 @@ var GramlotBuilder = class _GramlotBuilder extends HtmlBuilder {
23105
24159
  return node.builder.wrapSource(node);
23106
24160
  }
23107
24161
  loadCollection(document) {
23108
- this.loadGrammar(document);
24162
+ this.loadGrammar(document instanceof ComponentCollection ? document.toDocument() : document);
23109
24163
  return this;
23110
24164
  }
23111
24165
  /**
@@ -23140,6 +24194,9 @@ var GramlotBuilder = class _GramlotBuilder extends HtmlBuilder {
23140
24194
  }
23141
24195
  /** Builder's value check, plus the excluded attributes (authoring names the tag). */
23142
24196
  validateNodeValues(tag2, value, attrs = {}) {
24197
+ if (this.schema[tag2]?._meta?.gramlot_component && pointerTransform(attrs.value)) {
24198
+ throw new Error("'value' does not accept pointer suffixes");
24199
+ }
23143
24200
  if (tag2 === "webcomponent") webcomponentCode(attrs);
23144
24201
  const excluded = excludedAttribute(attrs);
23145
24202
  if (excluded) throw new Error(`${tag2}: attribute '${excluded}' is excluded from Gramlot 0.2.0`);
@@ -23149,6 +24206,9 @@ var GramlotBuilder = class _GramlotBuilder extends HtmlBuilder {
23149
24206
  }
23150
24207
  /** Builder's node check, plus the excluded attributes (a Source node names tag and label). */
23151
24208
  validateNode(node, options = {}) {
24209
+ if (node._getMeta("gramlot_component") && pointerTransform((options.attrs ?? node.getAttr()).value)) {
24210
+ throw new Error("'value' does not accept pointer suffixes");
24211
+ }
23152
24212
  if (node.nodeTag === "webcomponent") webcomponentCode(options.attrs ?? node.getAttr());
23153
24213
  const excluded = excludedAttribute(options.attrs ?? node.getAttr());
23154
24214
  if (excluded) throw new Error(`${node.nodeTag} '${node.label}': attribute '${excluded}' is excluded from Gramlot 0.2.0`);
@@ -23167,7 +24227,7 @@ var GramlotBuilder = class _GramlotBuilder extends HtmlBuilder {
23167
24227
  }
23168
24228
  /** Custom elements are outside the native HTML child catalogue, as components are. */
23169
24229
  _countsForGrammar(info) {
23170
- return info !== this.schema.webcomponent && super._countsForGrammar(info);
24230
+ return info === this.schema.button || !info?._meta?.gramlot_component && info !== this.schema.webcomponent && super._countsForGrammar(info);
23171
24231
  }
23172
24232
  /** Builder's child insertion; a plain object `value` of `dataSetter` becomes `new Bag(value)` (P25). */
23173
24233
  setChild(bag, tag2, value, attrs, parentOverride = null) {
@@ -23237,6 +24297,9 @@ var ControlAdapter = class _ControlAdapter {
23237
24297
  static liveWrites = false;
23238
24298
  // Whether a literal `value` is also written as the default a native form Reset restores.
23239
24299
  static writesDefault = true;
24300
+ static preservesUnchangedValue = false;
24301
+ #projectedValue;
24302
+ #hasProjectedValue = false;
23240
24303
  #binding;
23241
24304
  #record;
23242
24305
  #committing = false;
@@ -23254,6 +24317,10 @@ var ControlAdapter = class _ControlAdapter {
23254
24317
  */
23255
24318
  static classFor(element, attrs) {
23256
24319
  if (element.namespaceURI !== XHTML_NS) return null;
24320
+ if (element.constructor.gramlotComponent) {
24321
+ if (element.constructor.gramlotComponent.parameters.value?.binding !== "twoWay") return null;
24322
+ return element.control.type === "radio" ? ComponentRadioControl : ComponentControl;
24323
+ }
23257
24324
  if (element.localName === "textarea") return TextControl;
23258
24325
  if (element.localName === "select") return SelectControl;
23259
24326
  if (element.localName !== "input") return null;
@@ -23266,6 +24333,7 @@ var ControlAdapter = class _ControlAdapter {
23266
24333
  * `attrs` are the attributes of the renderer's resolved projection (`^`, `=` and `==` resolved).
23267
24334
  */
23268
24335
  static shape(element, attrs) {
24336
+ if (element?.constructor.gramlotComponent?.parameters.value?.binding === "twoWay" && element.control.type === "radio") return JSON.stringify([attrs.group ?? null]);
23269
24337
  if (element?.namespaceURI !== XHTML_NS || !CONTROL_TAGS.has(element.localName)) return null;
23270
24338
  return JSON.stringify(REBUILD_ATTRIBUTES.map((name) => attrs[name] ?? null));
23271
24339
  }
@@ -23282,6 +24350,9 @@ var ControlAdapter = class _ControlAdapter {
23282
24350
  get node() {
23283
24351
  return this.binding.node;
23284
24352
  }
24353
+ get eventElement() {
24354
+ return this.element;
24355
+ }
23285
24356
  /** The attributes of the last resolved projection of the node (`^`, `=` and `==` resolved). */
23286
24357
  get resolved() {
23287
24358
  return this.#record.resolved;
@@ -23309,6 +24380,9 @@ var ControlAdapter = class _ControlAdapter {
23309
24380
  this.#pending = true;
23310
24381
  return;
23311
24382
  }
24383
+ if (this.constructor.preservesUnchangedValue && this.#hasProjectedValue && this.same(this.#projectedValue, value)) return;
24384
+ this.#projectedValue = value;
24385
+ this.#hasProjectedValue = true;
23312
24386
  if (this.#committing && this.same(this.read(), value)) return;
23313
24387
  if (this.constructor.writesDefault && !this.node.pointerType(this.node.getAttr("value"))) {
23314
24388
  this.writeDefault(value);
@@ -23345,25 +24419,25 @@ var ControlAdapter = class _ControlAdapter {
23345
24419
  * input and writes nothing (gate decision 5); a null path raises from the listener (Q7). A closed
23346
24420
  * NodeBinding writes nothing (R12).
23347
24421
  */
23348
- commit(event) {
24422
+ commit(event, value = this.read()) {
23349
24423
  if (this.binding.closed) return;
23350
24424
  const pointer = this.node.getAttr("value");
23351
24425
  if (this.node.pointerType(pointer) !== "^") return;
23352
24426
  this.#committing = true;
23353
24427
  try {
23354
- this.node.setRelativeData(pointer.slice(1), this.read());
24428
+ this.node.setRelativeData(pointer.slice(1), value);
23355
24429
  } finally {
23356
24430
  this.#committing = false;
23357
24431
  }
23358
24432
  }
23359
24433
  attach() {
23360
24434
  for (const type of ["input", "change", "compositionstart", "compositionend"]) {
23361
- this.element.addEventListener(type, this);
24435
+ this.eventElement.addEventListener(type, this);
23362
24436
  }
23363
24437
  }
23364
24438
  detach() {
23365
24439
  for (const type of ["input", "change", "compositionstart", "compositionend"]) {
23366
- this.element.removeEventListener(type, this);
24440
+ this.eventElement.removeEventListener(type, this);
23367
24441
  }
23368
24442
  this.#pending = false;
23369
24443
  }
@@ -23393,6 +24467,49 @@ var ControlAdapter = class _ControlAdapter {
23393
24467
  if (event.type === this.writeEvent) this.commit(event);
23394
24468
  }
23395
24469
  };
24470
+ var ComponentControl = class extends ControlAdapter {
24471
+ static writesDefault = false;
24472
+ static preservesUnchangedValue = true;
24473
+ get eventElement() {
24474
+ return this.element.control;
24475
+ }
24476
+ attach() {
24477
+ this.element.setPageContext(componentContext(this));
24478
+ super.attach();
24479
+ }
24480
+ project(value, change) {
24481
+ if (this.element.shouldProjectControlValue(value)) super.project(value, change);
24482
+ }
24483
+ same(a, b) {
24484
+ return this.element.sameControlValue(a, b);
24485
+ }
24486
+ detach() {
24487
+ this.element.releaseControl();
24488
+ super.detach();
24489
+ }
24490
+ commit(event) {
24491
+ if (this.binding.closed || this.element.control.disabled || this.element.control.readOnly) return;
24492
+ commitComponent(this.element, this.element.acceptControlValue(), (result) => super.commit(event, result.value));
24493
+ }
24494
+ get writeEvent() {
24495
+ if (this.element.commitOnChange) return "change";
24496
+ const control = this.element.control;
24497
+ return this.live && (control.localName === "textarea" || ["text", "password", "range", "color"].includes(control.type)) ? "input" : "change";
24498
+ }
24499
+ read() {
24500
+ return this.element.readControlValue();
24501
+ }
24502
+ write(value) {
24503
+ this.element.writeControlValue(value);
24504
+ }
24505
+ handleEvent(event) {
24506
+ super.handleEvent(event);
24507
+ if (!event.composed && !this.binding.closed && ["input", "change"].includes(event.type)) {
24508
+ const Event = this.element.ownerDocument.defaultView.Event;
24509
+ this.element.dispatchEvent(new Event(event.type, { bubbles: true, composed: true }));
24510
+ }
24511
+ }
24512
+ };
23396
24513
  var TextControl = class extends ControlAdapter {
23397
24514
  static liveWrites = true;
23398
24515
  };
@@ -23562,6 +24679,58 @@ var RadioControl = class extends CheckboxControl {
23562
24679
  }
23563
24680
  }
23564
24681
  };
24682
+ var ComponentRadioControl = class extends RadioControl {
24683
+ static writesDefault = false;
24684
+ get host() {
24685
+ return super.element;
24686
+ }
24687
+ get element() {
24688
+ return this.host.control;
24689
+ }
24690
+ project(value, change) {
24691
+ if (this.host.shouldProjectControlValue(value)) super.project(value, change);
24692
+ }
24693
+ commit(event) {
24694
+ if (this.binding.closed || this.element.disabled || this.element.readOnly) return;
24695
+ commitComponent(this.host, this.host.acceptControlValue(), () => super.commit(event));
24696
+ }
24697
+ read() {
24698
+ return this.host.readControlValue();
24699
+ }
24700
+ write(value) {
24701
+ this.host.writeControlValue(value);
24702
+ }
24703
+ attach() {
24704
+ this.host.setPageContext(componentContext(this));
24705
+ super.attach();
24706
+ this.element.addEventListener("keydown", this);
24707
+ }
24708
+ detach() {
24709
+ this.host.releaseControl();
24710
+ this.element.removeEventListener("keydown", this);
24711
+ super.detach();
24712
+ }
24713
+ handleEvent(event) {
24714
+ if (this.binding.closed) return;
24715
+ if (event.type === "keydown") {
24716
+ if (this.resolved.group == null || !["ArrowLeft", "ArrowUp", "ArrowRight", "ArrowDown"].includes(event.key)) return;
24717
+ const peers = this.groups.peersOf(this.resolved.group, formNode(this.node)).filter((peer) => !peer.binding.closed && !peer.element.disabled);
24718
+ const index = peers.indexOf(this);
24719
+ if (index < 0) return;
24720
+ event.preventDefault();
24721
+ const delta = ["ArrowLeft", "ArrowUp"].includes(event.key) ? -1 : 1;
24722
+ const next = peers[(index + delta + peers.length) % peers.length];
24723
+ next.element.focus();
24724
+ next.element.click();
24725
+ return;
24726
+ }
24727
+ super.handleEvent(event);
24728
+ if (!event.composed && !this.binding.closed && ["input", "change"].includes(event.type)) {
24729
+ const Event = this.host.ownerDocument.defaultView.Event;
24730
+ this.host.dispatchEvent(new Event(event.type, { bubbles: true, composed: true }));
24731
+ }
24732
+ }
24733
+ };
23565
24734
  var RadioGroups = class {
23566
24735
  #renderer;
23567
24736
  #groups = /* @__PURE__ */ new Map();
@@ -23634,6 +24803,71 @@ var INPUT_CONTROLS = {
23634
24803
  reset: null,
23635
24804
  image: null
23636
24805
  };
24806
+ function componentContext(adapter) {
24807
+ const { binding, node } = adapter, app = binding.runtime.gramlot;
24808
+ const invoke = (attribute, code, keywords, expression = false) => {
24809
+ if (!expression && /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(code)) {
24810
+ const { group, method } = app.src.logicRegistry.resolve(code, node);
24811
+ return method.call(group, node, keywords);
24812
+ }
24813
+ return binding.runtime.inlineCompiler.compile(
24814
+ node,
24815
+ attribute,
24816
+ code,
24817
+ Object.keys(keywords),
24818
+ expression ? `return (${code});` : code
24819
+ )(keywords);
24820
+ };
24821
+ return {
24822
+ locale: app.locale,
24823
+ timeZone: app.timeZone,
24824
+ createDecimal,
24825
+ isDecimal: isDecimal2,
24826
+ getDecimalLibrary,
24827
+ isActive: () => !binding.closed,
24828
+ callLogic: (name, keywords) => {
24829
+ const { group, method } = app.src.logicRegistry.resolve(name, node);
24830
+ return method.call(group, node, keywords);
24831
+ },
24832
+ format: (value, options) => app.format(value, options),
24833
+ invoke,
24834
+ remote: (method, keywords, signal) => app.rpc.call("data", method, keywords, { signal }),
24835
+ validationCurrent: () => {
24836
+ const pointer = node.getAttr("value");
24837
+ const path = node.pointerType(pointer) ? node.absDatapath(pointer) : null;
24838
+ return () => !binding.closed && node.getAttr("value") === pointer && (path === null || node.absDatapath(pointer) === path);
24839
+ },
24840
+ finishValidation: ({ ok, result, rules }) => {
24841
+ if (binding.closed) return;
24842
+ if (ok) for (const patch of result.datachanges) node.getRelativeData(".").update(patch);
24843
+ const attribute = ok ? "validate_onAccept" : "validate_onReject";
24844
+ if (rules[attribute]) {
24845
+ const report = (error) => console.error("Validation notification failed:", error);
24846
+ try {
24847
+ const validations = Object.fromEntries(Object.entries(rules).map(([key, value]) => [key.slice(9), value]));
24848
+ const returned = invoke(attribute, rules[attribute], { value: result.value, result, validations, userChange: true });
24849
+ if (returned instanceof Promise) returned.catch(report);
24850
+ } catch (error) {
24851
+ report(error);
24852
+ }
24853
+ }
24854
+ },
24855
+ checkDataPatch: (patch) => {
24856
+ if (!(patch instanceof Bag)) throw new TypeError("Validation data changes must be a Bag.");
24857
+ if (!(node.getRelativeData(".") instanceof Bag)) throw new TypeError("Validation data changes require a Bag datapath.");
24858
+ }
24859
+ };
24860
+ }
24861
+ function commitComponent(host, outcome, commit) {
24862
+ const finish = (result) => {
24863
+ if (result.ok && result.isCurrent()) {
24864
+ commit(result);
24865
+ host.finishValidation(result);
24866
+ }
24867
+ };
24868
+ if (outcome instanceof Promise) outcome.then(finish).catch((error) => console.error("Validation notification failed:", error));
24869
+ else finish(outcome);
24870
+ }
23637
24871
 
23638
24872
  // src/view/html.js
23639
24873
  var DEFAULT_TEXT = /* @__PURE__ */ Symbol("source text");
@@ -23706,6 +24940,7 @@ var HtmlElement = class {
23706
24940
  throw new TypeError("HTML text must be scalar");
23707
24941
  }
23708
24942
  for (const [key, value] of Object.entries(node.attr)) {
24943
+ if (key === "value" && this.definition(node).meta.gramlot_component) continue;
23709
24944
  if (this.metadataAttributes.has(key) || ["ask", "_ask"].includes(key) || value && typeof value === "object" && Object.hasOwn(value, "$gramlotRef")) continue;
23710
24945
  if (value != null && !["string", "number", "boolean"].includes(typeof value)) {
23711
24946
  throw new TypeError(`HTML attribute ${key} must be scalar`);
@@ -23719,6 +24954,15 @@ var HtmlElement = class {
23719
24954
  const { tag: defaultTag, namespace, meta } = this.definition(node);
23720
24955
  tag2 ??= defaultTag;
23721
24956
  const element = namespace === XHTML_NS ? document.createElement(tag2) : document.createElementNS(namespace, tag2);
24957
+ if (meta.gramlot_component && element.constructor.gramlotComponent?.tag !== tag2) {
24958
+ throw new Error(`Component collection must be activated before rendering ${tag2}`);
24959
+ }
24960
+ if (meta.gramlot_component?.dataScope) {
24961
+ element.readDataScope = () => {
24962
+ if (!node.getAttr("datapath")) throw new Error("Data scope requires an explicit datapath");
24963
+ return node.getRelativeData(".");
24964
+ };
24965
+ }
23722
24966
  const text = document.createTextNode(this.text(node));
23723
24967
  if (namespace !== XHTML_NS || !meta.void) element.append(text);
23724
24968
  const record2 = { element, text, tag: tag2 };
@@ -23744,6 +24988,13 @@ var HtmlElement = class {
23744
24988
  const isHtml = element.namespaceURI === XHTML_NS;
23745
24989
  const renderAttributes = this.definition(node).meta.render_attributes ?? {};
23746
24990
  const previous = record2.attrs ?? {};
24991
+ if (this.definition(node).meta.gramlot_component) {
24992
+ attrs = element.projectAttributes(attrs, (values) => {
24993
+ requireNoScriptAttributes(node, values, node.builder.constructor.dialectPrefixes);
24994
+ requireStyleClassAttributes(node, values, node.builder.constructor.dialectPrefixes);
24995
+ return node.builder.renderer_html.adaptAttrs(values);
24996
+ });
24997
+ }
23747
24998
  attrs = Object.fromEntries(sourceAttributeItems({ ...attrs, ...renderAttributes }));
23748
24999
  const controlled = ControlAdapter.classFor(element, attrs) !== null;
23749
25000
  if (textValue2 === DEFAULT_TEXT) textValue2 = this.text(node);
@@ -23899,8 +25150,8 @@ var AskDialog = class {
23899
25150
  else row.input({ ...attrs, type: field.type ?? "text" });
23900
25151
  }
23901
25152
  const buttons = form.div({ style: "display:flex;justify-content:flex-end;gap:8px;margin-top:16px;" });
23902
- buttons.button("Cancel", { type: "button", request: id, connect_onclick: `${page.group}.cancel` });
23903
- buttons.button("Confirm", { type: "submit", autofocus: fields.length === 0 });
25153
+ buttons.html_button("Cancel", { type: "button", request: id, connect_onclick: `${page.group}.cancel` });
25154
+ buttons.html_button("Confirm", { type: "submit", autofocus: fields.length === 0 });
23904
25155
  app.src.source.setItem(id, app.src.prepareSource(builder.source));
23905
25156
  const node = app.src.binding.nodeIds.get(id);
23906
25157
  app.dom.getDomNode(node).showModal();
@@ -23920,7 +25171,7 @@ var ButtonBinding = class _ButtonBinding {
23920
25171
  /** The binding of a Gramlot button; html_button remains native despite its DOM tag. */
23921
25172
  static for(binding, record2) {
23922
25173
  const element = record2.element;
23923
- if (binding.node.nodeTag !== "button" || element?.namespaceURI !== XHTML_NS || element.localName !== "button") return null;
25174
+ if (!element?.constructor.gramlotComponent?.command) return null;
23924
25175
  return new _ButtonBinding(binding, record2);
23925
25176
  }
23926
25177
  constructor(binding, record2) {
@@ -23965,6 +25216,8 @@ var ButtonBinding = class _ButtonBinding {
23965
25216
  /** Check the mechanism, apply R3's `type`, then listen to `click`. */
23966
25217
  attach() {
23967
25218
  this.refresh();
25219
+ this.element.activateCommand = (event) => this.onClick(event);
25220
+ this.element.attachCommand();
23968
25221
  this.element.addEventListener("click", this);
23969
25222
  }
23970
25223
  /**
@@ -23979,6 +25232,8 @@ var ButtonBinding = class _ButtonBinding {
23979
25232
  }
23980
25233
  detach() {
23981
25234
  this.element.removeEventListener("click", this);
25235
+ this.element.releaseCommand();
25236
+ delete this.element.activateCommand;
23982
25237
  this.#cancelDelay?.();
23983
25238
  }
23984
25239
  handleEvent(event) {
@@ -23990,7 +25245,14 @@ var ButtonBinding = class _ButtonBinding {
23990
25245
  * the mechanism. An error propagates from the listener.
23991
25246
  */
23992
25247
  onClick(event) {
23993
- if (this.binding.closed) return;
25248
+ if (this.binding.closed || this.element.disabled) return;
25249
+ const target = this.element.commandTarget(event);
25250
+ if (target === null) return;
25251
+ if (target !== this.element) {
25252
+ event.stopPropagation();
25253
+ return target.activateCommand(event);
25254
+ }
25255
+ if (!this.element.prepareCommand(event)) return;
23994
25256
  const mechanism = this.mechanism;
23995
25257
  if (!mechanism) return;
23996
25258
  event.stopPropagation();
@@ -24038,7 +25300,7 @@ var ButtonBinding = class _ButtonBinding {
24038
25300
  return { ...this.binding.runtime.renderer.references.resolveArguments(authored), event, _counter: counter, modifiers };
24039
25301
  };
24040
25302
  const execute = (result) => {
24041
- if (this.binding.closed || result === null) return;
25303
+ if (this.binding.closed || this.element.disabled || result === null) return;
24042
25304
  const values = { ...read(), ...result };
24043
25305
  if (result) values._askResult = result;
24044
25306
  this.binding.runtime.inlineCompiler.compile(node, "action", node.getAttr("action"), Object.keys(values))(values);
@@ -24475,7 +25737,7 @@ var DataInstaller = class {
24475
25737
  const special = {};
24476
25738
  for (const [name, value] of Object.entries(attrs)) {
24477
25739
  if (name.startsWith("attr_")) {
24478
- special[name.slice(5)] = node.pointerType(value) ? node.getRelativeData(value) : value;
25740
+ special[name.slice(5)] = pointerTransform(value) ? resolvePointerAttribute(node, name) : node.pointerType(value) ? node.getRelativeData(value) : value;
24479
25741
  }
24480
25742
  }
24481
25743
  if (!Object.keys(special).length) return;
@@ -24646,7 +25908,7 @@ var CONTROL_ATTRIBUTES = /* @__PURE__ */ new Set([
24646
25908
  var Provider = class {
24647
25909
  #binding;
24648
25910
  #registrations = [];
24649
- #timingRegistration = null;
25911
+ #timingRegistrations = /* @__PURE__ */ new Set();
24650
25912
  #stopTiming = null;
24651
25913
  #cancelDelay = null;
24652
25914
  // The AbortController of the in-flight call of a `dataRpc`: a new call aborts it (latest wins).
@@ -24687,6 +25949,7 @@ var Provider = class {
24687
25949
  }
24688
25950
  this.#closeRegistrations();
24689
25951
  const router = this.binding.runtime.router;
25952
+ const timingDependencies = pointerDependencies(node, node.getAttr("_timing"));
24690
25953
  for (const [name, pointer] of node.pointers()) {
24691
25954
  if (name === "datapath") continue;
24692
25955
  const absolute = node.absDatapath(pointer);
@@ -24694,7 +25957,7 @@ var Provider = class {
24694
25957
  const [path, attr = null] = absolute.split("?", 2);
24695
25958
  const registration = router.register({ path, attr, recipient: this });
24696
25959
  this.#registrations.push(registration);
24697
- if (name === "_timing") this.#timingRegistration = registration;
25960
+ if (name === "_timing" || timingDependencies.has(name)) this.#timingRegistrations.add(registration);
24698
25961
  }
24699
25962
  const subscriptions = this.binding.runtime.gramlot._subscriptions;
24700
25963
  for (const name of Object.keys(node.getAttr())) {
@@ -24719,7 +25982,7 @@ var Provider = class {
24719
25982
  * debounces, the last call wins, and the arguments are read when the body runs.
24720
25983
  */
24721
25984
  receive(change) {
24722
- if (change.registration === this.#timingRegistration) {
25985
+ if (this.#timingRegistrations.has(change.registration)) {
24723
25986
  this.#startTiming();
24724
25987
  return;
24725
25988
  }
@@ -24850,6 +26113,7 @@ var Provider = class {
24850
26113
  #resolved(name) {
24851
26114
  const node = this.node;
24852
26115
  const value = node.getAttr(name);
26116
+ if (pointerTransform(value)) return resolvePointerAttribute(node, name);
24853
26117
  return node.pointerType(value) ? node.getRelativeData(value) : value ?? null;
24854
26118
  }
24855
26119
  /**
@@ -24960,7 +26224,7 @@ var Provider = class {
24960
26224
  }
24961
26225
  #closeRegistrations() {
24962
26226
  for (const registration of this.#registrations.splice(0)) registration.close();
24963
- this.#timingRegistration = null;
26227
+ this.#timingRegistrations.clear();
24964
26228
  }
24965
26229
  };
24966
26230
  var FormulaProvider = class extends Provider {
@@ -25131,30 +26395,31 @@ var InlineCompiler = class {
25131
26395
  * The function of the `==` expression `code` of the attribute `attr` of `node` (`''` for the node
25132
26396
  * value), as written in the Source: `run(resolved)` evaluates it on the attributes resolved by
25133
26397
  * runtimeValues. Its arguments are the
25134
- * other attributes of the node, except the other `==` (Q11.2): the resolved value, or, for an
25135
- * attribute a template consumed, its pointer resolved from Data (D6). A consumed attribute that is
25136
- * itself a template has no value: an expression using it is an error naming both attributes.
26398
+ * other attributes of the node, except the other `==` (Q11.2). Named pointer slots retain
26399
+ * those attributes in the resolved projection; ordinary ${name} strings remain literal.
25137
26400
  */
25138
26401
  compileExpression(node, attr, code) {
25139
26402
  const expr = code.slice(2);
25140
26403
  const items = sourceAttributeItems(node.getAttr()).filter(([, raw]) => !isExpression2(raw));
25141
- const run = this.compile(node, attr, code, items.map(([name]) => name), `return ${expr}`);
26404
+ const run = this.compile(node, attr, code, [...items.map(([name]) => name).filter((name) => name !== "_F"), "_F"], `return ${expr}`);
25142
26405
  return (resolved2) => {
25143
26406
  const values = {};
25144
26407
  for (const [name, raw] of items) {
25145
26408
  if (Object.hasOwn(resolved2, name)) {
25146
26409
  values[name] = resolved2[name];
25147
- } else if (templateParameters(raw).length) {
25148
- if (isIdentifier(name) && new RegExp(`(?<![\\w$])${name.replaceAll("$", "\\$")}(?![\\w$])`).test(expr)) {
25149
- throw new Error(`${node.nodeTag} '${node.label}': '${attr}' uses '${name}', a template consumed by another template, whose value is not available; write a dataFormula`);
25150
- }
25151
26410
  } else {
25152
26411
  values[name] = node.pointerType(raw) ? node.getRelativeData(raw) : raw;
25153
26412
  }
25154
26413
  }
25155
- return run(values);
26414
+ return run({ ...values, _F: (value, options) => this.runtime.gramlot.format(value, options) });
25156
26415
  };
25157
26416
  }
26417
+ /** Typed placeholder inputs, compiled under the exact declaration activated with Source. */
26418
+ compilePointerExpression(node, attr, code, expression) {
26419
+ const run = this.compile(node, attr, code, ["_pointerValues", "_F"], `return (${expression}
26420
+ )`);
26421
+ return (values) => run({ _pointerValues: values, _F: (value, options) => this.runtime.gramlot.format(value, options) });
26422
+ }
25158
26423
  /**
25159
26424
  * Release the compiled declarations of `node`: those of the attributes `names` (Source names; `''`
25160
26425
  * is the node value, `_if`/`_else`/`formula`/`script` their own), or all of them when `names` is null.
@@ -25606,7 +26871,7 @@ var NodeBinding = class {
25606
26871
  // The clicks of a button, counted for its whole semantic life: a rebuild keeps them (P9, S12).
25607
26872
  #clickCount = 0;
25608
26873
  // The registration of the node's own variable datapath, read in the parent's context.
25609
- #datapathRegistration = null;
26874
+ #datapathRegistrations = /* @__PURE__ */ new Set();
25610
26875
  constructor(runtime, node) {
25611
26876
  this.#runtime = runtime;
25612
26877
  this.#node = node;
@@ -25664,6 +26929,10 @@ var NodeBinding = class {
25664
26929
  const dataElement = node._getMeta("data_element");
25665
26930
  if (dataElement && !PROVIDERS[node.nodeTag]) return;
25666
26931
  if (!dataElement && typeof node.getAttr("remote") === "string") this.#remote ??= new RemoteBinding(this);
26932
+ const remoteDependencies = /* @__PURE__ */ new Set();
26933
+ if (this.remote) for (const [name, raw] of Object.entries(node.getAttr())) {
26934
+ if (name.startsWith("remote_")) for (const dependency of pointerDependencies(node, raw)) remoteDependencies.add(dependency);
26935
+ }
25667
26936
  for (const [name, pointer] of node.pointers()) {
25668
26937
  if (dataElement && name !== "datapath") continue;
25669
26938
  const context = name === "datapath" ? node.parentNode : node;
@@ -25672,8 +26941,8 @@ var NodeBinding = class {
25672
26941
  const [path, attr = null] = absolute.split("?", 2);
25673
26942
  const registration = this.runtime.router.register({ path, attr, recipient: this });
25674
26943
  this.#registrations.push(registration);
25675
- if (name === "datapath") this.#datapathRegistration = registration;
25676
- if (this.remote && (name === "remote" || name.startsWith("remote_"))) this.#remoteRegistrations.add(registration);
26944
+ if (name === "datapath") this.#datapathRegistrations.add(registration);
26945
+ if (this.remote && (name === "remote" || name.startsWith("remote_") || remoteDependencies.has(name))) this.#remoteRegistrations.add(registration);
25677
26946
  }
25678
26947
  if (!dataElement) {
25679
26948
  this.#registerTopics();
@@ -25715,7 +26984,7 @@ var NodeBinding = class {
25715
26984
  * after a registration of `remote` or of a `remote_<k>` parameter requested the fragment again.
25716
26985
  */
25717
26986
  receive(change) {
25718
- if (change.registration === this.#datapathRegistration) {
26987
+ if (this.#datapathRegistrations.has(change.registration)) {
25719
26988
  this.runtime.rebindBranch(this.node);
25720
26989
  return;
25721
26990
  }
@@ -25749,7 +27018,7 @@ var NodeBinding = class {
25749
27018
  }
25750
27019
  #closeRegistrations() {
25751
27020
  for (const registration of this.#registrations.splice(0)) registration.close();
25752
- this.#datapathRegistration = null;
27021
+ this.#datapathRegistrations.clear();
25753
27022
  this.#remoteRegistrations.clear();
25754
27023
  }
25755
27024
  };
@@ -25763,6 +27032,8 @@ var GramlotRenderer = class extends GramlotHtmlRenderer {
25763
27032
  #resolvedAttributes = /* @__PURE__ */ new WeakMap();
25764
27033
  // The resolved projection that `project` hands to the rebuild of a control whose shape changed.
25765
27034
  #rebuildAttributes = /* @__PURE__ */ new WeakMap();
27035
+ // Own presentation defaults, resolved once in their declaring Source scope.
27036
+ #presentationDefaults = /* @__PURE__ */ new WeakMap();
25766
27037
  /** The live renderer of one Gramlot page: `binding` is the page's BindingRuntime (§4.3). */
25767
27038
  constructor(builder, source, destination, { binding } = {}) {
25768
27039
  super(builder);
@@ -25803,7 +27074,19 @@ var GramlotRenderer = class extends GramlotHtmlRenderer {
25803
27074
  * its `==` are evaluated once.
25804
27075
  */
25805
27076
  evaluateExpressions(node, runtimeAttrs) {
25806
- const attrs = this.#rebuildAttributes.get(node) ?? super.evaluateExpressions(node, runtimeAttrs);
27077
+ let attrs = this.#rebuildAttributes.get(node) ?? super.evaluateExpressions(node, runtimeAttrs);
27078
+ const component = node._getMeta("gramlot_component");
27079
+ if (component?.presentationDefaults.length) {
27080
+ const declared = node.getAttr();
27081
+ this.#presentationDefaults.set(node, Object.fromEntries(Object.entries(attrs).filter(([name]) => Object.hasOwn(declared, name) && component.presentationDefaults.some((prefix) => name.startsWith(prefix)))));
27082
+ }
27083
+ if (component && (component.parameters.value?.binding === "twoWay" || component.presentationDefaults.length)) {
27084
+ const ancestors = [];
27085
+ for (let parent = node.parentNode; parent; parent = parent.parentNode) {
27086
+ if (this.#presentationDefaults.has(parent)) ancestors.unshift(this.#presentationDefaults.get(parent));
27087
+ }
27088
+ attrs = Object.assign({}, ...ancestors, attrs);
27089
+ }
25807
27090
  this.#rebuildAttributes.delete(node);
25808
27091
  this.#resolvedAttributes.set(node, attrs);
25809
27092
  return attrs;
@@ -25864,8 +27147,14 @@ var GramlotRenderer = class extends GramlotHtmlRenderer {
25864
27147
  let attrs = runtimeAttrs;
25865
27148
  item = this.expressionValue(node, item);
25866
27149
  if (this.getRender(node.builder) === this) {
25867
- [item, attrs] = displayItem(item, this.restoreNativeAttributes(node, runtimeAttrs));
27150
+ attrs = this.restoreNativeAttributes(node, runtimeAttrs);
27151
+ if (!node._getMeta("gramlot_component")) [item, attrs] = displayItem(
27152
+ item,
27153
+ attrs,
27154
+ (value, options) => this._binding.gramlot.format(value, options)
27155
+ );
25868
27156
  }
27157
+ attrs = this.componentAttributes(node, attrs);
25869
27158
  const children = Array.isArray(item) ? item : [];
25870
27159
  const text = Array.isArray(item) ? attrs._text : item;
25871
27160
  const resolved2 = this.#resolvedAttributes.get(node);
@@ -26186,6 +27475,7 @@ var GramlotRenderer = class extends GramlotHtmlRenderer {
26186
27475
  const record2 = this.records.get(node);
26187
27476
  if (!record2?.element) return;
26188
27477
  const renderer = this.getRender(node.builder);
27478
+ const previousDefaults = this.#presentationDefaults.get(node);
26189
27479
  const [value, runtimeAttrs] = node.builder.runtimeValues(node);
26190
27480
  const [, resolvedAttrs] = renderer._handleMeta(node, runtimeAttrs);
26191
27481
  const resolved2 = this.#resolvedAttributes.get(node);
@@ -26203,16 +27493,52 @@ var GramlotRenderer = class extends GramlotHtmlRenderer {
26203
27493
  let attrs = node._getMeta("subbuilder") ? resolvedAttrs : renderer.adaptAttrs(resolvedAttrs);
26204
27494
  const branch = node.value instanceof SourceBag;
26205
27495
  let text = branch ? [] : this.expressionValue(node, value);
26206
- if (renderer === this) [text, attrs] = displayItem(text, this.restoreNativeAttributes(node, attrs));
27496
+ if (renderer === this) {
27497
+ attrs = this.restoreNativeAttributes(node, attrs);
27498
+ if (!node._getMeta("gramlot_component")) [text, attrs] = displayItem(
27499
+ text,
27500
+ attrs,
27501
+ (value2, options) => this._binding.gramlot.format(value2, options)
27502
+ );
27503
+ }
27504
+ attrs = this.componentAttributes(node, attrs);
26207
27505
  this.html.update(record2, node, attrs, branch ? attrs._text : text, resolved2.visible ?? null);
26208
27506
  this.#projectControl(record2, node, attrs, change);
26209
27507
  record2.control?.refresh();
26210
27508
  record2.button?.refresh();
26211
27509
  this.#connectEvents(record2);
27510
+ const defaults = this.#presentationDefaults.get(node);
27511
+ if (defaults) {
27512
+ const changed = new Set([...Object.keys(previousDefaults ?? {}), ...Object.keys(defaults)].filter((name) => !Object.is(previousDefaults?.[name], defaults[name])));
27513
+ if (changed.size) this.#refreshPresentation(node, changed);
27514
+ }
26212
27515
  if (record2.element.localName === "option" || record2.element.localName === "optgroup") {
26213
27516
  this.#optionsChanged(record2.parent);
26214
27517
  }
26215
27518
  }
27519
+ /** Only affected consumers project; nested providers mask their own declared defaults. */
27520
+ #refreshPresentation(parent, changed) {
27521
+ if (!(parent.value instanceof SourceBag)) return;
27522
+ for (const child of parent.value.getNodes()) {
27523
+ const component = child._getMeta("gramlot_component");
27524
+ const declared = child.getAttr();
27525
+ let inherited = changed;
27526
+ if (component?.presentationDefaults.length) {
27527
+ inherited = new Set([...changed].filter((name) => !Object.hasOwn(declared, name)));
27528
+ } else if (component?.parameters.value?.binding === "twoWay" && [...changed].some((name) => !Object.hasOwn(declared, name))) {
27529
+ this.project(child);
27530
+ }
27531
+ if (inherited.size) this.#refreshPresentation(child, inherited);
27532
+ }
27533
+ }
27534
+ /** Component parameters use resolved Source values, before HTML-only filtering (e.g. validate_*). */
27535
+ componentAttributes(node, attrs) {
27536
+ const component = node._getMeta("gramlot_component");
27537
+ if (!component) return attrs;
27538
+ const resolved2 = this.#resolvedAttributes.get(node);
27539
+ const parameters2 = Object.fromEntries([.../* @__PURE__ */ new Set([...Object.keys(component.parameters), ...Object.keys(resolved2).filter((name) => name.startsWith("validate_"))])].filter((name) => Object.hasOwn(resolved2, name)).map((name) => [name, resolved2[name]]));
27540
+ return { ...attrs, ...parameters2 };
27541
+ }
26216
27542
  /**
26217
27543
  * The resolved `value` to the ControlAdapter of `record` when the node declares a `value`, or declared
26218
27544
  * one at the previous projection: its removal shows the control empty once, as html.js did (S10).
@@ -26342,6 +27668,8 @@ var GramlotRenderer = class extends GramlotHtmlRenderer {
26342
27668
  record2.end?.remove();
26343
27669
  record2.parent?.children.delete(node);
26344
27670
  this.records.delete(node);
27671
+ this.#resolvedAttributes.delete(node);
27672
+ this.#presentationDefaults.delete(node);
26345
27673
  if (errors.length) throw new AggregateError(errors, "Source cleanup failed");
26346
27674
  }
26347
27675
  dispose() {
@@ -26722,6 +28050,13 @@ var RpcHandler = class extends Handler {
26722
28050
 
26723
28051
  // src/handlers/dom-handler.js
26724
28052
  var DomHandler = class extends Handler {
28053
+ /** Size controls for the input device without rebuilding the page. */
28054
+ setTouchMode(mode = "auto") {
28055
+ if (!["auto", "on", "off"].includes(mode)) throw new TypeError(`Invalid touch mode: ${mode}`);
28056
+ const root = this.gramlot.src.renderer.destination.ownerDocument.documentElement;
28057
+ if (mode === "auto") root.removeAttribute("data-gramlot-touch");
28058
+ else root.setAttribute("data-gramlot-touch", mode);
28059
+ }
26725
28060
  reference(descriptor) {
26726
28061
  return this.gramlot.src.renderer.references.resolve(descriptor);
26727
28062
  }
@@ -27121,9 +28456,20 @@ var Gramlot = class {
27121
28456
  element = null,
27122
28457
  document = element?.ownerDocument ?? globalThis.document,
27123
28458
  transport = null,
27124
- collections = []
28459
+ collections = [],
28460
+ locale = null,
28461
+ timeZone = null,
28462
+ devices = []
27125
28463
  } = {}) {
28464
+ buttons_default.register(document.defaultView);
28465
+ for (const collection of collections) {
28466
+ if (collection instanceof ComponentCollection) collection.register(document.defaultView);
28467
+ }
27126
28468
  this.pageId = pageId;
28469
+ const browserContext = locale == null || timeZone == null ? document.defaultView.Intl.DateTimeFormat().resolvedOptions() : null;
28470
+ this.devices = Object.freeze([...devices]);
28471
+ this.locale = locale ?? browserContext.locale;
28472
+ this.timeZone = timeZone ?? browserContext.timeZone;
27127
28473
  Object.defineProperty(this, "_subscriptions", { value: new SubscriptionsHandler(this) });
27128
28474
  this.capabilities = Object.freeze([...capabilities]);
27129
28475
  this.src = new SourceHandler(this, { collections, destination: element ?? document.getElementById(rootId) });
@@ -27151,6 +28497,9 @@ var Gramlot = class {
27151
28497
  unsubscribe(registration) {
27152
28498
  this._subscriptions.unsubscribe(registration);
27153
28499
  }
28500
+ format(value, options) {
28501
+ return formatValue(value, options, { locale: this.locale, timeZone: this.timeZone });
28502
+ }
27154
28503
  start() {
27155
28504
  if (this.state === "disposed") return Promise.reject(new Error("Gramlot is disposed"));
27156
28505
  if (!this.rpc.transport) return Promise.reject(new Error("This Gramlot instance has no server transport"));
@@ -27222,7 +28571,7 @@ var PageBootstrap = class {
27222
28571
  this.closePage();
27223
28572
  };
27224
28573
  window2.addEventListener("pagehide", pagehide);
27225
- let entries;
28574
+ let entries, collections;
27226
28575
  try {
27227
28576
  const settled = await Promise.allSettled(resources.js.map(({ url }) => import(new URL(url, document.baseURI).href)));
27228
28577
  if (closed) return null;
@@ -27234,13 +28583,26 @@ var PageBootstrap = class {
27234
28583
  return { logicClass: outcome.value.Logic, group, resource: url };
27235
28584
  });
27236
28585
  LogicRegistry.check(entries);
28586
+ collections = await Promise.all((resources.collections ?? []).map(async (url) => {
28587
+ try {
28588
+ return (await import(new URL(url, document.baseURI).href)).default;
28589
+ } catch (error) {
28590
+ throw new Error(`${url}: collection import failed: ${error.message}`, { cause: error });
28591
+ }
28592
+ }));
28593
+ if (closed) return null;
28594
+ for (const collection of collections) collection.register(window2);
27237
28595
  } catch (error) {
27238
28596
  this.closePage();
27239
28597
  throw error;
27240
28598
  } finally {
27241
28599
  window2.removeEventListener("pagehide", pagehide);
27242
28600
  }
27243
- const app = new Gramlot({ ...config2, document });
28601
+ const app = new Gramlot({
28602
+ ...config2,
28603
+ document,
28604
+ collections: [...config2.collections ?? [], ...collections.map((collection) => collection.toDocument())]
28605
+ });
27244
28606
  for (const { logicClass, group, resource } of entries) app.src.logicRegistry.register(logicClass, { group, resource });
27245
28607
  window2.gramlot = app;
27246
28608
  await app.start();
@@ -27274,6 +28636,9 @@ function declare(PageClass, methodName, marker, auth) {
27274
28636
  }
27275
28637
  var Page = class {
27276
28638
  static title = "Gramlot";
28639
+ static devices = [];
28640
+ static locale = null;
28641
+ static timeZone = null;
27277
28642
  static installable = false;
27278
28643
  static appIcon = null;
27279
28644
  /** Default root manifest. appIcon is a 512px square PNG below the app root. */
@@ -27324,6 +28689,7 @@ var IndexPage = class extends Page {
27324
28689
  main(root) {
27325
28690
  const families = this.constructor.navigation;
27326
28691
  const shell = root.div({ class: "index-shell", id: this.constructor.shellId });
28692
+ this.header(shell);
27327
28693
  const sidebar = shell.aside({ class: "index-sidebar", id: "index-sidebar" });
27328
28694
  const brand = sidebar.header();
27329
28695
  if (this.constructor.logoUrl) brand.img({ src: this.constructor.logoUrl, alt: this.constructor.title, class: "index-logo" });
@@ -27362,7 +28728,7 @@ var IndexPage = class extends Page {
27362
28728
  });
27363
28729
  const content = shell.main({ class: "index-main" });
27364
28730
  const tabs = content.div({ class: "index-tabs", role: "tablist", aria_label: "Open pages" });
27365
- tabs.button("Introduction", {
28731
+ tabs.html_button("Introduction", {
27366
28732
  type: "button",
27367
28733
  role: "tab",
27368
28734
  id: "tab-intro",
@@ -27373,7 +28739,7 @@ var IndexPage = class extends Page {
27373
28739
  });
27374
28740
  for (const family of families) {
27375
28741
  for (const { key, title } of [family, ...family.children]) {
27376
- tabs.button(title, {
28742
+ tabs.html_button(title, {
27377
28743
  type: "button",
27378
28744
  role: "tab",
27379
28745
  id: `tab-${key}`,
@@ -27408,6 +28774,8 @@ var IndexPage = class extends Page {
27408
28774
  this.footer(footer);
27409
28775
  this.behavior(shell);
27410
28776
  }
28777
+ header(shell) {
28778
+ }
27411
28779
  behavior(shell) {
27412
28780
  shell.dataController({ func: "indexMount", _onStart: true, shell_id: this.constructor.shellId });
27413
28781
  }
@@ -27424,6 +28792,8 @@ var IndexPage = class extends Page {
27424
28792
  const appearance = theme.select({ id: "index-appearance", value: "compact" });
27425
28793
  appearance.option("Base", { value: "base", selected: false });
27426
28794
  appearance.option("Compact", { value: "compact", selected: true });
28795
+ appearance.option("mimi", { value: "mimi" });
28796
+ appearance.option("joanna", { value: "joanna" });
27427
28797
  const color = footer.div({ class: "index-theme" });
27428
28798
  color.html_label("Color mode", { for: "index-theme" });
27429
28799
  const choices = color.select({ id: "index-theme", value: "light" });
@@ -27436,7 +28806,7 @@ var IndexPage = class extends Page {
27436
28806
  if (this.constructor.installable) {
27437
28807
  const app = footer.details({ class: "index-install" });
27438
28808
  app.summary("Install app");
27439
- app.button("Install", { type: "button", id: "index-install-button", hidden: true });
28809
+ app.html_button("Install", { type: "button", id: "index-install-button", hidden: true });
27440
28810
  app.p("", { id: "index-install-status", role: "status" });
27441
28811
  app.p("Chrome: use Install page as app in the browser menu. Safari on macOS Sonoma or later: File > Add to Dock.");
27442
28812
  app.p("Use HTTPS or localhost. For a static export, serve the directory; direct file opening is not installable. Keep the server running for hosted pages.");
@@ -27455,13 +28825,13 @@ var IndexPage = class extends Page {
27455
28825
  };
27456
28826
 
27457
28827
  // src/index-page-styles.js
27458
- var compactStyle = '/* Gramlot Compact: load after gramlot-base/theme.css. Colors and behavior stay in Base. */\n@layer gramlot.tokens {\n :root {\n --gramlot-space-1: .2rem;\n --gramlot-space-2: .4rem;\n --gramlot-space-3: .5rem;\n --gramlot-space-4: .6rem;\n --gramlot-space-6: .9rem;\n --gramlot-space-8: 1.2rem;\n --gramlot-space-12: 1.8rem;\n --gramlot-radius-sm: .25rem;\n --gramlot-radius: .35rem;\n --gramlot-radius-lg: .4rem;\n }\n}\n\n@layer gramlot.base {\n html { font-size: 13px; }\n body { line-height: 1.35; }\n :where(h1, h2, h3, h4, h5, h6, p, ul, ol, dl, blockquote, pre, figure) { margin-block: 0 .5rem; }\n h1 { font-size: 1.35rem; }\n h2 { font-size: 1.15rem; }\n h3 { font-size: 1.05rem; }\n pre { padding: .5rem; }\n blockquote { padding-inline-start: .6rem; }\n hr { margin-block: 1rem; }\n}\n\n@layer gramlot.components {\n :where(button, input[type="button"], input[type="submit"], input[type="reset"], .button) {\n min-block-size: 28px;\n padding: .25rem .5rem;\n font-size: 1rem;\n line-height: 1.35;\n }\n :where(label) { font-size: .95rem; }\n :where(input:not([type="button"]):not([type="submit"]):not([type="reset"]):not([type="checkbox"]):not([type="radio"]):not([type="range"]):not([type="color"]):not([type="file"]):not([type="hidden"]), select, textarea) {\n min-block-size: 28px;\n padding: .25rem .5rem;\n font-size: 1rem;\n line-height: 1.35;\n }\n :where(textarea) { min-block-size: 5rem; }\n :where(input[type="color"]) { min-block-size: 28px; }\n :where(input[type="file"])::file-selector-button { margin-inline-end: .5rem; padding: .25rem .5rem; }\n :where(fieldset) { margin-block-end: .6rem; padding: .5rem; }\n :where(table) { font-size: 1rem; }\n :where(th, td) { padding: .4rem .5rem; }\n :where(details) { padding: .4rem .5rem; }\n :where(details[open] > summary) { margin-block-end: .5rem; }\n :where(dialog) { padding: .75rem; }\n}\n\n@layer gramlot.utilities {\n .example-page { inline-size: min(100% - 1.2rem, var(--gramlot-page-width)); padding-block: .6rem; }\n .card { padding: .6rem; box-shadow: none; }\n}\n';
28828
+ var appearanceStyles = { "base": "", "compact": '/* Gramlot Compact: load after gramlot-base/theme.css. Colors and behavior stay in Base. */\n@layer gramlot.tokens {\n :root {\n --gramlot-field-height: 28px;\n --gramlot-field-line-height: 1.35;\n --gramlot-field-padding: .25rem .5rem;\n --gramlot-field-font-size: 1rem;\n --gramlot-space-1: .2rem;\n --gramlot-space-2: .4rem;\n --gramlot-space-3: .5rem;\n --gramlot-space-4: .6rem;\n --gramlot-space-6: .9rem;\n --gramlot-space-8: 1.2rem;\n --gramlot-space-12: 1.8rem;\n --gramlot-radius-sm: .25rem;\n --gramlot-radius: .35rem;\n --gramlot-radius-lg: .4rem;\n }\n}\n\n@layer gramlot.base {\n html { font-size: 13px; }\n body { line-height: 1.35; }\n :where(h1, h2, h3, h4, h5, h6, p, ul, ol, dl, blockquote, pre, figure) { margin-block: 0 .5rem; }\n h1 { font-size: 1.35rem; }\n h2 { font-size: 1.15rem; }\n h3 { font-size: 1.05rem; }\n pre { padding: .5rem; }\n blockquote { padding-inline-start: .6rem; }\n hr { margin-block: 1rem; }\n}\n\n@layer gramlot.components {\n :where(button, input[type="button"], input[type="submit"], input[type="reset"], .button) {\n min-block-size: 28px;\n padding: .25rem .5rem;\n font-size: 1rem;\n line-height: 1.35;\n }\n :where(label) { font-size: .95rem; }\n :where(input:not([type="button"]):not([type="submit"]):not([type="reset"]):not([type="checkbox"]):not([type="radio"]):not([type="range"]):not([type="color"]):not([type="file"]):not([type="hidden"]), select, textarea) {\n min-block-size: var(--gramlot-field-height);\n padding: var(--gramlot-field-padding);\n font-size: var(--gramlot-field-font-size);\n line-height: var(--gramlot-field-line-height);\n }\n :where(textarea) { min-block-size: 5rem; }\n :where(input[type="color"]) { min-block-size: 28px; }\n :where(input[type="file"])::file-selector-button { margin-inline-end: .5rem; padding: .25rem .5rem; }\n :where(fieldset) { margin-block-end: .6rem; padding: .5rem; }\n :where(table) { font-size: 1rem; }\n :where(th, td) { padding: .4rem .5rem; }\n :where(details) { padding: .4rem .5rem; }\n :where(details[open] > summary) { margin-block-end: .5rem; }\n :where(dialog) { padding: .75rem; }\n}\n\n@layer gramlot.utilities {\n .example-page { inline-size: min(100% - 1.2rem, var(--gramlot-page-width)); padding-block: .6rem; }\n .card { padding: .6rem; box-shadow: none; }\n}\n', "mimi": '/* Gramlot Compact: load after gramlot-base/theme.css. Colors and behavior stay in Base. */\n@layer gramlot.tokens {\n :root {\n --gramlot-field-height: 28px;\n --gramlot-field-line-height: 1.35;\n --gramlot-field-padding: .25rem .5rem;\n --gramlot-field-font-size: 1rem;\n --gramlot-space-1: .2rem;\n --gramlot-space-2: .4rem;\n --gramlot-space-3: .5rem;\n --gramlot-space-4: .6rem;\n --gramlot-space-6: .9rem;\n --gramlot-space-8: 1.2rem;\n --gramlot-space-12: 1.8rem;\n --gramlot-radius-sm: .25rem;\n --gramlot-radius: .35rem;\n --gramlot-radius-lg: .4rem;\n }\n}\n\n@layer gramlot.base {\n html { font-size: 13px; }\n body { line-height: 1.35; }\n :where(h1, h2, h3, h4, h5, h6, p, ul, ol, dl, blockquote, pre, figure) { margin-block: 0 .5rem; }\n h1 { font-size: 1.35rem; }\n h2 { font-size: 1.15rem; }\n h3 { font-size: 1.05rem; }\n pre { padding: .5rem; }\n blockquote { padding-inline-start: .6rem; }\n hr { margin-block: 1rem; }\n}\n\n@layer gramlot.components {\n :where(button, input[type="button"], input[type="submit"], input[type="reset"], .button) {\n min-block-size: 28px;\n padding: .25rem .5rem;\n font-size: 1rem;\n line-height: 1.35;\n }\n :where(label) { font-size: .95rem; }\n :where(input:not([type="button"]):not([type="submit"]):not([type="reset"]):not([type="checkbox"]):not([type="radio"]):not([type="range"]):not([type="color"]):not([type="file"]):not([type="hidden"]), select, textarea) {\n min-block-size: var(--gramlot-field-height);\n padding: var(--gramlot-field-padding);\n font-size: var(--gramlot-field-font-size);\n line-height: var(--gramlot-field-line-height);\n }\n :where(textarea) { min-block-size: 5rem; }\n :where(input[type="color"]) { min-block-size: 28px; }\n :where(input[type="file"])::file-selector-button { margin-inline-end: .5rem; padding: .25rem .5rem; }\n :where(fieldset) { margin-block-end: .6rem; padding: .5rem; }\n :where(table) { font-size: 1rem; }\n :where(th, td) { padding: .4rem .5rem; }\n :where(details) { padding: .4rem .5rem; }\n :where(details[open] > summary) { margin-block-end: .5rem; }\n :where(dialog) { padding: .75rem; }\n}\n\n@layer gramlot.utilities {\n .example-page { inline-size: min(100% - 1.2rem, var(--gramlot-page-width)); padding-block: .6rem; }\n .card { padding: .6rem; box-shadow: none; }\n}\n\n/* Gramlot adaptation of legacy mimi; load after Base and Compact. */\n@layer gramlot.tokens {\n :root {\n --gramlot-background: #EDEEF0;\n --gramlot-surface: #F5F5F6;\n --gramlot-surface-subtle: #E0E1E3;\n --gramlot-ink: #3C3D40;\n --gramlot-text-secondary: #6B6E72;\n --gramlot-border: #BDBFC2;\n --gramlot-border-control: #9EA0A3;\n --gramlot-navigation: #48494C;\n --gramlot-navigation-text: #FFFFFF;\n --gramlot-action: #0071E3;\n --gramlot-action-hover: #005BBB;\n --gramlot-brand-blue: #0071E3;\n --gramlot-brand-yellow: #9EA0A3;\n --gramlot-selected: #E8F1FC;\n --gramlot-focus-ring: #0071E3;\n --gramlot-field-background: #FFFFFF;\n --gramlot-field-readonly-background: #E0E1E3;\n --gramlot-error: #B3261E;\n --gramlot-error-background: #FFF1F0;\n --gramlot-shadow: 0 1px 4px rgb(0 0 0 / 6%);\n --gramlot-radius-sm: 4px;\n --gramlot-radius: 3px;\n --gramlot-radius-lg: 3px;\n --gramlot-field-height: 18px;\n --gramlot-field-padding: 1px 3px;\n --gramlot-field-line-height: 1.15;\n --gramlot-field-font-size: 1rem;\n --gramlot-label-size: .9em;\n --gramlot-label-gap: 2px;\n --gramlot-label-color: var(--gramlot-text-secondary);\n --gramlot-space-4: 6px;\n --gramlot-font-ui: -apple-system, BlinkMacSystemFont, "Helvetica Neue", Arial, sans-serif;\n }\n @media (prefers-color-scheme: dark) {\n :root:not([data-theme="light"]) {\n --gramlot-background: #242527;\n --gramlot-surface: #303134;\n --gramlot-surface-subtle: #3C3D40;\n --gramlot-ink: #F2F2F7;\n --gramlot-text-secondary: #C7C7CC;\n --gramlot-border: #6B6E72;\n --gramlot-border-control: #8E8E93;\n --gramlot-navigation: #1C1C1E;\n --gramlot-action: #78B7FF;\n --gramlot-action-hover: #A6CFFF;\n --gramlot-brand-blue: #3478CA;\n --gramlot-selected: #254163;\n --gramlot-focus-ring: #78B7FF;\n --gramlot-field-background: #202124;\n --gramlot-field-readonly-background: #3C3D40;\n --gramlot-error: #FFB4AB;\n --gramlot-error-background: #482524;\n --gramlot-shadow: 0 1px 4px rgb(0 0 0 / 20%);\n }\n }\n :root[data-theme="dark"] {\n --gramlot-background: #242527;\n --gramlot-surface: #303134;\n --gramlot-surface-subtle: #3C3D40;\n --gramlot-ink: #F2F2F7;\n --gramlot-text-secondary: #C7C7CC;\n --gramlot-border: #6B6E72;\n --gramlot-border-control: #8E8E93;\n --gramlot-navigation: #1C1C1E;\n --gramlot-action: #78B7FF;\n --gramlot-action-hover: #A6CFFF;\n --gramlot-brand-blue: #3478CA;\n --gramlot-selected: #254163;\n --gramlot-focus-ring: #78B7FF;\n --gramlot-field-background: #202124;\n --gramlot-field-readonly-background: #3C3D40;\n --gramlot-error: #FFB4AB;\n --gramlot-error-background: #482524;\n --gramlot-shadow: 0 1px 4px rgb(0 0 0 / 20%);\n }\n}\n@layer gramlot.base {\n html { font-size: 12px; }\n}\n@layer gramlot.components {\n :where(label) { font-size: var(--gramlot-label-size); font-weight: normal; color: var(--gramlot-label-color); margin-block-end: var(--gramlot-label-gap); }\n :where(button, input[type="button"], input[type="submit"], input[type="reset"], .button) { min-block-size: 24px; padding: 2px 8px; font-weight: 500; }\n}\n@layer gramlot.utilities {\n .card { box-shadow: var(--gramlot-shadow); }\n}\n', "joanna": '/* Gramlot Compact: load after gramlot-base/theme.css. Colors and behavior stay in Base. */\n@layer gramlot.tokens {\n :root {\n --gramlot-field-height: 28px;\n --gramlot-field-line-height: 1.35;\n --gramlot-field-padding: .25rem .5rem;\n --gramlot-field-font-size: 1rem;\n --gramlot-space-1: .2rem;\n --gramlot-space-2: .4rem;\n --gramlot-space-3: .5rem;\n --gramlot-space-4: .6rem;\n --gramlot-space-6: .9rem;\n --gramlot-space-8: 1.2rem;\n --gramlot-space-12: 1.8rem;\n --gramlot-radius-sm: .25rem;\n --gramlot-radius: .35rem;\n --gramlot-radius-lg: .4rem;\n }\n}\n\n@layer gramlot.base {\n html { font-size: 13px; }\n body { line-height: 1.35; }\n :where(h1, h2, h3, h4, h5, h6, p, ul, ol, dl, blockquote, pre, figure) { margin-block: 0 .5rem; }\n h1 { font-size: 1.35rem; }\n h2 { font-size: 1.15rem; }\n h3 { font-size: 1.05rem; }\n pre { padding: .5rem; }\n blockquote { padding-inline-start: .6rem; }\n hr { margin-block: 1rem; }\n}\n\n@layer gramlot.components {\n :where(button, input[type="button"], input[type="submit"], input[type="reset"], .button) {\n min-block-size: 28px;\n padding: .25rem .5rem;\n font-size: 1rem;\n line-height: 1.35;\n }\n :where(label) { font-size: .95rem; }\n :where(input:not([type="button"]):not([type="submit"]):not([type="reset"]):not([type="checkbox"]):not([type="radio"]):not([type="range"]):not([type="color"]):not([type="file"]):not([type="hidden"]), select, textarea) {\n min-block-size: var(--gramlot-field-height);\n padding: var(--gramlot-field-padding);\n font-size: var(--gramlot-field-font-size);\n line-height: var(--gramlot-field-line-height);\n }\n :where(textarea) { min-block-size: 5rem; }\n :where(input[type="color"]) { min-block-size: 28px; }\n :where(input[type="file"])::file-selector-button { margin-inline-end: .5rem; padding: .25rem .5rem; }\n :where(fieldset) { margin-block-end: .6rem; padding: .5rem; }\n :where(table) { font-size: 1rem; }\n :where(th, td) { padding: .4rem .5rem; }\n :where(details) { padding: .4rem .5rem; }\n :where(details[open] > summary) { margin-block-end: .5rem; }\n :where(dialog) { padding: .75rem; }\n}\n\n@layer gramlot.utilities {\n .example-page { inline-size: min(100% - 1.2rem, var(--gramlot-page-width)); padding-block: .6rem; }\n .card { padding: .6rem; box-shadow: none; }\n}\n\n/* Gramlot adaptation of legacy joanna; load after Base and Compact. */\n@layer gramlot.tokens {\n :root {\n --gramlot-background: #F2F2F7;\n --gramlot-surface: #FFFFFF;\n --gramlot-surface-subtle: #F2F2F7;\n --gramlot-ink: #3A3A3C;\n --gramlot-text-secondary: #636366;\n --gramlot-border: #D1D1D6;\n --gramlot-border-control: #AEAEB2;\n --gramlot-navigation: #3A3A3C;\n --gramlot-navigation-text: #FFFFFF;\n --gramlot-action: #007AFF;\n --gramlot-action-hover: #0061CC;\n --gramlot-brand-blue: #007AFF;\n --gramlot-brand-yellow: #AEAEB2;\n --gramlot-selected: #E0EFFF;\n --gramlot-focus-ring: #007AFF;\n --gramlot-field-background: #FFFFFF;\n --gramlot-field-readonly-background: #F2F2F7;\n --gramlot-error: #B3261E;\n --gramlot-error-background: #FFF1F0;\n --gramlot-shadow: 0 1px 4px rgb(0 0 0 / 6%);\n --gramlot-radius-sm: 6px;\n --gramlot-radius: 6px;\n --gramlot-radius-lg: 6px;\n --gramlot-field-height: 20px;\n --gramlot-field-padding: 1px 3px;\n --gramlot-field-line-height: 1.15;\n --gramlot-field-font-size: 1rem;\n --gramlot-label-size: .8em;\n --gramlot-label-gap: 2px;\n --gramlot-label-color: var(--gramlot-text-secondary);\n --gramlot-space-4: 6px;\n --gramlot-font-ui: -apple-system, BlinkMacSystemFont, "Helvetica Neue", Arial, sans-serif;\n }\n @media (prefers-color-scheme: dark) {\n :root:not([data-theme="light"]) {\n --gramlot-background: #1C1C1E;\n --gramlot-surface: #2C2C2E;\n --gramlot-surface-subtle: #3A3A3C;\n --gramlot-ink: #F2F2F7;\n --gramlot-text-secondary: #C7C7CC;\n --gramlot-border: #636366;\n --gramlot-border-control: #8E8E93;\n --gramlot-navigation: #1C1C1E;\n --gramlot-action: #78B7FF;\n --gramlot-action-hover: #A6CFFF;\n --gramlot-brand-blue: #3478CA;\n --gramlot-selected: #254163;\n --gramlot-focus-ring: #78B7FF;\n --gramlot-field-background: #202124;\n --gramlot-field-readonly-background: #3A3A3C;\n --gramlot-error: #FFB4AB;\n --gramlot-error-background: #482524;\n --gramlot-shadow: 0 1px 4px rgb(0 0 0 / 20%);\n }\n }\n :root[data-theme="dark"] {\n --gramlot-background: #1C1C1E;\n --gramlot-surface: #2C2C2E;\n --gramlot-surface-subtle: #3A3A3C;\n --gramlot-ink: #F2F2F7;\n --gramlot-text-secondary: #C7C7CC;\n --gramlot-border: #636366;\n --gramlot-border-control: #8E8E93;\n --gramlot-navigation: #1C1C1E;\n --gramlot-action: #78B7FF;\n --gramlot-action-hover: #A6CFFF;\n --gramlot-brand-blue: #3478CA;\n --gramlot-selected: #254163;\n --gramlot-focus-ring: #78B7FF;\n --gramlot-field-background: #202124;\n --gramlot-field-readonly-background: #3A3A3C;\n --gramlot-error: #FFB4AB;\n --gramlot-error-background: #482524;\n --gramlot-shadow: 0 1px 4px rgb(0 0 0 / 20%);\n }\n}\n@layer gramlot.base {\n html { font-size: 13px; }\n}\n@layer gramlot.components {\n :where(label) { font-size: var(--gramlot-label-size); font-weight: normal; color: var(--gramlot-label-color); margin-block-end: var(--gramlot-label-gap); }\n :where(button, input[type="button"], input[type="submit"], input[type="reset"], .button) { min-block-size: 26px; padding: 2px 8px; font-weight: 500; }\n}\n@layer gramlot.utilities {\n .card { box-shadow: var(--gramlot-shadow); }\n}\n' };
27459
28829
 
27460
28830
  // src/index-theme.js
27461
28831
  var THEME_READY = "index:theme-ready";
27462
28832
  var THEME_SET = "index:theme-set";
27463
28833
  var THEMES = /* @__PURE__ */ new Set(["light", "dark"]);
27464
- var APPEARANCES = /* @__PURE__ */ new Set(["base", "compact"]);
28834
+ var APPEARANCES = /* @__PURE__ */ new Set(["base", "compact", "mimi", "joanna"]);
27465
28835
 
27466
28836
  // src/index-page-runtime.js
27467
28837
  function mountIndexPage(renderer, root, onSelection = () => {
@@ -27478,6 +28848,10 @@ function mountIndexPage(renderer, root, onSelection = () => {
27478
28848
  const appearance = byId("index-appearance");
27479
28849
  const sidebar = byId("index-sidebar");
27480
28850
  const sidebarHandle = byId("index-sidebar-divider");
28851
+ const navigationToggle = byId("index-navigation-toggle");
28852
+ const codeToggle = byId("index-code-toggle");
28853
+ const codeSidebar = byId("index-code");
28854
+ const codeHandle = byId("index-code-divider");
27481
28855
  const preferencesKey = `gramlot.${shell.id}.preferences:${window2.location.pathname}`;
27482
28856
  let preferences = {};
27483
28857
  try {
@@ -27501,12 +28875,17 @@ function mountIndexPage(renderer, root, onSelection = () => {
27501
28875
  state.setItem("keyboard", keyboard?.checked ?? false);
27502
28876
  state.setItem("theme", theme?.value ?? "light");
27503
28877
  state.setItem("appearance", appearance?.value ?? "compact");
28878
+ state.setItem("navigationVisible", preferences.navigationVisible !== false);
28879
+ state.setItem("codeVisible", preferences.codeVisible !== false);
27504
28880
  const savePreferences = () => {
27505
28881
  try {
27506
28882
  window2.localStorage.setItem(preferencesKey, JSON.stringify({
27507
28883
  theme: state.getItem("theme"),
27508
28884
  appearance: state.getItem("appearance"),
27509
- sidebarWidth: state.getItem("preferredSidebarWidth")
28885
+ sidebarWidth: state.getItem("preferredSidebarWidth"),
28886
+ codeWidth: state.getItem("preferredCodeWidth"),
28887
+ navigationVisible: state.getItem("navigationVisible"),
28888
+ codeVisible: state.getItem("codeVisible")
27510
28889
  }));
27511
28890
  } catch (error) {
27512
28891
  if (error.name !== "SecurityError" && error.name !== "QuotaExceededError") throw error;
@@ -27514,7 +28893,7 @@ function mountIndexPage(renderer, root, onSelection = () => {
27514
28893
  };
27515
28894
  const entries = /* @__PURE__ */ new Map();
27516
28895
  const releases = [];
27517
- const style = root.builder.wrapSource(root.value).style(compactStyle, { media: (appearance?.value ?? "compact") === "compact" ? "all" : "not all" });
28896
+ const style = root.builder.wrapSource(root.value).style(appearanceStyles[appearance?.value ?? "compact"]);
27518
28897
  let drag = null;
27519
28898
  let disposed = false;
27520
28899
  let installPrompt = null;
@@ -27544,10 +28923,27 @@ function mountIndexPage(renderer, root, onSelection = () => {
27544
28923
  const send = (frame) => frame.contentWindow.postMessage({ type: THEME_SET, theme: state.getItem("theme"), appearance: state.getItem("appearance") }, "*");
27545
28924
  const applyTheme = () => {
27546
28925
  document.documentElement.setAttribute("data-theme", state.getItem("theme"));
27547
- style.setAttr({ media: state.getItem("appearance") === "compact" ? "all" : "not all" });
28926
+ style.setValue(appearanceStyles[state.getItem("appearance")]);
27548
28927
  for (const { frame } of entries.values()) if (frame) send(frame);
27549
28928
  };
27550
28929
  const updateInspector = () => onSelection(entries, state.getItem("active"));
28930
+ const updatePanels = () => {
28931
+ if (navigationToggle) {
28932
+ const visible = state.getItem("navigationVisible");
28933
+ set(sidebar, { hidden: !visible });
28934
+ set(sidebarHandle, { hidden: !visible });
28935
+ set(navigationToggle, { aria_expanded: String(visible) });
28936
+ set(shell, { data_navigation_hidden: String(!visible) });
28937
+ }
28938
+ if (codeSidebar) {
28939
+ const available = Boolean(entries.get(state.getItem("active"))?.code);
28940
+ const visible = available && state.getItem("codeVisible");
28941
+ set(codeSidebar, { hidden: !visible });
28942
+ set(codeHandle, { hidden: !visible });
28943
+ set(codeToggle, { disabled: !available, aria_expanded: String(visible) });
28944
+ set(shell, { data_code_visible: String(visible) });
28945
+ }
28946
+ };
27551
28947
  function select(key) {
27552
28948
  const entry = entries.get(key);
27553
28949
  if (!opened.getItem(key)) {
@@ -27560,29 +28956,38 @@ function mountIndexPage(renderer, root, onSelection = () => {
27560
28956
  const active = current === key;
27561
28957
  set(item.tab, { aria_selected: String(active), tabindex: active && state.getItem("keyboard") ? 0 : -1 });
27562
28958
  set(item.panel, { hidden: !active });
28959
+ if (item.code) set(item.code, { hidden: !active });
27563
28960
  if (item.open) set(item.open, { aria_current: active ? "page" : null });
27564
28961
  }
27565
28962
  state.setItem("active", key);
28963
+ updatePanels();
27566
28964
  updateInspector();
27567
28965
  }
27568
- function setRatio(entry, value) {
27569
- const ratio = Math.max(20, Math.min(80, value));
27570
- state.setItem(`ratio.${entry.key}`, ratio);
27571
- set(entry.split, { style: `--split-position: ${ratio}%` });
27572
- set(entry.handle, { aria_valuenow: ratio });
27573
- }
27574
28966
  const sidebarMaximum = () => Math.max(120, Math.min(460, Math.floor(window2.innerWidth * 0.6)));
28967
+ const applyWidths = () => set(shell, { style: `--sidebar-width: ${state.getItem("sidebarWidth")}px; --code-width: ${state.getItem("codeWidth") ?? 420}px` });
27575
28968
  const setSidebarWidth = (value, remember = false) => {
27576
28969
  const maximum = sidebarMaximum();
27577
28970
  const width = Math.max(120, Math.min(maximum, value));
27578
28971
  state.setItem("sidebarWidth", width);
27579
- set(shell, { style: `--sidebar-width: ${width}px` });
28972
+ applyWidths();
27580
28973
  set(sidebarHandle, { aria_valuenow: width, aria_valuemax: maximum });
27581
28974
  if (remember) {
27582
28975
  state.setItem("preferredSidebarWidth", width);
27583
28976
  savePreferences();
27584
28977
  }
27585
28978
  };
28979
+ const codeMaximum = () => Math.max(200, Math.floor(window2.innerWidth * 0.6));
28980
+ const setCodeWidth = (value, remember = false) => {
28981
+ const maximum = codeMaximum();
28982
+ const width = Math.max(200, Math.min(maximum, value));
28983
+ state.setItem("codeWidth", width);
28984
+ applyWidths();
28985
+ set(codeHandle, { aria_valuenow: width, aria_valuemax: maximum });
28986
+ if (remember) {
28987
+ state.setItem("preferredCodeWidth", width);
28988
+ savePreferences();
28989
+ }
28990
+ };
27586
28991
  const beginDrag = (handle, event, move) => {
27587
28992
  if (event.button !== 0) return;
27588
28993
  stopDrag();
@@ -27627,6 +29032,38 @@ function mountIndexPage(renderer, root, onSelection = () => {
27627
29032
  const width = typeof savedWidth === "number" && Number.isFinite(savedWidth) && savedWidth >= 120 && savedWidth <= 460 ? savedWidth : sidebar.getBoundingClientRect().width || Number(sidebarHandle.getAttribute("aria-valuenow"));
27628
29033
  state.setItem("preferredSidebarWidth", width);
27629
29034
  setSidebarWidth(width);
29035
+ listen(navigationToggle, "click", () => {
29036
+ state.setItem("navigationVisible", !state.getItem("navigationVisible"));
29037
+ updatePanels();
29038
+ savePreferences();
29039
+ });
29040
+ listen(codeToggle, "click", () => {
29041
+ state.setItem("codeVisible", !state.getItem("codeVisible"));
29042
+ updatePanels();
29043
+ savePreferences();
29044
+ });
29045
+ if (codeHandle) {
29046
+ const saved = preferences.codeWidth;
29047
+ const width2 = typeof saved === "number" && Number.isFinite(saved) && saved >= 200 ? saved : 420;
29048
+ state.setItem("preferredCodeWidth", width2);
29049
+ setCodeWidth(width2);
29050
+ listen(codeHandle, "keydown", (event) => {
29051
+ const current = state.getItem("codeWidth");
29052
+ const value = event.key === "ArrowLeft" ? current + 10 : event.key === "ArrowRight" ? current - 10 : event.key === "Home" ? 200 : event.key === "End" ? codeMaximum() : null;
29053
+ if (value == null) return;
29054
+ event.preventDefault();
29055
+ setCodeWidth(value, true);
29056
+ });
29057
+ listen(codeHandle, "pointerdown", (event) => beginDrag(
29058
+ codeHandle,
29059
+ event,
29060
+ (x) => setCodeWidth(Math.round(shell.getBoundingClientRect().right - x), true)
29061
+ ));
29062
+ listen(codeHandle, "lostpointercapture", () => {
29063
+ if (drag?.handle === codeHandle) stopDrag();
29064
+ });
29065
+ listen(window2, "resize", () => setCodeWidth(state.getItem("preferredCodeWidth")));
29066
+ }
27630
29067
  listen(sidebarHandle, "keydown", (event) => {
27631
29068
  const current = state.getItem("sidebarWidth");
27632
29069
  const value = event.key === "ArrowLeft" ? current - 10 : event.key === "ArrowRight" ? current + 10 : event.key === "Home" ? 120 : event.key === "End" ? sidebarMaximum() : null;
@@ -27649,6 +29086,7 @@ function mountIndexPage(renderer, root, onSelection = () => {
27649
29086
  key,
27650
29087
  tab,
27651
29088
  panel: byId(`panel-${key}`),
29089
+ code: byId(`codepane-${key}`),
27652
29090
  open: key === "intro" ? null : byId(`open-${key}`)
27653
29091
  };
27654
29092
  entries.set(key, entry);
@@ -27673,25 +29111,7 @@ function mountIndexPage(renderer, root, onSelection = () => {
27673
29111
  prepareEntry(entry, { byId, node, set, listen });
27674
29112
  if (entry.panel.classList.contains("index-category")) continue;
27675
29113
  entry.frame = byId(`frame-${key}`);
27676
- entry.split = byId(`split-${key}`);
27677
- entry.handle = byId(`divider-${key}`);
27678
- if (entry.handle) state.setItem(`ratio.${key}`, Number(entry.handle.getAttribute("aria-valuenow")));
27679
29114
  listen(entry.frame, "load", () => send(entry.frame));
27680
- if (!entry.handle) continue;
27681
- listen(entry.handle, "keydown", (event) => {
27682
- const current = state.getItem(`ratio.${key}`);
27683
- const value = event.key === "ArrowLeft" ? current - 5 : event.key === "ArrowRight" ? current + 5 : event.key === "Home" ? 20 : event.key === "End" ? 80 : null;
27684
- if (value == null) return;
27685
- event.preventDefault();
27686
- setRatio(entry, value);
27687
- });
27688
- listen(entry.handle, "pointerdown", (event) => beginDrag(entry.handle, event, (x) => {
27689
- const bounds = entry.split.getBoundingClientRect();
27690
- if (bounds.width > 0) setRatio(entry, Math.round((x - bounds.left) * 100 / bounds.width));
27691
- }));
27692
- listen(entry.handle, "lostpointercapture", () => {
27693
- if (drag?.handle === entry.handle) stopDrag();
27694
- });
27695
29115
  }
27696
29116
  listen(document, "pointermove", (event) => {
27697
29117
  if (!drag || event.pointerId !== drag.pointerId) return;
@@ -27710,7 +29130,7 @@ function mountIndexPage(renderer, root, onSelection = () => {
27710
29130
  }
27711
29131
  });
27712
29132
  listen(appearance, "change", () => {
27713
- if (!APPEARANCES.has(appearance?.value ?? "compact")) throw new Error("Index appearance must be base or compact");
29133
+ if (!APPEARANCES.has(appearance?.value ?? "compact")) throw new Error("Unknown index appearance");
27714
29134
  state.setItem("appearance", appearance?.value ?? "compact");
27715
29135
  set(appearance, { value: appearance?.value ?? "compact" });
27716
29136
  for (const option of appearance.options) set(option, { selected: option.value === (appearance?.value ?? "compact") });
@@ -27736,6 +29156,7 @@ function mountIndexPage(renderer, root, onSelection = () => {
27736
29156
  }
27737
29157
  });
27738
29158
  applyTheme();
29159
+ updatePanels();
27739
29160
  updateInspector();
27740
29161
  renderer.onDispose(root, dispose);
27741
29162
  } catch (error) {
@@ -27751,6 +29172,505 @@ var IndexLogic = class {
27751
29172
  this.index = mountIndexPage(renderer, renderer.elements.get(element).node);
27752
29173
  }
27753
29174
  };
29175
+
29176
+ // src/date-parser/civil.js
29177
+ function daysInMonth(year, month) {
29178
+ if (month === 2) return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : 28;
29179
+ return [4, 6, 9, 11].includes(month) ? 30 : 31;
29180
+ }
29181
+ function civil(year, month, day) {
29182
+ if (![year, month, day].every(Number.isInteger) || year < 1 || year > 9999 || month < 1 || month > 12 || day < 1 || day > daysInMonth(year, month)) {
29183
+ throw new RangeError("Date must exist in Gregorian years 0001\u20139999.");
29184
+ }
29185
+ return `${String(year).padStart(4, "0")}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
29186
+ }
29187
+ function parts(date) {
29188
+ if (typeof date !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(date)) {
29189
+ throw new RangeError("Expected a civil date in YYYY-MM-DD format.");
29190
+ }
29191
+ const result = date.split("-").map(Number);
29192
+ civil(...result);
29193
+ return result;
29194
+ }
29195
+ function ordinal(year, month, day) {
29196
+ const previous = year - 1;
29197
+ let result = 365 * previous + Math.floor(previous / 4) - Math.floor(previous / 100) + Math.floor(previous / 400) + day - 1;
29198
+ for (let m = 1; m < month; m++) result += daysInMonth(year, m);
29199
+ return result;
29200
+ }
29201
+ function addDays(date, offset) {
29202
+ let target = ordinal(...parts(date)) + offset;
29203
+ if (!Number.isSafeInteger(target) || target < 0 || target > ordinal(9999, 12, 31)) {
29204
+ throw new RangeError("Date offset exceeds Gregorian years 0001\u20139999.");
29205
+ }
29206
+ let low = 1, high = 1e4;
29207
+ while (high - low > 1) {
29208
+ const middle = Math.floor((low + high) / 2);
29209
+ if (ordinal(middle, 1, 1) <= target) low = middle;
29210
+ else high = middle;
29211
+ }
29212
+ target -= ordinal(low, 1, 1);
29213
+ let month = 1;
29214
+ while (target >= daysInMonth(low, month)) target -= daysInMonth(low, month++);
29215
+ return civil(low, month, target + 1);
29216
+ }
29217
+ function monday(date) {
29218
+ return addDays(date, -(ordinal(...parts(date)) % 7));
29219
+ }
29220
+ function monthPeriod(year, month, offset = 0, count = 1) {
29221
+ const index = year * 12 + month - 1 + offset;
29222
+ const y = Math.floor(index / 12), m = (index % 12 + 12) % 12 + 1;
29223
+ const endIndex = index + count - 1;
29224
+ const ey = Math.floor(endIndex / 12), em = (endIndex % 12 + 12) % 12 + 1;
29225
+ return { start: civil(y, m, 1), end: civil(ey, em, daysInMonth(ey, em)) };
29226
+ }
29227
+
29228
+ // src/date-parser/locales.js
29229
+ var locales = {
29230
+ "it": {
29231
+ "months": {
29232
+ "gennaio": 1,
29233
+ "febbraio": 2,
29234
+ "marzo": 3,
29235
+ "aprile": 4,
29236
+ "maggio": 5,
29237
+ "giugno": 6,
29238
+ "luglio": 7,
29239
+ "agosto": 8,
29240
+ "settembre": 9,
29241
+ "ottobre": 10,
29242
+ "novembre": 11,
29243
+ "dicembre": 12,
29244
+ "gen": 1,
29245
+ "feb": 2,
29246
+ "mar": 3,
29247
+ "apr": 4,
29248
+ "mag": 5,
29249
+ "giu": 6,
29250
+ "lug": 7,
29251
+ "ago": 8,
29252
+ "set": 9,
29253
+ "ott": 10,
29254
+ "nov": 11,
29255
+ "dic": 12
29256
+ },
29257
+ "weekdays": {
29258
+ "luned\xEC": 0,
29259
+ "marted\xEC": 1,
29260
+ "mercoled\xEC": 2,
29261
+ "gioved\xEC": 3,
29262
+ "venerd\xEC": 4,
29263
+ "sabato": 5,
29264
+ "domenica": 6,
29265
+ "lun": 0,
29266
+ "mar": 1,
29267
+ "mer": 2,
29268
+ "gio": 3,
29269
+ "ven": 4,
29270
+ "sab": 5,
29271
+ "dom": 6
29272
+ },
29273
+ "quarters": {
29274
+ "1\xBA trimestre": 1,
29275
+ "2\xBA trimestre": 2,
29276
+ "3\xBA trimestre": 3,
29277
+ "4\xBA trimestre": 4,
29278
+ "1\xB0 trimestre": 1,
29279
+ "2\xB0 trimestre": 2,
29280
+ "3\xB0 trimestre": 3,
29281
+ "4\xB0 trimestre": 4,
29282
+ "t1": 1,
29283
+ "t2": 2,
29284
+ "t3": 3,
29285
+ "t4": 4,
29286
+ "q1": 1,
29287
+ "q2": 2,
29288
+ "q3": 3,
29289
+ "q4": 4
29290
+ },
29291
+ "keywords": {
29292
+ "today": [
29293
+ "oggi"
29294
+ ],
29295
+ "yesterday": [
29296
+ "ieri"
29297
+ ],
29298
+ "tomorrow": [
29299
+ "domani"
29300
+ ],
29301
+ "this_week": [
29302
+ "questa settimana",
29303
+ "settimana"
29304
+ ],
29305
+ "last_week": [
29306
+ "settimana scorsa"
29307
+ ],
29308
+ "next_week": [
29309
+ "settimana prossima"
29310
+ ],
29311
+ "this_month": [
29312
+ "questo mese",
29313
+ "mese"
29314
+ ],
29315
+ "last_month": [
29316
+ "mese scorso"
29317
+ ],
29318
+ "next_month": [
29319
+ "mese prossimo"
29320
+ ],
29321
+ "last": [
29322
+ "scorso",
29323
+ "scorsa"
29324
+ ],
29325
+ "next": [
29326
+ "prossimo",
29327
+ "prossima"
29328
+ ],
29329
+ "articles": [
29330
+ "il",
29331
+ "lo",
29332
+ "la"
29333
+ ],
29334
+ "from": [
29335
+ "da",
29336
+ "dal",
29337
+ "dalla",
29338
+ "tra",
29339
+ "fra"
29340
+ ],
29341
+ "to": [
29342
+ "a",
29343
+ "al",
29344
+ "alla",
29345
+ "e"
29346
+ ],
29347
+ "no_period": [
29348
+ "-",
29349
+ "senza periodo",
29350
+ "sempre"
29351
+ ]
29352
+ },
29353
+ "date_order": {
29354
+ "default": "DMY"
29355
+ }
29356
+ },
29357
+ "en": {
29358
+ "months": {
29359
+ "january": 1,
29360
+ "february": 2,
29361
+ "march": 3,
29362
+ "april": 4,
29363
+ "may": 5,
29364
+ "june": 6,
29365
+ "july": 7,
29366
+ "august": 8,
29367
+ "september": 9,
29368
+ "october": 10,
29369
+ "november": 11,
29370
+ "december": 12,
29371
+ "jan": 1,
29372
+ "feb": 2,
29373
+ "mar": 3,
29374
+ "apr": 4,
29375
+ "jun": 6,
29376
+ "jul": 7,
29377
+ "aug": 8,
29378
+ "sep": 9,
29379
+ "oct": 10,
29380
+ "nov": 11,
29381
+ "dec": 12
29382
+ },
29383
+ "weekdays": {
29384
+ "monday": 0,
29385
+ "tuesday": 1,
29386
+ "wednesday": 2,
29387
+ "thursday": 3,
29388
+ "friday": 4,
29389
+ "saturday": 5,
29390
+ "sunday": 6,
29391
+ "mon": 0,
29392
+ "tue": 1,
29393
+ "wed": 2,
29394
+ "thu": 3,
29395
+ "fri": 4,
29396
+ "sat": 5,
29397
+ "sun": 6
29398
+ },
29399
+ "quarters": {
29400
+ "1st quarter": 1,
29401
+ "2nd quarter": 2,
29402
+ "3rd quarter": 3,
29403
+ "4th quarter": 4,
29404
+ "q1": 1,
29405
+ "q2": 2,
29406
+ "q3": 3,
29407
+ "q4": 4
29408
+ },
29409
+ "keywords": {
29410
+ "today": [
29411
+ "today"
29412
+ ],
29413
+ "yesterday": [
29414
+ "yesterday"
29415
+ ],
29416
+ "tomorrow": [
29417
+ "tomorrow"
29418
+ ],
29419
+ "this_week": [
29420
+ "this week",
29421
+ "week"
29422
+ ],
29423
+ "last_week": [
29424
+ "last week"
29425
+ ],
29426
+ "next_week": [
29427
+ "next week"
29428
+ ],
29429
+ "this_month": [
29430
+ "this month",
29431
+ "month"
29432
+ ],
29433
+ "last_month": [
29434
+ "last month"
29435
+ ],
29436
+ "next_month": [
29437
+ "next month"
29438
+ ],
29439
+ "last": [
29440
+ "last"
29441
+ ],
29442
+ "next": [
29443
+ "next"
29444
+ ],
29445
+ "articles": [
29446
+ "the"
29447
+ ],
29448
+ "from": [
29449
+ "from",
29450
+ "between"
29451
+ ],
29452
+ "to": [
29453
+ "to",
29454
+ "and"
29455
+ ],
29456
+ "no_period": [
29457
+ "no period",
29458
+ "always"
29459
+ ]
29460
+ },
29461
+ "date_order": {
29462
+ "default": "MDY",
29463
+ "GB": "DMY",
29464
+ "AU": "DMY",
29465
+ "IE": "DMY",
29466
+ "NZ": "DMY",
29467
+ "IN": "DMY"
29468
+ }
29469
+ }
29470
+ };
29471
+ function localeContext(locale) {
29472
+ if (typeof locale !== "string") throw new RangeError("A supported locale is required.");
29473
+ const tag2 = locale.replaceAll("-", "_");
29474
+ const split = tag2.indexOf("_");
29475
+ const language = (split < 0 ? tag2 : tag2.slice(0, split)).toLowerCase();
29476
+ const region = (split < 0 ? "" : tag2.slice(split + 1)).toUpperCase();
29477
+ if (!Object.hasOwn(locales, language)) throw new RangeError(`Unsupported locale: ${locale}`);
29478
+ const dictionary = locales[language];
29479
+ const phrases = (key) => [.../* @__PURE__ */ new Set([...dictionary.keywords[key], ...locales.en.keywords[key]])];
29480
+ return { dictionary, phrases, order: dictionary.date_order[region] ?? dictionary.date_order.default };
29481
+ }
29482
+
29483
+ // src/date-parser/index.js
29484
+ var yearPattern = /^(?:\d{4}|\d{2})$/;
29485
+ var dayPattern = /^\d{1,2}$/;
29486
+ var fail2 = (code, message) => ({ ok: false, error: { code, message } });
29487
+ var unrecognized = (code = "UNRECOGNIZED_EXPRESSION", message = "Text is not a supported date expression.") => {
29488
+ throw Object.assign(new SyntaxError(message), { code });
29489
+ };
29490
+ var own = (object, key) => Object.hasOwn(object, key);
29491
+ function decodeYear(text, context) {
29492
+ if (text.length === 4) return Number(text);
29493
+ const lowest = context.year + context.twoDigitYearAhead - 100;
29494
+ return lowest + ((Number(text) - lowest) % 100 + 100) % 100;
29495
+ }
29496
+ function boundTexts(text, context) {
29497
+ if (text.includes(";")) {
29498
+ const bounds = text.split(";").map((part) => part.trim());
29499
+ if (bounds.length !== 2) return unrecognized("INVALID_RANGE", "A range must have exactly two endpoints.");
29500
+ return { bounds, range: true };
29501
+ }
29502
+ if (context.phrases("no_period").includes(text)) return { bounds: ["", ""], range: true };
29503
+ const to = context.phrases("to"), from = context.phrases("from");
29504
+ for (const word of to) {
29505
+ if (text.startsWith(`${word} `)) return { bounds: ["", text.slice(word.length + 1).trim()], range: true };
29506
+ }
29507
+ for (const word of to) {
29508
+ const separator = ` ${word} `;
29509
+ if (!text.includes(separator)) continue;
29510
+ for (const prefix of from) {
29511
+ if (text.startsWith(`${prefix} `)) {
29512
+ text = text.slice(prefix.length + 1);
29513
+ break;
29514
+ }
29515
+ }
29516
+ const bounds = text.split(separator).map((part) => part.trim());
29517
+ if (bounds.length !== 2) return unrecognized("INVALID_RANGE", "A range must have exactly two endpoints.");
29518
+ return { bounds, range: true };
29519
+ }
29520
+ for (const word of from) {
29521
+ if (text.startsWith(`${word} `)) return { bounds: [text.slice(word.length + 1).trim(), ""], range: true };
29522
+ }
29523
+ return { bounds: [text, text], range: false };
29524
+ }
29525
+ function keywordDate(text, context, isEnd) {
29526
+ const candidates = [[text, 0]];
29527
+ const offset = /^(.+?)\s*([+-])\s*(\d+)$/.exec(text);
29528
+ if (offset) candidates.push([offset[1], Number(offset[2] + offset[3])]);
29529
+ const shifts = {
29530
+ today: 0,
29531
+ yesterday: -1,
29532
+ tomorrow: 1,
29533
+ this_week: 0,
29534
+ last_week: -1,
29535
+ next_week: 1,
29536
+ this_month: 0,
29537
+ last_month: -1,
29538
+ next_month: 1
29539
+ };
29540
+ for (const [body, amount] of candidates) {
29541
+ for (const [key, shift] of Object.entries(shifts)) {
29542
+ if (!context.phrases(key).includes(body)) continue;
29543
+ if (key.endsWith("_week")) return addDays(monday(context.workdate), (shift + amount) * 7 + (isEnd ? 6 : 0));
29544
+ if (key.endsWith("_month")) {
29545
+ const span = monthPeriod(context.year, context.month, shift + amount);
29546
+ return isEnd ? span.end : span.start;
29547
+ }
29548
+ return addDays(context.workdate, shift + amount);
29549
+ }
29550
+ }
29551
+ return null;
29552
+ }
29553
+ function quarter(text, context, isEnd) {
29554
+ const entries = Object.entries(context.dictionary.quarters).sort((a, b) => b[0].length - a[0].length);
29555
+ for (const [name, number] of entries) {
29556
+ let year;
29557
+ if (text === name) year = null;
29558
+ else if (text.startsWith(name) && yearPattern.test(text.slice(name.length).trim())) {
29559
+ year = decodeYear(text.slice(name.length).trim(), context);
29560
+ } else if (text.endsWith(name) && yearPattern.test(text.slice(0, -name.length).trim())) {
29561
+ year = decodeYear(text.slice(0, -name.length).trim(), context);
29562
+ } else continue;
29563
+ return { year, month: isEnd ? number * 3 : number * 3 - 2 };
29564
+ }
29565
+ return null;
29566
+ }
29567
+ function monthNumber(token, dictionary) {
29568
+ if (own(dictionary.months, token)) return dictionary.months[token];
29569
+ const match = /^m(\d{1,2})$/.exec(token);
29570
+ return match && Number(match[1]) >= 1 && Number(match[1]) <= 12 ? Number(match[1]) : null;
29571
+ }
29572
+ function namedMonth(text, context) {
29573
+ const tokens = text.split(/\s+/);
29574
+ const positions = tokens.map((token, i) => monthNumber(token, context.dictionary) ? i : -1).filter((i) => i >= 0);
29575
+ if (!positions.length) return null;
29576
+ if (positions.length !== 1) return unrecognized();
29577
+ const position = positions[0], month = monthNumber(tokens[position], context.dictionary);
29578
+ const before = tokens.slice(0, position), after = tokens.slice(position + 1), others = [...before, ...after];
29579
+ if (others.length === 1 && context.phrases("last").includes(others[0])) {
29580
+ return { year: context.year - (month > context.month ? 1 : 0), month };
29581
+ }
29582
+ if (others.length === 1 && context.phrases("next").includes(others[0])) {
29583
+ return { year: context.year + (month < context.month ? 1 : 0), month };
29584
+ }
29585
+ if (!others.length) return { year: null, month };
29586
+ if (!before.length && after.length === 1 && yearPattern.test(after[0])) return { year: decodeYear(after[0], context), month };
29587
+ if (before.length === 1 && dayPattern.test(before[0])) {
29588
+ if (!after.length) return civil(context.year, month, Number(before[0]));
29589
+ if (after.length === 1 && yearPattern.test(after[0])) return civil(decodeYear(after[0], context), month, Number(before[0]));
29590
+ }
29591
+ if (!before.length && after.length === 2 && dayPattern.test(after[0]) && yearPattern.test(after[1])) {
29592
+ return civil(decodeYear(after[1], context), month, Number(after[0]));
29593
+ }
29594
+ return unrecognized();
29595
+ }
29596
+ function numericDate(text, context) {
29597
+ const iso = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text);
29598
+ if (iso) return civil(...iso.slice(1).map(Number));
29599
+ const numeric = /^(\d{1,4})[/\-. ]+(\d{1,4})[/\-. ]+(\d{1,4})$/.exec(text);
29600
+ const values = {};
29601
+ if (numeric) context.order.split("").forEach((letter, i) => {
29602
+ values[letter] = numeric[i + 1];
29603
+ });
29604
+ else if (/^(?:\d{6}|\d{8})$/.test(text)) {
29605
+ const yearWidth = text.length === 8 ? 4 : 2;
29606
+ for (const letter of context.order) {
29607
+ const width = letter === "Y" ? yearWidth : 2;
29608
+ values[letter] = text.slice(0, width);
29609
+ text = text.slice(width);
29610
+ }
29611
+ } else return null;
29612
+ if (!yearPattern.test(values.Y) || values.D.length > 2 || values.M.length > 2) return unrecognized();
29613
+ let day = Number(values.D), month = Number(values.M);
29614
+ if (numeric && month > 12 && day <= 12) [day, month] = [month, day];
29615
+ return civil(decodeYear(values.Y, context), month, day);
29616
+ }
29617
+ function getBound(text, context, isEnd) {
29618
+ if (!text) return null;
29619
+ const articles = context.phrases("articles");
29620
+ text = text.split(/\s+/).filter((token) => !articles.includes(token)).join(" ");
29621
+ if (!text) return unrecognized();
29622
+ if (yearPattern.test(text)) return civil(decodeYear(text, context), isEnd ? 12 : 1, isEnd ? 31 : 1);
29623
+ const value = keywordDate(text, context, isEnd) ?? quarter(text, context, isEnd) ?? namedMonth(text, context);
29624
+ if (value !== null) return value;
29625
+ if (own(context.dictionary.weekdays, text)) return addDays(monday(context.workdate), context.dictionary.weekdays[text]);
29626
+ return numericDate(text, context) ?? unrecognized();
29627
+ }
29628
+ function startDate(start, end, context) {
29629
+ if (start === null || typeof start === "string") return start;
29630
+ let year = start.year ?? context.year;
29631
+ const endYear = typeof end === "string" ? parts(end)[0] : end?.year;
29632
+ const endMonth = typeof end === "string" ? parts(end)[1] : end?.month;
29633
+ if (endYear) {
29634
+ if (year > endYear) year = endYear;
29635
+ if (year === endYear && start.month > endMonth) year--;
29636
+ }
29637
+ return civil(year, start.month, 1);
29638
+ }
29639
+ function endDate(end, start, context) {
29640
+ if (end === null || typeof end === "string") return end;
29641
+ let year = end.year ?? context.year;
29642
+ if (start !== null) {
29643
+ const [startYear, startMonth] = parts(start);
29644
+ if (year < startYear) year = startYear;
29645
+ if (year === startYear && startMonth > end.month) year++;
29646
+ }
29647
+ return civil(year, end.month, daysInMonth(year, end.month));
29648
+ }
29649
+ function parseDateExpression(text, options = {}) {
29650
+ if (!options || typeof options !== "object" || Array.isArray(options)) return fail2("INVALID_CONTEXT", "Options must provide a civil workdate and supported locale.");
29651
+ let context;
29652
+ try {
29653
+ const { locale = "it-IT", workdate, twoDigitYearAhead = 20 } = options;
29654
+ const [year, month] = parts(workdate);
29655
+ if (!Number.isInteger(twoDigitYearAhead) || twoDigitYearAhead < 0 || twoDigitYearAhead > 99) throw new RangeError("twoDigitYearAhead must be an integer from 0 to 99.");
29656
+ context = { ...localeContext(locale), workdate, year, month, twoDigitYearAhead };
29657
+ } catch (error) {
29658
+ return fail2("INVALID_CONTEXT", error.message);
29659
+ }
29660
+ if (typeof text !== "string") return fail2("INVALID_INPUT", "Expression must be a string.");
29661
+ try {
29662
+ const expression = text.toLowerCase().trim().replaceAll(",", "");
29663
+ const { bounds, range } = boundTexts(expression, context);
29664
+ const right = getBound(bounds[1], context, true), left = getBound(bounds[0], context, false);
29665
+ const start = startDate(left, right, context), end = endDate(right, start, context);
29666
+ if (!range && typeof left === "string" && start === end) return { ok: true, kind: "date", date: start };
29667
+ return { ok: true, kind: "period", start, end };
29668
+ } catch (error) {
29669
+ if (error instanceof RangeError) return fail2("INVALID_DATE", error.message);
29670
+ if (error instanceof SyntaxError) return fail2(error.code, error.message);
29671
+ throw error;
29672
+ }
29673
+ }
27754
29674
  export {
27755
29675
  Bag,
27756
29676
  BagNode,
@@ -27772,5 +29692,6 @@ export {
27772
29692
  RpcHandler,
27773
29693
  SourceHandler,
27774
29694
  UtilitiesHandler,
27775
- mountIndexPage
29695
+ mountIndexPage,
29696
+ parseDateExpression
27776
29697
  };