contour-ds 1.9.0 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/README.md +4 -4
  2. package/dist/build-manifest.json +205 -204
  3. package/dist/contour-wc-content.esm.js +1 -1
  4. package/dist/contour-wc-content.esm.min.js +1 -1
  5. package/dist/contour-wc-core.esm.js +712 -45
  6. package/dist/contour-wc-core.esm.min.js +1 -1
  7. package/dist/contour-wc-dashboard.esm.js +596 -90
  8. package/dist/contour-wc-dashboard.esm.min.js +1 -1
  9. package/dist/contour-wc-data.esm.js +467 -70
  10. package/dist/contour-wc-data.esm.min.js +1 -1
  11. package/dist/contour-wc-docs.esm.js +1 -1
  12. package/dist/contour-wc-docs.esm.min.js +1 -1
  13. package/dist/contour-wc-feedback.esm.js +260 -29
  14. package/dist/contour-wc-feedback.esm.min.js +1 -1
  15. package/dist/contour-wc-forms.esm.js +133 -40
  16. package/dist/contour-wc-forms.esm.min.js +1 -1
  17. package/dist/contour-wc-interaction.esm.js +64 -5
  18. package/dist/contour-wc-interaction.esm.min.js +1 -1
  19. package/dist/contour-wc-layout.esm.js +72 -10
  20. package/dist/contour-wc-layout.esm.min.js +1 -1
  21. package/dist/contour-wc-map.esm.js +69 -9
  22. package/dist/contour-wc-map.esm.min.js +1 -1
  23. package/dist/contour-wc-misc.esm.js +1 -1
  24. package/dist/contour-wc-misc.esm.min.js +1 -1
  25. package/dist/contour-wc-navigation.esm.js +136 -20
  26. package/dist/contour-wc-navigation.esm.min.js +1 -1
  27. package/dist/contour-wc-ui.esm.js +505 -80
  28. package/dist/contour-wc-ui.esm.min.js +1 -1
  29. package/dist/contour-wc.esm.js +2539 -320
  30. package/dist/contour-wc.esm.min.js +1 -1
  31. package/dist/contour-wc.js +2539 -320
  32. package/dist/contour-wc.min.js +1 -1
  33. package/dist/contour.code-snippets +44 -0
  34. package/dist/contour.components.json +12064 -135
  35. package/dist/contour.css +1368 -451
  36. package/dist/contour.d.ts +42 -21
  37. package/dist/contour.esm.js +138 -21
  38. package/dist/contour.esm.min.js +1 -1
  39. package/dist/contour.html-data.json +249 -9
  40. package/dist/contour.js +138 -21
  41. package/dist/contour.min.css +1 -1
  42. package/dist/contour.min.js +1 -1
  43. package/dist/contour.react.d.ts +5 -1
  44. package/dist/contour.single.html +2 -2
  45. package/dist/contour.single.min.css +1 -1
  46. package/dist/contour.tokens.json +36 -1
  47. package/dist/contour.vue.d.ts +5 -1
  48. package/dist/contour.web-types.json +241 -9
  49. package/dist/custom-elements.json +1225 -55
  50. package/dist/docs/actions.md +1 -1
  51. package/dist/docs/affordances.md +1 -1
  52. package/dist/docs/apireference.md +1 -1
  53. package/dist/docs/colour.md +1 -1
  54. package/dist/docs/componentindex.md +1 -1
  55. package/dist/docs/data.md +6 -2
  56. package/dist/docs/docs.md +1 -1
  57. package/dist/docs/feedback.md +1 -1
  58. package/dist/docs/field.md +1 -1
  59. package/dist/docs/forms.md +1 -1
  60. package/dist/docs/index.json +8 -8
  61. package/dist/docs/install.md +1 -1
  62. package/dist/docs/landing.md +1 -1
  63. package/dist/docs/mapengine.md +1 -1
  64. package/dist/docs/motion.md +1 -1
  65. package/dist/docs/navigation.md +1 -1
  66. package/dist/docs/overlays.md +1 -1
  67. package/dist/docs/overview.md +1 -1
  68. package/dist/docs/patterns.md +1 -1
  69. package/dist/docs/playground.md +1 -1
  70. package/dist/docs/principles.md +1 -1
  71. package/dist/docs/recipes.md +1 -1
  72. package/dist/docs/space.md +1 -1
  73. package/dist/docs/status.md +1 -1
  74. package/dist/docs/surfaces.md +1 -1
  75. package/dist/docs/theming.md +5 -2
  76. package/dist/docs/type.md +1 -1
  77. package/dist/docs/webcomponents.md +1 -1
  78. package/dist/hljs.css +34 -17
  79. package/dist/map-chrome-contract.json +26 -0
  80. package/dist/map-chrome.mapbox.css +121 -0
  81. package/dist/map-chrome.maplibre.css +121 -0
  82. package/dist/registry/items/contour-core.json +2 -2
  83. package/dist/registry/items/contour-data.json +2 -2
  84. package/dist/registry/items/contour-docs.json +2 -2
  85. package/dist/registry/items/contour-landing.json +2 -2
  86. package/dist/registry/registry.json +8 -8
  87. package/dist/surfaces/contour-core.min.css +1 -1
  88. package/dist/surfaces/contour-data.min.css +1 -1
  89. package/dist/surfaces/contour-docs.min.css +1 -1
  90. package/dist/surfaces/contour-landing.min.css +1 -1
  91. package/dist/wc/behaviours.mjs +11 -3
  92. package/dist/wc/core.mjs +307 -32
  93. package/dist/wc/dashboard.mjs +129 -20
  94. package/dist/wc/data-chart.mjs +170 -22
  95. package/dist/wc/data-export.mjs +150 -29
  96. package/dist/wc/data-gauge.mjs +11 -4
  97. package/dist/wc/data-geo.mjs +1 -1
  98. package/dist/wc/data-legend.mjs +15 -2
  99. package/dist/wc/data-readout.mjs +12 -1
  100. package/dist/wc/data-series.mjs +73 -5
  101. package/dist/wc/data-table.mjs +37 -8
  102. package/dist/wc/feedback.mjs +259 -28
  103. package/dist/wc/forms-controls.mjs +44 -16
  104. package/dist/wc/forms-field.mjs +46 -4
  105. package/dist/wc/forms-groups.mjs +31 -8
  106. package/dist/wc/forms-input.mjs +11 -11
  107. package/dist/wc/index.mjs +1 -1
  108. package/dist/wc/interaction.mjs +63 -4
  109. package/dist/wc/layout.mjs +72 -10
  110. package/dist/wc/map.mjs +68 -8
  111. package/dist/wc/navigation-menu.mjs +43 -9
  112. package/dist/wc/navigation-shell.mjs +39 -6
  113. package/dist/wc/navigation-tree.mjs +53 -4
  114. package/dist/wc/states.mjs +350 -9
  115. package/dist/wc/svg.mjs +43 -0
  116. package/dist/wc/ui-data.mjs +268 -28
  117. package/dist/wc/ui-feedback.mjs +36 -11
  118. package/dist/wc/ui-inputs.mjs +63 -25
  119. package/dist/wc/ui-overlays.mjs +138 -16
  120. package/integrations/ai/v0-prompt.md +1 -1
  121. package/integrations/frameworks/fixtures/authored/sample.jsx +15 -0
  122. package/integrations/frameworks/fixtures/authored/sample.vue +15 -0
  123. package/integrations/frameworks/fixtures/dist/rendered.html +32 -0
  124. package/integrations/libreship/contract.json +1025 -0
  125. package/integrations/native/README.md +24 -4
  126. package/integrations/native/build/android/colors.xml +278 -0
  127. package/integrations/native/build/flutter/contour_tokens.dart +280 -0
  128. package/integrations/native/build/ios/ContourTokens.swift +280 -0
  129. package/integrations/validate-markup.mjs +57 -7
  130. package/package.json +45 -18
@@ -1,4 +1,4 @@
1
- export var CONTOUR_VERSION = "1.9.0";
1
+ export var CONTOUR_VERSION = "1.10.0";
2
2
  /* CONTOUR Web Components — two light-DOM layers over ds.css blocks; publishes the frozen `window.ContourElements` registry. */
3
3
  "use strict";
4
4
 
@@ -90,10 +90,83 @@ export var CONTOUR_VERSION = "1.9.0";
90
90
  */
91
91
  const JSON_TYPE = Symbol("JSON");
92
92
 
