@gramlot/gramlot 0.3.16 → 0.3.18

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 (102) hide show
  1. package/dist/components/editors/__init__.py +1 -1
  2. package/dist/components/editors/assets/collection.js +16162 -11689
  3. package/dist/components/editors/assets/index.js +1 -1
  4. package/dist/components/editors/grammar.json +3 -0
  5. package/dist/components/inputs/__init__.py +1 -1
  6. package/dist/components/inputs/assets/collection.js +134 -179
  7. package/dist/components/inputs/assets/index.js +1 -1
  8. package/dist/components/inputs/grammar.json +19 -0
  9. package/dist/components/layout/__init__.py +1 -1
  10. package/dist/components/layout/assets/collection.js +4643 -3481
  11. package/dist/components/layout/assets/index.js +1 -1
  12. package/dist/components/layout/grammar.json +509 -1
  13. package/dist/components/tree/__init__.py +1 -1
  14. package/dist/components/tree/assets/collection.js +306 -94
  15. package/dist/components/tree/assets/index.js +1 -1
  16. package/dist/components/tree/grammar.json +16 -0
  17. package/dist/components/typst/__init__.py +1 -1
  18. package/dist/components/typst/assets/collection.js +2 -2
  19. package/dist/components/typst/assets/index.js +1 -1
  20. package/dist/gramlot.js +2126 -506
  21. package/dist/gramlot.min.js +97 -40
  22. package/dist/runtime-notices.json +4 -0
  23. package/package.json +12 -8
  24. package/src/binding/device-resolver.js +27 -0
  25. package/src/binding/error-notifications.js +84 -0
  26. package/src/binding/remote-resolver.d.ts +18 -0
  27. package/src/binding/remote.js +11 -4
  28. package/src/binding/runtime.js +6 -2
  29. package/src/bootstrap.js +4 -4
  30. package/src/components/buttons.js +10 -3
  31. package/src/components/code-mirror-engine.js +14 -4
  32. package/src/components/code-mirror.js +2 -3
  33. package/src/components/container.js +1 -1
  34. package/src/components/date-calendar.js +1 -1
  35. package/src/components/formlet-labels.js +5 -4
  36. package/src/components/html-document.js +4 -2
  37. package/src/components/html-editor.js +2 -2
  38. package/src/components/jodit-engine.js +72 -11
  39. package/src/components/labelbox.js +19 -63
  40. package/src/components/layout.js +31 -19
  41. package/src/components/markdown-document.js +1 -1
  42. package/src/components/markdown-editor.js +2 -2
  43. package/src/components/menus.js +7 -6
  44. package/src/components/prose-mirror-engine.js +14 -1
  45. package/src/components/registry.js +2 -0
  46. package/src/components/selected-container.js +107 -14
  47. package/src/components/toolbar-overflow.js +9 -8
  48. package/src/components/transform-pane.js +140 -0
  49. package/src/components/tray-geometry.js +87 -0
  50. package/src/components/tray-pane.js +435 -0
  51. package/src/components/tray-settings.js +62 -0
  52. package/src/components/tree.js +115 -21
  53. package/src/components/typed-editor.js +1 -1
  54. package/src/components/typst-client.js +14 -13
  55. package/src/components/validation.js +1 -1
  56. package/src/components/window-surface.js +281 -0
  57. package/src/components/windows.js +32 -261
  58. package/src/device-frames.js +195 -0
  59. package/src/filesystem.d.ts +12 -5
  60. package/src/filesystem.js +8 -8
  61. package/src/gramlot.d.ts +3 -1
  62. package/src/gramlot.js +11 -4
  63. package/src/handlers/device-handler.d.ts +75 -0
  64. package/src/handlers/device-handler.js +1037 -0
  65. package/src/handlers/dom-handler.d.ts +2 -0
  66. package/src/handlers/dom-handler.js +9 -0
  67. package/src/handlers/rpc-handler.d.ts +2 -2
  68. package/src/http-transport.d.ts +3 -3
  69. package/src/http-transport.js +17 -11
  70. package/src/ide-documents.js +6 -4
  71. package/src/ide-runtime.d.ts +14 -3
  72. package/src/ide-runtime.js +123 -94
  73. package/src/index-page-runtime.d.ts +2 -2
  74. package/src/index-page-runtime.js +91 -43
  75. package/src/index-page-styles.js +1 -1
  76. package/src/index.d.ts +7 -2
  77. package/src/index.js +5 -1
  78. package/src/inout.d.ts +1 -1
  79. package/src/inout.js +5 -1
  80. package/src/mobile-environment.d.ts +6 -0
  81. package/src/mobile-environment.js +52 -0
  82. package/src/navigation-resolver.d.ts +14 -2
  83. package/src/renderer/attributes.js +5 -2
  84. package/src/renderer/drag-drop.js +5 -4
  85. package/src/renderer/gramlot-renderer.d.ts +13 -2
  86. package/src/renderer/gramlot-renderer.js +49 -13
  87. package/src/server/index-page.js +4 -4
  88. package/src/view/controls.js +48 -23
  89. package/src/view/html.js +85 -4
  90. package/src/view/labelbox.js +97 -0
  91. package/themes/gramlot-base/theme.css +10 -0
  92. package/themes/gramlot-compact/theme.css +6 -0
  93. package/themes/joanna/theme.css +6 -0
  94. package/themes/mela/theme.css +68 -15
  95. package/themes/mimi/theme.css +6 -0
  96. package/themes/palettes/compact.css +6 -0
  97. package/themes/palettes/joanna.css +6 -0
  98. package/themes/palettes/mimi.css +6 -0
  99. package/src/date-parser/civil.js +0 -61
  100. package/src/date-parser/index.d.ts +0 -18
  101. package/src/date-parser/index.js +0 -196
  102. package/src/date-parser/locales.js +0 -257
package/dist/gramlot.js CHANGED
@@ -6519,6 +6519,78 @@ var require_lib = __commonJS({
6519
6519
  }
6520
6520
  });
6521
6521
 
6522
+ // src/mobile-environment.js
6523
+ var environments = /* @__PURE__ */ new WeakMap();
6524
+ var TOUCH = `
6525
+ --gramlot-toolbar-thickness:56px; --gramlot-toolbar-control-size:44px; --gramlot-toolbar-padding:6px;
6526
+ `;
6527
+ var EDGES = `
6528
+ box-sizing:border-box; height:100dvh; min-height:0; overflow:auto;
6529
+ padding:env(safe-area-inset-top) max(12px,env(safe-area-inset-right)) max(24px,env(safe-area-inset-bottom)) max(12px,env(safe-area-inset-left));
6530
+ background:var(--gramlot-chrome-background,color-mix(in srgb,var(--gramlot-surface-subtle,Canvas) 88%,var(--gramlot-ink,CanvasText) 12%)); color:var(--gramlot-ink,CanvasText);
6531
+ `;
6532
+ var mobileEnvironmentStyle = `
6533
+ [data-gramlot-viewport]{--gramlot-toolbar-thickness:42px;--gramlot-toolbar-control-size:36px;--gramlot-toolbar-padding:2px 3px;}
6534
+ :root[data-gramlot-touch="on"] [data-gramlot-viewport]{${TOUCH}}
6535
+ :root[data-gramlot-touch="on"] [data-gramlot-viewport="root"]{${EDGES}}
6536
+ :root[data-gramlot-touch="on"] [data-gramlot-viewport="root"] > *{max-height:100%;}
6537
+ @media(pointer:coarse){
6538
+ :root:not([data-gramlot-touch="off"]) [data-gramlot-viewport]{${TOUCH}}
6539
+ :root:not([data-gramlot-touch="off"]) [data-gramlot-viewport="root"]{${EDGES}}
6540
+ :root:not([data-gramlot-touch="off"]) [data-gramlot-viewport="root"] > *{max-height:100%;}
6541
+ }
6542
+ `;
6543
+ var MobileEnvironment = class _MobileEnvironment {
6544
+ static install({ document, root }) {
6545
+ if (!environments.has(root)) environments.set(root, new _MobileEnvironment(document, root));
6546
+ return environments.get(root);
6547
+ }
6548
+ constructor(document, root) {
6549
+ this.document = document;
6550
+ this.root = root;
6551
+ this.releases = [];
6552
+ this.closed = false;
6553
+ root.setAttribute("data-gramlot-viewport", document.defaultView.parent === document.defaultView ? "root" : "child");
6554
+ let viewport = document.querySelector('meta[name="viewport"]');
6555
+ if (!viewport) {
6556
+ viewport = document.createElement("meta");
6557
+ viewport.name = "viewport";
6558
+ viewport.content = "width=device-width,initial-scale=1";
6559
+ document.head.append(viewport);
6560
+ }
6561
+ const parts2 = viewport.content.split(",").map((s) => s.trim()).filter((s) => !s.startsWith("viewport-fit="));
6562
+ viewport.content = [...parts2, "viewport-fit=cover"].join(",");
6563
+ this.style = document.createElement("style");
6564
+ this.style.textContent = mobileEnvironmentStyle;
6565
+ document.head.append(this.style);
6566
+ }
6567
+ subscribeAppearance(callback) {
6568
+ const window2 = this.document.defaultView, media = window2.matchMedia("(prefers-color-scheme: dark)");
6569
+ const update = () => {
6570
+ const scheme = window2.getComputedStyle(this.document.documentElement).colorScheme;
6571
+ callback({ dark: scheme === "dark" || !["light", "dark"].includes(scheme) && media.matches });
6572
+ };
6573
+ const observer = new window2.MutationObserver(update);
6574
+ observer.observe(this.document.documentElement, { attributes: true, attributeFilter: ["data-theme", "style", "class"] });
6575
+ media.addEventListener("change", update);
6576
+ update();
6577
+ const release = () => {
6578
+ observer.disconnect();
6579
+ media.removeEventListener("change", update);
6580
+ };
6581
+ this.releases.push(release);
6582
+ return release;
6583
+ }
6584
+ dispose() {
6585
+ if (this.closed) return;
6586
+ this.closed = true;
6587
+ for (const release of this.releases) release();
6588
+ this.style.remove();
6589
+ this.root.removeAttribute("data-gramlot-viewport");
6590
+ environments.delete(this.root);
6591
+ }
6592
+ };
6593
+
6522
6594
  // src/commands.js
6523
6595
  var CommandRegistry = class {
6524
6596
  #groups = /* @__PURE__ */ new Map();
@@ -6596,21 +6668,21 @@ var HttpTransport = class {
6596
6668
  return request.responseText;
6597
6669
  }
6598
6670
  /**
6599
- * Send the close message `{pageId}` without waiting for the answer: a beacon on page hide, else a
6600
- * `keepalive` POST. A failed delivery leaves the page to the server TTL; local disposal does not wait.
6671
+ * Queue `{pageId}` as a JSON beacon for every close. A refused or undelivered
6672
+ * beacon leaves cleanup to the server TTL; configuration errors remain visible.
6601
6673
  */
6602
- close(pageId, { beacon = false } = {}) {
6603
- const body = JSON.stringify({ pageId });
6604
- if (beacon) {
6605
- this.navigator.sendBeacon(this.closeUrl, new Blob([body], { type: "application/json" }));
6606
- } else {
6607
- this.fetcher(this.closeUrl, {
6608
- method: "POST",
6609
- credentials: "same-origin",
6610
- keepalive: true,
6611
- headers: { "Content-Type": "application/json" },
6612
- body
6613
- });
6674
+ close(pageId) {
6675
+ if (typeof this.closeUrl !== "string" || !this.closeUrl.trim()) {
6676
+ throw new TypeError("HttpTransport.closeUrl must be nonempty text");
6677
+ }
6678
+ if (typeof this.navigator?.sendBeacon !== "function") {
6679
+ throw new TypeError("HttpTransport requires navigator.sendBeacon");
6680
+ }
6681
+ const body = new Blob([JSON.stringify({ pageId })], { type: "application/json" });
6682
+ try {
6683
+ this.navigator.sendBeacon(this.closeUrl, body);
6684
+ } catch (error) {
6685
+ if (error.name === "TypeError") throw error;
6614
6686
  }
6615
6687
  }
6616
6688
  /** Release the transport at the dispose of the page: HTTP holds no connection, so nothing is released. The
@@ -22155,6 +22227,103 @@ var Handler = class {
22155
22227
  }
22156
22228
  };
22157
22229
 
22230
+ // src/view/labelbox.js
22231
+ var labelboxPositions = ["TL", "TC", "TR", "L", "R", "BL", "BC", "BR"];
22232
+ var labelboxStyle = `.gramlot-labelbox[hidden]{display:none!important}
22233
+ .gramlot-labelbox{box-sizing:border-box;min-width:0;min-height:0;--gramlot-label-width:initial;--gramlot-formlet-label-width:initial;display:grid;gap:var(--gramlot-label-gap,.25em);grid-template-areas:'label' 'control';grid-template-columns:minmax(0,1fr);grid-template-rows:max-content minmax(0,1fr)}
22234
+ .gramlot-labelbox>.label-box{grid-area:label;color:var(--gramlot-label-color,var(--gramlot-text-secondary,inherit));font-size:var(--gramlot-label-size,1em)} .gramlot-labelbox>.control-box{box-sizing:border-box;grid-area:control;min-width:0;min-height:0;display:grid;grid-template-columns:minmax(0,1fr);grid-template-rows:minmax(0,1fr)}
22235
+ .gramlot-labelbox>.control-box>*{max-width:100%;box-sizing:border-box}
22236
+ .gramlot-labelbox[data-position='L']{grid-template-areas:'label control';grid-template-rows:minmax(0,1fr)}
22237
+ .gramlot-labelbox[data-position='R']{grid-template-areas:'control label';grid-template-columns:minmax(0,1fr) max-content;grid-template-rows:minmax(0,1fr)}
22238
+ .gramlot-labelbox[data-position='L']>.label-box,.gramlot-labelbox[data-position='R']>.label-box{align-self:center}
22239
+ .gramlot-labelbox[data-position^='B']{grid-template-areas:'control' 'label';grid-template-rows:minmax(0,1fr) max-content}
22240
+ .gramlot-labelbox[data-position$='C']>.label-box{text-align:center}
22241
+ .gramlot-labelbox[data-position$='R']>.label-box{text-align:right}
22242
+ .gramlot-labelbox>.label-box[hidden]{display:none} .gramlot-labelbox>.label-box label{display:block}
22243
+ .gramlot-labelbox[data-position='L']>.label-box{text-align:right;padding-right:2px}
22244
+ .gramlot-labelbox[data-formlet-aligned]>.label-box>label{width:max-content;margin-left:auto}
22245
+ .gramlot-labelbox[data-position='L']{grid-template-columns:var(--gramlot-label-width,var(--gramlot-formlet-label-width,max-content)) minmax(0,1fr)}
22246
+ .gramlot-labelbox:has(>.label-box[hidden]){gap:0;grid-template-areas:'control';grid-template-columns:minmax(0,1fr);grid-template-rows:minmax(0,1fr)}
22247
+ .gramlot-labelbox[data-variant='card']{gap:0;border:1px solid var(--gramlot-border-control,#b9c2ce);border-radius:var(--gramlot-window-radius,9px);background:var(--gramlot-surface,#fff);color:var(--gramlot-ink,CanvasText);box-shadow:0 3px 10px #0002}
22248
+ .gramlot-labelbox[data-variant='card']>.label-box{background:var(--gramlot-card-header-background,var(--gramlot-header-background,#303946));color:var(--gramlot-card-header-color,var(--gramlot-header-color,#fff));box-sizing:border-box;min-height:28px;padding:3px 10px;border-radius:calc(var(--gramlot-window-radius,9px) - 1px) calc(var(--gramlot-window-radius,9px) - 1px) 0 0;font-weight:600}
22249
+ .gramlot-labelbox[data-variant='card']>.label-box>label{color:inherit;font:inherit;line-height:20px;margin:0}
22250
+ .gramlot-labelbox[data-variant='card']>.control-box{padding:12px}
22251
+ .gramlot-labelbox[data-movable]>.label-box{cursor:grab;touch-action:none;user-select:none}
22252
+ .gramlot-labelbox[data-movable]>.label-box>label{cursor:inherit;user-select:none;-webkit-user-select:none}
22253
+ .gramlot-labelbox[data-selected]{outline:2px solid var(--gramlot-focus-ring,var(--gramlot-brand-blue,#3766b5));outline-offset:-2px}
22254
+ .gramlot-labelbox[data-tray-block]>.label-box{position:relative;padding-inline:32px 60px}
22255
+ .gramlot-labelbox>.label-box>.tray-settings-button{position:absolute;right:3px;top:50%;transform:translateY(-50%);display:grid;place-items:center;width:26px;height:26px;padding:4px;border:0;border-radius:4px;background:transparent;color:inherit;cursor:pointer}
22256
+ .gramlot-labelbox>.label-box>button[hidden]{display:none}
22257
+ .gramlot-labelbox>.label-box>.tray-settings-button[data-kind=layer]{right:31px}
22258
+ .tray-settings-button{opacity:.65}
22259
+ .tray-settings-button:hover,.tray-settings-button:focus-visible{opacity:1}
22260
+ .tray-settings-button svg{width:18px;height:18px;pointer-events:none}
22261
+ .gramlot-labelbox>.label-box>.tray-settings-button:hover{background:color-mix(in srgb,currentColor 12%,transparent)}
22262
+ .tray-settings-button:focus-visible{outline:2px solid var(--gramlot-focus-ring,Highlight);outline-offset:-2px}
22263
+
22264
+ .gramlot-labelbox>.label-box>.tray-rotate{position:absolute;left:3px;top:50%;transform:translateY(-50%);display:grid;place-items:center;width:26px;height:26px;padding:4px;border:0;border-radius:4px;background:transparent;color:inherit;cursor:grab;touch-action:none;opacity:.7}
22265
+ .tray-rotate svg{width:18px;height:18px;pointer-events:none}
22266
+ .gramlot-labelbox>.label-box>.tray-rotate:hover{opacity:1;background:color-mix(in srgb,currentColor 12%,transparent)}
22267
+ .tray-rotate:focus-visible{opacity:1;outline:2px solid var(--gramlot-focus-ring,Highlight);outline-offset:-2px}
22268
+ .gramlot-labelbox[data-rotating]>.label-box>.tray-rotate{cursor:grabbing}
22269
+ .gramlot-labelbox[data-moving]>.label-box{cursor:grabbing}
22270
+ .gramlot-labelbox[data-resizable]>.control-box{overflow:auto}
22271
+ .gramlot-labelbox>.tray-resize{position:absolute;right:1px;bottom:1px;width:22px;height:22px;padding:2px;display:grid;place-items:end;border:0;background:transparent;color:inherit;cursor:nwse-resize;touch-action:none;border-radius:3px;opacity:.65}
22272
+ .gramlot-labelbox>.tray-resize[hidden]{display:none}
22273
+ .gramlot-labelbox>.tray-resize svg{width:16px;height:16px;pointer-events:none}
22274
+ .gramlot-labelbox>.tray-resize:hover,.gramlot-labelbox>.tray-resize:focus-visible{opacity:1}
22275
+ .gramlot-labelbox>.tray-resize:focus-visible{outline:2px solid var(--gramlot-focus-ring,Highlight);outline-offset:-2px}`;
22276
+ function createLabelbox(document, controlBox) {
22277
+ const box = document.createElement("div"), labelBox = document.createElement("div");
22278
+ const fieldLabel = document.createElement("label");
22279
+ labelBox.append(fieldLabel);
22280
+ box.append(labelBox, controlBox);
22281
+ const layout = { box, labelBox, fieldLabel, controlBox, previous: { box: {}, label: {}, labelBox: {}, controlBox: {} } };
22282
+ box.labelbox = layout;
22283
+ return layout;
22284
+ }
22285
+ function projectLabelbox(layout, attrs, adapt) {
22286
+ const { lbl, lbl_variant, lbl_position = lbl_variant === "card" ? "TC" : "TL", ...rest } = attrs;
22287
+ if (!labelboxPositions.includes(lbl_position)) throw new TypeError(`Invalid lbl_position: ${lbl_position}`);
22288
+ const groups = { box: {}, label: {}, labelBox: {}, controlBox: {} };
22289
+ const prefixes = [["box_l_", "labelBox"], ["box_c_", "controlBox"], ["lbl_", "label"], ["box_", "box"]];
22290
+ for (const [name, value] of Object.entries(rest)) {
22291
+ const match = prefixes.find(([prefix]) => name.startsWith(prefix));
22292
+ if (match) {
22293
+ groups[match[1]][name.slice(match[0].length)] = value;
22294
+ delete rest[name];
22295
+ }
22296
+ }
22297
+ const elements = { box: layout.box, label: layout.fieldLabel, labelBox: layout.labelBox, controlBox: layout.controlBox };
22298
+ for (const [name, element] of Object.entries(elements)) {
22299
+ const next = adapt(groups[name]), previous = layout.previous[name];
22300
+ for (const key of /* @__PURE__ */ new Set([...Object.keys(previous), ...Object.keys(next)])) {
22301
+ if (next[key] == null) element.removeAttribute(key);
22302
+ else element.setAttribute(key, String(next[key]));
22303
+ }
22304
+ layout.previous[name] = next;
22305
+ }
22306
+ if (attrs.lbl_width == null) layout.box.style.removeProperty("--gramlot-label-width");
22307
+ else layout.box.style.setProperty("--gramlot-label-width", attrs.lbl_width);
22308
+ layout.box.classList.add("labelbox", "gramlot-labelbox");
22309
+ layout.labelBox.classList.add("label-box");
22310
+ layout.controlBox.classList.add("control-box");
22311
+ layout.box.dataset.position = lbl_position;
22312
+ if (lbl_variant == null) delete layout.box.dataset.variant;
22313
+ else layout.box.dataset.variant = lbl_variant;
22314
+ layout.fieldLabel.textContent = lbl ?? "";
22315
+ layout.labelBox.hidden = lbl == null || lbl === "";
22316
+ layout.box.dispatchEvent(new layout.box.ownerDocument.defaultView.Event("gramlot-label-layout", { bubbles: true }));
22317
+ return rest;
22318
+ }
22319
+ function labelboxContent(presentation) {
22320
+ return presentation?.labelbox ? presentation.labelbox.controlBox.firstElementChild : presentation;
22321
+ }
22322
+ function labelboxPresentation(content) {
22323
+ const box = content?.parentElement?.parentElement;
22324
+ return box?.labelbox && labelboxContent(box) === content ? box : content;
22325
+ }
22326
+
22158
22327
  // src/webcomponent.js
22159
22328
  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;
22160
22329
  var RESERVED = /* @__PURE__ */ new Set([
@@ -22213,6 +22382,7 @@ function defineComponent({ name, tag: tag2, base, mixins = [], parameters: param
22213
22382
  command,
22214
22383
  bagStore,
22215
22384
  mixins: Object.freeze([...mixins]),
22385
+ labelbox: mixins.some((mixin) => mixin.labelbox === true),
22216
22386
  parameters: freeze(structuredClone(effective)),
22217
22387
  childParameters: freeze(structuredClone(childParameters)),
22218
22388
  sourceContext,
@@ -22289,6 +22459,7 @@ var ComponentCollection = class _ComponentCollection {
22289
22459
  command: component.command,
22290
22460
  ...Object.keys(component.childParameters).length ? { childParameters: structuredClone(component.childParameters) } : {},
22291
22461
  ...component.sourceContext ? { sourceContext: true } : {},
22462
+ ...component.labelbox ? { labelbox: true } : {},
22292
22463
  ...component.dragSource ? { dragSource: true } : {},
22293
22464
  ...component.bagStore ? { bagStore: true } : {}
22294
22465
  } }
@@ -22703,6 +22874,7 @@ var BINDING_ATTRIBUTES = /* @__PURE__ */ new Set([
22703
22874
  "_onRemote",
22704
22875
  "_onCalling",
22705
22876
  "onClose",
22877
+ "onEnd",
22706
22878
  "onDrag",
22707
22879
  "onDrop",
22708
22880
  "dropTargetCb",
@@ -22724,7 +22896,7 @@ var NATIVE_ATTRIBUTES = {
22724
22896
  canvas: ["width", "height"]
22725
22897
  };
22726
22898
  var DISPLAY_ATTRIBUTES = ["format", "mask", "locale", "timeZone", "places", "dtype"];
22727
- var URL_ATTRIBUTES = /* @__PURE__ */ new Set(["href", "src", "action", "formaction", "xlink:href", "xlink_href"]);
22899
+ var URL_ATTRIBUTES = /* @__PURE__ */ new Set(["href", "src", "data", "action", "formaction", "xlink:href", "xlink_href"]);
22728
22900
  function withoutBindingAttributes(attrs) {
22729
22901
  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))));
22730
22902
  }
@@ -22746,6 +22918,9 @@ function requireNoScriptAttributes(node, attrs, prefixes = []) {
22746
22918
  }
22747
22919
  }
22748
22920
  }