93
+ /**
94
+ * R34-46: the complete, executable property-descriptor model. Every declared
95
+ * property resolves to exactly these fields — the ones a framework wrapper (or
96
+ * a generated declaration) needs to agree with the runtime about:
97
+ *
98
+ * attribute the reflected attribute name (or the property name).
99
+ * type String | Number | Boolean | JSON_TYPE (runtime constructor/sentinel).
100
+ * reflect assignment writes the attribute (default true). `false` keeps
101
+ * the value in an internal store and never touches the attribute.
102
+ * controlled the parent owns the value (value/checked/selected); the host
103
+ * never treats its own write as the source of truth.
104
+ * null "clear" removes the attribute on null/undefined (default), or
105
+ * "preserve" keeps the previous value.
106
+ * collection "none" (default) | "copy" (a JSON value is parsed fresh on
107
+ * each read, so a caller cannot mutate the host's state) | "mutate"
108
+ * (the same object reference is handed back).
109
+ * json the value is JSON-serialised (default: type === JSON_TYPE).
110
+ */
111
+ export const PROPERTY_FIELDS = Object.freeze(["attribute", "type", "reflect", "controlled", "null", "collection", "json"]);
112
+
113
+ /** The artifact-facing type name for a runtime `type` (symbol/constructor). */
114
+ export function propertyTypeOf(type) {
115
+ if (type === Boolean) return "boolean";
116
+ if (type === Number) return "number";
117
+ if (type === JSON_TYPE) return "json";
118
+ return "string";
119
+ }
120
+
121
+ /**
122
+ * Resolve a raw `properties` entry to the complete descriptor, filling every
123
+ * field with its default so an unannotated property is still *complete* (the
124
+ * defaults are the correct semantics for the common case). The runtime install
125
+ * and the generators both call this, so the published metadata cannot disagree
126
+ * with what the element actually does.
127
+ */
128
+ export function normalizeProperty(name, spec) {
129
+ const s = spec || {};
130
+ const type = s.type || String;
131
+ const json = s.json !== undefined ? !!s.json : type === JSON_TYPE;
132
+ let collection = s.collection;
133
+ if (collection !== "copy" && collection !== "mutate") collection = json ? "copy" : "none";
134
+ return {
135
+ name,
136
+ attribute: s.attribute || name,
137
+ type,
138
+ reflect: s.reflect !== undefined ? !!s.reflect : true,
139
+ controlled: !!s.controlled,
140
+ null: s.null === "preserve" ? "preserve" : "clear",
141
+ collection,
142
+ json,
143
+ };
144
+ }
145
+
146
+ /**
147
+ * The complete descriptor as a compact JSON-safe record (for generated
148
+ * artifacts). `name` is the map key and `attribute` is omitted when it equals
149
+ * the name, so the common case carries only the six behavioural fields; a
150
+ * consumer fills the two implied defaults (name = key, attribute = name).
151
+ */
152
+ export function propertyDescriptor(name, spec) {
153
+ const d = normalizeProperty(name, spec);
154
+ const rec = {};
155
+ if (d.attribute !== name) rec.attribute = d.attribute;
156
+ rec.type = propertyTypeOf(d.type);
157
+ rec.reflect = d.reflect;
158
+ rec.controlled = d.controlled;
159
+ rec.null = d.null;
160
+ rec.collection = d.collection;
161
+ rec.json = d.json;
162
+ return rec;
163
+ }
164
+
93
165
  /** Frozen event vocabulary with the public detail keys for each event. */
94
166
  export const CONTOUR_EVENTS = Object.freeze({
95
167
  "contour:activate": { payload: ["files", "label", "row", "value"], composed: true },
96
168
  "contour:add": { payload: ["value"], composed: true },
169
+ "contour:annotation-action": { payload: ["action", "kind", "label"], composed: true },
97
170
  "contour:activity-clear": { payload: [], composed: true },
98
171
  "contour:activity-filter": { payload: ["unread"], composed: true },
99
172
  "contour:activity-select": { payload: ["index", "text"], composed: true },
@@ -110,17 +183,20 @@ export var CONTOUR_VERSION = "1.9.0";
110
183
  "contour:brush-start": { payload: ["end", "range", "start", "value"], composed: true },
111
184
  "contour:brush-end": { payload: ["end", "range", "start", "value"], composed: true },
112
185
  "contour:brush": { payload: ["end", "range", "start", "value"], composed: true },
113
- "contour:change": { payload: ["checked", "color", "direction", "end", "files", "high", "index", "low", "month", "name", "paused", "query", "speed", "start", "unit", "value", "values", "year"], composed: true },
186
+ "contour:change": { payload: ["checked", "color", "direction", "draft", "end", "files", "high", "index", "low", "month", "name", "paused", "query", "speed", "start", "unit", "value", "values", "year"], composed: true },
114
187
  "contour:collapse": { payload: ["collapsed"], composed: true },
115
188
  "contour:cluster-toggle": { payload: ["count", "expanded"], composed: true },
116
189
  "contour:clear": { payload: [], composed: true },
117
190
  "contour:clear-all": { payload: [], composed: true },
118
191
  "contour:close": { payload: ["count", "index", "label", "message", "open", "value"], composed: true },
119
192
  "contour:copy": { payload: ["text"], composed: true },
193
+ "contour:default": { payload: ["default", "name"], composed: true },
194
+ "contour:duplicate": { payload: ["name"], composed: true },
120
195
  "contour:apply": { payload: ["name"], composed: true },
121
196
  "contour:dash-action": { payload: ["label"], composed: true },
122
197
  "contour:diff-activate": { payload: ["kind", "text"], composed: true },
123
198
  "contour:dismiss": { payload: ["label"], composed: true },
199
+ "contour:toast-action": { payload: ["action"], composed: true },
124
200
  "contour:draw-start": { payload: ["mode"], composed: true },
125
201
  "contour:drag": { payload: ["delta", "key", "value"], composed: true },
126
202
  "contour:do-dont-activate": { payload: ["kind", "text"], composed: true },
@@ -132,7 +208,7 @@ export var CONTOUR_VERSION = "1.9.0";
132
208
  "contour:filter": { payload: ["query"], composed: true },
133
209
  "contour:filter-change": { payload: ["source", "filter"], composed: true },
134
210
  "contour:error": { payload: ["src", "message", "name", "status"], composed: true },
135
- "contour:export": { payload: ["format"], composed: true },
211
+ "contour:export": { payload: ["format", "scope", "count", "total", "filename", "crs", "provenance"], composed: true },
136
212
  "contour:refresh": { payload: [], composed: true },
137
213
  "contour:hide": { payload: [], composed: true, deprecated: "use contour:close instead" },
138
214
  "contour:hover": { payload: ["row"], composed: true },
@@ -167,17 +243,26 @@ export var CONTOUR_VERSION = "1.9.0";
167
243
  "contour:ready": { payload: ["version", "count"], composed: true },
168
244
  "contour:read": { payload: ["label"], composed: true },
169
245
  "contour:remove": { payload: ["key", "label", "name", "value"], composed: true },
246
+ "contour:rename": { payload: ["name"], composed: true },
247
+ "contour:share": { payload: ["name"], composed: true },
170
248
  "contour:reorder": { payload: ["from", "to"], composed: true },
249
+ "contour:row-action": { payload: ["index", "item", "label"], composed: true },
171
250
  "contour:range-change": { payload: ["value"], composed: true },
172
251
  "contour:resize": { payload: ["column", "delta", "height", "value", "width"], composed: true },
173
252
  "contour:retry": { payload: ["src"], composed: true },
253
+ "contour:chart-zoom": { payload: ["zoom", "panX", "panY"], composed: true },
254
+ "contour:brownout": { payload: ["level", "reason", "shed", "recovery"], composed: true },
255
+ "contour:offline": { payload: ["reason"], composed: true },
256
+ "contour:online": { payload: [], composed: true },
257
+ "contour:parse-error": { payload: ["src", "reason", "partial"], composed: true },
174
258
  "contour:loop-change": { payload: ["loop"], composed: true },
175
259
  "contour:pause": { payload: [], composed: true },
176
260
  "contour:play": { payload: [], composed: true },
177
261
  "contour:seek": { payload: ["progress", "value"], composed: true },
178
262
  "contour:select": { payload: ["area", "col", "expanded", "href", "index", "key", "label", "labels", "level", "path", "range", "result", "row", "rows", "series", "value"], composed: true },
263
+ "contour:selection": { payload: ["mode", "value"], composed: true },
179
264
  "contour:search": { payload: ["query"], composed: true },
180
- "contour:spatial-filter": { payload: ["action", "mode", "operator"], composed: true },
265
+ "contour:spatial-filter": { payload: ["action", "count", "crs", "mode", "operator"], composed: true },
181
266
  "contour:split-change": { payload: ["value", "width", "height"], composed: true },
182
267
  "contour:speed-change": { payload: ["speed"], composed: true },
183
268
  "contour:showcase-activate": { payload: ["title"], composed: true },
@@ -189,10 +274,10 @@ export var CONTOUR_VERSION = "1.9.0";
189
274
  "contour:submit": { payload: ["submitting"], composed: true },
190
275
  "contour:stream-state": { payload: ["running"], composed: true },
191
276
  "contour:tab-change": { payload: ["index", "label"], composed: true },
192
- "contour:theme-change": { payload: ["theme"], composed: true },
193
- "contour:tick": { payload: ["frame"], composed: true },
277
+ "contour:theme-change": { payload: ["source", "theme", "value"], composed: true },
278
+ "contour:tick": { payload: ["frame", "interval", "timestamp"], composed: true },
194
279
  "contour:time-change": { payload: ["progress", "value"], composed: true },
195
- "contour:time-range-change": { payload: ["value"], composed: true },
280
+ "contour:time-range-change": { payload: ["end", "preset", "start", "timezone", "value"], composed: true },
196
281
  "contour:toggle": { payload: ["collapsed", "expanded", "label", "open", "path", "playing"], composed: true },
197
282
  "contour:view-enter": { payload: [], composed: true },
198
283
  "contour:view-leave": { payload: [], composed: true },
@@ -378,7 +463,12 @@ export var CONTOUR_VERSION = "1.9.0";
378
463
  "autocomplete", "levels", "submit-label",
379
464
  "fields", "gap",
380
465
  "flush", "head", "preview", "tags", "url",
381
- "custom-error",
466
+ // R34-154/156: the brownout detail and offline lifecycle are read by the
467
+ // base brownout/offline mixins, so they belong in the shared vocabulary.
468
+ "brownout-reason", "brownout-recovery", "offline",
469
+ // `custom-error` is written by the field itself (setCustomValidity) and
470
+ // observed per-class (forms-field), so it is NOT in the shared list: a
471
+ // shared entry plus the self-write is the re-entrant arm wc-contract flags.
382
472
  ];
383
473
 
384
474
  /** Resolve an authored heading level while keeping the fallback valid. */
@@ -442,6 +532,10 @@ export var CONTOUR_VERSION = "1.9.0";
442
532
  }
443
533
  }
444
534
 
535
+ // R35: hosts that have already logged the contour:show/hide deprecation
536
+ // warning, so the warning fires once per host rather than on every emission.
537
+ let wcOverlayDeprecationWarned = null;
538
+
445
539
  /**
446
540
  * R24-93: Emit an overlay visibility event. `contour:open`/`contour:close`
447
541
  * are the canonical pair; `contour:show`/`contour:hide` are deprecated
@@ -464,12 +558,18 @@ export var CONTOUR_VERSION = "1.9.0";
464
558
  }
465
559
  // Canonical event first.
466
560
  host.dispatchEvent(new CustomEvent(type, { detail, bubbles: true, composed: true }));
467
- // Deprecated alias with a one-minor deprecation warning.
561
+ // Deprecated alias with a one-minor deprecation warning — once per host,
562
+ // not on every emission (R35: the per-emit warning spammed every open/close
563
+ // in tests and the guide).
468
564
  const alias = isOpen ? "contour:show" : "contour:hide";
469
- console.warn(
470
- `[Contour] ${alias} is deprecated, use ${type} instead. ` +
471
- `Will be removed in v2.0. (host: ${host.tagName || host.constructor.name})`
472
- );
565
+ if (!wcOverlayDeprecationWarned) wcOverlayDeprecationWarned = new WeakSet();
566
+ if (!wcOverlayDeprecationWarned.has(host)) {
567
+ wcOverlayDeprecationWarned.add(host);
568
+ console.warn(
569
+ `[Contour] ${alias} is deprecated, use ${type} instead. ` +
570
+ `Will be removed in v2.0. (host: ${host.tagName || host.constructor.name})`
571
+ );
572
+ }
473
573
  host.dispatchEvent(new CustomEvent(alias, { detail, bubbles: true, composed: true }));
474
574
  }
475
575
 
@@ -572,8 +672,17 @@ export var CONTOUR_VERSION = "1.9.0";
572
672
  const _ContourBaseParent = (typeof HTMLElement !== "undefined") ? HTMLElement : Object;
573
673
  // R31-39: constructors whose property accessors are already installed.
574
674
  const INSTALLED_PROPS = new WeakSet();
675
+ // R34-35: opt-in lifecycle diagnostics (page-wide, off by default).
676
+ let DIAG = typeof location !== "undefined" && /[?&]contour-diag\b/.test(location.search || "");
677
+ export function contourDiagnosticsEnabled() { return DIAG; }
678
+ export function setContourDiagnostics(on) { DIAG = !!on; }
575
679
  export class ContourBase extends _ContourBaseParent {
576
680
  static formAssociated = false;
681
+ // R35: a behavior-only subclass (a withResilience/withBrownout mixin that
682
+ // adds lifecycle without drawing markup) has nothing to render. Default to
683
+ // a no-op so connectedCallback/attributeChangedCallback do not throw
684
+ // "this.render is not a function" — subclasses that draw override it.
685
+ render() {}
577
686
  constructor() {
578
687
  super();
579
688
  if (this.constructor.formAssociated && typeof this.attachInternals === "function") {
@@ -623,6 +732,24 @@ export var CONTOUR_VERSION = "1.9.0";
623
732
  return this._contourRenderCount || 0;
624
733
  }
625
734
 
735
+ /**
736
+ * R34-35: opt-in lifecycle diagnostic. Returns a snapshot of the host's
737
+ * render/observer/listener counters so a page (or a test) can see what the
738
+ * component is doing without a devtools trace. Enabled globally with
739
+ * `?contour-diag` (or `contourDiagnosticsEnabled()`); when off it is a pure
740
+ * read with no side effects.
741
+ */
742
+ contourDiagnostics() {
743
+ return {
744
+ tag: this.tagName.toLowerCase(),
745
+ updateMode: this.constructor.updateMode,
746
+ renderCount: this.renderCount,
747
+ observed: [...(this.constructor.observedAttributes || [])],
748
+ hostListeners: this._contourHostListeners ? this._contourHostListeners.length : 0,
749
+ childNodes: this.childNodes.length,
750
+ };
751
+ }
752
+
626
753
  /**
627
754
  * Resolves one microtask after the last render has settled (render →
628
755
  * enhance → restore for a re-render, render → enhance for a first paint).
@@ -659,6 +786,8 @@ export var CONTOUR_VERSION = "1.9.0";
659
786
 
660
787
  _countRender() {
661
788
  this._contourRenderCount = (this._contourRenderCount || 0) + 1;
789
+ // R34-35: opt-in lifecycle trace — one line per render, only when enabled.
790
+ if (DIAG) console.debug("[contour:diag] render", this.tagName.toLowerCase(), this._contourRenderCount);
662
791
  }
663
792
 
664
793
  // Install accessors once per class, so `el.value = 42` writes the attribute
@@ -684,12 +813,25 @@ export var CONTOUR_VERSION = "1.9.0";
684
813
  }
685
814
  return raw;
686
815
  };
687
- for (const [name, spec] of Object.entries(props)) {
688
- const attr = (spec && spec.attribute) || name;
689
- declared.add(attr);
690
- const type = (spec && spec.type) || String;
816
+ for (const [name, rawSpec] of Object.entries(props)) {
817
+ // R34-46: resolve the complete descriptor; the runtime honours every
818
+ // field, and the defaults reproduce the historical behaviour exactly
819
+ // (reflect true, null clears, JSON copied) so an unannotated property
820
+ // is unchanged.
821
+ const spec = normalizeProperty(name, rawSpec);
822
+ const attr = spec.attribute;
823
+ const type = spec.type;
824
+ const reflect = spec.reflect;
825
+ const nullMode = spec.null;
826
+ const collection = spec.collection;
827
+ if (reflect) declared.add(attr);
828
+ const store = () => (this._contourPropValues || (this._contourPropValues = {}));
691
829
  Object.defineProperty(ctor.prototype, name, {
692
830
  get() {
831
+ if (!reflect) {
832
+ const s = store.call(this);
833
+ return name in s ? s[name] : (rawSpec && rawSpec.default !== undefined ? rawSpec.default : null);
834
+ }
693
835
  const raw = this.getAttribute(attr);
694
836
  // R31-37: a boolean property must agree with what render() draws.
695
837
  // The render path reads flags through flagOn()/flagOnValue(), which
@@ -697,19 +839,40 @@ export var CONTOUR_VERSION = "1.9.0";
697
839
  // `el.closable` true for `closable="false"` while the close button
698
840
  // was absent. Presence with a false-y string is off.
699
841
  if (type === Boolean) return flagOnValue(raw);
700
- if (raw === null) return spec && spec.default !== undefined ? spec.default : null;
842
+ if (raw === null) return rawSpec && rawSpec.default !== undefined ? rawSpec.default : null;
701
843
  if (type === Number) { const n = Number(raw); return Number.isNaN(n) ? null : n; }
702
- if (type === JSON_TYPE) return deserialize(raw);
844
+ if (type === JSON_TYPE) {
845
+ if (collection === "mutate") { const s = store.call(this); if (name in s) return s[name]; }
846
+ return deserialize(raw);
847
+ }
703
848
  return raw;
704
849
  },
705
850
  set(v) {
706
- if (v === null || v === undefined || v === false) this.removeAttribute(attr);
707
- else if (type === Boolean) {
708
- // R24-91: route string negatives ("false", "0", "no", "off", …) through the flagOn vocabulary so el.disabled = "false" ...
851
+ if (!reflect) {
852
+ if (v === null || v === undefined) {
853
+ if (nullMode === "preserve") return;
854
+ delete store.call(this)[name];
855
+ } else store.call(this)[name] = v;
856
+ this.requestRender();
857
+ return;
858
+ }
859
+ if (v === null || v === undefined) {
860
+ if (nullMode === "preserve") return;
861
+ this.removeAttribute(attr);
862
+ return;
863
+ }
864
+ // R24-91: `false` removes a reflected attribute (a boolean's off
865
+ // state and the historical non-boolean behaviour agree here).
866
+ if (v === false) { this.removeAttribute(attr); return; }
867
+ if (type === Boolean) {
868
+ // route string negatives ("false", "0", "no", "off", …) through
869
+ // the flagOn vocabulary so el.disabled = "false" stays off.
709
870
  if (!flagOnValue(v)) this.removeAttribute(attr);
710
871
  else this.setAttribute(attr, "");
872
+ return;
711
873
  }
712
- else this.setAttribute(attr, serialize(v));
874
+ if (type === JSON_TYPE && collection === "mutate") store.call(this)[name] = v;
875
+ this.setAttribute(attr, serialize(v));
713
876
  },
714
877
  configurable: true,
715
878
  });
@@ -1087,15 +1250,33 @@ export var CONTOUR_VERSION = "1.9.0";
1087
1250
  }
1088
1251
 
1089
1252
  // Form lifecycle (form-associated components only). The platform calls these on <form>.reset(), on disable by a fieldse...
1253
+ // R35-001/003: the single capability-safe writers. jsdom's attachInternals()
1254
+ // returns an ElementInternals without setFormValue/setValidity; a direct call
1255
+ // throws an unhandled async TypeError (the unit lane then exits non-zero
1256
+ // despite every test passing). Every form family routes through these two
1257
+ // helpers instead of touching `this._internals` directly, so one partial
1258
+ // platform implementation degrades cleanly across the whole family.
1259
+ _setFormValue(value) {
1260
+ if (!this._internals || typeof this._internals.setFormValue !== "function") return;
1261
+ this._internals.setFormValue(value);
1262
+ }
1263
+ _setValidity(flags, msg) {
1264
+ if (!this._internals || typeof this._internals.setValidity !== "function") return;
1265
+ this._internals.setValidity(flags, msg);
1266
+ }
1090
1267
  _syncFormValue() {
1091
- if (!this._internals) return;
1268
+ // jsdom's attachInternals() returns an ElementInternals without
1269
+ // setFormValue/setValidity; guard so a form-associated component under
1270
+ // test does not throw an unhandled async TypeError (the unit lane then
1271
+ // exits non-zero despite every test passing).
1272
+ if (!this._internals || typeof this._internals.setFormValue !== "function") return;
1092
1273
  // A boolean group (a contour-radio-list) submits the *checked* item's
1093
1274
  // value, so prefer the checked control over the first one found.
1094
1275
  const ctl = this.querySelector("input:checked, textarea, select") || this.querySelector("input, textarea, select");
1095
1276
  if (!ctl) return;
1096
1277
  const boolean = ctl.type === "checkbox" || ctl.type === "radio";
1097
1278
  const value = boolean ? (ctl.checked ? (ctl.value || "on") : null) : ctl.value;
1098
- this._internals.setFormValue(value);
1279
+ this._setFormValue(value);
1099
1280
  this._syncValidity(this.hasAttribute("required") && !value);
1100
1281
  }
1101
1282
 
@@ -1121,7 +1302,7 @@ export var CONTOUR_VERSION = "1.9.0";
1121
1302
  if (v.tooShort) { flags.tooShort = true; msg = msg || "Value is too short."; }
1122
1303
  if (v.badInput) { flags.badInput = true; msg = msg || "Invalid input."; }
1123
1304
  }
1124
- this._internals.setValidity(flags, msg);
1305
+ this._setValidity(flags, msg);
1125
1306
  this._setCustomState("data-invalid", Object.keys(flags).length > 0);
1126
1307
  }
1127
1308
 
@@ -1205,10 +1386,20 @@ export var CONTOUR_VERSION = "1.9.0";
1205
1386
 
1206
1387
  // Keep internals in step with the group. Checking radio B fires `change` on B only — the deselected host A hears nothin...
1207
1388
  _wireFormData() {
1208
- if (!this._internals || this._wiredFormData) return;
1389
+ if (!this._internals) return;
1390
+ // R34-45: rebind when the form owner changes. The `form` attribute can be
1391
+ // set, removed or changed after the host is connected (and a host can be
1392
+ // moved between forms); the platform updates `_internals.form` and fires
1393
+ // `formAssociatedCallback`, but listeners added for the previous owner
1394
+ // would keep firing on the old form and never on the new one. `_wiredForm`
1395
+ // is the owner the current listeners are bound to; a mismatch detaches the
1396
+ // old listeners before binding the new, so exactly one form is listened to.
1209
1397
  const form = this._internals.form;
1398
+ if (form === this._wiredForm) return; // already bound to this owner
1399
+ if (this._formDataCleanup) { this._formDataCleanup(); this._formDataCleanup = null; }
1400
+ this._wiredForm = form || null;
1401
+ this._wiredFormData = !!form;
1210
1402
  if (!form) return;
1211
- this._wiredFormData = true;
1212
1403
  const myName = this.getAttribute("name");
1213
1404
  const onFormChange = (e) => {
1214
1405
  const t = e.target;
@@ -1217,10 +1408,28 @@ export var CONTOUR_VERSION = "1.9.0";
1217
1408
  form.addEventListener("change", onFormChange);
1218
1409
  const onFormData = () => this._syncFormValue();
1219
1410
  form.addEventListener("formdata", onFormData);
1220
- onDispose(this, () => {
1411
+ this._formDataCleanup = () => {
1221
1412
  form.removeEventListener("change", onFormChange);
1222
1413
  form.removeEventListener("formdata", onFormData);
1223
- });
1414
+ };
1415
+ // One onDispose per mount (not per rebind): it runs the *current* cleanup
1416
+ // and resets the guard so a reconnect re-registers against the new owner.
1417
+ if (!this._formDataDisposeWired) {
1418
+ this._formDataDisposeWired = true;
1419
+ onDispose(this, () => {
1420
+ if (this._formDataCleanup) { this._formDataCleanup(); this._formDataCleanup = null; }
1421
+ this._wiredForm = null;
1422
+ this._wiredFormData = false;
1423
+ this._formDataDisposeWired = false;
1424
+ });
1425
+ }
1426
+ }
1427
+
1428
+ // The form owner changed (the `form` attribute was set/removed/changed, or
1429
+ // the host was moved between forms). Rebind the form listeners to the new
1430
+ // owner (R34-45); a no-op for non-form components.
1431
+ formAssociatedCallback() {
1432
+ this._wireFormData();
1224
1433
  }
1225
1434
 
1226
1435
  // User-dirty value tracking (R20 T-02). The restore path only fills controls a render left empty, so a host with an aut...
@@ -1295,6 +1504,27 @@ export var CONTOUR_VERSION = "1.9.0";
1295
1504
  });
1296
1505
  }
1297
1506
 
1507
+ // R33-42: state serialization. `toJSON()` captures the author-controlled
1508
+ // surface (the observed attributes that are present) as a plain object;
1509
+ // `fromJSON(obj)` restores it. This is the state a host copies, shares or
1510
+ // undoes — it deliberately excludes internal/generated state.
1511
+ toJSON() {
1512
+ const out = {};
1513
+ for (const attr of this.constructor.observed || []) {
1514
+ const v = this.getAttribute(attr);
1515
+ if (v !== null) out[attr] = v;
1516
+ }
1517
+ return out;
1518
+ }
1519
+ fromJSON(obj) {
1520
+ if (!obj || typeof obj !== "object") return this;
1521
+ for (const [key, value] of Object.entries(obj)) {
1522
+ if (value === null || value === undefined) this.removeAttribute(key);
1523
+ else this.setAttribute(key, String(value));
1524
+ }
1525
+ return this;
1526
+ }
1527
+
1298
1528
  // R31-15: the light layer no longer writes `part=` on generated nodes.
1299
1529
  // `::part()` matches only shadow parts, so the attribute was inert on every
1300
1530
  // light component while `_applyParts` scanned every `[class]` on every
@@ -1371,11 +1601,29 @@ export var CONTOUR_VERSION = "1.9.0";
1371
1601
  return class extends Base {
1372
1602
  static get observed() {
1373
1603
  const base = (super.observed && Array.isArray(super.observed)) ? super.observed : [];
1374
- const extra = ["brownout", "brownout-level"];
1604
+ const extra = ["brownout", "brownout-level", "brownout-reason", "brownout-recovery"];
1375
1605
  return Array.from(new Set(base.concat(extra)));
1376
1606
  }
1377
1607
  brownoutLevel() { return super.brownoutLevel ? super.brownoutLevel() : (parseInt(this.getAttribute("brownout-level") || this.getAttribute("brownout") || "0", 10) || 0); }
1378
1608
  shed(kind, threshold) { return this.brownoutLevel() >= (threshold || 1); }
1609
+ // R34-154: the degraded-state contract — why it is degraded, what was
1610
+ // shed, and the action that recovers it — published as one event so a
1611
+ // shell can badge the widget and a consumer can offer the recovery.
1612
+ brownoutDetail() {
1613
+ const level = this.brownoutLevel();
1614
+ return {
1615
+ level,
1616
+ reason: this.getAttribute("brownout-reason") || "",
1617
+ shed: level > 0,
1618
+ recovery: this.getAttribute("brownout-recovery") || "",
1619
+ };
1620
+ }
1621
+ attributeChangedCallback(name, old, val) {
1622
+ if (super.attributeChangedCallback) super.attributeChangedCallback(name, old, val);
1623
+ if (name === "brownout" || name === "brownout-level" || name === "brownout-reason" || name === "brownout-recovery") {
1624
+ this.dispatchEvent(new CustomEvent("contour:brownout", { bubbles: true, composed: true, detail: this.brownoutDetail() }));
1625
+ }
1626
+ }
1379
1627
  };
1380
1628
  }
1381
1629
  /** Pure helper: compute brownout level from an attribute bag (framework-neutral). */