22921
+ if (attrs.onEnd != null && (node.nodeTag.toLowerCase() !== "transformpane" || !node._getMeta("gramlot_component")?.parameters?.onEnd)) {
22922
+ throw new Error("onEnd is only supported on transformPane");
22923
+ }
22749
22924
  if (attrs.onClose != null && !node.parentNode?._getMeta("gramlot_component")?.childParameters?.onClose) {
22750
22925
  throw new Error("onClose is only supported on a tab/stack panel");
22751
22926
  }
@@ -22976,7 +23151,7 @@ var ToolbarOverflow = class {
22976
23151
  if (available <= 0) return;
22977
23152
  let active = menu.ownerDocument.activeElement;
22978
23153
  while (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement;
22979
- const units = [...menu.children].filter((unit) => !unit.hidden && (unit.localName !== "gramlot-menu" || unit.permanent));
23154
+ const units = [...menu.children].filter((unit) => !unit.hidden && (labelboxContent(unit).localName !== "gramlot-menu" || labelboxContent(unit).permanent));
22980
23155
  for (const unit of this.#units) if (!units.includes(unit)) {
22981
23156
  this.#resize.unobserve(unit);
22982
23157
  unit.removeAttribute("slot");
@@ -22994,15 +23169,15 @@ var ToolbarOverflow = class {
22994
23169
  const gap = parseFloat(win.getComputedStyle(this.#viewport).gap) || 0;
22995
23170
  const lengths = new Map(units.map((unit) => {
22996
23171
  const css = win.getComputedStyle(unit);
22997
- const length = unit.localName === "gramlot-spacer" ? unit.parameters.size ?? 0 : unit.getBoundingClientRect()[axis];
23172
+ const length = labelboxContent(unit).localName === "gramlot-spacer" ? labelboxContent(unit).parameters.size ?? 0 : unit.getBoundingClientRect()[axis];
22998
23173
  return [unit, length + (parseFloat(css[vertical ? "marginTop" : "marginLeft"]) || 0) + (parseFloat(css[vertical ? "marginBottom" : "marginRight"]) || 0)];
22999
23174
  }));
23000
- const separator = (unit) => unit.getAttribute("role") === "separator";
23001
- const tidy = (list) => list.filter((unit, index) => !separator(unit) || list.slice(0, index).some((item) => item.localName !== "gramlot-spacer" && !separator(item)) && list.slice(index + 1).find((item) => item.localName !== "gramlot-spacer") && !separator(list.slice(index + 1).find((item) => item.localName !== "gramlot-spacer")));
23175
+ const separator = (unit) => labelboxContent(unit).getAttribute("role") === "separator";
23176
+ const tidy = (list) => list.filter((unit, index) => !separator(unit) || list.slice(0, index).some((item) => labelboxContent(item).localName !== "gramlot-spacer" && !separator(item)) && list.slice(index + 1).find((item) => labelboxContent(item).localName !== "gramlot-spacer") && !separator(list.slice(index + 1).find((item) => labelboxContent(item).localName !== "gramlot-spacer")));
23002
23177
  const required = (remaining2) => remaining2.reduce((sum2, unit) => sum2 + lengths.get(unit), 0) + Math.max(0, remaining2.length - 1) * gap;
23003
23178
  let remaining = tidy(units);
23004
23179
  if (required(remaining) > available) {
23005
- const candidates = units.map((unit, index) => ({ unit, index })).filter(({ unit }) => unit.localName === "gramlot-menu-line" && !separator(unit) && unit.parameters.overflowable).sort((a, b) => a.unit.parameters.priority - b.unit.parameters.priority || b.index - a.index);
23180
+ const candidates = units.map((unit, index) => ({ unit, index })).filter(({ unit }) => labelboxContent(unit).localName === "gramlot-menu-line" && !separator(unit) && labelboxContent(unit).parameters.overflowable).sort((a, b) => labelboxContent(a.unit).parameters.priority - labelboxContent(b.unit).parameters.priority || b.index - a.index);
23006
23181
  for (const { unit } of candidates) {
23007
23182
  if (required(remaining) <= available - 32) break;
23008
23183
  this.#overflow.add(unit);
@@ -23144,7 +23319,7 @@ function MenuContainer(HTMLElement) {
23144
23319
  return this.#overflow.contains(item);
23145
23320
  }
23146
23321
  get usableItems() {
23147
- return this.items.filter((item) => item.slot !== "suppressed" && !item.disabled && !item.hidden && !item.closest("[hidden]") && item.getAttribute("role") !== "separator");
23322
+ return this.items.filter((item) => labelboxPresentation(item).slot !== "suppressed" && !item.disabled && !item.hidden && !item.closest("[hidden]") && item.getAttribute("role") !== "separator");
23148
23323
  }
23149
23324
  get parentMenu() {
23150
23325
  return this.parentElement?.closest("gramlot-menu") ?? null;
@@ -23192,13 +23367,13 @@ function MenuContainer(HTMLElement) {
23192
23367
  return keys;
23193
23368
  }
23194
23369
  #attachOpening() {
23195
- const owner = this.parentElement;
23370
+ const owner = labelboxPresentation(this).parentElement;
23196
23371
  if (this.permanent || !owner) return;
23197
23372
  if (["gramlot-menu-line", "gramlot-drop-down-button"].includes(owner.localName)) {
23198
- this.slot = "menu";
23373
+ labelboxPresentation(this).slot = "menu";
23199
23374
  return;
23200
23375
  }
23201
- this.removeAttribute("slot");
23376
+ labelboxPresentation(this).removeAttribute("slot");
23202
23377
  if (owner.localName === "gramlot-menu") return;
23203
23378
  this.#attachment = owner;
23204
23379
  this.#attachmentEvents = new this.ownerDocument.defaultView.AbortController();
@@ -23420,7 +23595,7 @@ function menuLine(Base) {
23420
23595
  return this.parentElement?.closest("gramlot-menu") ?? null;
23421
23596
  }
23422
23597
  get submenu() {
23423
- return [...this.children].find((child) => child.localName === "gramlot-menu") ?? null;
23598
+ return [...this.children].map(labelboxContent).find((child) => child.localName === "gramlot-menu") ?? null;
23424
23599
  }
23425
23600
  get entryCaption() {
23426
23601
  return this.parameters.caption ?? this.#registry?.label ?? "";
@@ -23521,7 +23696,7 @@ function menuLine(Base) {
23521
23696
  else this.openSubmenu();
23522
23697
  return false;
23523
23698
  }
23524
- const drop = this.menuOwner?.parentElement;
23699
+ const drop = labelboxPresentation(this.menuOwner)?.parentElement;
23525
23700
  if (drop?.localName === "gramlot-drop-down-button") drop.selectCommand(this, event.shiftKey);
23526
23701
  else this.menuOwner.closeChain();
23527
23702
  return true;
@@ -23547,11 +23722,15 @@ function Command(HTMLElement) {
23547
23722
  const style = doc.createElement("style");
23548
23723
  style.textContent = `:host{vertical-align:middle} .control-box{display:flex;align-items:stretch}
23549
23724
  button{display:inline-flex;align-items:center;justify-content:center;gap:var(--gramlot-button-gap,.35em);font:inherit;
23550
- color:var(--gramlot-ink,CanvasText);background:var(--gramlot-button-background,var(--gramlot-field-background,Canvas));
23725
+ color:var(--gramlot-button-color,var(--gramlot-ink,CanvasText));background:var(--gramlot-button-background,var(--gramlot-field-background,Canvas));
23551
23726
  border:1px solid var(--gramlot-border-control,#888);border-radius:var(--gramlot-radius-sm,4px);
23552
23727
  min-height:max(var(--gramlot-field-height,28px),var(--gramlot-touch-target,0px));
23553
23728
  padding:var(--gramlot-button-padding,.25em .65em);cursor:pointer}
23554
23729
  button:hover:not(:disabled){background:var(--gramlot-button-hover,var(--gramlot-field-readonly-background,#eee))}
23730
+ :host(.button--secondary) button{background:var(--gramlot-selected,Highlight);color:var(--gramlot-action,CanvasText);border-color:transparent}
23731
+ :host(.button--secondary) button:hover:not(:disabled){background:var(--gramlot-selected,Highlight);color:var(--gramlot-action-hover,CanvasText);border-color:var(--gramlot-action,CanvasText)}
23732
+ button:active:not(:disabled){filter:brightness(.9)}
23733
+ @media(prefers-contrast:more){button{border:2px solid currentColor}}
23555
23734
  :host(.button--quiet) button{background:transparent;color:var(--gramlot-action,CanvasText);border-color:transparent}
23556
23735
  :host(.button--quiet) button:hover:not(:disabled){background:var(--gramlot-selected,Highlight);color:var(--gramlot-action-hover,CanvasText);border-color:transparent}
23557
23736
  button:focus-visible{outline:2px solid var(--gramlot-focus-ring,Highlight);outline-offset:2px}
@@ -23566,7 +23745,9 @@ function Command(HTMLElement) {
23566
23745
  color:var(--gramlot-ink,CanvasText);background:var(--gramlot-field-background,Canvas);box-shadow:0 3px 12px #0003}
23567
23746
  :host(:is([role=menuitem],[role=menuitemcheckbox])){display:block} :host(:is([role=menuitem],[role=menuitemcheckbox])) button{width:100%;justify-content:start;border:0;background:transparent}
23568
23747
  :host([role=separator]){display:block;border-top:1px solid var(--gramlot-border-control,#888);margin:.25em}
23569
- :host([role=separator]) button{display:none}`;
23748
+ :host([role=separator]) button{display:none}
23749
+ @media(forced-colors:active){button,:host(.button--secondary) button,:host(.button--quiet) button{background:ButtonFace;color:ButtonText;border-color:ButtonText;filter:none}}
23750
+ `;
23570
23751
  this.shadowRoot.append(style);
23571
23752
  }
23572
23753
  get disabled() {
@@ -23763,7 +23944,7 @@ var DropDownButton = defineComponent({
23763
23944
  });
23764
23945
  }
23765
23946
  get menu() {
23766
- return [...this.children].find((child) => child.localName === "gramlot-menu");
23947
+ return [...this.children].map(labelboxContent).find((child) => child.localName === "gramlot-menu");
23767
23948
  }
23768
23949
  get menuItems() {
23769
23950
  return this.menu?.items ?? [];
@@ -25355,10 +25536,10 @@ function invokeHook(runtime, node, attribute, handler, context, inlineNames = Ob
25355
25536
 
25356
25537
  // src/view/controls.js
25357
25538
  var CONTROL_TAGS = /* @__PURE__ */ new Set(["input", "select", "textarea"]);
25358
- var REBUILD_ATTRIBUTES = ["type", "multiple", "group"];
25359
- function resolved(node, name) {
25360
- const value = node.getAttr(name);
25361
- return node.pointerType(value) ? node.getRelativeData(value) : value;
25539
+ var REBUILD_ATTRIBUTES = ["type", "multiple"];
25540
+ function resolved(control, name) {
25541
+ const node = control.node, value = node.getAttr(name);
25542
+ return node.pointerType(value) ? node.getRelativeData(value) : control.resolved[name];
25362
25543
  }
25363
25544
  var ControlAdapter = class _ControlAdapter {
25364
25545
  // Whether `live` moves the write from `change` to `input` (gate decision 3).
@@ -25396,14 +25577,15 @@ var ControlAdapter = class _ControlAdapter {
25396
25577
  return Object.hasOwn(INPUT_CONTROLS, type) ? INPUT_CONTROLS[type] : TextControl;
25397
25578
  }
25398
25579
  /**
25399
- * The resolved `type`, `multiple` and `group` of a form control element, as one comparable
25400
- * string, or null for any other element: a different shape rebuilds the element (C04.1, D7).
25580
+ * Attributes still requiring reconstruction, as one comparable string, or null for other
25581
+ * elements. Native input.type and input/select.multiple use setters; radio group changes
25582
+ * update the existing membership and never contribute to this signature.
25401
25583
  * `attrs` are the attributes of the renderer's resolved projection (`^`, `=` and `==` resolved).
25402
25584
  */
25403
25585
  static shape(element, attrs) {
25404
- if (element?.constructor.gramlotComponent?.parameters.value?.binding === "twoWay" && element.control.type === "radio") return JSON.stringify([attrs.group ?? null]);
25586
+ if (element?.constructor.gramlotComponent?.parameters.value?.binding === "twoWay" && element.control.type === "radio") return JSON.stringify([]);
25405
25587
  if (element?.namespaceURI !== XHTML_NS || !CONTROL_TAGS.has(element.localName)) return null;
25406
- return JSON.stringify(REBUILD_ATTRIBUTES.map((name) => attrs[name] ?? null));
25588
+ return JSON.stringify(REBUILD_ATTRIBUTES.filter((name) => (name !== "type" || element.localName !== "input") && (name !== "multiple" || !["input", "select"].includes(element.localName))).map((name) => attrs[name] ?? null));
25407
25589
  }
25408
25590
  constructor(binding, record2) {
25409
25591
  this.#binding = binding;
@@ -25448,7 +25630,7 @@ var ControlAdapter = class _ControlAdapter {
25448
25630
  this.#pending = true;
25449
25631
  return;
25450
25632
  }
25451
- if (this.constructor.preservesUnchangedValue && this.#hasProjectedValue && this.same(this.#projectedValue, value)) return;
25633
+ if (this.constructor.preservesUnchangedValue && this.#hasProjectedValue && this.same(this.#projectedValue, value) && (!this.#committing || this.same(this.read(), value))) return;
25452
25634
  this.#projectedValue = value;
25453
25635
  this.#hasProjectedValue = true;
25454
25636
  if (this.#committing && this.same(this.read(), value)) return;
@@ -25687,15 +25869,31 @@ var RadioControl = class extends CheckboxControl {
25687
25869
  super.detach();
25688
25870
  }
25689
25871
  /**
25690
- * Follow the semantic form owner: when a `form` or `formId` above the node was added, removed or
25691
- * moved, the button leaves its group and joins the group of the same name in its new scope, with a
25692
- * new generated `name`; the NodeBinding and the element stay (ASTRA-04). A button that is on and
25693
- * meets another button on in the new scope raises before any effect, as at the join (P11).
25872
+ * A changed group clears writable selections in both scopes without replacing the control.
25873
+ * Membership moves before Data writes so synchronous binding projections see the new group.
25874
+ * Form-owner-only moves keep their existing initial-conflict rule.
25694
25875
  */
25695
- refresh() {
25696
- if (this.#name === null) return;
25697
- const group = this.resolved.group;
25876
+ refresh(previousGroup = this.resolved.group) {
25877
+ const group = this.resolved.group ?? null;
25698
25878
  const form = formNode(this.node);
25879
+ if (!Object.is(previousGroup ?? null, group)) {
25880
+ const affected = /* @__PURE__ */ new Set([
25881
+ this,
25882
+ ...this.groups.peers(this),
25883
+ ...group === null ? [] : this.groups.peersOf(group, form)
25884
+ ]);
25885
+ this.groups.leave(this);
25886
+ this.#name = group === null ? null : this.groups.join(this, group, form);
25887
+ if (this.#name === null) this.element.removeAttribute("name");
25888
+ else this.element.setAttribute("name", this.#name);
25889
+ for (const peer of affected) {
25890
+ if (this.binding.closed || !this.binding.runtime.renderer.attached(this.node)) return;
25891
+ if (peer.binding.closed || !peer.binding.runtime.renderer.attached(peer.node)) continue;
25892
+ peer.binding.runtime.renderer.html.writeParameter(peer.node, "value", false);
25893
+ }
25894
+ return;
25895
+ }
25896
+ if (this.#name === null) return;
25699
25897
  if (this.groups.nameOf(group, form) === this.#name) return;
25700
25898
  this.#requireSingleTrue(group, form);
25701
25899
  this.groups.leave(this);
@@ -25708,7 +25906,7 @@ var RadioControl = class extends CheckboxControl {
25708
25906
  */
25709
25907
  #requireSingleTrue(group, form) {
25710
25908
  const node = this.node;
25711
- if (resolved(node, "value") && this.groups.peersOf(group, form).some((peer) => !peer.binding.closed && peer.read())) {
25909
+ if (resolved(this, "value") && this.groups.peersOf(group, form).some((peer) => !peer.binding.closed && peer.read())) {
25712
25910
  throw new Error(`${node.nodeTag} '${node.label}': several true values in radio group '${group}'`);
25713
25911
  }
25714
25912
  }
@@ -25742,7 +25940,7 @@ var RadioControl = class extends CheckboxControl {
25742
25940
  if (this.binding.closed) return;
25743
25941
  if (peer.binding.closed) continue;
25744
25942
  if (peer.element.checked) peer.element.checked = false;
25745
- if (resolved(peer.node, "value")) peer.commit(null);
25943
+ if (resolved(peer, "value")) peer.commit(null);
25746
25944
  }
25747
25945
  }
25748
25946
  };
@@ -25890,6 +26088,9 @@ function componentContext(adapter) {
25890
26088
  getDecimalLibrary,
25891
26089
  publish: (topic, payload) => node.publish(topic, payload),
25892
26090
  isActive: () => !binding.closed,
26091
+ reportError: (error, title) => {
26092
+ if (!binding.closed) binding.runtime.reportError(error, title);
26093
+ },
25893
26094
  callLogic: (name, keywords) => callLogic(binding.runtime, node, name, keywords),
25894
26095
  format: (value, options) => app.format(value, options),
25895
26096
  invoke,
@@ -25912,7 +26113,9 @@ function componentContext(adapter) {
25912
26113
  if (ok) for (const patch of result.datachanges) node.getRelativeData(".").update(patch);
25913
26114
  const attribute = ok ? "validate_onAccept" : "validate_onReject";
25914
26115
  if (rules[attribute]) {
25915
- const report = (error) => console.error("Validation notification failed:", error);
26116
+ const report = (error) => {
26117
+ if (!binding.closed) binding.runtime.reportError(error, "Validation callback failed");
26118
+ };
25916
26119
  try {
25917
26120
  const validations = Object.fromEntries(Object.entries(rules).map(([key, value]) => [key.slice(9), value]));
25918
26121
  const returned = invoke(attribute, rules[attribute], { value: result.value, result, validations, userChange: true });
@@ -25929,14 +26132,21 @@ function componentContext(adapter) {
25929
26132
  };
25930
26133
  }
25931
26134
  function commitComponent(host, outcome, commit) {
26135
+ const context = host.pageContext;
25932
26136
  const finish = (result) => {
25933
26137
  if (result.ok && result.isCurrent()) {
25934
26138
  commit(result);
25935
26139
  host.finishValidation(result);
25936
26140
  }
25937
26141
  };
25938
- if (outcome instanceof Promise) outcome.then(finish).catch((error) => console.error("Validation notification failed:", error));
25939
- else finish(outcome);
26142
+ if (outcome instanceof Promise) outcome.then(finish).catch((error) => context.reportError(error, "Field update failed"));
26143
+ else {
26144
+ try {
26145
+ finish(outcome);
26146
+ } catch (error) {
26147
+ context.reportError(error, "Field update failed");
26148
+ }
26149
+ }
25940
26150
  }
25941
26151
 
25942
26152
  // src/view/html.js
@@ -25988,9 +26198,10 @@ function domPropertyName(name) {
25988
26198
  return PROPERTY_NAMES.get(camel.toLowerCase()) ?? camel;
25989
26199
  }
25990
26200
  var HtmlElement = class {
25991
- constructor({ metadataAttributes = [], invokeScript = null, callLogic: callLogic2 = null } = {}) {
26201
+ constructor({ metadataAttributes = [], invokeScript = null, callLogic: callLogic2 = null, reportError = null } = {}) {
25992
26202
  this.invokeScript = invokeScript;
25993
26203
  this.callLogic = callLogic2;
26204
+ this.reportError = reportError;
25994
26205
  this.metadataAttributes = /* @__PURE__ */ new Set([...META_ATTRS, "_text", ...metadataAttributes]);
25995
26206
  }
25996
26207
  definition(node) {
@@ -26006,6 +26217,7 @@ var HtmlElement = class {
26006
26217
  return { meta, namespace, tag: tag2 };
26007
26218
  }
26008
26219
  validate(node, builder = node.builder) {
26220
+ this.validateLabelbox(node);
26009
26221
  const branch = node.value instanceof SourceBag;
26010
26222
  const text2 = branch ? node.getAttr("_text") : node.value;
26011
26223
  if (text2 != null && !["string", "number", "boolean"].includes(typeof text2)) {
@@ -26023,6 +26235,24 @@ var HtmlElement = class {
26023
26235
  const childTags = branch ? node.value.getNodes().map((child) => child.nodeTag).filter(Boolean) : [];
26024
26236
  builder.validateNode(node, { value: text2, attrs: declaredAttrs, childTags });
26025
26237
  }
26238
+ hasLabelbox(node) {
26239
+ const component = this.definition(node).meta.gramlot_component;
26240
+ if (component?.labelbox) return true;
26241
+ if (component?.presentationDefaults.length) return Object.hasOwn(node.attr, "lbl");
26242
+ return Object.keys(node.attr).some((name) => name === "lbl" || name.startsWith("lbl_") || name.startsWith("box_"));
26243
+ }
26244
+ validateLabelbox(node) {
26245
+ if (!this.hasLabelbox(node)) return;
26246
+ const { tag: tag2, namespace } = this.definition(node);
26247
+ if (namespace !== XHTML_NS && tag2 !== "svg" || ["html", "head", "body", "style", "script", "link", "meta", "title", "base", "tr", "td", "th", "thead", "tbody", "tfoot", "col", "colgroup", "caption", "option", "optgroup", "li", "dt", "dd", "source", "track", "param", "area"].includes(tag2))
26248
+ throw new TypeError("Labelbox requires content that can be placed in an HTML flow container");
26249
+ const parent = node.parentNode;
26250
+ if (parent?.nodeTag) {
26251
+ const definition = this.definition(parent);
26252
+ if (definition.namespace !== XHTML_NS && definition.tag !== "foreignObject" || ["table", "thead", "tbody", "tfoot", "tr", "colgroup", "select", "optgroup", "ul", "ol", "dl", "p", "button", "label"].includes(definition.tag))
26253
+ throw new TypeError("Labelbox requires an HTML flow container");
26254
+ }
26255
+ }
26026
26256
  create(node, document, tag2 = null, attrs = node.attr, visible = null) {
26027
26257
  const { tag: defaultTag, namespace, meta } = this.definition(node);
26028
26258
  tag2 ??= defaultTag;
@@ -26038,6 +26268,7 @@ var HtmlElement = class {
26038
26268
  }
26039
26269
  if (meta.gramlot_component?.sourceContext) {
26040
26270
  element.setSourceContext({
26271
+ reportError: (error, title) => this.reportError(node, error, title),
26041
26272
  publish: (topic, payload) => node.publish(topic, payload),
26042
26273
  writeParameter: (name, value) => this.writeParameter(node, name, value),
26043
26274
  callLogic: (name, keywords) => this.callLogic(node, name, keywords)
@@ -26045,7 +26276,20 @@ var HtmlElement = class {
26045
26276
  }
26046
26277
  const text2 = document.createTextNode(this.text(node));
26047
26278
  if (namespace !== XHTML_NS || !meta.void) element.append(text2);
26048
- const record2 = { element, text: text2, tag: tag2 };
26279
+ const record2 = { element, text: text2, tag: tag2, presentation: element };
26280
+ if (this.hasLabelbox(node)) {
26281
+ this.validateLabelbox(node);
26282
+ const controlBox = document.createElement("div");
26283
+ controlBox.append(element);
26284
+ record2.labelbox = createLabelbox(document, controlBox);
26285
+ record2.presentation = record2.labelbox.box;
26286
+ record2.labelId = `gramlot-label-${randomId()}`;
26287
+ record2.controlId = `gramlot-control-${randomId()}`;
26288
+ const style = document.createElement("style");
26289
+ style.textContent = labelboxStyle;
26290
+ record2.presentation.prepend(style);
26291
+ if (meta.gramlot_component?.labelbox) element.setLabelbox(record2.labelbox);
26292
+ }
26049
26293
  this.update(record2, node, attrs, DEFAULT_TEXT, visible);
26050
26294
  return record2;
26051
26295
  }
@@ -26085,6 +26329,8 @@ var HtmlElement = class {
26085
26329
  }
26086
26330
  }
26087
26331
  const { element, text: text2 } = record2;
26332
+ if (this.hasLabelbox(node) && !record2.labelbox)
26333
+ throw new TypeError("Declare lbl or box_* when creating an experimental HTML labelbox");
26088
26334
  const isHtml = element.namespaceURI === XHTML_NS;
26089
26335
  const renderAttributes = this.definition(node).meta.render_attributes ?? {};
26090
26336
  const previous = record2.attrs ?? {};
@@ -26096,31 +26342,55 @@ var HtmlElement = class {
26096
26342
  const parent = node.parentNode;
26097
26343
  if (parent?._getMeta("gramlot_component")?.childParameters) {
26098
26344
  const Parent = element.ownerDocument.defaultView.customElements.get(parent._getMeta("render_tag"));
26099
- attrs = Parent.projectChild(element, attrs, {
26345
+ attrs = Parent.projectChild(record2.presentation, attrs, {
26346
+ label: node.label,
26100
26347
  adapt,
26101
26348
  invoke: (name, code, keywords) => this.invokeScript(node, name, code, keywords),
26349
+ reportError: (error, title) => this.reportError(node, error, title),
26102
26350
  publish: (topic, payload) => node.publish(topic, payload),
26103
26351
  publishParent: (topic, payload) => parent.publish(topic, payload),
26104
26352
  writeParameter: (name, value) => this.writeParameter(node, name, value),
26105
26353
  remove: () => node.parentBag.popNode(node.label)
26106
26354
  });
26107
26355
  }
26356
+ if (record2.labelbox) {
26357
+ record2.labelbox.box.style.visibility = "";
26358
+ projectLabelbox(record2.labelbox, attrs, adapt);
26359
+ }
26108
26360
  if (this.definition(node).meta.gramlot_component) {
26109
26361
  if (this.definition(node).meta.gramlot_component.bagStore) {
26110
26362
  element.setStoreBag(node.getRelativeData(node.getAttr("storepath")));
26111
26363
  }
26112
26364
  attrs = element.projectAttributes(attrs, adapt);
26113
26365
  }
26366
+ if (record2.labelbox) {
26367
+ attrs = Object.fromEntries(Object.entries(attrs).filter(([name]) => name !== "lbl" && !name.startsWith("lbl_") && !name.startsWith("box_")));
26368
+ if (attrs.slot != null) record2.presentation.setAttribute("slot", attrs.slot);
26369
+ else if (record2.presentationSlot != null) record2.presentation.removeAttribute("slot");
26370
+ record2.presentationSlot = attrs.slot;
26371
+ delete attrs.slot;
26372
+ }
26114
26373
  attrs = Object.fromEntries(sourceAttributeItems({ ...attrs, ...renderAttributes }));
26115
26374
  const controlled = ControlAdapter.classFor(element, attrs) !== null;
26116
26375
  if (textValue2 === DEFAULT_TEXT) textValue2 = this.text(node);
26117
26376
  const nextText = textValue2 == null ? "" : String(textValue2);
26118
26377
  if (text2.data !== nextText) text2.data = nextText;
26119
26378
  const keys = [.../* @__PURE__ */ new Set([...Object.keys(previous), ...Object.keys(attrs)])];
26120
- keys.sort((a, b) => (b === "sandbox") - (a === "sandbox"));
26379
+ keys.sort((a, b) => (b === "sandbox") - (a === "sandbox") || (isHtml && element.localName === "input" ? (b === "type") - (a === "type") : 0));
26121
26380
  for (const key of keys) {
26122
26381
  if (this.metadataAttributes.has(key) || ["ask", "_ask"].includes(key) || controlled && key === "value") continue;
26123
26382
  const value = attrs[key];
26383
+ if (isHtml && key === "multiple" && ["input", "select"].includes(element.localName)) {
26384
+ if (element.multiple !== Boolean(value)) element.multiple = Boolean(value);
26385
+ continue;
26386
+ }
26387
+ if (isHtml && element.localName === "input" && key === "type") {
26388
+ if (!Object.is(previous.type, value)) {
26389
+ if (value == null) element.removeAttribute("type");
26390
+ else element.type = String(value);
26391
+ }
26392
+ continue;
26393
+ }
26124
26394
  const attrName = key;
26125
26395
  const propertyName = domPropertyName(attrName);
26126
26396
  const isBoolean = isHtml && BOOLEAN_PROPERTIES.has(propertyName) && typeof element[propertyName] === "boolean";
@@ -26145,6 +26415,22 @@ var HtmlElement = class {
26145
26415
  else element.setAttribute("style", String(attrs.style));
26146
26416
  }
26147
26417
  record2.visible = visible;
26418
+ if (record2.labelbox) {
26419
+ const { fieldLabel, labelBox, box } = record2.labelbox;
26420
+ if (["input", "textarea", "select", "button", "output", "meter", "progress"].includes(record2.tag)) {
26421
+ if (!element.id) element.id = record2.controlId;
26422
+ fieldLabel.htmlFor = element.id;
26423
+ } else {
26424
+ fieldLabel.id = record2.labelId;
26425
+ if (!this.definition(node).meta.gramlot_component?.labelbox) {
26426
+ box.setAttribute("role", "group");
26427
+ if (labelBox.hidden) box.removeAttribute("aria-labelledby");
26428
+ else box.setAttribute("aria-labelledby", fieldLabel.id);
26429
+ }
26430
+ }
26431
+ box.hidden = !!attrs.hidden;
26432
+ if (visible === false) box.style.visibility = "hidden";
26433
+ }
26148
26434
  record2.attrs = attrs;
26149
26435
  }
26150
26436
  text(node) {
@@ -27764,7 +28050,7 @@ var RemoteBinding = class {
27764
28050
  }
27765
28051
  /** Start `_timing` again from its current value: called at every registration of the node's pointers. */
27766
28052
  register() {
27767
- this.#timers.startTiming(this.#control("_timing"), () => this.update());
28053
+ this.#timers.startTiming(this.#control("_timing"), () => this.trigger());
27768
28054
  }
27769
28055
  /**
27770
28056
  * A Data change of `remote` or of a `remote_<k>` parameter: `_userChanges` lets only the level `node`
@@ -27773,8 +28059,14 @@ var RemoteBinding = class {
27773
28059
  receive(change) {
27774
28060
  if (this.#control("_userChanges") && change.level !== "node") return;
27775
28061
  const delay = this.#control("_delay");
27776
- if (delay > 0) this.#timers.debounce(delay, () => this.update());
27777
- else this.update();
28062
+ if (delay > 0) this.#timers.debounce(delay, () => this.trigger());
28063
+ else this.trigger();
28064
+ }
28065
+ /** Runtime-owned triggers report failures; explicit update callers still receive rejection. */
28066
+ trigger() {
28067
+ void this.update().catch((error) => {
28068
+ if (!this.closed) this.binding.runtime.reportError(error, "Content could not be loaded");
28069
+ });
27778
28070
  }
27779
28071
  /**
27780
28072
  * Request the fragment for the current parameters. Nothing happens before the node's `start` step,
@@ -27809,7 +28101,7 @@ var RemoteBinding = class {
27809
28101
  throw new Error(`${node.nodeTag} '${node.label}': remote '${name}' failed: ${error.message}`, { cause: error });
27810
28102
  }
27811
28103
  const onRemote = node.getAttr("_onRemote");
27812
- if (!this.closed && mounted && onRemote) this.#inline("_onRemote", onRemote, onRemote, params);
28104
+ if (!this.closed && mounted && onRemote) await this.#inline("_onRemote", onRemote, onRemote, params);
27813
28105
  }
27814
28106
  /**
27815
28107
  * Record the fragment `remoteSource` mounted on the node, with its method and the TYTX of its parameters:
@@ -27975,6 +28267,101 @@ var AskDialog = class {
27975
28267
  }
27976
28268
  };
27977
28269
 
28270
+ // src/binding/error-notifications.js
28271
+ var ErrorNotifications = class {
28272
+ #runtime;
28273
+ #id = `errors_${randomId()}`;
28274
+ #group = null;
28275
+ #notices = /* @__PURE__ */ new Map();
28276
+ #dismissed = /* @__PURE__ */ new Set();
28277
+ #overflowCount = 0;
28278
+ constructor(runtime) {
28279
+ this.#runtime = runtime;
28280
+ }
28281
+ show(error, title) {
28282
+ const seen = /* @__PURE__ */ new Set(), details = [];
28283
+ for (let current = error; current !== null && typeof current === "object" && !seen.has(current); current = current.cause) {
28284
+ if (current.name === "AbortError") return;
28285
+ seen.add(current);
28286
+ details.push(current.stack ?? current.message);
28287
+ }
28288
+ const message = typeof error?.message === "string" ? error.message : String(error);
28289
+ queueMicrotask(() => {
28290
+ if (this.#runtime.disposed) return;
28291
+ this.#show(message, title, details.join("\nCaused by:\n"));
28292
+ });
28293
+ }
28294
+ #show(message, title, details) {
28295
+ const app = this.#runtime.gramlot, key = JSON.stringify([title, message]);
28296
+ if (this.#dismissed.has(key)) return;
28297
+ let panel = this.#runtime.nodeIds.get(this.#id);
28298
+ if (!panel) {
28299
+ this.#notices.clear();
28300
+ this.#overflowCount = 0;
28301
+ if (this.#group === null) {
28302
+ const notices = this;
28303
+ class Logic {
28304
+ close(node) {
28305
+ notices.#close(node.getAttr("notice"));
28306
+ }
28307
+ }
28308
+ this.#group = `errors_${randomId()}`;
28309
+ this.#runtime.logicRegistry.register(Logic, { group: this.#group, resource: "gramlot:error-notifications" });
28310
+ }
28311
+ const builder = new GramlotBuilder();
28312
+ builder.root.aside({
28313
+ nodeId: this.#id,
28314
+ class: "gramlot-error-notifications",
28315
+ popover: "manual",
28316
+ "aria-label": "Error notifications",
28317
+ style: "position:fixed;inset:auto max(12px,env(safe-area-inset-right)) max(12px,env(safe-area-inset-bottom)) auto;margin:0;width:360px;max-width:calc(100vw - 24px);max-height:50vh;overflow:auto;box-sizing:border-box;padding:0;border:1px solid var(--gramlot-border-control,#aab4c2);border-radius:8px;background:var(--gramlot-surface,#fff);color:var(--gramlot-ink,#222);font:13px/1.4 system-ui;box-shadow:0 6px 24px #0003;"
28318
+ });
28319
+ app.src.source.setItem(this.#id, app.src.prepareSource(builder.source));
28320
+ panel = this.#runtime.nodeIds.get(this.#id);
28321
+ }
28322
+ if (this.#notices.has(key)) return;
28323
+ if (this.#notices.size === 5) {
28324
+ const text2 = `${++this.#overflowCount} additional errors`;
28325
+ const counter = panel.value.getNode("overflow");
28326
+ if (counter) counter.setValue(text2);
28327
+ else app.src.builder.wrapSource(panel).p(text2, { node_label: "overflow", role: "status", style: "margin:0;padding:12px;" });
28328
+ return;
28329
+ }
28330
+ const id = `notice_${randomId()}`;
28331
+ const fragment = new GramlotBuilder();
28332
+ const notice = fragment.root.article({ role: "alert", style: "color:inherit;padding:12px;border-bottom:1px solid var(--gramlot-border,#ddd);" });
28333
+ const header = notice.div({ style: "display:flex;align-items:start;gap:12px;" });
28334
+ header.strong(`==${JSON.stringify(title)}`, { style: "flex:1;color:var(--gramlot-error,#b13d48);" });
28335
+ header.html_button("\xD7", {
28336
+ type: "button",
28337
+ notice: id,
28338
+ connect_onclick: `${this.#group}.close`,
28339
+ "aria-label": "Dismiss notification",
28340
+ title: "Dismiss notification",
28341
+ style: "border:0;background:transparent;color:inherit;font:18px/1 system-ui;width:24px;height:24px;flex:0 0 24px;padding:0;cursor:pointer;"
28342
+ });
28343
+ notice.p(`==${JSON.stringify(message)}`, { style: "margin:6px 0;overflow-wrap:anywhere;" });
28344
+ const disclosure = notice.details({ style: "border:0;padding:0;margin:8px 0 0;background:transparent;" });
28345
+ disclosure.summary("Details", { style: "cursor:pointer;" });
28346
+ disclosure.pre(`==${JSON.stringify(details)}`, { style: "font:11px/1.4 monospace;white-space:pre-wrap;overflow-wrap:anywhere;margin:6px 0 0;padding:8px;border:0;border-radius:4px;background:var(--gramlot-surface-subtle,#f2f4f6);" });
28347
+ const slot = app.src.builder.wrapSource(panel).div({ node_label: id });
28348
+ sourceTarget(slot).setValue(app.src.prepareSource(fragment.source));
28349
+ this.#notices.set(key, id);
28350
+ app.dom.getDomNode(panel).showPopover();
28351
+ }
28352
+ #close(id) {
28353
+ const panel = this.#runtime.nodeIds.get(this.#id);
28354
+ panel.value.popNode(id);
28355
+ for (const [key, value] of this.#notices) if (value === id) {
28356
+ this.#notices.delete(key);
28357
+ this.#dismissed.add(key);
28358
+ }
28359
+ if (!this.#notices.size) {
28360
+ this.#runtime.gramlot.src.source.popNode(this.#id);
28361
+ }
28362
+ }
28363
+ };
28364
+
27978
28365
  // src/binding/runtime.js
27979
28366
  var PROVIDERS = {
27980
28367
  dataFormula: FormulaProvider,
@@ -27991,6 +28378,7 @@ var BindingRuntime = class {
27991
28378
  #installer;
27992
28379
  #inlineCompiler;
27993
28380
  #askDialog;
28381
+ #errorNotifications;
27994
28382
  #subscriptions;
27995
28383
  #subscription = `gramlot-data-${randomId()}`;
27996
28384
  #disposed = false;
@@ -28001,10 +28389,14 @@ var BindingRuntime = class {
28001
28389
  this.#installer = new DataInstaller(this);
28002
28390
  this.#inlineCompiler = new InlineCompiler(this);
28003
28391
  this.#askDialog = new AskDialog(this);
28392
+ this.#errorNotifications = new ErrorNotifications(this);
28004
28393
  }
28005
28394
  get gramlot() {
28006
28395
  return this.#gramlot;
28007
28396
  }
28397
+ reportError(error, title) {
28398
+ if (!this.disposed) this.#errorNotifications.show(error, title);
28399
+ }
28008
28400
  /** The page topics and Source self-topics: the private `_subscriptions` of the Gramlot instance, given at construction. */
28009
28401
  get subscriptions() {
28010
28402
  return this.#subscriptions;
@@ -28108,7 +28500,7 @@ var BindingRuntime = class {
28108
28500
  const nodes = this.#branchNodes(node);
28109
28501
  for (const each of nodes) this.bindingFor(each)?.rebind();
28110
28502
  for (const each of nodes) this.renderer.project(each);
28111
- for (const each of nodes) this.bindingFor(each)?.remote?.update();
28503
+ for (const each of nodes) this.bindingFor(each)?.remote?.trigger();
28112
28504
  }
28113
28505
  /**
28114
28506
  * Semantic work of one Source event, called inside the renderer FIFO (§5.2).
@@ -28258,7 +28650,7 @@ var BindingRuntime = class {
28258
28650
  if (binding.hasStamp("start")) return;
28259
28651
  binding.stamp("start");
28260
28652
  this.#lifecycle(binding, "start", "_onStart");
28261
- binding.remote?.update();
28653
+ binding.remote?.trigger();
28262
28654
  }
28263
28655
  /** Invoke the providers of `binding` for the lifecycle trigger `kind` when `attribute` is on; a number delays it. */
28264
28656
  #lifecycle(binding, kind, attribute) {
@@ -28677,7 +29069,7 @@ var DragDrop = class {
28677
29069
  effectAllowed,
28678
29070
  phase: "active",
28679
29071
  tags: [declaredTags, prepared.dragValues.dragTags].filter(Boolean).join(","),
28680
- endTopic: this.#renderer.binding.gramlot._subscriptions.topicFor(record2.node, "endDrag"),
29072
+ endTopic: this.#renderer.binding.subscriptions.topicFor(record2.node, "endDrag"),
28681
29073
  source: {
28682
29074
  pageId: this.#renderer.binding.gramlot.pageId ?? null,
28683
29075
  sourcePath: record2.node.fullpath,
@@ -28778,8 +29170,9 @@ var DragDrop = class {
28778
29170
  event.preventDefault();
28779
29171
  if (this.#session.phase !== "active") return;
28780
29172
  const session = this.#session;
29173
+ let target;
28781
29174
  try {
28782
- const target = this.#target(event);
29175
+ target = this.#target(event);
28783
29176
  if (this.#session !== session) {
28784
29177
  event.dataTransfer.dropEffect = "none";
28785
29178
  return;
@@ -28798,7 +29191,7 @@ var DragDrop = class {
28798
29191
  session.phase = "rejected";
28799
29192
  this.#clearPayload();
28800
29193
  }
28801
- this.#report(error);
29194
+ if (!target || this.#renderer.records.has(target.record.node)) this.#report(error);
28802
29195
  }
28803
29196
  }
28804
29197
  #showFeedback(element, accepted) {
@@ -28837,7 +29230,7 @@ var DragDrop = class {
28837
29230
  void this.#renderer.endDrag(session.record.node, { source: { ...session.source }, dropEffect }, session.endTopic).catch((error) => this.#report(error));
28838
29231
  }
28839
29232
  #report(error) {
28840
- console.error("Gramlot drag/drop failed:", error);
29233
+ this.#renderer.binding.reportError(error, "Drag and drop failed");
28841
29234
  }
28842
29235
  dispose() {
28843
29236
  this.#clearSession();
@@ -28870,6 +29263,9 @@ var GramlotRenderer = class extends GramlotHtmlRenderer {
28870
29263
  this.destination = destination;
28871
29264
  this.html = new HtmlElement({
28872
29265
  metadataAttributes: ["__ref"],
29266
+ reportError: (node, error, title) => {
29267
+ if (this.records.has(node)) binding.reportError(error, title);
29268
+ },
28873
29269
  callLogic: (node, name, keywords) => {
28874
29270
  const { group, method } = binding.gramlot.src.logicRegistry.resolve(name, node);
28875
29271
  return method.call(group, node, keywords);
@@ -28959,7 +29355,7 @@ var GramlotRenderer = class extends GramlotHtmlRenderer {
28959
29355
  const declared = node.getAttr();
28960
29356
  this.#presentationDefaults.set(node, Object.fromEntries(Object.entries(attrs).filter(([name]) => Object.hasOwn(declared, name) && component.presentationDefaults.some((prefix) => name.startsWith(prefix)))));
28961
29357
  }
28962
- if (component && (component.parameters.value?.binding === "twoWay" || component.presentationDefaults.length)) {
29358
+ if (this.html.hasLabelbox(node) || component?.presentationDefaults.length) {
28963
29359
  const ancestors = [];
28964
29360
  for (let parent = node.parentNode; parent; parent = parent.parentNode) {
28965
29361
  if (this.#presentationDefaults.has(parent)) ancestors.unshift(this.#presentationDefaults.get(parent));
@@ -29051,11 +29447,13 @@ var GramlotRenderer = class extends GramlotHtmlRenderer {
29051
29447
  record2.shape = ControlAdapter.shape(record2.element, resolved2);
29052
29448
  this.records.set(node, record2);
29053
29449
  this.elements.set(record2.element, record2);
29450
+ this.elements.set(record2.presentation, record2);
29054
29451
  const control = ControlAdapter.for(record2.binding, record2);
29452
+ if (control || record2.element.namespaceURI === XHTML_NS && record2.element.localName === "input")
29453
+ record2.cleanup.push(() => record2.control?.detach());
29055
29454
  if (control) {
29056
29455
  record2.control = control;
29057
29456
  control.attach();
29058
- record2.cleanup.push(() => control.detach());
29059
29457
  this.#projectControl(record2, node, attrs, null);
29060
29458
  }
29061
29459
  const button = ButtonBinding.for(record2.binding, record2);
@@ -29078,7 +29476,7 @@ var GramlotRenderer = class extends GramlotHtmlRenderer {
29078
29476
  child.container = record2.element;
29079
29477
  record2.children.add(child.node);
29080
29478
  }
29081
- return record2.element;
29479
+ return record2.presentation;
29082
29480
  }
29083
29481
  /**
29084
29482
  * Validate a detached candidate without changing the observed Source (§5.1 step 1): grammar,
@@ -29274,7 +29672,7 @@ var GramlotRenderer = class extends GramlotHtmlRenderer {
29274
29672
  for (let i = siblings.indexOf(node) + 1; i < siblings.length; i++) {
29275
29673
  const record2 = this.records.get(siblings[i]);
29276
29674
  if (record2) {
29277
- before = record2.element ?? record2.start;
29675
+ before = record2.presentation ?? record2.start;
29278
29676
  break;
29279
29677
  }
29280
29678
  }
@@ -29353,18 +29751,23 @@ var GramlotRenderer = class extends GramlotHtmlRenderer {
29353
29751
  * adaptation as the first render, by the node's own renderer (R16). A node without an element
29354
29752
  * (not built yet, frozen before its first build, a fragment) is left alone; under freeze the
29355
29753
  * elements already built are projected. `change` is the DataChange that asked for it, or null.
29356
- * A form control whose resolved `type`, `multiple` or `group` changed is rebuilt instead, keeping
29754
+ * Native input.type and input/select.multiple use setters. Other shape changes rebuild, keeping
29357
29755
  * its NodeBinding; under freeze the rebuild waits for the thaw (C04.1, D7). The resolved projection
29358
29756
  * (runtimeValues, then `==`) is computed once and is what every consumer reads, the rebuild included.
29359
29757
  */
29360
29758
  project(node, change = null) {
29361
29759
  const record2 = this.records.get(node);
29362
- if (!record2?.element) return;
29760
+ if (!record2?.element || !this.attached(node)) return;
29363
29761
  const renderer = this.getRender(node.builder);
29364
29762
  const previousDefaults = this.#presentationDefaults.get(node);
29365
29763
  const [value, runtimeAttrs] = node.rootBuilder.runtimeValues(node);
29366
29764
  const [, resolvedAttrs] = renderer._handleMeta(node, runtimeAttrs);
29367
29765
  const resolved2 = this.#resolvedAttributes.get(node);
29766
+ const typeChanged = record2.element.namespaceURI === XHTML_NS && record2.element.localName === "input" && !Object.is(record2.resolved.type, resolved2.type);
29767
+ const multipleChanged = record2.element.namespaceURI === XHTML_NS && ["input", "select"].includes(record2.element.localName) && Boolean(record2.resolved.multiple) !== Boolean(resolved2.multiple);
29768
+ const previousGroup = record2.resolved.group;
29769
+ const groupChanged = record2.control instanceof RadioControl && !Object.is(previousGroup ?? null, resolved2.group ?? null);
29770
+ if ((typeChanged || multipleChanged || groupChanged) && this.#isFrozen(node)) return;
29368
29771
  if (record2.shape !== ControlAdapter.shape(record2.element, resolved2)) {
29369
29772
  if (this.#isFrozen(node)) return;
29370
29773
  this.#rebuildAttributes.set(node, resolved2);
@@ -29375,6 +29778,16 @@ var GramlotRenderer = class extends GramlotHtmlRenderer {
29375
29778
  }
29376
29779
  return;
29377
29780
  }
29781
+ const Control = typeChanged ? ControlAdapter.classFor(record2.element, resolved2) : null;
29782
+ const replaceControl = typeChanged && (record2.control?.constructor ?? null) !== Control;
29783
+ const keepDraft = (typeChanged || multipleChanged && record2.element.localName === "input") && !replaceControl && record2.control && Object.is(record2.resolved.value, resolved2.value);
29784
+ if (replaceControl) {
29785
+ record2.control?.detach();
29786
+ record2.control = null;
29787
+ }
29788
+ if (groupChanged && !replaceControl && resolved2.group != null && node.getAttr("name") != null) {
29789
+ throw new TypeError(`${node.nodeTag} '${node.label}': name and group are two names`);
29790
+ }
29378
29791
  record2.resolved = resolved2;
29379
29792
  let attrs = node._getMeta("subbuilder") ? resolvedAttrs : renderer.adaptAttrs(resolvedAttrs);
29380
29793
  const branch = node.value instanceof SourceBag;
@@ -29389,7 +29802,16 @@ var GramlotRenderer = class extends GramlotHtmlRenderer {
29389
29802
  }
29390
29803
  attrs = this.componentAttributes(node, attrs);
29391
29804
  this.html.update(record2, node, attrs, branch ? attrs._text : text2, resolved2.visible ?? null);
29392
- this.#projectControl(record2, node, attrs, change);
29805
+ if (replaceControl && Control) {
29806
+ record2.control = new Control(record2.binding, record2);
29807
+ record2.control.attach();
29808
+ }
29809
+ if (groupChanged && !replaceControl) {
29810
+ record2.control.refresh(previousGroup ?? null);
29811
+ if (this.records.get(node) === record2 && !record2.binding.closed) this.project(node);
29812
+ return;
29813
+ }
29814
+ if (!keepDraft) this.#projectControl(record2, node, attrs, change);
29393
29815
  record2.control?.refresh();
29394
29816
  record2.button?.refresh();
29395
29817
  record2.menu?.refresh();
@@ -29412,7 +29834,7 @@ var GramlotRenderer = class extends GramlotHtmlRenderer {
29412
29834
  let inherited = changed;
29413
29835
  if (component?.presentationDefaults.length) {
29414
29836
  inherited = new Set([...changed].filter((name) => !Object.hasOwn(declared, name)));
29415
- } else if (component?.parameters.value?.binding === "twoWay" && [...changed].some((name) => !Object.hasOwn(declared, name))) {
29837
+ } else if (this.html.hasLabelbox(child) && [...changed].some((name) => !Object.hasOwn(declared, name))) {
29416
29838
  this.project(child);
29417
29839
  }
29418
29840
  if (inherited.size) this.#refreshPresentation(child, inherited);
@@ -29500,7 +29922,7 @@ var GramlotRenderer = class extends GramlotHtmlRenderer {
29500
29922
  }
29501
29923
  #rebuild(node) {
29502
29924
  const record2 = this.records.get(node);
29503
- const before = record2.element?.nextSibling ?? record2.end?.nextSibling ?? null;
29925
+ const before = record2.presentation?.nextSibling ?? record2.end?.nextSibling ?? null;
29504
29926
  const container = record2.container;
29505
29927
  const parent = record2.parent;
29506
29928
  let removeError = null;
@@ -29551,7 +29973,8 @@ var GramlotRenderer = class extends GramlotHtmlRenderer {
29551
29973
  }
29552
29974
  this.references?.remove(node);
29553
29975
  if (record2.element) this.elements.delete(record2.element);
29554
- record2.element?.remove();
29976
+ if (record2.presentation) this.elements.delete(record2.presentation);
29977
+ record2.presentation?.remove();
29555
29978
  record2.start?.remove();
29556
29979
  record2.end?.remove();
29557
29980
  record2.parent?.children.delete(node);
@@ -30004,6 +30427,15 @@ var DomHandler = class extends Handler {
30004
30427
  if (mode === "auto") root.removeAttribute("data-gramlot-touch");
30005
30428
  else root.setAttribute("data-gramlot-touch", mode);
30006
30429
  }
30430
+ /** Navigate the current document to an explicit HTTP(S) URL selected by page policy. */
30431
+ navigate(url) {
30432
+ if (typeof url !== "string" || !url) throw new TypeError("Navigation requires an absolute HTTP(S) URL");
30433
+ const target = new URL(url);
30434
+ if (!["http:", "https:"].includes(target.protocol) || target.username || target.password) {
30435
+ throw new TypeError("Navigation requires an HTTP(S) URL without credentials");
30436
+ }
30437
+ this.gramlot.src.renderer.destination.ownerDocument.defaultView.location.assign(target.href);
30438
+ }
30007
30439
  reference(descriptor) {
30008
30440
  return this.gramlot.src.renderer.references.resolve(descriptor);
30009
30441
  }
@@ -30291,117 +30723,1244 @@ var SubscriptionsHandler = class extends Handler {
30291
30723
  }
30292
30724
  };
30293
30725
 
30294
- // src/inout.js
30295
- var MAILTO_LIMIT = 2e3;
30296
- function leafText(value) {
30297
- if (!(value instanceof Date)) return String(value ?? "");
30298
- const text2 = value.toISOString();
30299
- return text2.endsWith("T00:00:00.000Z") ? text2.slice(0, 10) : text2;
30300
- }
30301
- var InOut = class {
30302
- constructor(gramlot, document) {
30303
- this.gramlot = gramlot;
30304
- this.document = document;
30726
+ // src/binding/device-resolver.js
30727
+ var DeviceResolver = class extends BagResolver {
30728
+ constructor(handler, name, cacheTime) {
30729
+ super({ cacheTime });
30730
+ this.handler = handler;
30731
+ this.name = name;
30732
+ this.failed = false;
30733
+ this.writing = false;
30734
+ this.request = null;
30735
+ this.revision = 0;
30736
+ this.received = 0;
30305
30737
  }
30306
- /** The Bag at path in the Data. */
30307
- branch(path) {
30308
- const value = this.gramlot.data.getItem(path);
30309
- if (!(value instanceof Bag)) throw new Error(`gramlot.utl.inout: no data Bag at '${path}'`);
30310
- return value;
30738
+ resolve({ static: isStatic = false } = {}) {
30739
+ if (!isStatic && !this.handler.disposed && !this.writing && !this.request && !this.failed && !this._node.attr.watching && this.expired) this.handler.refresh(this.name);
30740
+ return this.cachedValue;
30311
30741
  }
30312
- /** One `relative.path: value` line per leaf of the branch at path. */
30313
- mailText(path) {
30314
- const lines = [];
30315
- const walk2 = (bag, prefix) => {
30316
- for (const node of bag.getNodes()) {
30317
- const label = prefix + node.label;
30318
- if (node.value instanceof Bag) walk2(node.value, `${label}.`);
30319
- else lines.push(`${label}: ${leafText(node.value)}`);
30320
- }
30321
- };
30322
- walk2(this.branch(path), "");
30323
- return lines.join("\n");
30742
+ reset() {
30743
+ super.reset();
30744
+ this.failed = false;
30745
+ this.revision++;
30324
30746
  }
30325
- /** The mailto: URL of sendMail; longer than MAILTO_LIMIT raises an Error. */
30326
- mailtoUrl(path, email) {
30327
- const url = `mailto:${encodeURIComponent(email)}?subject=${encodeURIComponent(this.document.title)}&body=${encodeURIComponent(this.mailText(path))}`;
30328
- if (url.length > MAILTO_LIMIT) {
30329
- throw new Error(`gramlot.utl.inout.sendMail: the email of '${path}' is ${url.length} characters long, over the mailto: limit of ${MAILTO_LIMIT}; send it with sendHttp or save it as a file`);
30747
+ };
30748
+
30749
+ // src/handlers/device-handler.js
30750
+ var NAMES = ["appinfo", "location"];
30751
+ var ERROR_STATUS = {
30752
+ UNAVAILABLE: "unavailable",
30753
+ PERMISSION_DENIED: "denied",
30754
+ TIMEOUT: "error",
30755
+ FAILED: "error",
30756
+ CANCELLED: "cancelled"
30757
+ };
30758
+ function failureAttributes(error) {
30759
+ const code = Object.hasOwn(ERROR_STATUS, error?.code) ? error.code : "FAILED";
30760
+ return {
30761
+ status: ERROR_STATUS[code],
30762
+ error: code === "CANCELLED" ? null : { code, message: String(error?.message ?? "Device operation failed") }
30763
+ };
30764
+ }
30765
+ var DeviceHandler = class extends Handler {
30766
+ #database = null;
30767
+ #clipboardRequest = null;
30768
+ #captureRequest = null;
30769
+ #audio = null;
30770
+ #barcodeRequest = null;
30771
+ #hapticRequest = null;
30772
+ #stateEvents = /* @__PURE__ */ new Map();
30773
+ #sensors = /* @__PURE__ */ new Map();
30774
+ #biometricsRequest = null;
30775
+ #notificationRequest = null;
30776
+ #notificationEvents = null;
30777
+ #pushRequest = null;
30778
+ #pushEvents = null;
30779
+ #shortcutEvents = null;
30780
+ #linkEvents = null;
30781
+ constructor(gramlot) {
30782
+ super(gramlot);
30783
+ this.provider = null;
30784
+ this.disposed = false;
30785
+ this.monitor = null;
30786
+ this.retiring = null;
30787
+ this.resolvers = /* @__PURE__ */ new Map();
30788
+ this.cleanup = Promise.resolve();
30789
+ }
30790
+ installData() {
30791
+ const { gramlot } = this;
30792
+ gramlot.data.setItem("gramlot.device.database", null, { status: "idle", error: null });
30793
+ gramlot.data.setItem("gramlot.device.orientation", null, { status: "idle", error: null, listening: false });
30794
+ for (const name of ["gyroscope", "accelerometer"]) {
30795
+ gramlot.data.setItem(
30796
+ `gramlot.device.${name}`,
30797
+ null,
30798
+ { enabled: false, watching: false, status: "idle", error: null }
30799
+ );
30800
+ gramlot.data.getNode(`gramlot.device.${name}`).setAttr({ error: null }, false, true, false);
30801
+ this.#sensors.set(name, {
30802
+ node: gramlot.data.getNode(`gramlot.device.${name}`),
30803
+ stream: null,
30804
+ cleanup: Promise.resolve()
30805
+ });
30330
30806
  }
30331
- return url;
30332
- }
30333
- /** Prepare an email to email in the mail program of the user, with the data at path as text lines. */
30334
- sendMail(path, email) {
30335
- this.open(this.mailtoUrl(path, email));
30807
+ for (const name of NAMES) {
30808
+ const path = `gramlot.device.${name}`;
30809
+ const attrs = { status: "idle", error: null, cacheTime: name === "appinfo" ? -1 : 5 };
30810
+ if (name === "location") Object.assign(attrs, { enabled: false, watching: false });
30811
+ gramlot.data.setItem(path, null);
30812
+ const node = gramlot.data.getNode(path);
30813
+ node.setAttr(attrs, false, true, false);
30814
+ const resolver = new DeviceResolver(this, name, attrs.cacheTime);
30815
+ node.resolver = resolver;
30816
+ this.resolvers.set(name, resolver);
30817
+ }
30818
+ gramlot.data.setItem(
30819
+ "gramlot.device.clipboard",
30820
+ null,
30821
+ { status: "idle", error: null, text: "", copy: null, paste: null, operation: null }
30822
+ );
30823
+ const clipboard = gramlot.data.getNode("gramlot.device.clipboard");
30824
+ gramlot.data.setItem("gramlot.device.camera", null, { status: "idle", error: null, capture: null, choose: null });
30825
+ const camera = gramlot.data.getNode("gramlot.device.camera");
30826
+ gramlot.data.setItem("gramlot.device.barcode", null, { status: "idle", error: null, scan: null });
30827
+ const barcode = gramlot.data.getNode("gramlot.device.barcode");
30828
+ gramlot.data.setItem("gramlot.device.biometrics", null, { status: "idle", error: null, verify: null });
30829
+ const biometrics = gramlot.data.getNode("gramlot.device.biometrics");
30830
+ const notifications = new Bag();
30831
+ notifications.setItem("request", new Bag());
30832
+ for (const name of ["scheduled", "received", "action"]) notifications.setItem(name, null);
30833
+ gramlot.data.setItem(
30834
+ "gramlot.device.notifications",
30835
+ notifications,
30836
+ { status: "idle", error: null, schedule: null, listening: false, listenerError: null }
30837
+ );
30838
+ const notificationNode = gramlot.data.getNode("gramlot.device.notifications");
30839
+ const push = new Bag();
30840
+ for (const name of ["registration", "received", "action"]) push.setItem(name, null);
30841
+ gramlot.data.setItem(
30842
+ "gramlot.device.push",
30843
+ push,
30844
+ { status: "idle", error: null, register: null, listening: false, listenerError: null }
30845
+ );
30846
+ const pushNode = gramlot.data.getNode("gramlot.device.push");
30847
+ const links = new Bag();
30848
+ links.setItem("request", null);
30849
+ gramlot.data.setItem("gramlot.device.links", links, { listening: false, listenerError: null });
30850
+ const shortcuts = new Bag();
30851
+ shortcuts.setItem("request", null);
30852
+ gramlot.data.setItem("gramlot.device.shortcuts", shortcuts, { listening: false, listenerError: null });
30853
+ gramlot.data.setItem("gramlot.device.network", null, { status: "idle", error: null, listening: false });
30854
+ const lifecycle = new Bag();
30855
+ lifecycle.setItem("active", null);
30856
+ lifecycle.setItem("event", null);
30857
+ lifecycle.setItem("sequence", 0);
30858
+ gramlot.data.setItem("gramlot.device.lifecycle", lifecycle, { status: "idle", error: null, listening: false });
30859
+ gramlot.data.setItem(
30860
+ "gramlot.device.haptics",
30861
+ null,
30862
+ { status: "idle", error: null, impact: null, style: "medium", vibrate: null, duration: 600 }
30863
+ );
30864
+ const haptics = gramlot.data.getNode("gramlot.device.haptics");
30865
+ gramlot.data.setItem(
30866
+ "gramlot.device.audio",
30867
+ null,
30868
+ {
30869
+ status: "idle",
30870
+ error: null,
30871
+ recording: false,
30872
+ start: null,
30873
+ stop: null,
30874
+ cancel: null,
30875
+ share: null,
30876
+ shareStatus: "idle",
30877
+ shareError: null,
30878
+ shareActivity: null
30879
+ }
30880
+ );
30881
+ const audio = gramlot.data.getNode("gramlot.device.audio");
30882
+ gramlot.data.subscribe("gramlot.device", { update: (event) => {
30883
+ if (this.disposed) return;
30884
+ for (const [name, sensor] of this.#sensors) {
30885
+ if (event.node === sensor.node && event.attrs_diff?.enabled) {
30886
+ if (typeof sensor.node.attr.enabled !== "boolean") throw new TypeError("Device enabled must be boolean");
30887
+ this.#reconcileSensor(name, sensor);
30888
+ }
30889
+ }
30890
+ if (event.node === clipboard && event.fired) {
30891
+ if (event.attrs_diff?.copy?.new === true) this.#clipboardCommand(clipboard, "copy");
30892
+ if (event.attrs_diff?.paste?.new === true) this.#clipboardCommand(clipboard, "paste");
30893
+ }
30894
+ if (event.node === audio && event.fired) {
30895
+ if (event.attrs_diff?.start?.new === true) this.#startAudio(audio);
30896
+ if (event.attrs_diff?.stop?.new === true) this.#stopAudio(audio);
30897
+ if (event.attrs_diff?.cancel?.new === true) this.#cancelAudio(audio);
30898
+ if (event.attrs_diff?.share?.new === true) this.#shareAudio(audio);
30899
+ }
30900
+ if (event.node === haptics && event.fired && event.attrs_diff?.impact?.new === true) {
30901
+ this.#impact(haptics);
30902
+ }
30903
+ if (event.node === haptics && event.fired && event.attrs_diff?.vibrate?.new === true) {
30904
+ this.#vibrate(haptics);
30905
+ }
30906
+ if (event.node === barcode && event.fired && event.attrs_diff?.scan?.new === true) {
30907
+ this.#scanBarcode(barcode);
30908
+ }
30909
+ if (event.node === camera && event.fired && event.attrs_diff?.choose?.new === true) {
30910
+ this.#photo(camera, "choose");
30911
+ }
30912
+ if (event.node === camera && event.fired && event.attrs_diff?.capture?.new === true) {
30913
+ this.#photo(camera, "capture");
30914
+ }
30915
+ if (event.node === biometrics && event.fired && event.attrs_diff?.verify?.new === true) {
30916
+ this.#verifyBiometrics(biometrics);
30917
+ }
30918
+ if (event.node === notificationNode && event.fired && event.attrs_diff?.schedule?.new === true) {
30919
+ this.#scheduleNotification(notificationNode);
30920
+ }
30921
+ if (event.node === pushNode && event.fired && event.attrs_diff?.register?.new === true) {
30922
+ this.#registerPush(pushNode);
30923
+ }
30924
+ for (const resolver of this.resolvers.values()) {
30925
+ if (event.node !== resolver._node) continue;
30926
+ const { cacheTime } = event.node.attr;
30927
+ if (typeof cacheTime !== "number" || !Number.isFinite(cacheTime) || cacheTime < 0 && cacheTime !== -1) {
30928
+ throw new TypeError("Device cacheTime must be -1 or a nonnegative number of seconds");
30929
+ }
30930
+ resolver.cacheTime = cacheTime;
30931
+ if (resolver.name === "location") {
30932
+ if (typeof event.node.attr.enabled !== "boolean") throw new TypeError("Device enabled must be boolean");
30933
+ this.reconcile();
30934
+ }
30935
+ }
30936
+ } });
30336
30937
  }
30337
- /** POST the data at path as a JSON object to url; resolves with the Response, rejects on a status out of 2xx. */
30338
- async sendHttp(path, url) {
30339
- const body = JSON.stringify(this.branch(path).asDict(false, false, true));
30340
- const response = await this.document.defaultView.fetch(url, {
30341
- method: "POST",
30342
- headers: { "Content-Type": "application/json" },
30343
- body
30938
+ /** Attach the explicitly selected provider once, before the page reads device values. */
30939
+ attach(provider, { dispose = null } = {}) {
30940
+ this.assertLive();
30941
+ if (this.provider) throw new Error("A device provider is already attached");
30942
+ if (!Array.isArray(provider.capabilities) || provider.capabilities.some((name) => ![...NAMES, "camera", "biometrics", "notifications", "push", "shortcuts", "barcode", "network", "lifecycle", "haptics", "audio", "clipboard", "links", "orientation", "gyroscope", "accelerometer", "database"].includes(name))) {
30943
+ throw new TypeError("Unknown device provider capability");
30944
+ }
30945
+ if (dispose !== null && typeof dispose !== "function") throw new TypeError("Device attachment dispose must be a function");
30946
+ this.releaseProvider = dispose;
30947
+ this.provider = provider;
30948
+ this.installData();
30949
+ this.reconcile();
30950
+ this.#startStateEvents("orientation", (callback, signal) => provider.startOrientationEvents(callback, signal), (node, state) => {
30951
+ if (!["portrait", "landscape"].includes(state?.type) || !["primary", "secondary"].includes(state.direction) || !Number.isFinite(state.timestamp)) throw new TypeError("Invalid screen orientation from device provider");
30952
+ const value = new Bag();
30953
+ for (const key of ["type", "direction", "timestamp"]) value.setItem(key, state[key]);
30954
+ node.setValue(value, true, { status: "success", error: null }, true, false);
30955
+ });
30956
+ this.#startStateEvents("network", (callback, signal) => provider.startNetworkEvents(callback, signal), (node, state) => {
30957
+ if (typeof state?.connected !== "boolean" || !["none", "unknown", "wifi", "cellular"].includes(state.type)) {
30958
+ throw new TypeError("Invalid network state from device provider");
30959
+ }
30960
+ const value = new Bag();
30961
+ value.setItem("connected", state.connected);
30962
+ value.setItem("type", state.type);
30963
+ node.setValue(value, true, { status: "success", error: null }, true, false);
30964
+ });
30965
+ this.#startStateEvents("lifecycle", (callback, signal) => provider.startLifecycleEvents(callback, signal), (node, event) => {
30966
+ if (event?.kind === "state" && typeof event.active === "boolean") {
30967
+ node.staticValue.setItem("active", event.active);
30968
+ } else if (event?.kind === "pause" || event?.kind === "resume") {
30969
+ node.staticValue.setItem("event", event.kind);
30970
+ node.staticValue.setItem("sequence", node.staticValue.getItem("sequence") + 1);
30971
+ } else {
30972
+ throw new TypeError("Invalid lifecycle event from device provider");
30973
+ }
30974
+ node.setAttr({ status: "success", error: null }, true, true, false);
30975
+ });
30976
+ if (provider.capabilities.includes("links")) {
30977
+ this.#startLinkEvents(this.gramlot.data.getNode("gramlot.device.links"));
30978
+ }
30979
+ if (provider.capabilities.includes("shortcuts")) {
30980
+ this.#startShortcutEvents(this.gramlot.data.getNode("gramlot.device.shortcuts"));
30981
+ }
30982
+ if (provider.capabilities.includes("push")) {
30983
+ this.#startPushEvents(this.gramlot.data.getNode("gramlot.device.push"));
30984
+ }
30985
+ if (provider.capabilities.includes("notifications")) {
30986
+ this.#startNotificationEvents(this.gramlot.data.getNode("gramlot.device.notifications"));
30987
+ }
30988
+ }
30989
+ assertLive() {
30990
+ if (this.disposed) throw new Error("DeviceHandler is disposed");
30991
+ }
30992
+ resolver(name) {
30993
+ this.assertLive();
30994
+ if (!this.resolvers.has(name)) throw new TypeError(`Unknown device value: ${name}`);
30995
+ return this.resolvers.get(name);
30996
+ }
30997
+ invalidate(name) {
30998
+ this.resolver(name).reset();
30999
+ }
31000
+ /** Command only. Success/failure is delivered through Data, never a public Promise. */
31001
+ refresh(name) {
31002
+ const resolver = this.resolver(name);
31003
+ if (resolver.request) return;
31004
+ const request = { revision: resolver.revision, received: resolver.received };
31005
+ resolver.request = request;
31006
+ this.attributes(resolver, { status: "pending", error: null });
31007
+ Promise.resolve().then(() => {
31008
+ if (this.disposed || resolver.request !== request) return;
31009
+ this.requireCapability(name);
31010
+ return name === "appinfo" ? this.provider.readAppInfo() : this.provider.readLocation();
31011
+ }).then((value) => {
31012
+ if (this.disposed || resolver.request !== request) return;
31013
+ this.accept(resolver, value);
31014
+ if (resolver.revision !== request.revision) resolver._lastUpdate = null;
31015
+ }).catch((error) => {
31016
+ if (!this.disposed && resolver.request === request && resolver.received === request.received) {
31017
+ this.failure(resolver, error);
31018
+ }
31019
+ }).finally(() => {
31020
+ if (resolver.request === request) resolver.request = null;
30344
31021
  });
30345
- if (!response.ok) throw new Error(`gramlot.utl.inout.sendHttp: ${url} answered ${response.status}`);
30346
- return response;
30347
- }
30348
- /** Save the data at path as a TYTX file, which restore reads back with its exact types. */
30349
- save(path, filename) {
30350
- this.saveText(this.branch(path).toTytx(), filename, "application/json");
30351
31022
  }
30352
- /** Read a TYTX file chosen by the user into path; resolves with the restored Bag. Needs a user gesture. */
30353
- restore(path) {
30354
- const input = this.document.createElement("input");
30355
- input.type = "file";
30356
- input.accept = ".json,application/json";
30357
- return new Promise((resolve, reject) => {
30358
- input.addEventListener("change", async () => {
31023
+ // Page-owned state streams share lifetime/error handling, never public dispatch.
31024
+ #startStateEvents(name, start, accept) {
31025
+ const node = this.gramlot.data.getNode(`gramlot.device.${name}`);
31026
+ if (!this.provider.capabilities.includes(name)) {
31027
+ node.setAttr(failureAttributes({ code: "UNAVAILABLE", message: `${name} is unavailable` }), true, true, false);
31028
+ return;
31029
+ }
31030
+ const events = { controller: new AbortController() };
31031
+ this.#stateEvents.set(name, events);
31032
+ node.setAttr({ status: "pending", error: null }, true, true, false);
31033
+ events.start = Promise.resolve().then(() => {
31034
+ if (events.controller.signal.aborted) return async () => {
31035
+ };
31036
+ return start((value) => {
31037
+ if (events.controller.signal.aborted) return;
30359
31038
  try {
30360
- const bag = fromTytx(await input.files[0].text());
30361
- if (!(bag instanceof Bag)) throw new TypeError("the file must contain a typed Bag");
30362
- this.gramlot.data.setItem(path, bag);
30363
- resolve(bag);
31039
+ accept(node, value);
30364
31040
  } catch (error) {
30365
- reject(new Error(
30366
- `gramlot.utl.inout.restore: the file is not a saved Gramlot branch: ${error.message}`,
30367
- { cause: error }
30368
- ));
31041
+ node.setAttr(failureAttributes(error), true, true, false);
30369
31042
  }
30370
- }, { once: true });
30371
- input.click();
31043
+ }, events.controller.signal);
31044
+ }).then((stop) => {
31045
+ if (!events.controller.signal.aborted) node.setAttr({ listening: true }, true, true, false);
31046
+ return stop;
31047
+ });
31048
+ events.start.catch((error) => {
31049
+ const aborted = events.controller.signal.aborted;
31050
+ events.controller.abort();
31051
+ if (!aborted) node.setAttr({ ...failureAttributes(error), listening: false }, true, true, false);
30372
31052
  });
30373
31053
  }
30374
- /** Export the data at path as 'json' (Bag.toJson) or 'xml' (Bag.toXml, inside one root element named
30375
- * after the last segment of path); types become text. */
30376
- download(path, filename, format) {
30377
- if (!["json", "xml"].includes(format)) {
30378
- throw new Error(`gramlot.utl.inout.download: format '${format}' is not 'json' or 'xml'`);
31054
+ #reconcileSensor(name, sensor) {
31055
+ const { node } = sensor;
31056
+ if (!node.attr.enabled) {
31057
+ const stream2 = sensor.stream;
31058
+ if (!stream2) return;
31059
+ sensor.stream = null;
31060
+ stream2.controller.abort();
31061
+ sensor.cleanup = stream2.start.then((stop) => stop(), () => void 0).then(() => {
31062
+ if (!this.disposed && !sensor.stream) node.setAttr({ watching: false, status: "idle", error: null }, true, true, false);
31063
+ });
31064
+ sensor.cleanup.catch((error) => {
31065
+ if (!this.disposed) node.setAttr(failureAttributes(error), true, true, false);
31066
+ });
31067
+ return;
30379
31068
  }
30380
- const bag = this.branch(path);
30381
- if (format === "json") {
30382
- this.saveText(bag.toJson(false), filename, "application/json");
30383
- } else {
30384
- const root = path.split(".").at(-1);
30385
- this.saveText(
30386
- `<?xml version='1.0' encoding='UTF-8'?>
30387
- <${root}>${bag.toXml()}</${root}>`,
30388
- filename,
30389
- "application/xml"
30390
- );
31069
+ if (sensor.stream) return;
31070
+ const stream = { controller: new AbortController() };
31071
+ sensor.stream = stream;
31072
+ stream.start = sensor.cleanup.then(() => {
31073
+ if (stream.controller.signal.aborted) return async () => {
31074
+ };
31075
+ this.requireCapability(name);
31076
+ const accept = (event) => {
31077
+ if (this.disposed || stream.controller.signal.aborted) return;
31078
+ try {
31079
+ if (event?.kind === "state" && typeof event.watching === "boolean") {
31080
+ node.setAttr({ watching: event.watching, status: event.watching ? "pending" : "idle", error: null }, true, true, false);
31081
+ } else if (event?.kind === "sample") {
31082
+ for (const field of ["x", "y", "z", "timestamp"]) {
31083
+ if (!Number.isFinite(event[field])) throw new TypeError(`Invalid ${name}.${field}`);
31084
+ }
31085
+ if (!node.attr.watching) return;
31086
+ if (node.staticValue && event.timestamp < node.staticValue.getItem("timestamp")) return;
31087
+ const value = new Bag();
31088
+ for (const field of ["x", "y", "z", "timestamp"]) value.setItem(field, event[field]);
31089
+ node.setValue(value, true, { status: "success", error: null }, true, false);
31090
+ } else if (event?.kind === "error" && event.error instanceof Error) {
31091
+ node.setAttr({ ...failureAttributes(event.error), watching: false }, true, true, false);
31092
+ } else throw new TypeError(`Invalid ${name} event`);
31093
+ } catch (error) {
31094
+ node.setAttr(failureAttributes(error), true, true, false);
31095
+ }
31096
+ };
31097
+ return name === "gyroscope" ? this.provider.startGyroscopeUpdates(accept, stream.controller.signal) : this.provider.startAccelerometerUpdates(accept, stream.controller.signal);
31098
+ });
31099
+ stream.start.catch((error) => {
31100
+ if (!this.disposed && !stream.controller.signal.aborted) {
31101
+ node.setAttr({ ...failureAttributes(error), watching: false }, true, true, false);
31102
+ }
31103
+ });
31104
+ node.setAttr({ status: "pending", error: null }, true, true, false);
31105
+ }
31106
+ #startAudio(node) {
31107
+ const previous = this.#audio;
31108
+ if (previous) {
31109
+ if (previous.phase !== "complete") return;
31110
+ previous.phase = "replacing";
31111
+ node.setValue(null, true, {
31112
+ status: "pending",
31113
+ error: null,
31114
+ recording: false,
31115
+ shareStatus: "idle",
31116
+ shareError: null,
31117
+ shareActivity: null
31118
+ }, true, false);
31119
+ previous.close = previous.start.then((session) => session.dispose()).then(() => {
31120
+ if (this.disposed || previous.controller.signal.aborted || this.#audio !== previous) return;
31121
+ this.#audio = null;
31122
+ this.#startAudio(node);
31123
+ }).catch((error) => {
31124
+ if (!this.disposed && this.#audio === previous) {
31125
+ previous.phase = "failed";
31126
+ node.setAttr(failureAttributes(error), true, true, false);
31127
+ }
31128
+ });
31129
+ return;
30391
31130
  }
31131
+ const audio = { controller: new AbortController(), phase: "starting" };
31132
+ this.#audio = audio;
31133
+ node.setValue(null, true, {
31134
+ status: "pending",
31135
+ error: null,
31136
+ recording: false,
31137
+ shareStatus: "idle",
31138
+ shareError: null,
31139
+ shareActivity: null
31140
+ }, true, false);
31141
+ audio.start = Promise.resolve().then(async () => {
31142
+ if (audio.controller.signal.aborted) return null;
31143
+ this.requireCapability("audio");
31144
+ return this.provider.startAudioRecording((error) => {
31145
+ if (this.#audio === audio && !audio.controller.signal.aborted) this.#cancelAudio(node, error);
31146
+ }, audio.controller.signal);
31147
+ });
31148
+ audio.start.then((session) => {
31149
+ if (!session || audio.controller.signal.aborted || this.disposed) return;
31150
+ audio.phase = "recording";
31151
+ node.setAttr({ status: "recording", error: null, recording: true }, true, true, false);
31152
+ }).catch((error) => {
31153
+ if (audio.controller.signal.aborted || this.disposed) return;
31154
+ if (this.#audio === audio) this.#audio = null;
31155
+ node.setAttr({ ...failureAttributes(error), recording: false }, true, true, false);
31156
+ });
30392
31157
  }
30393
- /** Hand text to the browser as a file named filename. */
30394
- saveText(text2, filename, type) {
30395
- const window2 = this.document.defaultView;
30396
- const url = window2.URL.createObjectURL(new window2.Blob([text2], { type }));
30397
- this.open(url, filename);
30398
- window2.setTimeout(() => window2.URL.revokeObjectURL(url), 1e3);
31158
+ #stopAudio(node) {
31159
+ const audio = this.#audio;
31160
+ if (!audio || audio.phase !== "recording") return;
31161
+ audio.phase = "stopping";
31162
+ node.setAttr({ status: "pending", error: null }, true, true, false);
31163
+ audio.stop = audio.start.then((session) => session.stop()).then((result) => {
31164
+ if (audio.controller.signal.aborted || this.disposed) return;
31165
+ if (typeof result?.url !== "string" || !result.url || typeof result.mimeType !== "string" || !result.mimeType.startsWith("audio/") || !Number.isFinite(result.duration) || result.duration < 0) {
31166
+ throw new TypeError("Invalid audio result from device provider");
31167
+ }
31168
+ const value = new Bag();
31169
+ for (const key of ["url", "mimeType", "duration"]) value.setItem(key, result[key]);
31170
+ audio.phase = "complete";
31171
+ node.setValue(value, true, { status: "success", error: null, recording: false }, true, false);
31172
+ }).catch((error) => {
31173
+ if (!audio.controller.signal.aborted && !this.disposed) this.#cancelAudio(node, error);
31174
+ });
30399
31175
  }
30400
- /** Follow url through a link, as a download when filename is given. */
30401
- open(url, filename = null) {
30402
- const link = this.document.createElement("a");
30403
- link.href = url;
30404
- if (filename !== null) link.download = filename;
31176
+ #shareAudio(node) {
31177
+ const audio = this.#audio;
31178
+ if (audio?.phase === "sharing") return;
31179
+ if (!audio || audio.phase !== "complete") {
31180
+ const failure = failureAttributes(new Error("Record and stop audio before sharing"));
31181
+ node.setAttr({ shareStatus: failure.status, shareError: failure.error, shareActivity: null }, true, true, false);
31182
+ return;
31183
+ }
31184
+ audio.phase = "sharing";
31185
+ node.setAttr({ shareStatus: "pending", shareError: null, shareActivity: null }, true, true, false);
31186
+ audio.share = audio.start.then((session) => session.share(audio.controller.signal)).then((result) => {
31187
+ if (audio.controller.signal.aborted || this.disposed) return;
31188
+ if (typeof result?.activity !== "string") throw new TypeError("Invalid audio share result from device provider");
31189
+ node.setAttr({ shareStatus: "success", shareError: null, shareActivity: result.activity }, true, true, false);
31190
+ }).catch((error) => {
31191
+ if (audio.controller.signal.aborted || this.disposed) return;
31192
+ const failure = failureAttributes(error);
31193
+ node.setAttr({ shareStatus: failure.status, shareError: failure.error, shareActivity: null }, true, true, false);
31194
+ }).finally(() => {
31195
+ if (this.#audio === audio && !audio.controller.signal.aborted) audio.phase = "complete";
31196
+ });
31197
+ }
31198
+ #cancelAudio(node, error = { code: "CANCELLED", message: "Audio recording cancelled" }) {
31199
+ const audio = this.#audio;
31200
+ if (!audio || audio.phase === "closing" || audio.phase === "sharing") return;
31201
+ audio.phase = "closing";
31202
+ audio.controller.abort();
31203
+ node.setValue(null, true, {
31204
+ status: "pending",
31205
+ error: null,
31206
+ shareStatus: "idle",
31207
+ shareError: null,
31208
+ shareActivity: null
31209
+ }, true, false);
31210
+ audio.close = audio.start.then((session) => session === null ? void 0 : session.dispose(), (error2) => {
31211
+ if (error2?.code !== "CANCELLED") throw error2;
31212
+ }).then(() => {
31213
+ if (this.disposed || this.#audio !== audio) return;
31214
+ this.#audio = null;
31215
+ node.setAttr({ ...failureAttributes(error), recording: false }, true, true, false);
31216
+ }).catch((cleanupError) => {
31217
+ if (!this.disposed && this.#audio === audio) {
31218
+ audio.phase = "failed";
31219
+ node.setAttr(failureAttributes(cleanupError), true, true, false);
31220
+ }
31221
+ });
31222
+ }
31223
+ #clipboardCommand(node, operation) {
31224
+ if (this.#clipboardRequest) return;
31225
+ const request = new AbortController();
31226
+ this.#clipboardRequest = request;
31227
+ const text2 = node.attr.text;
31228
+ node.setValue(null, true, { status: "pending", error: null, operation }, true, false);
31229
+ Promise.resolve().then(async () => {
31230
+ if (request.signal.aborted) return;
31231
+ this.requireCapability("clipboard");
31232
+ let result;
31233
+ if (operation === "copy") {
31234
+ if (typeof text2 !== "string") throw new TypeError("Clipboard text must be a string");
31235
+ await this.provider.copyText(text2, request.signal);
31236
+ result = { text: text2 };
31237
+ } else {
31238
+ result = await this.provider.pasteText(request.signal);
31239
+ }
31240
+ if (request.signal.aborted) return;
31241
+ if (typeof result?.text !== "string") throw new TypeError("Invalid clipboard text from device provider");
31242
+ const value = new Bag();
31243
+ value.setItem("text", result.text);
31244
+ node.setValue(value, true, { status: "success", error: null }, true, false);
31245
+ }).catch((error) => {
31246
+ if (!request.signal.aborted) node.setAttr(failureAttributes(error), true, true, false);
31247
+ }).finally(() => {
31248
+ if (this.#clipboardRequest === request) this.#clipboardRequest = null;
31249
+ });
31250
+ }
31251
+ #vibrate(node) {
31252
+ if (this.#hapticRequest) return;
31253
+ const request = new AbortController();
31254
+ this.#hapticRequest = request;
31255
+ const { duration } = node.attr;
31256
+ node.setValue(null, true, { status: "pending", error: null }, true, false);
31257
+ Promise.resolve().then(async () => {
31258
+ if (request.signal.aborted) return;
31259
+ this.requireCapability("haptics");
31260
+ if (!Number.isInteger(duration) || duration < 1 || duration > 5e3) {
31261
+ throw new TypeError("Vibration duration must be an integer from 1 to 5000 milliseconds");
31262
+ }
31263
+ await this.provider.vibrate(duration, request.signal);
31264
+ if (request.signal.aborted) return;
31265
+ const value = new Bag();
31266
+ value.setItem("duration", duration);
31267
+ value.setItem("acknowledged", true);
31268
+ node.setValue(value, true, { status: "success", error: null }, true, false);
31269
+ }).catch((error) => {
31270
+ if (!request.signal.aborted) node.setAttr(failureAttributes(error), true, true, false);
31271
+ }).finally(() => {
31272
+ if (this.#hapticRequest === request) this.#hapticRequest = null;
31273
+ });
31274
+ }
31275
+ #impact(node) {
31276
+ if (this.#hapticRequest) return;
31277
+ const request = new AbortController();
31278
+ this.#hapticRequest = request;
31279
+ const { style } = node.attr;
31280
+ node.setValue(null, true, { status: "pending", error: null }, true, false);
31281
+ Promise.resolve().then(async () => {
31282
+ if (request.signal.aborted) return;
31283
+ this.requireCapability("haptics");
31284
+ if (!["light", "medium", "heavy"].includes(style)) throw new TypeError("Invalid haptic style");
31285
+ await this.provider.impact(style, request.signal);
31286
+ if (request.signal.aborted) return;
31287
+ const value = new Bag();
31288
+ value.setItem("style", style);
31289
+ value.setItem("acknowledged", true);
31290
+ node.setValue(value, true, { status: "success", error: null }, true, false);
31291
+ }).catch((error) => {
31292
+ if (!request.signal.aborted) node.setAttr(failureAttributes(error), true, true, false);
31293
+ }).finally(() => {
31294
+ if (this.#hapticRequest === request) this.#hapticRequest = null;
31295
+ });
31296
+ }
31297
+ #scanBarcode(node) {
31298
+ if (this.#barcodeRequest) return;
31299
+ const request = new AbortController();
31300
+ this.#barcodeRequest = request;
31301
+ node.setValue(null, true, { status: "pending", error: null }, true, false);
31302
+ Promise.resolve().then(() => {
31303
+ if (request.signal.aborted) return;
31304
+ this.requireCapability("barcode");
31305
+ return this.provider.scanBarcode(request.signal);
31306
+ }).then((result) => {
31307
+ if (request.signal.aborted) return;
31308
+ if (typeof result?.text !== "string" || !result.text || typeof result.format !== "string" || !result.format) {
31309
+ throw new TypeError("Invalid barcode result from device provider");
31310
+ }
31311
+ const value = new Bag();
31312
+ value.setItem("text", result.text);
31313
+ value.setItem("format", result.format);
31314
+ node.setValue(value, true, { status: "success", error: null }, true, false);
31315
+ }).catch((error) => {
31316
+ if (!request.signal.aborted) node.setAttr(failureAttributes(error), true, true, false);
31317
+ }).finally(() => {
31318
+ if (this.#barcodeRequest === request) this.#barcodeRequest = null;
31319
+ });
31320
+ }
31321
+ // Camera is an explicit Data event, never a resolver read with a UI side effect.
31322
+ #photo(node, operation) {
31323
+ if (this.#captureRequest) return;
31324
+ const request = new AbortController();
31325
+ this.#captureRequest = request;
31326
+ node.setAttr({ status: "pending", error: null }, true, true, false);
31327
+ Promise.resolve().then(() => {
31328
+ if (request.signal.aborted) return;
31329
+ this.requireCapability("camera");
31330
+ return operation === "choose" ? this.provider.choosePhoto(request.signal) : this.provider.takePhoto(request.signal);
31331
+ }).then((photo) => {
31332
+ if (request.signal.aborted) return;
31333
+ if (typeof photo?.url !== "string" || !photo.url || typeof photo.format !== "string" || !photo.format) {
31334
+ throw new TypeError("Invalid camera photo from device provider");
31335
+ }
31336
+ const value = new Bag();
31337
+ value.setItem("url", photo.url);
31338
+ value.setItem("format", photo.format);
31339
+ node.setValue(value, true, { status: "success", error: null }, true, false);
31340
+ }).catch((error) => {
31341
+ if (!request.signal.aborted) node.setAttr(failureAttributes(error), true, true, false);
31342
+ }).finally(() => {
31343
+ if (this.#captureRequest === request) this.#captureRequest = null;
31344
+ });
31345
+ }
31346
+ // A fresh attempt clears the previous local verification, including on cancellation.
31347
+ #verifyBiometrics(node) {
31348
+ if (this.#biometricsRequest) return;
31349
+ const request = new AbortController();
31350
+ this.#biometricsRequest = request;
31351
+ node.setValue(null, true, { status: "pending", error: null }, true, false);
31352
+ Promise.resolve().then(() => {
31353
+ if (request.signal.aborted) return;
31354
+ this.requireCapability("biometrics");
31355
+ return this.provider.verifyBiometrics(request.signal);
31356
+ }).then(() => {
31357
+ if (request.signal.aborted) return;
31358
+ const result = new Bag();
31359
+ result.setItem("verified", true);
31360
+ node.setValue(result, true, { status: "success", error: null }, true, false);
31361
+ }).catch((error) => {
31362
+ if (!request.signal.aborted) node.setValue(null, true, failureAttributes(error), true, false);
31363
+ }).finally(() => {
31364
+ if (this.#biometricsRequest === request) this.#biometricsRequest = null;
31365
+ });
31366
+ }
31367
+ #startNotificationEvents(node) {
31368
+ if (this.#notificationEvents) return this.#notificationEvents.start;
31369
+ const events = { controller: new AbortController() };
31370
+ this.#notificationEvents = events;
31371
+ events.start = Promise.resolve().then(() => {
31372
+ if (events.controller.signal.aborted) return async () => {
31373
+ };
31374
+ return this.provider.startNotificationEvents((event) => {
31375
+ if (events.controller.signal.aborted) return;
31376
+ try {
31377
+ if (!["received", "action"].includes(event.kind) || !Number.isInteger(event.id) || typeof event.title !== "string" || typeof event.body !== "string" || event.kind === "action" && typeof event.actionId !== "string") {
31378
+ throw new TypeError("Invalid notification event from device provider");
31379
+ }
31380
+ const value = new Bag();
31381
+ for (const key of ["id", "title", "body"]) value.setItem(key, event[key]);
31382
+ if (event.kind === "action") value.setItem("actionId", event.actionId);
31383
+ node.staticValue.setItem(event.kind, value);
31384
+ } catch (error) {
31385
+ node.setAttr({ listenerError: failureAttributes(error).error }, true, true, false);
31386
+ }
31387
+ }, events.controller.signal);
31388
+ }).then((stop) => {
31389
+ if (!events.controller.signal.aborted) node.setAttr({ listening: true }, true, true, false);
31390
+ return stop;
31391
+ });
31392
+ events.start.catch((error) => {
31393
+ const aborted = events.controller.signal.aborted;
31394
+ events.controller.abort();
31395
+ if (this.#notificationEvents === events) this.#notificationEvents = null;
31396
+ if (!aborted) {
31397
+ node.setAttr({ listening: false, listenerError: failureAttributes(error).error }, true, true, false);
31398
+ }
31399
+ });
31400
+ node.setAttr({ listenerError: null }, true, true, false);
31401
+ return events.start;
31402
+ }
31403
+ #scheduleNotification(node) {
31404
+ if (this.#notificationRequest) return;
31405
+ const request = new AbortController();
31406
+ this.#notificationRequest = request;
31407
+ const value = node.staticValue.getItem("request");
31408
+ const input = value instanceof Bag ? Object.fromEntries(["id", "title", "body", "delay"].map((key) => [key, value.getItem(key)])) : null;
31409
+ node.staticValue.setItem("scheduled", null);
31410
+ node.setAttr({ status: "pending", error: null }, true, true, false);
31411
+ Promise.resolve().then(async () => {
31412
+ if (request.signal.aborted) return;
31413
+ this.requireCapability("notifications");
31414
+ if (!input || !Number.isInteger(input.id) || input.id < 1 || input.id > 2147483647 || typeof input.title !== "string" || !input.title.trim() || typeof input.body !== "string" || !input.body.trim() || typeof input.delay !== "number" || !Number.isFinite(input.delay) || input.delay <= 0) {
31415
+ throw new TypeError("Notification requires a positive 32-bit id, title, body and positive delay in seconds");
31416
+ }
31417
+ await this.#startNotificationEvents(node);
31418
+ if (request.signal.aborted) return;
31419
+ return this.provider.scheduleNotification(input, request.signal);
31420
+ }).then((result) => {
31421
+ if (request.signal.aborted) return;
31422
+ if (result?.id !== input.id || typeof result.at !== "number" || !Number.isFinite(result.at)) {
31423
+ throw new TypeError("Invalid notification scheduling acknowledgement");
31424
+ }
31425
+ const scheduled = new Bag();
31426
+ scheduled.setItem("id", result.id);
31427
+ scheduled.setItem("at", result.at);
31428
+ node.staticValue.setItem("scheduled", scheduled);
31429
+ node.setAttr({ status: "success", error: null }, true, true, false);
31430
+ }).catch((error) => {
31431
+ if (!request.signal.aborted) node.setAttr(failureAttributes(error), true, true, false);
31432
+ }).finally(() => {
31433
+ if (this.#notificationRequest === request) this.#notificationRequest = null;
31434
+ });
31435
+ }
31436
+ #finishPushRequest() {
31437
+ const request = this.#pushRequest;
31438
+ this.#pushRequest = null;
31439
+ if (request) clearTimeout(request.timer);
31440
+ return request;
31441
+ }
31442
+ #acceptPushEvent(node, event) {
31443
+ if (event.kind === "registration") {
31444
+ if (typeof event.token !== "string" || !event.token) throw new TypeError("Invalid push registration token");
31445
+ this.#finishPushRequest();
31446
+ const value = new Bag();
31447
+ value.setItem("token", event.token);
31448
+ node.staticValue.setItem("registration", value);
31449
+ node.setAttr({ status: "success", error: null }, true, true, false);
31450
+ } else if (event.kind === "registrationError") {
31451
+ this.#finishPushRequest();
31452
+ node.staticValue.setItem("registration", null);
31453
+ node.setAttr(failureAttributes(event.error), true, true, false);
31454
+ } else {
31455
+ if (!["received", "action"].includes(event.kind)) throw new TypeError("Invalid push event kind");
31456
+ const fields = ["id", "title", "body", "messageId", "destination"];
31457
+ if (event.kind === "action") fields.push("actionId");
31458
+ const value = new Bag();
31459
+ for (const key of fields) {
31460
+ if (typeof event[key] !== "string") throw new TypeError(`Invalid push event ${key}`);
31461
+ value.setItem(key, event[key]);
31462
+ }
31463
+ node.staticValue.setItem(event.kind, value);
31464
+ }
31465
+ }
31466
+ #startPushEvents(node) {
31467
+ if (this.#pushEvents) return this.#pushEvents.start;
31468
+ const events = { controller: new AbortController() };
31469
+ this.#pushEvents = events;
31470
+ events.start = Promise.resolve().then(() => {
31471
+ if (events.controller.signal.aborted) return async () => {
31472
+ };
31473
+ return this.provider.startPushEvents((event) => {
31474
+ if (events.controller.signal.aborted) return;
31475
+ try {
31476
+ this.#acceptPushEvent(node, event);
31477
+ } catch (error) {
31478
+ node.setAttr({ listenerError: failureAttributes(error).error }, true, true, false);
31479
+ }
31480
+ }, events.controller.signal);
31481
+ }).then((stop) => {
31482
+ if (!events.controller.signal.aborted) node.setAttr({ listening: true }, true, true, false);
31483
+ return stop;
31484
+ });
31485
+ events.start.catch((error) => {
31486
+ const aborted = events.controller.signal.aborted;
31487
+ events.controller.abort();
31488
+ if (this.#pushEvents === events) this.#pushEvents = null;
31489
+ if (!aborted) node.setAttr({ listening: false, listenerError: failureAttributes(error).error }, true, true, false);
31490
+ });
31491
+ node.setAttr({ listenerError: null }, true, true, false);
31492
+ return events.start;
31493
+ }
31494
+ #registerPush(node) {
31495
+ if (this.#pushRequest) return;
31496
+ const request = { controller: new AbortController(), timer: null };
31497
+ this.#pushRequest = request;
31498
+ request.timer = setTimeout(() => {
31499
+ if (this.disposed || this.#pushRequest !== request) return;
31500
+ this.#finishPushRequest();
31501
+ request.controller.abort();
31502
+ node.setAttr(failureAttributes({ code: "TIMEOUT", message: "Push registration has not returned a token" }), true, true, false);
31503
+ }, 3e4);
31504
+ node.staticValue.setItem("registration", null);
31505
+ node.setAttr({ status: "pending", error: null }, true, true, false);
31506
+ Promise.resolve().then(async () => {
31507
+ if (request.controller.signal.aborted) return;
31508
+ this.requireCapability("push");
31509
+ await this.#startPushEvents(node);
31510
+ if (request.controller.signal.aborted || this.#pushRequest !== request) return;
31511
+ await this.provider.registerPush(request.controller.signal);
31512
+ }).catch((error) => {
31513
+ if (this.disposed || this.#pushRequest !== request) return;
31514
+ this.#finishPushRequest();
31515
+ request.controller.abort();
31516
+ node.setAttr(failureAttributes(error), true, true, false);
31517
+ });
31518
+ }
31519
+ #startShortcutEvents(node) {
31520
+ const events = { controller: new AbortController() };
31521
+ this.#shortcutEvents = events;
31522
+ events.start = Promise.resolve().then(() => {
31523
+ if (events.controller.signal.aborted) return async () => {
31524
+ };
31525
+ return this.provider.startShortcutEvents((request, error = null) => {
31526
+ if (events.controller.signal.aborted) return;
31527
+ try {
31528
+ if (error) throw error;
31529
+ for (const key of ["id", "destination"]) {
31530
+ if (typeof request?.[key] !== "string" || !request[key]) {
31531
+ throw new TypeError(`Invalid shortcut request ${key}`);
31532
+ }
31533
+ }
31534
+ if (node.staticValue.getItem("request")?.getItem("id") === request.id) return;
31535
+ const value = new Bag();
31536
+ value.setItem("id", request.id);
31537
+ value.setItem("destination", request.destination);
31538
+ node.setAttr({ listenerError: null }, true, true, false);
31539
+ node.staticValue.setItem("request", value);
31540
+ } catch (error2) {
31541
+ node.setAttr({ listenerError: failureAttributes(error2).error }, true, true, false);
31542
+ }
31543
+ }, events.controller.signal);
31544
+ }).then((stop) => {
31545
+ if (!events.controller.signal.aborted) node.setAttr({ listening: true }, true, true, false);
31546
+ return stop;
31547
+ });
31548
+ events.start.catch((error) => {
31549
+ const aborted = events.controller.signal.aborted;
31550
+ events.controller.abort();
31551
+ if (!aborted) node.setAttr({ listening: false, listenerError: failureAttributes(error).error }, true, true, false);
31552
+ });
31553
+ }
31554
+ #startLinkEvents(node) {
31555
+ const events = { controller: new AbortController() };
31556
+ this.#linkEvents = events;
31557
+ events.start = Promise.resolve().then(() => {
31558
+ if (events.controller.signal.aborted) return async () => {
31559
+ };
31560
+ return this.provider.startLinkEvents((request, error = null) => {
31561
+ if (events.controller.signal.aborted) return;
31562
+ try {
31563
+ if (error) throw error;
31564
+ for (const key of ["id", "url"]) {
31565
+ if (typeof request?.[key] !== "string" || !request[key]) {
31566
+ throw new TypeError(`Invalid link request ${key}`);
31567
+ }
31568
+ }
31569
+ if (node.staticValue.getItem("request")?.getItem("id") === request.id) return;
31570
+ const value = new Bag();
31571
+ value.setItem("id", request.id);
31572
+ value.setItem("url", request.url);
31573
+ node.setAttr({ listenerError: null }, true, true, false);
31574
+ node.staticValue.setItem("request", value);
31575
+ } catch (error2) {
31576
+ node.setAttr({ listenerError: failureAttributes(error2).error }, true, true, false);
31577
+ }
31578
+ }, events.controller.signal);
31579
+ }).then((stop) => {
31580
+ if (!events.controller.signal.aborted) node.setAttr({ listening: true }, true, true, false);
31581
+ return stop;
31582
+ });
31583
+ events.start.catch((error) => {
31584
+ const aborted = events.controller.signal.aborted;
31585
+ events.controller.abort();
31586
+ if (!aborted) node.setAttr({ listening: false, listenerError: failureAttributes(error).error }, true, true, false);
31587
+ });
31588
+ }
31589
+ requireCapability(name) {
31590
+ if (!this.provider || !this.provider.capabilities.includes(name)) {
31591
+ throw Object.assign(new Error(`${name} is unavailable in this environment`), { code: "UNAVAILABLE" });
31592
+ }
31593
+ }
31594
+ attributes(resolver, attrs) {
31595
+ const writing = resolver.writing;
31596
+ resolver.writing = true;
31597
+ try {
31598
+ resolver._node.setAttr(attrs, true, true, false);
31599
+ } finally {
31600
+ resolver.writing = writing;
31601
+ }
31602
+ }
31603
+ accept(resolver, value) {
31604
+ const fields = resolver.name === "appinfo" ? ["id", "name", "version", "build"] : ["latitude", "longitude", "accuracy", "timestamp"];
31605
+ const type = resolver.name === "appinfo" ? "string" : "number";
31606
+ for (const key of fields) {
31607
+ if (typeof value[key] !== type || type === "number" && !Number.isFinite(value[key])) {
31608
+ throw new TypeError(`Invalid ${resolver.name}.${key} from device provider`);
31609
+ }
31610
+ }
31611
+ const current = resolver.cachedValue;
31612
+ if (resolver.name === "location" && current && value.timestamp < current.getItem("timestamp")) {
31613
+ this.attributes(resolver, { status: "success", error: null });
31614
+ return;
31615
+ }
31616
+ const bag = new Bag();
31617
+ for (const key of fields) bag.setItem(key, value[key]);
31618
+ resolver._lastUpdate = Date.now();
31619
+ resolver.failed = false;
31620
+ resolver.received++;
31621
+ const writing = resolver.writing;
31622
+ resolver.writing = true;
31623
+ try {
31624
+ resolver._node.setValue(bag, true, { status: "success", error: null }, true, false);
31625
+ } finally {
31626
+ resolver.writing = writing;
31627
+ }
31628
+ }
31629
+ failure(resolver, error) {
31630
+ resolver.failed = true;
31631
+ this.attributes(resolver, failureAttributes(error));
31632
+ }
31633
+ reconcile() {
31634
+ const resolver = this.resolvers.get("location");
31635
+ if (resolver._node.attr.enabled) {
31636
+ if (this.monitor) return;
31637
+ const monitor = { stop: null, controller: new AbortController() };
31638
+ this.monitor = monitor;
31639
+ monitor.start = Promise.resolve(this.cleanup).then(() => {
31640
+ if (this.disposed || this.monitor !== monitor) return null;
31641
+ this.requireCapability("location");
31642
+ return this.provider.startLocationUpdates((value, error) => {
31643
+ if (this.disposed || this.monitor !== monitor) return;
31644
+ if (error) this.failure(resolver, error);
31645
+ else {
31646
+ try {
31647
+ this.accept(resolver, value);
31648
+ } catch (failure) {
31649
+ this.failure(resolver, failure);
31650
+ }
31651
+ }
31652
+ }, monitor.controller.signal);
31653
+ });
31654
+ monitor.start.then((stop) => {
31655
+ if (stop === null || this.disposed || this.monitor !== monitor) return;
31656
+ monitor.stop = stop;
31657
+ this.attributes(resolver, { watching: true });
31658
+ }).catch((error) => {
31659
+ if (!this.disposed && this.monitor === monitor) {
31660
+ this.attributes(resolver, { watching: false });
31661
+ this.failure(resolver, error);
31662
+ }
31663
+ });
31664
+ this.attributes(resolver, { status: "pending", error: null });
31665
+ } else if (this.monitor) {
31666
+ const monitor = this.monitor;
31667
+ this.monitor = null;
31668
+ monitor.controller.abort();
31669
+ this.retiring = monitor;
31670
+ this.cleanup = monitor.start.then((stop) => stop === null ? void 0 : stop(), () => void 0).then(() => {
31671
+ if (this.retiring === monitor) this.retiring = null;
31672
+ if (!this.disposed) {
31673
+ const attrs = { watching: false };
31674
+ if (!this.monitor && !resolver.request && resolver._node.attr.status === "pending") {
31675
+ Object.assign(attrs, { status: "cancelled", error: null });
31676
+ }
31677
+ this.attributes(resolver, attrs);
31678
+ }
31679
+ });
31680
+ this.cleanup.catch((error) => {
31681
+ if (!this.disposed) this.failure(resolver, error);
31682
+ });
31683
+ }
31684
+ }
31685
+ /** A page-owned database connection; database technology remains provider-owned. */
31686
+ async openDatabase(name) {
31687
+ this.assertLive();
31688
+ if (!/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(name) || typeof name !== "string") throw new TypeError("Invalid database name");
31689
+ if (this.#database) throw new Error("This page already owns a database connection");
31690
+ const node = this.gramlot.data.getNode("gramlot.device.database");
31691
+ const state = (status, error = null) => {
31692
+ if (!this.disposed) node.setAttr({ status, error }, true, true, false);
31693
+ };
31694
+ if (!this.provider.capabilities.includes("database")) {
31695
+ const error = Object.assign(new Error("Native database unavailable"), { code: "UNAVAILABLE" });
31696
+ state("unavailable", { code: error.code, message: error.message });
31697
+ throw error;
31698
+ }
31699
+ const slot = { controller: new AbortController(), close: null, start: null };
31700
+ this.#database = slot;
31701
+ state("pending");
31702
+ slot.start = this.provider.openDatabase(name, slot.controller.signal);
31703
+ try {
31704
+ const connection = await slot.start;
31705
+ let closed = false, closing = null;
31706
+ const close = () => {
31707
+ if (closing) return closing;
31708
+ closed = true;
31709
+ closing = connection.close().then(() => {
31710
+ state("closed");
31711
+ }, (error) => {
31712
+ state("error", { code: "FAILED", message: error.message });
31713
+ throw error;
31714
+ }).finally(() => {
31715
+ if (this.#database === slot) this.#database = null;
31716
+ });
31717
+ return closing;
31718
+ };
31719
+ slot.close = close;
31720
+ if (this.disposed || slot.controller.signal.aborted) {
31721
+ await close();
31722
+ throw Object.assign(new Error("Page closed"), { code: "CANCELLED" });
31723
+ }
31724
+ const invoke = async (method, sql, params) => {
31725
+ this.assertLive();
31726
+ if (closed) throw new Error("Database connection is closed");
31727
+ state("pending");
31728
+ try {
31729
+ const result = await connection[method](sql, params);
31730
+ state("success");
31731
+ return result;
31732
+ } catch (error) {
31733
+ state("error", { code: "FAILED", message: error.message });
31734
+ throw error;
31735
+ }
31736
+ };
31737
+ state("success");
31738
+ return {
31739
+ query: (sql, params = []) => invoke("query", sql, params),
31740
+ execute: (sql, params = []) => invoke("execute", sql, params),
31741
+ close
31742
+ };
31743
+ } catch (error) {
31744
+ if (this.#database === slot) this.#database = null;
31745
+ if (!this.disposed) node.setAttr(failureAttributes(error), true, true, false);
31746
+ throw error;
31747
+ }
31748
+ }
31749
+ dispose() {
31750
+ if (this.disposed) return;
31751
+ this.disposed = true;
31752
+ const database = this.#database;
31753
+ database?.controller.abort();
31754
+ if (database) this.cleanup = Promise.all([
31755
+ this.cleanup,
31756
+ database.start.then(() => database.close?.(), () => void 0)
31757
+ ]).then(() => void 0);
31758
+ const sensorCleanup = [...this.#sensors.values()].map((sensor) => {
31759
+ const stream = sensor.stream;
31760
+ sensor.stream = null;
31761
+ stream?.controller.abort();
31762
+ return stream ? stream.start.then((stop) => stop(), () => void 0) : sensor.cleanup;
31763
+ });
31764
+ this.#clipboardRequest?.abort();
31765
+ this.#clipboardRequest = null;
31766
+ const audio = this.#audio;
31767
+ this.#audio = null;
31768
+ audio?.controller.abort();
31769
+ this.#hapticRequest?.abort();
31770
+ this.#hapticRequest = null;
31771
+ const stateEvents = [...this.#stateEvents.values()];
31772
+ this.#stateEvents.clear();
31773
+ for (const events of stateEvents) events.controller.abort();
31774
+ const linkEvents = this.#linkEvents;
31775
+ this.#linkEvents = null;
31776
+ linkEvents?.controller.abort();
31777
+ const shortcutEvents = this.#shortcutEvents;
31778
+ this.#shortcutEvents = null;
31779
+ shortcutEvents?.controller.abort();
31780
+ this.#finishPushRequest()?.controller.abort();
31781
+ const pushEvents = this.#pushEvents;
31782
+ this.#pushEvents = null;
31783
+ pushEvents?.controller.abort();
31784
+ this.#barcodeRequest?.abort();
31785
+ this.#barcodeRequest = null;
31786
+ this.#captureRequest?.abort();
31787
+ this.#captureRequest = null;
31788
+ this.#biometricsRequest?.abort();
31789
+ this.#biometricsRequest = null;
31790
+ this.#notificationRequest?.abort();
31791
+ this.#notificationRequest = null;
31792
+ const notificationEvents = this.#notificationEvents;
31793
+ this.#notificationEvents = null;
31794
+ notificationEvents?.controller.abort();
31795
+ this.gramlot.data.unsubscribe("gramlot.device", { any: true });
31796
+ const monitor = this.monitor;
31797
+ this.monitor = null;
31798
+ monitor?.controller.abort();
31799
+ if (monitor) {
31800
+ this.cleanup = monitor.start.then((stop) => stop === null ? void 0 : stop(), () => void 0);
31801
+ } else if (this.retiring?.stop) {
31802
+ const retiring = this.retiring;
31803
+ this.cleanup = this.cleanup.catch(() => retiring.stop());
31804
+ }
31805
+ if (notificationEvents) {
31806
+ this.cleanup = Promise.all([
31807
+ this.cleanup,
31808
+ notificationEvents.start.then((stop) => stop(), () => void 0)
31809
+ ]).then(() => void 0);
31810
+ }
31811
+ if (pushEvents) {
31812
+ this.cleanup = Promise.all([
31813
+ this.cleanup,
31814
+ pushEvents.start.then((stop) => stop(), () => void 0)
31815
+ ]).then(() => void 0);
31816
+ }
31817
+ if (linkEvents) {
31818
+ this.cleanup = Promise.all([
31819
+ this.cleanup,
31820
+ linkEvents.start.then((stop) => stop(), () => void 0)
31821
+ ]).then(() => void 0);
31822
+ }
31823
+ if (shortcutEvents) {
31824
+ this.cleanup = Promise.all([
31825
+ this.cleanup,
31826
+ shortcutEvents.start.then((stop) => stop(), () => void 0)
31827
+ ]).then(() => void 0);
31828
+ }
31829
+ this.cleanup = Promise.all([this.cleanup, ...sensorCleanup, ...stateEvents.map((events) => events.start.then((stop) => stop(), () => void 0))]).then(() => void 0);
31830
+ if (audio) {
31831
+ this.cleanup = Promise.all([
31832
+ this.cleanup,
31833
+ audio.start.then((session) => session === null ? void 0 : session.dispose(), (error) => {
31834
+ if (error?.code !== "CANCELLED") throw error;
31835
+ })
31836
+ ]).then(() => void 0);
31837
+ }
31838
+ this.cleanup = this.cleanup.finally(() => this.releaseProvider?.());
31839
+ this.cleanup.catch((error) => {
31840
+ this.cleanupError = error;
31841
+ });
31842
+ for (const resolver of this.resolvers.values()) resolver.request = null;
31843
+ }
31844
+ };
31845
+
31846
+ // src/inout.js
31847
+ var MAILTO_LIMIT = 2e3;
31848
+ function leafText(value) {
31849
+ if (!(value instanceof Date)) return String(value ?? "");
31850
+ const text2 = value.toISOString();
31851
+ return text2.endsWith("T00:00:00.000Z") ? text2.slice(0, 10) : text2;
31852
+ }
31853
+ var InOut = class {
31854
+ constructor(gramlot, document) {
31855
+ this.gramlot = gramlot;
31856
+ this.document = document;
31857
+ }
31858
+ /** The Bag at path in the Data. */
31859
+ branch(path) {
31860
+ const value = this.gramlot.data.getItem(path);
31861
+ if (!(value instanceof Bag)) throw new Error(`gramlot.utl.inout: no data Bag at '${path}'`);
31862
+ return value;
31863
+ }
31864
+ /** One `relative.path: value` line per leaf of the branch at path. */
31865
+ mailText(path) {
31866
+ const lines = [];
31867
+ const walk2 = (bag, prefix) => {
31868
+ for (const node of bag.getNodes()) {
31869
+ const label = prefix + node.label;
31870
+ if (node.value instanceof Bag) walk2(node.value, `${label}.`);
31871
+ else lines.push(`${label}: ${leafText(node.value)}`);
31872
+ }
31873
+ };
31874
+ walk2(this.branch(path), "");
31875
+ return lines.join("\n");
31876
+ }
31877
+ /** The mailto: URL of sendMail; longer than MAILTO_LIMIT raises an Error. */
31878
+ mailtoUrl(path, email) {
31879
+ const url = `mailto:${encodeURIComponent(email)}?subject=${encodeURIComponent(this.document.title)}&body=${encodeURIComponent(this.mailText(path))}`;
31880
+ if (url.length > MAILTO_LIMIT) {
31881
+ throw new Error(`gramlot.utl.inout.sendMail: the email of '${path}' is ${url.length} characters long, over the mailto: limit of ${MAILTO_LIMIT}; send it with sendHttp or save it as a file`);
31882
+ }
31883
+ return url;
31884
+ }
31885
+ /** Prepare an email to email in the mail program of the user, with the data at path as text lines. */
31886
+ sendMail(path, email) {
31887
+ this.open(this.mailtoUrl(path, email));
31888
+ }
31889
+ /** POST the data at path as a JSON object to url; resolves with the Response, rejects on a status out of 2xx. */
31890
+ async sendHttp(path, url) {
31891
+ const body = JSON.stringify(this.branch(path).asDict(false, false, true));
31892
+ const response = await this.document.defaultView.fetch(url, {
31893
+ method: "POST",
31894
+ headers: { "Content-Type": "application/json" },
31895
+ body
31896
+ });
31897
+ if (!response.ok) throw new Error(`gramlot.utl.inout.sendHttp: ${url} answered ${response.status}`);
31898
+ return response;
31899
+ }
31900
+ /** Save the data at path as a TYTX file, which restore reads back with its exact types. */
31901
+ save(path, filename) {
31902
+ this.saveText(this.branch(path).toTytx(), filename, "application/json");
31903
+ }
31904
+ /** Read a TYTX file into path; resolves with the Bag, rejects with AbortError on cancel. Needs a user gesture. */
31905
+ restore(path) {
31906
+ const input = this.document.createElement("input");
31907
+ input.type = "file";
31908
+ input.accept = ".json,application/json";
31909
+ return new Promise((resolve, reject) => {
31910
+ const cancel = () => reject(new this.document.defaultView.DOMException("File selection cancelled", "AbortError"));
31911
+ input.addEventListener("cancel", cancel, { once: true });
31912
+ input.addEventListener("change", async () => {
31913
+ input.removeEventListener("cancel", cancel);
31914
+ if (!input.files.length) {
31915
+ cancel();
31916
+ return;
31917
+ }
31918
+ try {
31919
+ const bag = fromTytx(await input.files[0].text());
31920
+ if (!(bag instanceof Bag)) throw new TypeError("the file must contain a typed Bag");
31921
+ this.gramlot.data.setItem(path, bag);
31922
+ resolve(bag);
31923
+ } catch (error) {
31924
+ reject(new Error(
31925
+ `gramlot.utl.inout.restore: the file is not a saved Gramlot branch: ${error.message}`,
31926
+ { cause: error }
31927
+ ));
31928
+ }
31929
+ }, { once: true });
31930
+ input.click();
31931
+ });
31932
+ }
31933
+ /** Export the data at path as 'json' (Bag.toJson) or 'xml' (Bag.toXml, inside one root element named
31934
+ * after the last segment of path); types become text. */
31935
+ download(path, filename, format) {
31936
+ if (!["json", "xml"].includes(format)) {
31937
+ throw new Error(`gramlot.utl.inout.download: format '${format}' is not 'json' or 'xml'`);
31938
+ }
31939
+ const bag = this.branch(path);
31940
+ if (format === "json") {
31941
+ this.saveText(bag.toJson(false), filename, "application/json");
31942
+ } else {
31943
+ const root = path.split(".").at(-1);
31944
+ this.saveText(
31945
+ `<?xml version='1.0' encoding='UTF-8'?>
31946
+ <${root}>${bag.toXml()}</${root}>`,
31947
+ filename,
31948
+ "application/xml"
31949
+ );
31950
+ }
31951
+ }
31952
+ /** Hand text to the browser as a file named filename. */
31953
+ saveText(text2, filename, type) {
31954
+ const window2 = this.document.defaultView;
31955
+ const url = window2.URL.createObjectURL(new window2.Blob([text2], { type }));
31956
+ this.open(url, filename);
31957
+ window2.setTimeout(() => window2.URL.revokeObjectURL(url), 1e3);
31958
+ }
31959
+ /** Follow url through a link, as a download when filename is given. */
31960
+ open(url, filename = null) {
31961
+ const link = this.document.createElement("a");
31962
+ link.href = url;
31963
+ if (filename !== null) link.download = filename;
30405
31964
  link.click();
30406
31965
  }
30407
31966
  };
@@ -30416,6 +31975,7 @@ var UtilitiesHandler = class extends Handler {
30416
31975
 
30417
31976
  // src/gramlot.js
30418
31977
  var Gramlot = class {
31978
+ #mobileEnvironment;
30419
31979
  constructor({
30420
31980
  pageId,
30421
31981
  rpcUrl = "/gramlot/rpc",
@@ -30451,7 +32011,9 @@ var Gramlot = class {
30451
32011
  subscriptions: this._subscriptions,
30452
32012
  nameSyntax: nameSyntax === null ? NAME_SYNTAX : NameSyntax.fromJSON(nameSyntax)
30453
32013
  });
32014
+ this.#mobileEnvironment = MobileEnvironment.install({ document, root: this.src.renderer.destination });
30454
32015
  this.data = this.src.builder.data;
32016
+ this.dvc = new DeviceHandler(this);
30455
32017
  this.rpc = new RpcHandler(this, { rpcUrl, closeUrl, document, transport });
30456
32018
  this.dom = new DomHandler(this);
30457
32019
  this.utl = new UtilitiesHandler(this, document);
@@ -30460,7 +32022,7 @@ var Gramlot = class {
30460
32022
  this.abort = new AbortController();
30461
32023
  if (this.rpc.transport) {
30462
32024
  this.pagehide = (event) => {
30463
- if (!event.persisted) this.dispose({ beacon: true });
32025
+ if (!event.persisted) this.dispose();
30464
32026
  };
30465
32027
  document.defaultView.addEventListener("pagehide", this.pagehide);
30466
32028
  this.window = document.defaultView;
@@ -30506,9 +32068,11 @@ var Gramlot = class {
30506
32068
  throw error;
30507
32069
  }
30508
32070
  }
30509
- dispose({ beacon = false } = {}) {
32071
+ dispose() {
30510
32072
  if (this.state === "disposed") return;
30511
32073
  this.state = "disposed";
32074
+ this.dvc.dispose();
32075
+ this.#mobileEnvironment.dispose();
30512
32076
  this._subscriptions.dispose();
30513
32077
  if (this.pagehide) this.window.removeEventListener("pagehide", this.pagehide);
30514
32078
  this.abort.abort();
@@ -30520,8 +32084,11 @@ var Gramlot = class {
30520
32084
  }
30521
32085
  } finally {
30522
32086
  if (this.rpc.transport) {
30523
- this.rpc.transport.close(this.pageId, { beacon });
30524
- this.rpc.transport.dispose();
32087
+ try {
32088
+ this.rpc.transport.close(this.pageId);
32089
+ } finally {
32090
+ this.rpc.transport.dispose();
32091
+ }
30525
32092
  }
30526
32093
  }
30527
32094
  }
@@ -30554,8 +32121,11 @@ var PageBootstrap = class {
30554
32121
  const pagehide = (event) => {
30555
32122
  if (event.persisted || closed) return;
30556
32123
  closed = true;
30557
- this.closePage();
30558
- resolveClosed(null);
32124
+ try {
32125
+ this.closePage();
32126
+ } finally {
32127
+ resolveClosed(null);
32128
+ }
30559
32129
  };
30560
32130
  window2.addEventListener("pagehide", pagehide);
30561
32131
  try {
@@ -30654,8 +32224,11 @@ var PageBootstrap = class {
30654
32224
  * with a beacon, as `Gramlot` sends on pagehide. */
30655
32225
  closePage() {
30656
32226
  const transport = this.serverAdapter.createTransport({ ...this.config, document: this.document });
30657
- transport.close(this.config.pageId, { beacon: true });
30658
- transport.dispose();
32227
+ try {
32228
+ transport.close(this.config.pageId);
32229
+ } finally {
32230
+ transport.dispose();
32231
+ }
30659
32232
  }
30660
32233
  };
30661
32234
 
@@ -30777,17 +32350,17 @@ var IndexPage = class extends FramePage {
30777
32350
  pane.setAttr({ width: "240px", splitter: true, drawer: true, drawer_label: "Navigation" });
30778
32351
  pane.tree({
30779
32352
  node_label: "tree",
30780
- storepath: `${this.constructor.datapath}.navigation`,
32353
+ storepath: ".navigation",
30781
32354
  labelAttribute: "title",
30782
32355
  hideValues: true,
30783
- selectedPath: `^${this.constructor.datapath}.navigationSelection`
32356
+ selectedPath: "^.navigationSelection"
30784
32357
  });
30785
32358
  }
30786
32359
  center(pane) {
30787
- pane.tabContainer({ node_label: "tabs", height: "100%", selectedPage: `^${this.constructor.datapath}.active` });
32360
+ pane.tabContainer({ node_label: "tabs", height: "100%", selectedPage: "^.active" });
30788
32361
  }
30789
32362
  behavior(shell) {
30790
- shell.dataController({ func: "indexMount", _onStart: true, shell_id: this.constructor.shellId });
32363
+ shell.dataController({ func: "indexMount", _onStart: true });
30791
32364
  }
30792
32365
  index_panel(pane, { selection }) {
30793
32366
  this.panel(pane, selection.getNode("#0"));
@@ -30808,7 +32381,7 @@ IndexPage.registerSource("index_panel");
30808
32381
  function mountIndexPage(renderer, root, onSelection = () => {
30809
32382
  }, prepareEntry = () => {
30810
32383
  }, {
30811
- state = root.builder.data.getItem(root.getAttr("datapath")),
32384
+ state = root.getRelativeData("."),
30812
32385
  createEntry = null,
30813
32386
  onLoad = () => {
30814
32387
  }
@@ -30818,7 +32391,8 @@ function mountIndexPage(renderer, root, onSelection = () => {
30818
32391
  const tabs = root.value.getNode("frame.center.tabs");
30819
32392
  const builder = root.builder;
30820
32393
  const entries2 = /* @__PURE__ */ new Map();
30821
- let disposed = false, selecting = false, sequence = 0, requested = null;
32394
+ const context = { entries: entries2, disposed: false, selecting: false, sequence: 0, requested: null };
32395
+ Object.defineProperty(root, "indexContext", { value: context, configurable: true });
30822
32396
  const opened = state.getItem("opened");
30823
32397
  for (const record2 of opened.getNodes()) {
30824
32398
  const { url, path, title } = record2.attr;
@@ -30826,45 +32400,65 @@ function mountIndexPage(renderer, root, onSelection = () => {
30826
32400
  const entry = { url, path, title, pane, node: navigation.getNode(path), loading: false };
30827
32401
  prepareEntry(entry);
30828
32402
  entries2.set(url, entry);
30829
- sequence++;
32403
+ context.sequence++;
30830
32404
  }
32405
+ const notifyLoad = (entry, status, error) => {
32406
+ try {
32407
+ onLoad(entry.url, status, error);
32408
+ } catch (callbackError) {
32409
+ renderer.binding.reportError(callbackError, "Page load callback failed");
32410
+ }
32411
+ };
32412
+ const finishLoad = (entry, status, error) => {
32413
+ if (!entry.loading) return;
32414
+ entry.loading = false;
32415
+ notifyLoad(entry, status, error);
32416
+ };
30831
32417
  const activate = (entry) => {
30832
- if (disposed) return;
30833
- selecting = true;
32418
+ if (context.disposed) return;
32419
+ context.selecting = true;
30834
32420
  try {
30835
32421
  state.setItem("active", entry.url);
30836
32422
  state.setItem("navigationSelection", entry.path);
30837
32423
  onSelection(entries2, entry.url);
30838
32424
  } finally {
30839
- selecting = false;
32425
+ context.selecting = false;
30840
32426
  }
30841
32427
  };
32428
+ function requestSelection(path) {
32429
+ void select(path).catch((error) => {
32430
+ if (!context.disposed) renderer.binding.reportError(error, "Page could not be opened");
32431
+ });
32432
+ }
30842
32433
  async function select(path) {
30843
32434
  const node = navigation.getNode(path);
30844
32435
  if (!node) throw new Error(`Unknown index navigation path: ${path}`);
30845
32436
  const url = node.attr.url;
30846
32437
  if (url == null) return;
30847
32438
  if (typeof url !== "string" || !url) throw new TypeError("IndexPage URL must be nonempty text");
30848
- requested = url;
32439
+ context.requested = url;
30849
32440
  let entry = entries2.get(url);
30850
32441
  if (entry) {
30851
32442
  entry.path = path;
30852
32443
  activate(entry);
30853
32444
  return;
30854
32445
  }
30855
- while (tabs.value !== null && tabs.value.getNode(`page${sequence}`)) sequence++;
32446
+ while (tabs.value !== null && tabs.value.getNode(`page${context.sequence}`)) context.sequence++;
30856
32447
  const pane = sourceTarget(builder.wrapSource(tabs).contentPane({
30857
- node_label: `page${sequence++}`,
32448
+ node_label: `page${context.sequence++}`,
30858
32449
  title: node.attr.title ?? node.label,
30859
32450
  pageName: url,
30860
- height: "100%"
32451
+ height: "100%",
32452
+ closable: true
30861
32453
  }));
30862
32454
  const previous = state.getItem("active");
30863
32455
  entry = { url, path, node, pane, title: node.attr.title ?? node.label, loading: true };
30864
32456
  entries2.set(url, entry);
30865
32457
  try {
32458
+ notifyLoad(entry, "loading");
32459
+ if (context.disposed || entries2.get(url) !== entry) return;
30866
32460
  activate(entry);
30867
- onLoad(url, "loading");
32461
+ if (context.disposed || entries2.get(url) !== entry) return;
30868
32462
  if (createEntry) await createEntry(entry);
30869
32463
  else {
30870
32464
  const selection = new Bag();
@@ -30872,69 +32466,105 @@ function mountIndexPage(renderer, root, onSelection = () => {
30872
32466
  const mounted = await renderer.binding.gramlot.src.remoteSource(pane, "index_panel", { selection });
30873
32467
  if (!mounted) throw new Error("Panel loading was cancelled");
30874
32468
  }
30875
- if (disposed) return;
30876
- entry.loading = false;
32469
+ if (context.disposed || entries2.get(url) !== entry) return;
30877
32470
  opened.setItem(pane.label, null, { url, path: entry.path, title: entry.title });
30878
32471
  prepareEntry(entry);
30879
- if (requested === url) {
30880
- onLoad(url, "ready");
30881
- activate(entry);
30882
- }
30883
32472
  } catch (error) {
30884
- entries2.delete(url);
30885
- if (opened.getNode(pane.label)) opened.popNode(pane.label);
30886
- if (pane.parentBag) pane.parentBag.popNode(pane.label);
30887
- if (!disposed && requested === url) {
30888
- onLoad(url, "error", error);
30889
- const restored = entries2.get(previous);
30890
- requested = restored?.url ?? null;
30891
- if (restored) activate(restored);
32473
+ if (context.disposed || entries2.get(url) !== entry) return;
32474
+ try {
32475
+ renderer.binding.reportError(error, "Page could not be opened");
32476
+ entries2.delete(url);
32477
+ if (opened.getNode(pane.label)) opened.popNode(pane.label);
32478
+ if (pane.parentBag) pane.parentBag.popNode(pane.label);
32479
+ if (!context.disposed && context.requested === url) {
32480
+ const restored = entries2.get(previous);
32481
+ context.requested = restored?.url ?? null;
32482
+ if (restored) activate(restored);
32483
+ else {
32484
+ context.selecting = true;
32485
+ try {
32486
+ state.setItem("active", null);
32487
+ state.setItem("navigationSelection", null);
32488
+ onSelection(entries2, null);
32489
+ } finally {
32490
+ context.selecting = false;
32491
+ }
32492
+ }
32493
+ }
32494
+ } finally {
32495
+ finishLoad(entry, "error", error);
32496
+ }
32497
+ return;
32498
+ }
32499
+ if (context.disposed || entries2.get(url) !== entry) return;
32500
+ finishLoad(entry, "ready");
32501
+ if (!context.disposed && entries2.get(url) === entry && context.requested === url) activate(entry);
32502
+ }
32503
+ const sourceSubscription = `${root.getAttr("id")}-page-close`;
32504
+ root.value.subscribe(sourceSubscription, { any: (event) => {
32505
+ if (event.evt !== "del") return;
32506
+ const entry = [...entries2.values()].find((candidate) => candidate.pane === event.node);
32507
+ if (!entry) return;
32508
+ const { url, pane } = entry;
32509
+ if (context.disposed || renderer.disposed || entries2.get(url) !== entry) return;
32510
+ entries2.delete(url);
32511
+ if (opened.getNode(pane.label)) opened.popNode(pane.label);
32512
+ try {
32513
+ if (state.getItem("active") === url) {
32514
+ const next = [...entries2.values()].at(-1);
32515
+ context.requested = next?.url ?? null;
32516
+ if (next) activate(next);
30892
32517
  else {
30893
- selecting = true;
32518
+ context.selecting = true;
30894
32519
  try {
30895
32520
  state.setItem("active", null);
30896
32521
  state.setItem("navigationSelection", null);
30897
32522
  onSelection(entries2, null);
30898
32523
  } finally {
30899
- selecting = false;
32524
+ context.selecting = false;
30900
32525
  }
30901
32526
  }
30902
- }
32527
+ } else onSelection(entries2, state.getItem("active"));
32528
+ } finally {
32529
+ finishLoad(entry, "cancelled");
30903
32530
  }
30904
- }
32531
+ } });
30905
32532
  const subscription = `${root.getAttr("id")}-selection`;
30906
32533
  state.subscribe(subscription, { any: (event) => {
30907
- if (selecting || disposed) return;
32534
+ if (context.selecting || context.disposed) return;
30908
32535
  if (event.node === state.getNode("navigationSelection")) {
30909
32536
  const path = state.getItem("navigationSelection");
30910
- if (path !== null) void select(path);
32537
+ if (path !== null) requestSelection(path);
30911
32538
  } else if (event.node === state.getNode("active")) {
30912
32539
  const entry = entries2.get(state.getItem("active"));
30913
32540
  if (entry) {
30914
- requested = entry.url;
32541
+ context.requested = entry.url;
30915
32542
  activate(entry);
30916
32543
  }
30917
32544
  }
30918
32545
  } });
30919
32546
  const dispose = () => {
30920
- if (disposed) return;
30921
- disposed = true;
32547
+ if (context.disposed) return;
32548
+ context.disposed = true;
30922
32549
  state.unsubscribe(subscription, { any: true });
30923
- for (const entry of entries2.values()) if (entry.loading && entry.pane.parentBag) {
30924
- entry.pane.parentBag.popNode(entry.pane.label);
32550
+ root.value.unsubscribe(sourceSubscription, { any: true });
32551
+ for (const entry of entries2.values()) if (entry.loading) {
32552
+ if (entry.pane.parentBag) entry.pane.parentBag.popNode(entry.pane.label);
32553
+ finishLoad(entry, "cancelled");
30925
32554
  }
32555
+ entries2.clear();
32556
+ if (root.indexContext === context) delete root.indexContext;
30926
32557
  };
32558
+ context.dispose = dispose;
30927
32559
  renderer.onDispose(root, dispose);
30928
32560
  const active = entries2.get(state.getItem("active"));
30929
32561
  if (active) activate(active);
30930
- else if (state.getItem("navigationSelection") !== null) void select(state.getItem("navigationSelection"));
30931
- return { entries: entries2, dispose };
32562
+ else if (state.getItem("navigationSelection") !== null) requestSelection(state.getItem("navigationSelection"));
32563
+ return context;
30932
32564
  }
30933
32565
  var IndexLogic = class {
30934
- indexMount(node, { shell_id }) {
30935
- const renderer = this.page.src.renderer;
30936
- const element = renderer.destination.ownerDocument.getElementById(shell_id);
30937
- this.index = mountIndexPage(renderer, renderer.elements.get(element).node);
32566
+ indexMount(node) {
32567
+ mountIndexPage(this.page.src.renderer, node.parentNode);
30938
32568
  }
30939
32569
  };
30940
32570
 
@@ -31054,13 +32684,16 @@ var DirectoryResolver = class _DirectoryResolver extends RemoteResolver {
31054
32684
  }
31055
32685
  };
31056
32686
  var FileSystemController = class {
31057
- constructor(gramlot, state) {
32687
+ constructor(gramlot, source) {
31058
32688
  this.gramlot = gramlot;
31059
- this.state = state;
32689
+ this.source = source;
31060
32690
  this.request = null;
31061
32691
  this.resolver = null;
31062
32692
  this.disposed = false;
31063
32693
  }
32694
+ get state() {
32695
+ return this.source.getRelativeData(".");
32696
+ }
31064
32697
  async open(root) {
31065
32698
  this.request?.abort();
31066
32699
  const request = this.request = new AbortController();
@@ -31097,14 +32730,13 @@ var FileSystemController = class {
31097
32730
  };
31098
32731
  var FileSystemLogic = class {
31099
32732
  fileSystemMount(node) {
31100
- this.fileSystems ??= /* @__PURE__ */ new WeakMap();
31101
- const scope = node.parentNode, state = scope.getRelativeData(".");
31102
- const controller = new FileSystemController(this.page, state);
31103
- this.fileSystems.set(state, controller);
32733
+ const scope = node.parentNode;
32734
+ const controller = new FileSystemController(this.page, scope);
32735
+ Object.defineProperty(scope, "fileSystemController", { value: controller, configurable: true });
31104
32736
  this.page.src.renderer.onDispose(scope, () => controller.dispose());
31105
32737
  }
31106
32738
  fileSystemOpen(node, { root }) {
31107
- if (root) return this.fileSystems.get(node.getRelativeData(".")).open(root);
32739
+ if (root) return node.parentNode.fileSystemController.open(root);
31108
32740
  }
31109
32741
  };
31110
32742
  function fileSystemTree(parent, { datapath, ...attributes }) {
@@ -31130,12 +32762,15 @@ function fileSystemTree(parent, { datapath, ...attributes }) {
31130
32762
  // src/ide-documents.js
31131
32763
  var documentKey = (root, path) => "d_" + [...new TextEncoder().encode(JSON.stringify([root, path]))].map((byte) => byte.toString(16).padStart(2, "0")).join("");
31132
32764
  var IdeDocuments = class {
31133
- constructor(gramlot, state) {
32765
+ constructor(gramlot, source) {
31134
32766
  this.gramlot = gramlot;
31135
- this.state = state;
32767
+ this.source = source;
31136
32768
  this.pending = /* @__PURE__ */ new Map();
31137
32769
  this.disposed = false;
31138
32770
  }
32771
+ get state() {
32772
+ return this.source.getRelativeData(".");
32773
+ }
31139
32774
  get documents() {
31140
32775
  return this.state.getItem("documents");
31141
32776
  }
@@ -31156,7 +32791,7 @@ var IdeDocuments = class {
31156
32791
  return promise;
31157
32792
  }
31158
32793
  newDocument(language, extension, root = "") {
31159
- const key = `new_${crypto.randomUUID().replaceAll("-", "")}`;
32794
+ const key = `new_${randomId()}`;
31160
32795
  const doc = new Bag();
31161
32796
  for (const [name, value] of Object.entries({
31162
32797
  language,
@@ -31315,6 +32950,13 @@ var RecentWorkspaces = class {
31315
32950
  };
31316
32951
 
31317
32952
  // src/ide-runtime.js
32953
+ function ideContext(node) {
32954
+ for (let scope = node; scope; scope = scope.parentNode) {
32955
+ const context = scope.ideContext;
32956
+ if (context) return context;
32957
+ }
32958
+ throw new Error("IDE operation requires a node inside a mounted IDE");
32959
+ }
31318
32960
  var IdeLogic = class {
31319
32961
  fileSystemMount(node) {
31320
32962
  return FileSystemLogic.prototype.fileSystemMount.call(this, node);
@@ -31323,77 +32965,89 @@ var IdeLogic = class {
31323
32965
  return FileSystemLogic.prototype.fileSystemOpen.call(this, node, args);
31324
32966
  }
31325
32967
  ideMount(node) {
31326
- this.ideRoot = node.parentNode;
31327
- this.ideState = node.getRelativeData(".");
31328
- this.ideDocuments = new IdeDocuments(this.page, this.ideState);
31329
- this.idePanels = /* @__PURE__ */ new Map();
31330
- this.ideDisposed = false;
31331
- this.ideRequested = 0;
31332
- this.ideRecent = new RecentWorkspaces(this.page.src.renderer.destination.ownerDocument.defaultView.sessionStorage);
31333
- const roots = this.ideRecent.read();
31334
- this.ideState.setItem("recent", this.ideRecent.choices(roots));
31335
- this.ideState.setItem("workspace", roots[0] ?? "");
31336
- const browser = this.ideState.getItem("browser");
32968
+ const scope = node.parentNode;
32969
+ const context = {
32970
+ scope,
32971
+ documents: new IdeDocuments(this.page, scope),
32972
+ requested: 0,
32973
+ editorPrefix: `ide_${randomId()}`,
32974
+ recent: new RecentWorkspaces(this.page.src.renderer.destination.ownerDocument.defaultView.sessionStorage)
32975
+ };
32976
+ Object.defineProperty(scope, "ideContext", { value: context, configurable: true });
32977
+ const { documents, recent } = context;
32978
+ const state = scope.getRelativeData(".");
32979
+ const roots = recent.read();
32980
+ state.setItem("recent", recent.choices(roots));
32981
+ state.setItem("workspace", roots[0] ?? "");
32982
+ const browser = state.getItem("browser");
31337
32983
  browser.subscribe("ide-browser", { any: (event) => {
31338
32984
  if (event.node === browser.getNode("root")) {
31339
32985
  const root = browser.getItem("root");
31340
- this.ideState.setItem("workspace", root);
31341
- this.ideState.setItem("recent", this.ideRecent.choices(this.ideRecent.remember(root)));
31342
- this.ideState.setItem("status", `Workspace: ${root}`);
32986
+ state.setItem("workspace", root);
32987
+ state.setItem("recent", recent.choices(recent.remember(root)));
32988
+ state.setItem("status", `Workspace: ${root}`);
31343
32989
  } else if (event.node === browser.getNode("selectedPath")) {
31344
32990
  const path = browser.getItem("selectedPath");
31345
32991
  const item = path === null ? null : browser.getItem("store").getNode(path);
31346
- if (item && !item.attr.is_directory) void this.ideOpenDocument(browser.getItem("root"), item.attr.path);
32992
+ if (item && !item.attr.is_directory) void this.ideOpenDocument(scope, browser.getItem("root"), item.attr.path);
31347
32993
  }
31348
32994
  } });
31349
- this.ideDocuments.documents.subscribe("ide-documents", { any: (event) => {
32995
+ const documentBag = documents.documents;
32996
+ documentBag.subscribe("ide-documents", { any: (event) => {
31350
32997
  if (!["content", "saved", "busy", "writable", "view", "isNew", "path", "root"].includes(event.node.label)) return;
31351
- for (const [key, pane] of this.idePanels) {
31352
- const doc = this.ideDocuments.documents.getItem(key);
32998
+ for (const pane of scope.value.getNode("frame.center.tabs").value?.getNodes() ?? []) {
32999
+ const key = pane.getAttr("documentKey");
33000
+ const doc = documents.documents.getItem(key);
31353
33001
  if (doc) {
31354
- if (event.node === doc.getNode("content")) this.ideDocuments.invalidateRecipe(key);
31355
- this.ideDocumentState(key);
31356
- pane.setAttr({ title: `${this.ideDocuments.dirty(key) ? "\u25CF " : ""}${doc.getItem("path")}` });
33002
+ if (event.node === doc.getNode("content")) documents.invalidateRecipe(key);
33003
+ this.ideDocumentState(scope, key);
33004
+ pane.setAttr({ title: `${documents.dirty(key) ? "\u25CF " : ""}${doc.getItem("path")}` });
31357
33005
  }
31358
33006
  }
31359
33007
  } });
31360
- this.page.src.renderer.onDispose(this.ideRoot, () => {
31361
- this.ideDisposed = true;
33008
+ this.page.src.renderer.onDispose(context.scope, () => {
31362
33009
  browser.unsubscribe("ide-browser", { any: true });
31363
- this.ideDocuments.documents.unsubscribe("ide-documents", { any: true });
31364
- this.ideDocuments.dispose();
33010
+ documentBag.unsubscribe("ide-documents", { any: true });
33011
+ documents.dispose();
31365
33012
  });
31366
33013
  }
31367
- ideOpenWorkspace() {
31368
- const root = this.ideState.getItem("workspace");
31369
- if (root && root !== this.ideState.getItem("browser.root")) this.ideState.setItem("browser.requestedRoot", root);
33014
+ ideOpenWorkspace(node) {
33015
+ const context = ideContext(node);
33016
+ const state = context.scope.getRelativeData(".");
33017
+ const root = state.getItem("workspace");
33018
+ if (root && root !== state.getItem("browser.root")) state.setItem("browser.requestedRoot", root);
31370
33019
  }
31371
- ideDocumentState(key) {
31372
- const doc = this.ideDocuments.documents.getItem(key);
31373
- const disabled = !this.ideDocuments.dirty(key) && !doc.getItem("isNew") || doc.getItem("busy");
33020
+ ideDocumentState(node, key) {
33021
+ const context = ideContext(node), { documents } = context;
33022
+ const doc = documents.documents.getItem(key);
33023
+ const disabled = !documents.dirty(key) && !doc.getItem("isNew") || doc.getItem("busy");
31374
33024
  doc.setItem("saveDisabled", Boolean(disabled || !doc.getItem("writable")));
31375
- doc.setItem("revertDisabled", Boolean(!this.ideDocuments.dirty(key) || doc.getItem("busy")));
33025
+ doc.setItem("revertDisabled", Boolean(!documents.dirty(key) || doc.getItem("busy")));
31376
33026
  doc.setItem("displayPath", doc.getItem("isNew") ? doc.getItem("path") : `${doc.getItem("root")}/${doc.getItem("path")}`);
31377
33027
  doc.setItem("pdfFilename", doc.getItem("path").split("/").at(-1).replace(/\.typ(?:\.py)?$/i, ".pdf"));
31378
33028
  doc.setItem("renderDisabled", Boolean(doc.getItem("busy") || !doc.getItem("writable")));
31379
33029
  this.ideHistoryState(doc);
31380
33030
  }
31381
- async ideOpenDocument(root, path) {
31382
- const requested = ++this.ideRequested;
33031
+ async ideOpenDocument(node, root, path) {
33032
+ const context = ideContext(node), { documents } = context;
33033
+ const state = context.scope.getRelativeData(".");
33034
+ const requested = ++context.requested;
31383
33035
  try {
31384
- const key = await this.ideDocuments.open(root, path);
31385
- if (key === null || this.ideDisposed) return;
31386
- this.ideShowDocument(key);
31387
- if (requested === this.ideRequested) {
31388
- this.ideState.setItem("active", key);
31389
- this.ideState.setItem("status", `${path}${this.ideDocuments.documents.getItem(key).getItem("writable") ? "" : " (draft only \u2014 Remote Edit is disabled)"}`);
33036
+ const key = await documents.open(root, path);
33037
+ if (key === null || documents.disposed) return;
33038
+ this.ideShowDocument(node, key);
33039
+ if (requested === context.requested) {
33040
+ state.setItem("active", key);
33041
+ state.setItem("status", `${path}${documents.documents.getItem(key).getItem("writable") ? "" : " (draft only \u2014 Remote Edit is disabled)"}`);
31390
33042
  }
31391
33043
  } catch (error) {
31392
- if (!this.ideDisposed) this.ideState.setItem("status", error.message);
33044
+ if (!documents.disposed) state.setItem("status", error.message);
31393
33045
  }
31394
33046
  }
31395
- ideNew() {
31396
- const type = this.ideState.getItem("newType");
33047
+ ideNew(node) {
33048
+ const context = ideContext(node), { documents } = context;
33049
+ const state = context.scope.getRelativeData(".");
33050
+ const type = state.getItem("newType");
31397
33051
  const language = type === "typstRecipe" ? "python" : type;
31398
33052
  const extensions = {
31399
33053
  typstRecipe: ".typ.py",
@@ -31409,27 +33063,28 @@ var IdeLogic = class {
31409
33063
  xml: ".xml",
31410
33064
  text: ".txt"
31411
33065
  };
31412
- const key = this.ideDocuments.newDocument(language, extensions[type], this.ideState.getItem("workspace"));
31413
- this.ideDocuments.documents.getItem(key).setItem("writable", this.ideState.getItem("browser.writable") === true);
31414
- ++this.ideRequested;
31415
- this.ideShowDocument(key);
31416
- this.ideState.setItem("active", key);
31417
- this.ideState.setItem("status", "New document. Choose directory and name when saving.");
31418
- }
31419
- ideShowDocument(key) {
31420
- const document = this.ideDocuments.documents.getItem(key);
33066
+ const key = documents.newDocument(language, extensions[type], state.getItem("workspace"));
33067
+ documents.documents.getItem(key).setItem("writable", state.getItem("browser.writable") === true);
33068
+ ++context.requested;
33069
+ this.ideShowDocument(node, key);
33070
+ state.setItem("active", key);
33071
+ state.setItem("status", "New document. Choose directory and name when saving.");
33072
+ }
33073
+ ideShowDocument(node, key) {
33074
+ const context = ideContext(node), { documents } = context;
33075
+ const document = documents.documents.getItem(key);
31421
33076
  const path = document.getItem("path");
31422
- if (!this.idePanels.has(key)) {
31423
- const doc = this.ideDocuments.documents.getItem(key);
33077
+ const tabs = context.scope.value.getNode("frame.center.tabs");
33078
+ if (!tabs.value?.getNode(key)) {
33079
+ const doc = documents.documents.getItem(key);
31424
33080
  const recipe = path.endsWith(".typ.py");
31425
- if (recipe) this.ideDocuments.invalidateRecipe(key);
33081
+ if (recipe) documents.invalidateRecipe(key);
31426
33082
  doc.setItem("readonly", false);
31427
- this.ideDocumentState(key);
33083
+ this.ideDocumentState(node, key);
31428
33084
  doc.setItem("view", "code");
31429
33085
  doc.setItem("createHidden", true);
31430
33086
  doc.setItem("undoDisabled", true);
31431
33087
  doc.setItem("redoDisabled", true);
31432
- const tabs = this.ideRoot.value.getNode("frame.center.tabs");
31433
33088
  const pane = sourceTarget(tabs.builder.wrapSource(tabs).contentPane({
31434
33089
  node_label: key,
31435
33090
  title: path,
@@ -31439,7 +33094,6 @@ var IdeLogic = class {
31439
33094
  onClose: "ideClose",
31440
33095
  height: "100%"
31441
33096
  }));
31442
- this.idePanels.set(key, pane);
31443
33097
  const target = pane.builder.wrapSource(pane).div({ display: "flex", flex_direction: "column", height: "100%" });
31444
33098
  const toolbar = target.div({
31445
33099
  datapath: `.documents.${key}`,
@@ -31515,11 +33169,11 @@ var IdeLogic = class {
31515
33169
  language: doc.getItem("language"),
31516
33170
  height: "100%",
31517
33171
  readonly: "^.readonly",
31518
- nodeId: `editor_${key}`,
33172
+ nodeId: `${context.editorPrefix}_editor_${key}`,
31519
33173
  editorView: "code",
31520
33174
  selfsubscribe_historyChanged: "ideHistoryChanged"
31521
33175
  });
31522
- target.dataController({ func: "ideSave", documentKey: key, [`subscribe_editor_${key}_save`]: true });
33176
+ target.dataController({ func: "ideSave", documentKey: key, [`subscribe_${context.editorPrefix}_editor_${key}_save`]: true });
31523
33177
  if (typst) views.contentPane({ title: "Preview", pageName: "preview", height: "100%" }).typstPreview({ value: `^.documents.${key}.content`, filename: `^.documents.${key}.pdfFilename`, height: "100%" });
31524
33178
  if (recipe) {
31525
33179
  const output = views.contentPane({ title: "Preview", pageName: "preview", height: "100%", display: "flex", flex_direction: "column" });
@@ -31550,53 +33204,61 @@ var IdeLogic = class {
31550
33204
  value: "^.content",
31551
33205
  readonly: "^.readonly",
31552
33206
  height: "100%",
31553
- nodeId: `rich_editor_${key}`,
33207
+ nodeId: `${context.editorPrefix}_rich_editor_${key}`,
31554
33208
  editorView: "rich",
31555
33209
  selfsubscribe_historyChanged: "ideHistoryChanged"
31556
33210
  });
31557
- target.dataController({ func: "ideSave", documentKey: key, [`subscribe_rich_editor_${key}_save`]: true });
33211
+ target.dataController({ func: "ideSave", documentKey: key, [`subscribe_${context.editorPrefix}_rich_editor_${key}_save`]: true });
31558
33212
  }
31559
33213
  }
31560
33214
  }
31561
33215
  async ideRenderRecipe(node, { documentKey: documentKey2 }) {
31562
- const doc = this.ideDocuments.documents.getItem(documentKey2);
33216
+ const context = ideContext(node), { documents } = context;
33217
+ const doc = documents.documents.getItem(documentKey2);
31563
33218
  doc.setItem("view", "preview");
31564
- await this.ideDocuments.renderRecipe(documentKey2);
33219
+ await documents.renderRecipe(documentKey2);
31565
33220
  }
31566
33221
  ideCancelCreate(node, { documentKey: documentKey2 }) {
31567
- this.ideDocuments.documents.getItem(documentKey2).setItem("createHidden", true);
33222
+ const context = ideContext(node), { documents } = context;
33223
+ documents.documents.getItem(documentKey2).setItem("createHidden", true);
31568
33224
  }
31569
33225
  async ideCreate(node, { documentKey: documentKey2 }) {
31570
- this.ideState.setItem("status", "Creating file\u2026");
33226
+ const context = ideContext(node), { documents } = context;
33227
+ const state = context.scope.getRelativeData(".");
33228
+ state.setItem("status", "Creating file\u2026");
31571
33229
  try {
31572
- const saved = await this.ideDocuments.create(documentKey2);
31573
- if (!this.ideDisposed && saved) {
31574
- this.ideState.setItem("status", "File created.");
31575
- const browser = this.ideState.getItem("browser");
31576
- if (browser.getItem("root")) await this.fileSystems.get(browser).open(browser.getItem("root"));
33230
+ const saved = await documents.create(documentKey2);
33231
+ if (!documents.disposed && saved) {
33232
+ state.setItem("status", "File created.");
33233
+ const browser = state.getItem("browser");
33234
+ if (browser.getItem("root")) await context.scope.value.getNode("frame.left.browser").fileSystemController.open(browser.getItem("root"));
31577
33235
  }
31578
33236
  } catch (error) {
31579
- if (!this.ideDisposed) this.ideState.setItem("status", error.message);
33237
+ if (!documents.disposed) state.setItem("status", error.message);
31580
33238
  }
31581
33239
  }
31582
33240
  async ideSave(node, { documentKey: documentKey2 = null } = {}) {
31583
- const key = documentKey2 ?? this.ideState.getItem("active");
31584
- if (!key || this.ideDocuments.documents.getItem(key).getItem("saveDisabled")) return;
31585
- const doc = this.ideDocuments.documents.getItem(key);
33241
+ const context = ideContext(node), { documents } = context;
33242
+ const state = context.scope.getRelativeData(".");
33243
+ const key = documentKey2 ?? state.getItem("active");
33244
+ if (!key || documents.documents.getItem(key).getItem("saveDisabled")) return;
33245
+ const doc = documents.documents.getItem(key);
31586
33246
  if (doc.getItem("isNew")) {
31587
33247
  doc.setItem("createHidden", false);
31588
33248
  return;
31589
33249
  }
31590
- this.ideState.setItem("status", "Saving\u2026");
33250
+ state.setItem("status", "Saving\u2026");
31591
33251
  try {
31592
- const saved = await this.ideDocuments.save(key);
31593
- if (!this.ideDisposed) this.ideState.setItem("status", saved ? "Saved." : "Document is read only or a request is pending.");
33252
+ const saved = await documents.save(key);
33253
+ if (!documents.disposed) state.setItem("status", saved ? "Saved." : "Document is read only or a request is pending.");
31594
33254
  } catch (error) {
31595
- if (!this.ideDisposed) this.ideState.setItem("status", error.message);
33255
+ if (!documents.disposed) state.setItem("status", error.message);
31596
33256
  }
31597
33257
  }
31598
33258
  ideRevert(node, { documentKey: documentKey2 }) {
31599
- if (this.ideDocuments.revert(documentKey2)) this.ideState.setItem("status", "Restored the last saved version.");
33259
+ const context = ideContext(node), { documents } = context;
33260
+ const state = context.scope.getRelativeData(".");
33261
+ if (documents.revert(documentKey2)) state.setItem("status", "Restored the last saved version.");
31600
33262
  }
31601
33263
  ideHistoryChanged(node, { canUndo, canRedo }) {
31602
33264
  const doc = node.getRelativeData(".");
@@ -31610,37 +33272,41 @@ var IdeLogic = class {
31610
33272
  doc.setItem("undoDisabled", !doc.getItem(`${view}CanUndo`));
31611
33273
  doc.setItem("redoDisabled", !doc.getItem(`${view}CanRedo`));
31612
33274
  }
31613
- ideEditor(documentKey2) {
31614
- const rich = this.ideDocuments.documents.getItem(documentKey2).getItem("view") === "rich";
31615
- const node = this.page.src.binding.nodeIds.get(`${rich ? "rich_" : ""}editor_${documentKey2}`);
31616
- return this.page.src.renderer.records.get(node).element;
33275
+ ideEditor(node, documentKey2) {
33276
+ const context = ideContext(node), { documents } = context;
33277
+ const rich = documents.documents.getItem(documentKey2).getItem("view") === "rich";
33278
+ const editor = this.page.src.binding.nodeIds.get(`${context.editorPrefix}_${rich ? "rich_" : ""}editor_${documentKey2}`);
33279
+ return this.page.src.renderer.records.get(editor).element;
31617
33280
  }
31618
33281
  ideUndo(node, { documentKey: documentKey2 }) {
31619
- this.ideEditor(documentKey2).undo();
33282
+ this.ideEditor(node, documentKey2).undo();
31620
33283
  }
31621
33284
  ideRedo(node, { documentKey: documentKey2 }) {
31622
- this.ideEditor(documentKey2).redo();
33285
+ this.ideEditor(node, documentKey2).redo();
31623
33286
  }
31624
33287
  ideClose(node) {
33288
+ const context = ideContext(node), { documents } = context;
33289
+ const state = context.scope.getRelativeData(".");
31625
33290
  const key = node.getAttr("documentKey");
31626
- if (!this.ideDocuments.canClose(key)) {
31627
- this.ideState.setItem("status", "Save or revert your changes before closing. Pending operations must finish first.");
33291
+ if (!documents.canClose(key)) {
33292
+ state.setItem("status", "Save or revert your changes before closing. Pending operations must finish first.");
31628
33293
  return false;
31629
33294
  }
31630
33295
  return true;
31631
33296
  }
31632
33297
  ideClosed(node, { pageName }) {
31633
- this.ideForgetDocument(pageName);
33298
+ this.ideForgetDocument(node, pageName);
31634
33299
  }
31635
- ideForgetDocument(key, discard = false) {
31636
- const document = this.ideDocuments.documents.getItem(key);
31637
- const browser = this.ideState.getItem("browser"), selectedPath = browser.getItem("selectedPath");
33300
+ ideForgetDocument(node, key, discard = false) {
33301
+ const context = ideContext(node), { documents } = context;
33302
+ const state = context.scope.getRelativeData(".");
33303
+ const document = documents.documents.getItem(key);
33304
+ const browser = state.getItem("browser"), selectedPath = browser.getItem("selectedPath");
31638
33305
  const selected = selectedPath === null ? null : browser.getItem("store").getNode(selectedPath);
31639
33306
  if (document && browser.getItem("root") === document.getItem("root") && selected?.attr.path === document.getItem("path")) {
31640
33307
  browser.setItem("selectedPath", null);
31641
33308
  }
31642
- this.idePanels.delete(key);
31643
- this.ideDocuments.close(key, discard);
33309
+ documents.close(key, discard);
31644
33310
  }
31645
33311
  };
31646
33312
 
@@ -31707,7 +33373,7 @@ var NavigationResolver = class _NavigationResolver extends RemoteResolver {
31707
33373
  }
31708
33374
  };
31709
33375
 
31710
- // src/date-parser/civil.js
33376
+ // node_modules/@genrojs/toolbox/js/src/dates/civil.js
31711
33377
  function daysInMonth(year, month) {
31712
33378
  if (month === 2) return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : 28;
31713
33379
  return [4, 6, 9, 11].includes(month) ? 30 : 31;
@@ -31759,8 +33425,121 @@ function monthPeriod(year, month, offset = 0, count = 1) {
31759
33425
  return { start: civil(y, m, 1), end: civil(ey, em, daysInMonth(ey, em)) };
31760
33426
  }
31761
33427
 
31762
- // src/date-parser/locales.js
33428
+ // node_modules/@genrojs/toolbox/js/src/dates/locales.js
31763
33429
  var locales = {
33430
+ "en": {
33431
+ "months": {
33432
+ "january": 1,
33433
+ "february": 2,
33434
+ "march": 3,
33435
+ "april": 4,
33436
+ "may": 5,
33437
+ "june": 6,
33438
+ "july": 7,
33439
+ "august": 8,
33440
+ "september": 9,
33441
+ "october": 10,
33442
+ "november": 11,
33443
+ "december": 12,
33444
+ "jan": 1,
33445
+ "feb": 2,
33446
+ "mar": 3,
33447
+ "apr": 4,
33448
+ "jun": 6,
33449
+ "jul": 7,
33450
+ "aug": 8,
33451
+ "sep": 9,
33452
+ "oct": 10,
33453
+ "nov": 11,
33454
+ "dec": 12
33455
+ },
33456
+ "weekdays": {
33457
+ "monday": 0,
33458
+ "tuesday": 1,
33459
+ "wednesday": 2,
33460
+ "thursday": 3,
33461
+ "friday": 4,
33462
+ "saturday": 5,
33463
+ "sunday": 6,
33464
+ "mon": 0,
33465
+ "tue": 1,
33466
+ "wed": 2,
33467
+ "thu": 3,
33468
+ "fri": 4,
33469
+ "sat": 5,
33470
+ "sun": 6
33471
+ },
33472
+ "quarters": {
33473
+ "1st quarter": 1,
33474
+ "2nd quarter": 2,
33475
+ "3rd quarter": 3,
33476
+ "4th quarter": 4,
33477
+ "q1": 1,
33478
+ "q2": 2,
33479
+ "q3": 3,
33480
+ "q4": 4
33481
+ },
33482
+ "keywords": {
33483
+ "today": [
33484
+ "today"
33485
+ ],
33486
+ "yesterday": [
33487
+ "yesterday"
33488
+ ],
33489
+ "tomorrow": [
33490
+ "tomorrow"
33491
+ ],
33492
+ "this_week": [
33493
+ "this week",
33494
+ "week"
33495
+ ],
33496
+ "last_week": [
33497
+ "last week"
33498
+ ],
33499
+ "next_week": [
33500
+ "next week"
33501
+ ],
33502
+ "this_month": [
33503
+ "this month",
33504
+ "month"
33505
+ ],
33506
+ "last_month": [
33507
+ "last month"
33508
+ ],
33509
+ "next_month": [
33510
+ "next month"
33511
+ ],
33512
+ "last": [
33513
+ "last"
33514
+ ],
33515
+ "next": [
33516
+ "next"
33517
+ ],
33518
+ "articles": [
33519
+ "the"
33520
+ ],
33521
+ "from": [
33522
+ "from",
33523
+ "between"
33524
+ ],
33525
+ "to": [
33526
+ "to",
33527
+ "and"
33528
+ ],
33529
+ "no_period": [
33530
+ "no period",
33531
+ "always"
33532
+ ]
33533
+ },
33534
+ "date_order": {
33535
+ "default": "MDY",
33536
+ "GB": "DMY",
33537
+ "AU": "DMY",
33538
+ "IE": "DMY",
33539
+ "NZ": "DMY",
33540
+ "IN": "DMY"
33541
+ }
33542
+ },
31764
33543
  "it": {
31765
33544
  "months": {
31766
33545
  "gennaio": 1,
@@ -31887,121 +33666,10 @@ var locales = {
31887
33666
  "date_order": {
31888
33667
  "default": "DMY"
31889
33668
  }
31890
- },
31891
- "en": {
31892
- "months": {
31893
- "january": 1,
31894
- "february": 2,
31895
- "march": 3,
31896
- "april": 4,
31897
- "may": 5,
31898
- "june": 6,
31899
- "july": 7,
31900
- "august": 8,
31901
- "september": 9,
31902
- "october": 10,
31903
- "november": 11,
31904
- "december": 12,
31905
- "jan": 1,
31906
- "feb": 2,
31907
- "mar": 3,
31908
- "apr": 4,
31909
- "jun": 6,
31910
- "jul": 7,
31911
- "aug": 8,
31912
- "sep": 9,
31913
- "oct": 10,
31914
- "nov": 11,
31915
- "dec": 12
31916
- },
31917
- "weekdays": {
31918
- "monday": 0,
31919
- "tuesday": 1,
31920
- "wednesday": 2,
31921
- "thursday": 3,
31922
- "friday": 4,
31923
- "saturday": 5,
31924
- "sunday": 6,
31925
- "mon": 0,
31926
- "tue": 1,
31927
- "wed": 2,
31928
- "thu": 3,
31929
- "fri": 4,
31930
- "sat": 5,
31931
- "sun": 6
31932
- },
31933
- "quarters": {
31934
- "1st quarter": 1,
31935
- "2nd quarter": 2,
31936
- "3rd quarter": 3,
31937
- "4th quarter": 4,
31938
- "q1": 1,
31939
- "q2": 2,
31940
- "q3": 3,
31941
- "q4": 4
31942
- },
31943
- "keywords": {
31944
- "today": [
31945
- "today"
31946
- ],
31947
- "yesterday": [
31948
- "yesterday"
31949
- ],
31950
- "tomorrow": [
31951
- "tomorrow"
31952
- ],
31953
- "this_week": [
31954
- "this week",
31955
- "week"
31956
- ],
31957
- "last_week": [
31958
- "last week"
31959
- ],
31960
- "next_week": [
31961
- "next week"
31962
- ],
31963
- "this_month": [
31964
- "this month",
31965
- "month"
31966
- ],
31967
- "last_month": [
31968
- "last month"
31969
- ],
31970
- "next_month": [
31971
- "next month"
31972
- ],
31973
- "last": [
31974
- "last"
31975
- ],
31976
- "next": [
31977
- "next"
31978
- ],
31979
- "articles": [
31980
- "the"
31981
- ],
31982
- "from": [
31983
- "from",
31984
- "between"
31985
- ],
31986
- "to": [
31987
- "to",
31988
- "and"
31989
- ],
31990
- "no_period": [
31991
- "no period",
31992
- "always"
31993
- ]
31994
- },
31995
- "date_order": {
31996
- "default": "MDY",
31997
- "GB": "DMY",
31998
- "AU": "DMY",
31999
- "IE": "DMY",
32000
- "NZ": "DMY",
32001
- "IN": "DMY"
32002
- }
32003
33669
  }
32004
33670
  };
33671
+
33672
+ // node_modules/@genrojs/toolbox/js/src/dates/locale-context.js
32005
33673
  function localeContext(locale) {
32006
33674
  if (typeof locale !== "string") throw new RangeError("A supported locale is required.");
32007
33675
  const tag2 = locale.replaceAll("-", "_");
@@ -32014,7 +33682,7 @@ function localeContext(locale) {
32014
33682
  return { dictionary, phrases, order: dictionary.date_order[region] ?? dictionary.date_order.default };
32015
33683
  }
32016
33684
 
32017
- // src/date-parser/index.js
33685
+ // node_modules/@genrojs/toolbox/js/src/dates/index.js
32018
33686
  var yearPattern = /^(?:\d{4}|\d{2})$/;
32019
33687
  var dayPattern = /^\d{1,2}$/;
32020
33688
  var fail2 = (code, message) => ({ ok: false, error: { code, message } });
@@ -32207,80 +33875,30 @@ function parseDateExpression(text2, options = {}) {
32207
33875
  }
32208
33876
 
32209
33877
  // src/components/labelbox.js
32210
- var POSITIONS = ["TL", "TC", "TR", "L", "R", "BL", "BC", "BR"];
32211
- function project2(element, attrs, adapt, previous) {
32212
- const next = adapt(attrs);
32213
- for (const key of /* @__PURE__ */ new Set([...Object.keys(previous), ...Object.keys(next)])) {
32214
- if (next[key] == null) element.removeAttribute(key);
32215
- else element.setAttribute(key, String(next[key]));
32216
- }
32217
- return next;
32218
- }
32219
33878
  function Labelbox(Base) {
32220
33879
  return class extends Base {
32221
- #previous = { box: {}, label: {}, labelBox: {}, controlBox: {} };
32222
- constructor() {
32223
- super();
32224
- this.box = this.ownerDocument.createElement("div");
32225
- this.box.className = "labelbox";
32226
- this.labelBox = this.ownerDocument.createElement("div");
32227
- this.labelBox.className = "label-box";
32228
- this.fieldLabel = this.ownerDocument.createElement("label");
32229
- this.fieldLabel.id = "field-label";
32230
- this.fieldLabel.htmlFor = "control";
32231
- this.labelBox.append(this.fieldLabel);
32232
- this.box.append(this.labelBox, this.controlBox);
32233
- const style = this.ownerDocument.createElement("style");
32234
- style.textContent = `.labelbox{--gramlot-label-width:initial;--gramlot-formlet-label-width:initial;display:grid;gap:var(--gramlot-label-gap,.25em);grid-template-areas:'label' 'control'}
32235
- .label-box{grid-area:label;color:var(--gramlot-label-color,var(--gramlot-text-secondary,inherit));font-size:var(--gramlot-label-size,1em)} .control-box{grid-area:control}
32236
- .labelbox[data-position='L']{grid-template-areas:'label control';align-items:center}
32237
- .labelbox[data-position='R']{grid-template-areas:'control label';align-items:center}
32238
- .labelbox[data-position^='B']{grid-template-areas:'control' 'label'}
32239
- .labelbox[data-position$='C']>.label-box{text-align:center}
32240
- .labelbox[data-position$='R']>.label-box{text-align:right}
32241
- .label-box[hidden]{display:none} .label-box label{display:block}
32242
- .labelbox[data-position='L']>.label-box{text-align:right;padding-right:2px}
32243
- .labelbox[data-formlet-aligned]>.label-box>label{width:max-content;margin-left:auto}
32244
- .labelbox[data-position='L']{grid-template-columns:var(--gramlot-label-width,var(--gramlot-formlet-label-width,max-content)) minmax(0,1fr)}`;
32245
- this.shadowRoot.append(style, this.box);
33880
+ setLabelbox(layout) {
33881
+ const { box, labelBox, fieldLabel } = layout;
33882
+ Object.assign(this, { box, labelBox, fieldLabel });
33883
+ fieldLabel.addEventListener("click", () => {
33884
+ this.control.focus();
33885
+ if (this.control.localName === "input" && ["checkbox", "radio"].includes(this.control.type))
33886
+ this.control.click();
33887
+ });
32246
33888
  }
32247
33889
  projectAttributes(attrs, adapt) {
32248
33890
  const rest = super.projectAttributes(attrs, adapt);
32249
- const { lbl, lbl_position = "TL" } = this.parameters;
32250
- if (!POSITIONS.includes(lbl_position)) throw new TypeError(`Invalid lbl_position: ${lbl_position}`);
32251
- const groups = { box: {}, label: {}, labelBox: {}, controlBox: {} };
32252
- const prefixes = [["box_l_", "labelBox"], ["box_c_", "controlBox"], ["lbl_", "label"], ["box_", "box"]];
32253
- for (const [name, value] of Object.entries(rest)) {
32254
- const match = prefixes.find(([prefix]) => name.startsWith(prefix));
32255
- if (match) {
32256
- groups[match[1]][name.slice(match[0].length)] = value;
32257
- delete rest[name];
32258
- }
32259
- }
32260
- const elements = { box: this.box, label: this.fieldLabel, labelBox: this.labelBox, controlBox: this.controlBox };
32261
- for (const [name, element] of Object.entries(elements)) {
32262
- this.#previous[name] = project2(element, groups[name], adapt, this.#previous[name]);
32263
- }
32264
- if (attrs.lbl_width == null) this.box.style.removeProperty("--gramlot-label-width");
32265
- else this.box.style.setProperty("--gramlot-label-width", attrs.lbl_width);
32266
- this.box.classList.add("labelbox");
32267
- this.labelBox.classList.add("label-box");
32268
- this.controlBox.classList.add("control-box");
32269
- this.box.dataset.position = lbl_position;
32270
- this.fieldLabel.textContent = lbl ?? "";
32271
- this.labelBox.hidden = lbl == null || lbl === "";
32272
- if (this.control.localName !== "input") {
32273
- if (this.labelBox.hidden) this.control.removeAttribute("aria-labelledby");
32274
- else this.control.setAttribute("aria-labelledby", "field-label");
32275
- }
32276
- this.dispatchEvent(new this.ownerDocument.defaultView.Event("gramlot-label-layout", { bubbles: true }));
33891
+ const label = this.parameters.lbl ?? "";
33892
+ if (label) this.control.setAttribute("aria-label", label);
33893
+ else this.control.removeAttribute("aria-label");
32277
33894
  return rest;
32278
33895
  }
32279
33896
  };
32280
33897
  }
33898
+ Labelbox.labelbox = true;
32281
33899
  Labelbox.parameters = {
32282
33900
  lbl: { dtype: "T", qualification: "intl_str", nullable: true, binding: "read" },
32283
- lbl_position: { dtype: "T", default: "TL", binding: "read", enum: POSITIONS }
33901
+ lbl_position: { dtype: "T", default: "TL", binding: "read", enum: labelboxPositions }
32284
33902
  };
32285
33903
 
32286
33904
  // src/components/validation.js
@@ -32696,6 +34314,7 @@ export {
32696
34314
  ChoiceGroup,
32697
34315
  CommandRegistry,
32698
34316
  ComponentCollection,
34317
+ DeviceHandler,
32699
34318
  DirectoryResolver,
32700
34319
  DomHandler,
32701
34320
  Exposed,
@@ -32715,6 +34334,7 @@ export {
32715
34334
  IndexLogic,
32716
34335
  IndexPage,
32717
34336
  Labelbox,
34337
+ MobileEnvironment,
32718
34338
  NativeControl,
32719
34339
  NavigationResolver,
32720
34340
  Page,