@@ -1427,9 +1675,13 @@ export var CONTOUR_VERSION = "1.9.0";
1427
1675
  export function formatValue(value, format, locale, unit) {
1428
1676
  if (!format) return value;
1429
1677
  const loc = locale || (typeof navigator !== "undefined" && navigator.language) || "en";
1430
- if (format === "date" || format === "time") {
1678
+ // R34-59: a JSON format string is Intl options, so a consumer can name the
1679
+ // calendar system, numbering system and time zone (DST is resolved by Intl
1680
+ // for the named zone) rather than being stuck with the runtime defaults.
1681
+ const jsonOpts = (() => { if (typeof format === "string" && format.trim()[0] === "{") { try { return JSON.parse(format); } catch (e) { return null; } } return null; })();
1682
+ if (format === "date" || format === "time" || (jsonOpts && ("dateStyle" in jsonOpts || "timeStyle" in jsonOpts || "calendar" in jsonOpts || "timeZone" in jsonOpts))) {
1431
1683
  try {
1432
- const opts = format === "time" ? { timeStyle: "short" } : undefined;
1684
+ const opts = jsonOpts || (format === "time" ? { timeStyle: "short" } : undefined);
1433
1685
  return new Intl.DateTimeFormat(loc, opts).format(new Date(value));
1434
1686
  } catch (e) { return value; }
1435
1687
  }
@@ -1461,6 +1713,29 @@ export var CONTOUR_VERSION = "1.9.0";
1461
1713
  catch (e) { return value; }
1462
1714
  }
1463
1715
 
1716
+ /**
1717
+ * R34-59: the locale's first day of the week (0=Sunday … 6=Saturday), for a
1718
+ * calendar or date grid that must not assume Sunday. Uses `Intl.Locale`
1719
+ * `weekInfo`/`firstDay` where the platform exposes it, else a small region
1720
+ * table, else 0. DST and calendar-system edges are Intl's job; this is only
1721
+ * the week-start seam a grid needs.
1722
+ */
1723
+ export function weekStart(locale) {
1724
+ const loc = locale || (typeof navigator !== "undefined" && navigator.language) || "en";
1725
+ try {
1726
+ const info = new Intl.Locale(loc).weekInfo || new Intl.Locale(loc).getWeekInfo?.();
1727
+ if (info && typeof info.firstDay === "number") return info.firstDay % 7;
1728
+ const fd = new Intl.Locale(loc).firstDay;
1729
+ if (typeof fd === "number") return fd % 7;
1730
+ } catch (e) { /* older platform without weekInfo */ }
1731
+ // Region fallback: most of the world starts Monday (1); the US/Canada/JP
1732
+ // start Sunday (0); much of the Middle East starts Saturday (6).
1733
+ const region = (() => { try { return new Intl.Locale(loc).region; } catch (e) { return ""; } })();
1734
+ if (/^(US|CA|JP|IL|MO|PH|IN|TW|HK|KR|ZA|NG|KE|GH|ET|UG|TZ|ZW|ZM|MW|NA|BW|LS|SZ|SS|SD|MU|SC|AO|MZ|CV|ST|GW|GQ|GA|CF|TD|CD|CG|CM|CI|BJ|BF|ML|NE|SN|TG|LR|SL|GM|GN|GW|MR|DJ|SO|ER|BI|RW|AF|IR|SY|IQ|JO|LB|PS|YE|OM|AE|QA|BH|KW|SA|EG|LY|TN|DZ|MA|EH|SU|NP|BD|PK|MM|LA|KH|TH|VN|MY|SG|BN|TL|PG|FJ|SB|VU|WS|TO|KI|TV|NR|MH|FM|PW|CL|PE|CO|VE|EC|GY|SR|PY|UY|BO|AR|CR|DO|GT|HN|NI|PA|SV|BZ|JM|TT|GD|LC|VC|BB|BS|KN|DM|AG|AW|CW|SX|BQ|AI|GP|MQ|MS|KY|TC|VG|PR|VI|GU|AS|MP|UM|FK|GS|IO|TF|HM|NF|CX|CC|AQ|BV|HK|MO|TW|KR|KP|JP)$/.test(region)) return 0;
1735
+ if (/^(IL|IR|AF|BD|PK|MM|NP|BT|MV|SD|DJ|SO|YE|OM|QA|BH|KW|AE|SA|JO|LB|SY|IQ|PS|EG|LY|TN|DZ|MA|EH)$/.test(region)) return 6;
1736
+ return 1;
1737
+ }
1738
+
1464
1739
  // Shared keyboard navigation for roving-tabindex patterns. Options: { wrap=true, enter=true, homeEnd=false, onKey(key,idx,item)→truthy prevents default, onNavigate(newIdx), rtl (defaults to dir attr) }.
1465
1740
  /** Navigate a roving-tabindex group with arrow keys, Home/End, Enter/Space. */
1466
1741
  export function navKey(e, items, { wrap = true, enter = true, homeEnd = false, onKey, onNavigate, rtl } = {}) {
@@ -1765,6 +2040,49 @@ export function polylinePoints(values, opts) {
1765
2040
  }).join(" ");
1766
2041
  }
1767
2042
 
2043
+ /**
2044
+ * Downsample a numeric series for rendering while preserving its shape.
2045
+ *
2046
+ * A fixed-stride sample drops extrema and short spikes: a 600-point cap over
2047
+ * 10,000 samples can step straight over a one-sample peak. Partition the
2048
+ * interior into buckets and keep each bucket's minimum and maximum index (in
2049
+ * input order), so peaks and troughs survive the reduction. Endpoints are
2050
+ * always kept. Returns a copy untouched when the input already fits.
2051
+ *
2052
+ * @param {number[]} values finite numbers, in plot order
2053
+ * @param {number} max target maximum length (>= 4)
2054
+ * @returns {number[]}
2055
+ */
2056
+ export function decimateMinMax(values, max) {
2057
+ if (!Array.isArray(values)) return [];
2058
+ const n = values.length;
2059
+ if (n <= max) return values.slice();
2060
+ if (max < 4) {
2061
+ const step = Math.ceil(n / max);
2062
+ const out = [];
2063
+ for (let i = 0; i < n; i += step) out.push(values[i]);
2064
+ if (out[out.length - 1] !== values[n - 1]) out.push(values[n - 1]);
2065
+ return out;
2066
+ }
2067
+ // Reserve the two endpoints; the rest of the budget is split across buckets,
2068
+ // each contributing up to two points (its min and its max).
2069
+ const buckets = Math.max(1, Math.floor((max - 2) / 2));
2070
+ const picked = new Set([0, n - 1]);
2071
+ for (let b = 0; b < buckets; b++) {
2072
+ const start = Math.floor((b * (n - 2)) / buckets) + 1;
2073
+ const end = Math.floor(((b + 1) * (n - 2)) / buckets) + 1; // exclusive
2074
+ if (end <= start) continue;
2075
+ let lo = start, hi = start;
2076
+ for (let i = start + 1; i < end; i++) {
2077
+ if (values[i] < values[lo]) lo = i;
2078
+ if (values[i] > values[hi]) hi = i;
2079
+ }
2080
+ picked.add(lo);
2081
+ picked.add(hi);
2082
+ }
2083
+ return [...picked].sort((a, b) => a - b).map((i) => values[i]);
2084
+ }
2085
+
1768
2086
  /**
1769
2087
  * Build a smooth (monotone) SVG path through a list of numbers.
1770
2088
  *
@@ -2193,8 +2511,11 @@ export function wireTabs(host) {
2193
2511
  try { restored = localStorage.getItem("contour-tabs:" + host.id); } catch (e) { restored = null; }
2194
2512
  } else if (persist === "url") {
2195
2513
  try {
2514
+ // R34-13: scope the URL key to the host id so two tab sets on one page
2515
+ // do not share (and overwrite) a single `c-tabs` parameter.
2516
+ const urlKey = host.id ? "c-tabs-" + host.id : "c-tabs";
2196
2517
  const params = new URLSearchParams(window.location.search);
2197
- const v = params.get("c-tabs");
2518
+ const v = params.get(urlKey);
2198
2519
  if (v !== null) restored = v;
2199
2520
  } catch (e) { restored = null; }
2200
2521
  }
@@ -2214,7 +2535,8 @@ export function wireTabs(host) {
2214
2535
  wcTrack(host, host, "contour:tab-change", (e) => {
2215
2536
  try {
2216
2537
  const url = new URL(window.location.href);
2217
- url.searchParams.set("c-tabs", String(e.detail && e.detail.index));
2538
+ const urlKey = host.id ? "c-tabs-" + host.id : "c-tabs"; // R34-13
2539
+ url.searchParams.set(urlKey, String(e.detail && e.detail.index));
2218
2540
  window.history.replaceState(null, "", url.toString());
2219
2541
  } catch (err) { /* no history API */ }
2220
2542
  });
@@ -3153,7 +3475,11 @@ export function modalContain(host, open) {
3153
3475
  for (const el of modalInerted) el.inert = false;
3154
3476
  modalInerted.clear();
3155
3477
  document.documentElement.style.overflow = modalSavedOverflow || "";
3156
- window.scrollTo(modalSavedX, modalSavedY);
3478
+ // jsdom defines window.scrollTo but logs "Not implemented" and throws;
3479
+ // skip it there. Real browsers restore the scroll position.
3480
+ if (typeof window.scrollTo === "function" && !navigator.userAgent.includes("jsdom")) {
3481
+ try { window.scrollTo(modalSavedX, modalSavedY); } catch (err) { /* jsdom */ }
3482
+ }
3157
3483
  if (modalTrapWired) {
3158
3484
  document.removeEventListener("keydown", modalTrapHandler);
3159
3485
  modalTrapWired = false;
@@ -3236,19 +3562,144 @@ export function stateLabel(host, key) {
3236
3562
  return fallback;
3237
3563
  }
3238
3564
 
3565
+ /**
3566
+ * Shared dashboard analysis-state vocabulary (R34-162).
3567
+ *
3568
+ * A dashboard composes several widgets and each may be loading, stale,
3569
+ * partial, filtered, selected, locked or pinned at once. This is the one
3570
+ * vocabulary a shell reads to badge a widget and a consumer reads to reason
3571
+ * about it: a component reflects its state as `data-analysis-state` and
3572
+ * announces the label, so no widget invents its own word for the same
3573
+ * condition. `ready` is the neutral default; the seven analysis states are
3574
+ * additive overlays on top of the load lifecycle (empty/loading/error).
3575
+ */
3576
+ export const ANALYSIS_STATES = Object.freeze({
3577
+ loading: "Loading…",
3578
+ stale: "Updating…",
3579
+ partial: "Partial data",
3580
+ filtered: "Filtered",
3581
+ selected: "Selected",
3582
+ locked: "Locked",
3583
+ pinned: "Pinned",
3584
+ ready: "Ready",
3585
+ });
3586
+
3587
+ /** Resolve an analysis-state label (R34-162). Unknown keys fall back to ready. */
3588
+ export function analysisLabel(key) {
3589
+ return ANALYSIS_STATES[key] || ANALYSIS_STATES.ready;
3590
+ }
3591
+
3592
+ /**
3593
+ * Reflect a host's analysis state (R34-162): set `data-analysis-state` (the
3594
+ * styling/test hook) and return the label. An unknown or absent key clears the
3595
+ * attribute back to the neutral `ready` contract. The host renders the label;
3596
+ * this only owns the vocabulary and the attribute.
3597
+ */
3598
+ export function setAnalysisState(host, key) {
3599
+ const state = ANALYSIS_STATES[key] ? key : "ready";
3600
+ if (state === "ready") host.removeAttribute("data-analysis-state");
3601
+ else host.setAttribute("data-analysis-state", state);
3602
+ return analysisLabel(state);
3603
+ }
3604
+
3239
3605
  // One in-flight request per URL, shared by every host that asked for it.
3240
3606
  const remoteInflight = new Map();
3241
3607
  // The last result per URL, so a re-mounted host paints instead of re-asking. A
3608
+ // bounded entry count AND byte budget (R34-143): a few huge payloads must not
3609
+ // crowd out many small ones, and the cache must not grow without limit.
3242
3610
  const REMOTE_CACHE_MAX = 64;
3611
+ const REMOTE_CACHE_MAX_BYTES = 5 * 1024 * 1024; // 5 MB
3243
3612
  const remoteCache = new Map();
3613
+ let remoteCacheBytes = 0;
3614
+
3615
+ const byteLen = (v) => { try { return JSON.stringify(v).length; } catch (e) { return 0; } };
3616
+ function cacheEvict(key) {
3617
+ if (!remoteCache.has(key)) return;
3618
+ remoteCacheBytes -= byteLen(remoteCache.get(key));
3619
+ remoteCache.delete(key);
3620
+ }
3621
+ function cacheClear() {
3622
+ remoteCache.clear();
3623
+ remoteCacheBytes = 0;
3624
+ }
3244
3625
 
3245
3626
  function cacheResult(src, data) {
3246
- if (remoteCache.size >= REMOTE_CACHE_MAX) remoteCache.delete(remoteCache.keys().next().value);
3627
+ const size = byteLen(data);
3628
+ // A single payload larger than the whole budget is not cached.
3629
+ if (size > REMOTE_CACHE_MAX_BYTES) return;
3630
+ // Evict oldest (Map insertion order) until both the entry and byte bounds hold.
3631
+ while (remoteCache.size >= REMOTE_CACHE_MAX || (remoteCacheBytes + size > REMOTE_CACHE_MAX_BYTES && remoteCache.size > 0)) {
3632
+ cacheEvict(remoteCache.keys().next().value);
3633
+ }
3634
+ cacheEvict(src); // replace an existing key without double-counting bytes
3247
3635
  remoteCache.set(src, data);
3636
+ remoteCacheBytes += size;
3248
3637
  }
3249
3638
 
3639
+ // Circuit breaker per URL (R33-73). A dead endpoint must not be hammered on
3640
+ // every mount and every `refresh` tick: after CIRCUIT_THRESHOLD consecutive
3641
+ // failures the circuit "opens" and hosts fail fast without a network call. It
3642
+ // "half-opens" after the cooldown to let a single probe through, and a success
3643
+ // closes it. The state is keyed by URL, the same key the cache and the in-flight
3644
+ // map use, so one endpoint shares one circuit across every host that asks for it.
3645
+ const CIRCUIT_THRESHOLD = 3;
3646
+ const CIRCUIT_COOLDOWN_MS = 30000;
3647
+ const remoteCircuit = new Map(); // src -> { failures, openUntil }
3648
+
3649
+ function circuitState(src) {
3650
+ const c = remoteCircuit.get(src);
3651
+ if (!c || !c.openUntil) return "closed";
3652
+ return Date.now() < c.openUntil ? "open" : "half-open";
3653
+ }
3654
+
3655
+ function circuitRecordFailure(src) {
3656
+ const c = remoteCircuit.get(src) || { failures: 0, openUntil: 0 };
3657
+ c.failures += 1;
3658
+ if (c.failures >= CIRCUIT_THRESHOLD) c.openUntil = Date.now() + CIRCUIT_COOLDOWN_MS;
3659
+ remoteCircuit.set(src, c);
3660
+ }
3661
+
3662
+ function circuitRecordSuccess(src) {
3663
+ remoteCircuit.delete(src);
3664
+ }
3665
+
3666
+ // R34-151: the module-level caches — the URL result cache, the circuit breaker
3667
+ // and the in-flight map — outlive any single host, so without a document-lifetime
3668
+ // policy a bfcache snapshot restores them into a page the reader left and came
3669
+ // back to: a stale result painted without re-asking, an open circuit that fails
3670
+ // fast for the rest of the cooldown, or a half-dead in-flight entry no host is
3671
+ // waiting on. `pagehide` drops all three and aborts live requests; a persisted
3672
+ // `pageshow` (a bfcache restore) leaves them empty so the first host to ask
3673
+ // re-fetches. Registered once for the document; a no-op where `window` is absent
3674
+ // (SSR import).
3675
+ let _docLifetimeWired = false;
3676
+ function wireDocumentLifetime() {
3677
+ if (_docLifetimeWired) return;
3678
+ _docLifetimeWired = true;
3679
+ if (typeof window === "undefined" || typeof window.addEventListener !== "function") return;
3680
+ const dropAll = () => {
3681
+ // Clear each entry's waiters before aborting, so the rejection handler that
3682
+ // would mark hosts as errored iterates an empty set — a page going away is
3683
+ // not a load failure, and a restored page must not open on a false error.
3684
+ for (const entry of remoteInflight.values()) {
3685
+ entry.hosts.clear();
3686
+ try { entry.controller.abort(); } catch (e) { /* already settled */ }
3687
+ }
3688
+ remoteInflight.clear();
3689
+ cacheClear();
3690
+ remoteCircuit.clear();
3691
+ };
3692
+ window.addEventListener("pagehide", dropAll);
3693
+ window.addEventListener("pageshow", (e) => { if (e.persisted) dropAll(); });
3694
+ }
3695
+ wireDocumentLifetime();
3696
+
3250
3697
  function setStatus(host, status) {
3251
3698
  host._remoteStatus = status;
3699
+ // R34-153: a retry is no longer pending once the request re-issues (loading)
3700
+ // or settles (ready/error); `idle` (set by the retry handler itself) leaves
3701
+ // the pending flag for the immediate re-render to clear.
3702
+ if (status === "loading" || status === "ready" || status === "error") host._contourRetryPending = false;
3252
3703
  if (status !== "error") host._remoteError = null;
3253
3704
  // `aria-busy` is the platform's own word for "this region is mid-update", it is
3254
3705
  if (status === "loading") host.setAttribute("aria-busy", "true");
@@ -3336,8 +3787,19 @@ export function loadRemote(host, fields) {
3336
3787
  // Already asked: a host still waiting, or one whose last ask settled in
3337
3788
  if (host._remoteSrc === src && (host._remoteStatus === "loading" || host._remoteStatus === "error")) return; // already asked
3338
3789
 
3790
+ // Circuit open (R33-73): the endpoint has failed CIRCUIT_THRESHOLD times in a
3791
+ // row and the cooldown has not elapsed. Fail fast without a network call; the
3792
+ // host paints the error state and the next mount after the cooldown probes.
3793
+ if (circuitState(src) === "open") {
3794
+ setStatus(host, "error");
3795
+ host._remoteError = STATE_FALLBACK.error;
3796
+ return;
3797
+ }
3798
+
3339
3799
  leaveRequest(host);
3340
3800
  host._remoteSrc = src;
3801
+ // R34-129: the moment the request was issued, for an opt-in minimum-busy floor.
3802
+ const started = Date.now();
3341
3803
  setStatus(host, "loading");
3342
3804
 
3343
3805
  let entry = remoteInflight.get(src);
@@ -3348,6 +3810,8 @@ export function loadRemote(host, fields) {
3348
3810
  entry.promise = startFetch(host, src, entry).then(
3349
3811
  (data) => {
3350
3812
  if (remoteInflight.get(src) === entry) remoteInflight.delete(src);
3813
+ // A success closes the circuit (R33-73): the endpoint answered.
3814
+ circuitRecordSuccess(src);
3351
3815
  // The entry is keyed by URL, but a host that named a cache-key must be
3352
3816
  cacheResult(src, data);
3353
3817
  for (const k of entry.cacheKeys) {
@@ -3356,12 +3820,28 @@ export function loadRemote(host, fields) {
3356
3820
  for (const h of entry.hosts) {
3357
3821
  h._remoteData = data;
3358
3822
  h._remoteEntry = null;
3359
- setStatus(h, "ready");
3360
- emitState(h, "contour:load", { src, count: countOf(data) });
3823
+ // R34-129: opt-in minimum-busy floor (`min-busy="<ms>"`). A load that
3824
+ // resolves faster than the floor holds the loading state for the
3825
+ // remainder, so a fast response does not flash a spinner. Default off
3826
+ // (no attribute) keeps the immediate behaviour.
3827
+ const floor = Number(h.getAttribute("min-busy")) || 0;
3828
+ const wait = floor > 0 ? Math.max(0, floor - (Date.now() - started)) : 0;
3829
+ const finish = () => {
3830
+ setStatus(h, "ready");
3831
+ emitState(h, "contour:load", { src, count: countOf(data) });
3832
+ };
3833
+ if (wait > 0) {
3834
+ if (h._remoteMinBusy) clearTimeout(h._remoteMinBusy);
3835
+ h._remoteMinBusy = setTimeout(finish, wait);
3836
+ } else {
3837
+ finish();
3838
+ }
3361
3839
  }
3362
3840
  },
3363
3841
  (err) => {
3364
3842
  if (remoteInflight.get(src) === entry) remoteInflight.delete(src);
3843
+ // A failure counts toward opening the circuit (R33-73).
3844
+ circuitRecordFailure(src);
3365
3845
  for (const h of entry.hosts) {
3366
3846
  h._remoteEntry = null;
3367
3847
  setStatus(h, "error");
@@ -3401,7 +3881,11 @@ export function loadRemote(host, fields) {
3401
3881
  */
3402
3882
  /** Invalidate cached remote data by source or key. */
3403
3883
  export function remoteInvalidate(srcOrKey) {
3404
- remoteCache.delete(srcOrKey);
3884
+ cacheEvict(srcOrKey);
3885
+ // Clearing the cache is also the page-side way to close an open circuit
3886
+ // (R33-73): an admin action or a websocket that says the endpoint recovered
3887
+ // should let the next host probe immediately rather than wait the cooldown.
3888
+ remoteCircuit.delete(srcOrKey);
3405
3889
  }
3406
3890
 
3407
3891
  // `AbortSignal.timeout` is the platform's own deadline; where it is missing, the
@@ -3516,10 +4000,19 @@ export function remoteRefresh(host) {
3516
4000
  host._remoteTimer = undefined;
3517
4001
  if (!host.isConnected || !host.hasAttribute("refresh")) { host._remoteLoop = false; return; }
3518
4002
  if (document.hidden) { host._remoteTimer = setTimeout(tick, 1000); return; }
4003
+ // R34-50: honour prefers-reduced-data at runtime — a 4× longer poll and a
4004
+ // reflected flag, so a metered/limited user is not re-fetching on the
4005
+ // default cadence. The data stays live, just cheaper.
4006
+ if (prefersReducedData()) {
4007
+ host.setAttribute("data-reduced-data", "");
4008
+ host._remoteTimer = setTimeout(tick, Math.max(1000, seconds * 1000 * reducedDataFactor()));
4009
+ return;
4010
+ }
4011
+ host.removeAttribute("data-reduced-data");
3519
4012
  const src = host.getAttribute("src");
3520
4013
  const namedKey = host.getAttribute("cache-key");
3521
- if (namedKey) remoteCache.delete(namedKey);
3522
- remoteCache.delete(src);
4014
+ if (namedKey) cacheEvict(namedKey);
4015
+ cacheEvict(src);
3523
4016
  host._remoteSrc = null;
3524
4017
  host._remoteLoop = false;
3525
4018
  host.requestRender();
@@ -3605,6 +4098,26 @@ export function watchViewport(host) {
3605
4098
 
3606
4099
  // ---------------------------------------------------------------------------
3607
4100
 
4101
+ /**
4102
+ * R34-17: the one virtual-window range calculation, shared by every virtualized
4103
+ * list/table/grid. Given a scroll offset, the measured row height, the measured
4104
+ * viewport height and the total row count, return the `[start, end)` band to
4105
+ * render plus an `overscan` of rows above and below so a fast wheel never shows
4106
+ * a blank edge. The table and the data grid both call this instead of each
4107
+ * re-deriving the clamp (which is how a 400px guess and a measured height came
4108
+ * to disagree in the first place).
4109
+ */
4110
+ export function virtualRange(scrollTop, rowHeight, viewport, total, overscan = 6) {
4111
+ const rh = rowHeight > 0 ? rowHeight : 1;
4112
+ const count = Math.ceil((viewport > 0 ? viewport : 400) / rh) + overscan;
4113
+ let start = Math.floor((scrollTop || 0) / rh);
4114
+ if (start < 0) start = 0;
4115
+ const maxStart = Math.max(0, total - count);
4116
+ if (start > maxStart) start = maxStart;
4117
+ const end = Math.min(total, start + count);
4118
+ return { start, end, count };
4119
+ }
4120
+
3608
4121
  // A state node carries the block-scoped element class the sheet already defines
3609
4122
  function stateNode(block, kind, text) {
3610
4123
  const node = document.createElement("div");
@@ -3634,10 +4147,23 @@ function skeletonRow(i, total) {
3634
4147
  export function renderStates(host, block, opts) {
3635
4148
  const options = opts || {};
3636
4149
  const loading = host.getAttribute("loading");
3637
- if (loading !== null || host._remoteStatus === "loading") {
4150
+ // R34-152: an authored `loading` always paints the loading state — the author
4151
+ // asked for it. A *remote* load only paints the spinner on the first load,
4152
+ // when there is nothing to show yet; a refresh keeps the previous content on
4153
+ // screen (stale-while-revalidate) under `aria-busy`, so a background poll or
4154
+ // a retry does not blank a grid the reader is scrolled into. Selection and
4155
+ // scroll live in the component and are left untouched.
4156
+ if (loading !== null) {
3638
4157
  host.appendChild(stateNode(block, "loading", loading || stateLabel(host, "loading")));
3639
4158
  return true;
3640
4159
  }
4160
+ if (host._remoteStatus === "loading") {
4161
+ if (host._remoteData === undefined) {
4162
+ host.appendChild(stateNode(block, "loading", stateLabel(host, "loading")));
4163
+ return true;
4164
+ }
4165
+ return false;
4166
+ }
3641
4167
  const error = host.getAttribute("error");
3642
4168
  if (error !== null || host._remoteStatus === "error") {
3643
4169
  const message = (error !== null && error !== "") ? error : (host._remoteError || stateLabel(host, "error"));
@@ -3700,19 +4226,160 @@ export function wireStates(host) {
3700
4226
  const btn = e.target && e.target.closest ? e.target.closest('[data-action="retry"]') : null;
3701
4227
  if (!btn || !host.contains(btn)) return;
3702
4228
  e.preventDefault();
4229
+ // R34-153: one retry at a time. A retry already in flight must not be
4230
+ // re-issued by a second click — that produced duplicate requests and
4231
+ // duplicate start events. The button only exists in the error state, but a
4232
+ // fast double-click (two clicks in one task, before the re-render microtask
4233
+ // flips the status to loading) lands here twice; `_contourRetryPending`
4234
+ // closes that window and is cleared by `setStatus` when the request
4235
+ // re-issues (loading) or settles (ready/error).
4236
+ if (host._contourRetryPending || host._remoteStatus === "loading") return;
4237
+ const hadFocus = document.activeElement === btn;
4238
+ // Invalidate only the source this host asked under (and its named key), so
4239
+ // a retry does not evict an unrelated endpoint's cache. Filters, sort,
4240
+ // selection and scroll are component state and are deliberately preserved.
3703
4241
  const src = host.getAttribute("src");
3704
4242
  const namedKey = host.getAttribute("cache-key");
3705
- if (namedKey) remoteCache.delete(namedKey);
3706
- if (src) remoteCache.delete(src);
4243
+ if (namedKey) cacheEvict(namedKey);
4244
+ if (src) cacheEvict(src);
3707
4245
  leaveRequest(host);
3708
4246
  host._remoteSrc = null;
3709
4247
  host._remoteData = undefined;
3710
4248
  setStatus(host, "idle");
4249
+ if (src) host._contourRetryPending = true;
4250
+ // Start event now; the result arrives as the loader's own contour:load /
4251
+ // contour:error when the request settles, so listeners get a matched pair.
3711
4252
  emitState(host, "contour:retry", { src });
3712
4253
  host.requestRender();
4254
+ // R34-153: the retry button is about to be replaced by the re-render; if it
4255
+ // held focus, return focus to the host's first control (or the host) so
4256
+ // focus is not dropped to <body>.
4257
+ if (hadFocus) queueMicrotask(() => {
4258
+ if (!host.isConnected) return;
4259
+ const f = host.querySelector('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])');
4260
+ const t = f || (typeof host.focus === "function" ? host : null);
4261
+ if (t) { try { t.focus(); } catch (err) {} }
4262
+ });
3713
4263
  });
3714
4264
  }
3715
4265
 
4266
+ /* ============================================================================
4267
+ Resilience (R34-154/155/156/159/161)
4268
+ ----------------------------------------------------------------------------
4269
+ A degraded surface is not a blank one: the widget keeps its last good data,
4270
+ says why it is degraded, names what was shed and the action that recovers it.
4271
+ These helpers are the shared vocabulary the state, map and data families use
4272
+ so a shell reads one shape and a consumer writes one handler.
4273
+ ========================================================================= */
4274
+
4275
+ /** R34-161: a malformed payload is typed and non-fatal — never a blank widget. */
4276
+ export function emitParseError(host, { src, reason, partial } = {}) {
4277
+ emitState(host, "contour:parse-error", {
4278
+ src: src || (host.getAttribute && host.getAttribute("src")) || "",
4279
+ reason: reason || "parse",
4280
+ partial: !!partial,
4281
+ });
4282
+ }
4283
+
4284
+ /** R34-155: bridge an async / engine / render error into the page error contract. */
4285
+ export function bridgeError(host, err, name) {
4286
+ const n = name || (err && err.name) || "error";
4287
+ const message = (err && err.message) || String(err || "Unknown error");
4288
+ const status = (err && err.status) || 0;
4289
+ if (host._remoteStatus !== "error") setStatus(host, "error");
4290
+ host._remoteError = message;
4291
+ emitState(host, "contour:error", {
4292
+ src: (host.getAttribute && host.getAttribute("src")) || "",
4293
+ message,
4294
+ name: n,
4295
+ status,
4296
+ });
4297
+ }
4298
+
4299
+ /**
4300
+ * R34-159: a debounced ResizeObserver with stale-callback cancellation. The
4301
+ * callback runs on the trailing edge only, so a drag that fires a burst of
4302
+ * observations collapses to one settle; the returned disposer disconnects and
4303
+ * cancels any pending callback, so a detached host never runs a stale one.
4304
+ */
4305
+ export function onResizeSettled(el, cb, { wait = 120, immediate = false } = {}) {
4306
+ if (!el || typeof ResizeObserver === "undefined") return () => {};
4307
+ let timer = 0;
4308
+ const ro = new ResizeObserver(() => {
4309
+ if (timer) clearTimeout(timer);
4310
+ timer = setTimeout(() => { timer = 0; cb(); }, wait);
4311
+ });
4312
+ ro.observe(el);
4313
+ if (immediate) cb();
4314
+ return () => { ro.disconnect(); if (timer) clearTimeout(timer); };
4315
+ }
4316
+
4317
+ /** R34-156: is the browser offline? (navigator is absent under jsdom/SSR.) */
4318
+ export function offlineFlag() {
4319
+ return typeof navigator !== "undefined" && navigator.onLine === false;
4320
+ }
4321
+
4322
+ /**
4323
+ * R34-50: `prefers-reduced-data` is a runtime budget, not a CSS media query.
4324
+ * Removing an animation saves no bytes; the bytes are the remote refresh, the
4325
+ * streaming cadence and the tile quality. A host reads this to slow its poll,
4326
+ * thin its stream and drop tile detail. Absent under jsdom/SSR (matchMedia is
4327
+ * not defined there), so it degrades to "no preference".
4328
+ */
4329
+ export function prefersReducedData() {
4330
+ return typeof matchMedia === "function" && matchMedia("(prefers-reduced-data: reduce)").matches;
4331
+ }
4332
+
4333
+ /** R34-50: the reduced-data poll multiplier — a 4× longer interval, floored. */
4334
+ export function reducedDataFactor() {
4335
+ return prefersReducedData() ? 4 : 1;
4336
+ }
4337
+
4338
+ /**
4339
+ * R34-156: offline/online lifecycle mixin. Reflects `data-offline`, emits
4340
+ * `contour:offline` / `contour:online`, and exposes `isOffline()` so a host
4341
+ * can pause remote refresh and hold stale data rather than blanking. A host
4342
+ * that is already offline at connect is announced once.
4343
+ */
4344
+ export function withResilience(Base) {
4345
+ return class extends Base {
4346
+ static get observed() {
4347
+ const base = (super.observed && Array.isArray(super.observed)) ? super.observed : [];
4348
+ return Array.from(new Set(base.concat(["offline"])));
4349
+ }
4350
+ connectedCallback() {
4351
+ if (super.connectedCallback) super.connectedCallback();
4352
+ if (this._resilienceWired || typeof window === "undefined") return;
4353
+ this._resilienceWired = true;
4354
+ this._onOffline = () => {
4355
+ this._offline = true;
4356
+ this.setAttribute("data-offline", "");
4357
+ emitState(this, "contour:offline", { reason: "network" });
4358
+ };
4359
+ this._onOnline = () => {
4360
+ this._offline = false;
4361
+ this.removeAttribute("data-offline");
4362
+ emitState(this, "contour:online", {});
4363
+ };
4364
+ window.addEventListener("offline", this._onOffline);
4365
+ window.addEventListener("online", this._onOnline);
4366
+ onDispose(this, () => {
4367
+ window.removeEventListener("offline", this._onOffline);
4368
+ window.removeEventListener("online", this._onOnline);
4369
+ });
4370
+ if (offlineFlag()) this._onOffline();
4371
+ }
4372
+ attributeChangedCallback(name, old, val) {
4373
+ if (super.attributeChangedCallback) super.attributeChangedCallback(name, old, val);
4374
+ if (name === "offline" && this.isConnected) {
4375
+ this._offline = this.hasAttribute("offline");
4376
+ this.toggleAttribute("data-offline", this._offline);
4377
+ }
4378
+ }
4379
+ isOffline() { return !!this._offline; }
4380
+ };
4381
+ }
4382
+
3716
4383
 
3717
4384
  if (typeof window !== "undefined") {
3718
4385
  window.ContourVersion = CONTOUR_VERSION;