contour-ds 1.7.2 → 1.8.1

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 (109) hide show
  1. package/README.md +80 -11
  2. package/dist/agent-rules.json +16 -0
  3. package/dist/build-manifest.json +181 -104
  4. package/dist/contour-wc-content.esm.js +5125 -0
  5. package/dist/contour-wc-content.esm.min.js +1 -0
  6. package/dist/contour-wc-dashboard.esm.js +8654 -0
  7. package/dist/contour-wc-dashboard.esm.min.js +1 -0
  8. package/dist/contour-wc-data.esm.js +8260 -0
  9. package/dist/contour-wc-data.esm.min.js +1 -0
  10. package/dist/contour-wc-docs.esm.js +4305 -0
  11. package/dist/contour-wc-docs.esm.min.js +1 -0
  12. package/dist/contour-wc-feedback.esm.js +4917 -0
  13. package/dist/contour-wc-feedback.esm.min.js +1 -0
  14. package/dist/contour-wc-forms.esm.js +5688 -0
  15. package/dist/contour-wc-forms.esm.min.js +1 -0
  16. package/dist/contour-wc-interaction.esm.js +4580 -0
  17. package/dist/contour-wc-interaction.esm.min.js +1 -0
  18. package/dist/contour-wc-layout.esm.js +4174 -0
  19. package/dist/contour-wc-layout.esm.min.js +1 -0
  20. package/dist/contour-wc-map.esm.js +5205 -0
  21. package/dist/contour-wc-map.esm.min.js +1 -0
  22. package/dist/contour-wc-misc.esm.js +4264 -0
  23. package/dist/contour-wc-misc.esm.min.js +1 -0
  24. package/dist/contour-wc-navigation.esm.js +5844 -0
  25. package/dist/contour-wc-navigation.esm.min.js +1 -0
  26. package/dist/contour-wc-ui.esm.js +9009 -0
  27. package/dist/contour-wc-ui.esm.min.js +1 -0
  28. package/dist/contour-wc.esm.js +6109 -1641
  29. package/dist/contour-wc.esm.min.js +1 -1
  30. package/dist/contour-wc.js +6108 -1641
  31. package/dist/contour-wc.min.js +1 -1
  32. package/dist/contour.code-snippets +4512 -0
  33. package/dist/contour.components.json +2597 -799
  34. package/dist/contour.css +5275 -4050
  35. package/dist/contour.d.ts +560 -1085
  36. package/dist/contour.esm.js +7 -0
  37. package/dist/contour.esm.min.js +1 -1
  38. package/dist/contour.html-data.json +10311 -0
  39. package/dist/contour.js +7 -0
  40. package/dist/contour.min.css +1 -1
  41. package/dist/contour.min.js +1 -1
  42. package/dist/contour.react.d.ts +420 -0
  43. package/dist/contour.single.html +17 -0
  44. package/dist/contour.single.min.css +1 -0
  45. package/dist/contour.tokens.json +940 -902
  46. package/dist/contour.vue.d.ts +418 -0
  47. package/dist/contour.web-types.json +10703 -0
  48. package/dist/custom-elements.json +30708 -0
  49. package/dist/docs/actions.md +3 -2
  50. package/dist/docs/affordances.md +23 -9
  51. package/dist/docs/apireference.md +1 -1
  52. package/dist/docs/colour.md +1 -1
  53. package/dist/docs/componentindex.md +6 -2
  54. package/dist/docs/data.md +7 -2
  55. package/dist/docs/docs.md +9 -2
  56. package/dist/docs/feedback.md +1 -1
  57. package/dist/docs/field.md +1 -1
  58. package/dist/docs/forms.md +1 -1
  59. package/dist/docs/index.json +22 -20
  60. package/dist/docs/install.md +1 -1
  61. package/dist/docs/landing.md +1 -1
  62. package/dist/docs/mapengine.md +19 -2
  63. package/dist/docs/motion.md +1 -1
  64. package/dist/docs/navigation.md +1 -1
  65. package/dist/docs/overlays.md +1 -1
  66. package/dist/docs/overview.md +1 -1
  67. package/dist/docs/patterns.md +2 -2
  68. package/dist/docs/playground.md +22 -2
  69. package/dist/docs/principles.md +1 -1
  70. package/dist/docs/recipes.md +13 -8
  71. package/dist/docs/space.md +1 -1
  72. package/dist/docs/status.md +14 -2
  73. package/dist/docs/surfaces.md +1 -1
  74. package/dist/docs/theming.md +1 -1
  75. package/dist/docs/type.md +1 -1
  76. package/dist/docs/webcomponents.md +17 -3
  77. package/dist/registry/items/contour-core.json +2 -2
  78. package/dist/registry/items/contour-data.json +2 -2
  79. package/dist/registry/items/contour-docs.json +2 -2
  80. package/dist/registry/items/contour-landing.json +2 -2
  81. package/dist/registry/registry.json +8 -8
  82. package/dist/surfaces/contour-core.min.css +1 -1
  83. package/dist/surfaces/contour-data.min.css +1 -1
  84. package/dist/surfaces/contour-docs.min.css +1 -1
  85. package/dist/surfaces/contour-landing.min.css +1 -1
  86. package/dist/wc/behaviours.mjs +45 -57
  87. package/dist/wc/content.mjs +263 -63
  88. package/dist/wc/core.mjs +390 -71
  89. package/dist/wc/dashboard.mjs +220 -13
  90. package/dist/wc/data.mjs +1075 -460
  91. package/dist/wc/docs.mjs +105 -12
  92. package/dist/wc/feedback.mjs +63 -14
  93. package/dist/wc/forms.mjs +733 -104
  94. package/dist/wc/index.mjs +9 -2
  95. package/dist/wc/interaction.mjs +182 -28
  96. package/dist/wc/layout.mjs +95 -25
  97. package/dist/wc/map.mjs +185 -118
  98. package/dist/wc/misc.mjs +124 -24
  99. package/dist/wc/navigation.mjs +384 -115
  100. package/dist/wc/shadow.mjs +94 -18
  101. package/dist/wc/states.mjs +21 -3
  102. package/dist/wc/svg.mjs +104 -0
  103. package/dist/wc/ui.mjs +1988 -476
  104. package/integrations/README.md +2 -0
  105. package/integrations/ai/CLAUDE.md +3 -3
  106. package/integrations/frameworks/README.md +235 -0
  107. package/integrations/native/style-dictionary.config.json +1 -1
  108. package/integrations/tailwind/contour-theme.css +5 -6
  109. package/package.json +53 -24
@@ -0,0 +1,4264 @@
1
+ /* ============================================================================
2
+ CONTOUR — Web Components (progressive enhancement)
3
+ ----------------------------------------------------------------------------
4
+ Two layers over the same blocks. The light-DOM wrappers add the CSS classes
5
+ the block already has and, where a block needs scaffolding, generate it from
6
+ attributes; styles come straight from ds.css. The contour-shadow-* wrappers
7
+ are an opt-in alternative for consumers who want an isolated root with named
8
+ parts to style through ::part(); they hold a template and slots and share the
9
+ document's sheets. Neither layer replaces a native element, and nothing here
10
+ is required for a page to work.
11
+
12
+ What this file registers is published as the frozen array
13
+ `window.ContourElements`, because `customElements` cannot be enumerated and a
14
+ reader should not have to infer the registry by scraping quoted strings out of
15
+ the source. A scrape counts whatever shape the prose happens to be in: it is
16
+ how a gate came to certify a fraction of this file's elements as the whole of
17
+ them, and call the difference a pass. No number is written down here for that
18
+ reason — the array is the count, and the contract gate reads it.
19
+ ========================================================================= */
20
+ "use strict";
21
+
22
+ // Every name this file actually registers, in registration order. define() is
23
+ // the only door to the registry, so the list cannot drift from what the
24
+ // browser was handed.
25
+ /** Names registered by this module, in registration order. */
26
+ export const REGISTERED = [];
27
+
28
+ // Per-host teardown, run when a host leaves the page.
29
+ //
30
+ // The layer had no way to stop anything: `grep -c removeEventListener src/js/wc`
31
+ // returned 0, and each component relied on GC. That is sound for a listener on a
32
+ // node the host owns, because the node and its listeners die together — but a
33
+ // fetch, a timer, or an IntersectionObserver is not owned by a node. It is owned
34
+ // by the document, and it outlives the host that asked for it. Measured
35
+ // (tmp/wc9/probe.mjs, 2026-10-27): a `contour-readout src=…` removed from the page
36
+ // mid-request kept `loadingAfterDetach: 2` stale nodes and was still written to
37
+ // after `isConnected` went false.
38
+ //
39
+ // So anything a host starts against the document registers its cleanup here, and
40
+ // `disconnectedCallback` runs the list. A reconnect re-renders and re-registers,
41
+ // which is why the list is dropped rather than kept: one disposal per mount.
42
+ const DISPOSERS = new WeakMap();
43
+ /** Register teardown work for the host's current connection. */
44
+ export const onDispose = (host, fn) => {
45
+ let list = DISPOSERS.get(host);
46
+ if (!list) { list = []; DISPOSERS.set(host, list); }
47
+ list.push(fn);
48
+ };
49
+ function contourDebugEnabled() {
50
+ try {
51
+ if (typeof window !== "undefined" && (window.ContourDebug || window.__CONTOUR_DEBUG__)) return true;
52
+ } catch (e) {}
53
+ try {
54
+ if (typeof process !== "undefined" && process.env && process.env.NODE_ENV !== "production" && process.env.CONTOUR_DEBUG) return true;
55
+ } catch (e) {}
56
+ return false;
57
+ }
58
+ const runDisposers = (host) => {
59
+ const list = DISPOSERS.get(host);
60
+ if (!list) return;
61
+ DISPOSERS.delete(host);
62
+ for (const fn of list) {
63
+ try { fn(); }
64
+ catch (e) {
65
+ // One bad cleanup cannot strand the rest. Surface the failure in
66
+ // development/debug mode so a leaking disposer is not invisible.
67
+ if (contourDebugEnabled()) {
68
+ try { console.warn("Contour disposer failed for", host && host.tagName, e); } catch (err) {}
69
+ }
70
+ }
71
+ }
72
+ };
73
+
74
+ // Monotonic counter for unique IDs (avoids Math.random() collision risk).
75
+ let _contourIdCounter = 0;
76
+ /** Return a unique, document-safe id with the supplied prefix. */
77
+ export const contourId = (prefix) => prefix + "-" + (++_contourIdCounter).toString(36);
78
+
79
+ /** Define a custom element once, while remaining safe in SSR runtimes. */
80
+ export const define = (name, cls) => {
81
+ // SSR-safe / constrained-runtime boundary: if the Custom Elements registry
82
+ // is unavailable, do not throw on import; registration is a no-op and the
83
+ // element remains an unknown (upgradable) tag until a browser defines it.
84
+ if (typeof customElements === "undefined" || !customElements || typeof customElements.define !== "function") return;
85
+ if (customElements.get(name)) return;
86
+ customElements.define(name, cls);
87
+ REGISTERED.push(name);
88
+ };
89
+
90
+ // The attributes a consumer may set to ask for a modifier class. Both layers
91
+ // read this one list: a wrapper that added a modifier from a different list is
92
+ // how the light and shadow halves drifted apart over "color".
93
+ /** Attribute names that map to component modifier classes. */
94
+ export const MODS = ["variant", "size", "color"];
95
+
96
+ // Every event this layer emits, with the payload keys each one carries and
97
+ // its composed flag. This is the count — a number written anywhere would go
98
+ // stale silently, so the gate compares the emitted names in the source
99
+ // against THIS object, and the publish freezes it exactly like ContourElements.
100
+ // Payload keys are the union of keys every emission site passes, read from
101
+ // the source rather than invented: contour:select carries {series, index},
102
+ // {index, label} and {value} across its sites, so all three are listed.
103
+ /** Frozen event vocabulary with the public detail keys for each event. */
104
+ export const CONTOUR_EVENTS = Object.freeze({
105
+ "contour:activate": { payload: ["files", "label", "row", "value"], composed: true },
106
+ "contour:add": { payload: ["value"], composed: true },
107
+ "contour:activity-clear": { payload: [], composed: true },
108
+ "contour:activity-filter": { payload: ["unread"], composed: true },
109
+ "contour:activity-select": { payload: ["index", "text"], composed: true },
110
+ "contour:break-change": { payload: ["layer", "value"], composed: true },
111
+ "contour:style-resolved": { payload: ["applied", "classification", "colors", "items", "layer", "n", "palette", "property", "value"], composed: true },
112
+ "contour:advanced-toggle": { payload: ["title"], composed: true },
113
+ "contour:affordance-activate": { payload: ["name"], composed: true },
114
+ "contour:aggregate": { payload: ["aggregate"], composed: true },
115
+ "contour:bearing": { payload: ["direction", "degrees"], composed: true },
116
+ "contour:btn-group-change": { payload: ["index", "label"], composed: true },
117
+ "contour:brush-start": { payload: ["end", "range", "start", "value"], composed: true },
118
+ "contour:brush-end": { payload: ["end", "range", "start", "value"], composed: true },
119
+ "contour:brush": { payload: ["end", "range", "start", "value"], composed: true },
120
+ "contour:change": { payload: ["checked", "color", "direction", "end", "files", "high", "index", "low", "month", "name", "paused", "query", "speed", "start", "unit", "value", "values", "year"], composed: true },
121
+ "contour:collapse": { payload: ["collapsed"], composed: true },
122
+ "contour:cluster-toggle": { payload: ["count", "expanded"], composed: true },
123
+ "contour:clear": { payload: [], composed: true },
124
+ "contour:clear-all": { payload: [], composed: true },
125
+ "contour:close": { payload: ["count", "index", "label", "message", "open", "value"], composed: true },
126
+ "contour:copy": { payload: ["text"], composed: true },
127
+ "contour:apply": { payload: ["name"], composed: true },
128
+ "contour:dash-action": { payload: ["label"], composed: true },
129
+ "contour:diff-activate": { payload: ["kind", "text"], composed: true },
130
+ "contour:dismiss": { payload: ["label"], composed: true },
131
+ "contour:draw-start": { payload: ["mode"], composed: true },
132
+ "contour:drag": { payload: ["delta", "key", "value"], composed: true },
133
+ "contour:do-dont-activate": { payload: ["kind", "text"], composed: true },
134
+ "contour:docs-nav-select": { payload: ["label", "href"], composed: true },
135
+ "contour:dragend": { payload: ["value"], composed: true },
136
+ "contour:dragstart": { payload: ["value"], composed: true },
137
+ "contour:drop": { payload: ["value", "label"], composed: true },
138
+ "contour:empty-action": { payload: ["state"], composed: true },
139
+ "contour:filter": { payload: ["query"], composed: true },
140
+ "contour:filter-change": { payload: ["source", "filter"], composed: true },
141
+ "contour:error": { payload: ["src", "message", "name", "status"], composed: true },
142
+ "contour:export": { payload: ["format"], composed: true },
143
+ "contour:refresh": { payload: [], composed: true },
144
+ "contour:hide": { payload: [], composed: true },
145
+ "contour:hover": { payload: ["row"], composed: true },
146
+ "contour:input": { payload: ["name", "value", "checked"], composed: true },
147
+ "contour:invalid": { payload: ["field", "input", "message"], composed: true, cancelable: true },
148
+ "contour:inspect-action": { payload: ["label"], composed: true },
149
+ "contour:layer-opacity": { payload: ["name", "opacity"], composed: true },
150
+ "contour:layer-rename": { payload: ["name", "newName"], composed: true },
151
+ "contour:layer-duplicate": { payload: ["name"], composed: true },
152
+ "contour:layer-zoom": { payload: ["name"], composed: true },
153
+ "contour:zoom": { payload: ["data", "index", "row"], composed: true },
154
+ "contour:layer-projection": { payload: ["name", "projection"], composed: true },
155
+ "contour:layer-remove": { payload: ["name"], composed: true },
156
+ "contour:layer-reorder": { payload: ["layerIds"], composed: true },
157
+ "contour:layer-toggle": { payload: ["name", "visible"], composed: true },
158
+ "contour:layer-visibility": { payload: ["name", "visible"], composed: true },
159
+ "contour:legend-toggle": { payload: ["index", "key", "label", "pressed"], composed: true },
160
+ "contour:leave": { payload: [], composed: true },
161
+ "contour:load": { payload: ["src", "count"], composed: true },
162
+ "contour:map-control": { payload: ["control"], composed: true },
163
+ "contour:map-attach": { payload: [], composed: true },
164
+ "contour:map-detach": { payload: [], composed: true },
165
+ "contour:map-popup-reposition": { payload: ["anchor", "flippedX", "flippedY", "left", "top"], composed: true },
166
+ "contour:mode-change": { payload: ["mode"], composed: true },
167
+ "contour:scope-change": { payload: ["scope"], composed: true },
168
+ "contour:move": { payload: ["direction", "from", "to"], composed: true },
169
+ "contour:open": { payload: [], composed: true },
170
+ "contour:page": { payload: ["page"], composed: true },
171
+ "contour:ready": { payload: ["version", "count"], composed: true },
172
+ "contour:read": { payload: ["label"], composed: true },
173
+ "contour:remove": { payload: ["key", "label", "name", "value"], composed: true },
174
+ "contour:reorder": { payload: ["from", "to"], composed: true },
175
+ "contour:range-change": { payload: ["value"], composed: true },
176
+ "contour:resize": { payload: ["delta", "height", "value", "width"], composed: true },
177
+ "contour:retry": { payload: ["src"], composed: true },
178
+ "contour:loop-change": { payload: ["loop"], composed: true },
179
+ "contour:pause": { payload: [], composed: true },
180
+ "contour:play": { payload: [], composed: true },
181
+ "contour:seek": { payload: ["progress", "value"], composed: true },
182
+ "contour:select": { payload: ["area", "col", "expanded", "href", "index", "key", "label", "labels", "path", "range", "result", "row", "rows", "series", "value"], composed: true },
183
+ "contour:search": { payload: ["query"], composed: true },
184
+ "contour:spatial-filter": { payload: ["action", "mode", "operator"], composed: true },
185
+ "contour:split-change": { payload: ["value", "width", "height"], composed: true },
186
+ "contour:speed-change": { payload: ["speed"], composed: true },
187
+ "contour:showcase-activate": { payload: ["title"], composed: true },
188
+ "contour:step-activate": { payload: ["index", "title"], composed: true },
189
+ "contour:step-change": { payload: ["direction", "index", "title"], composed: true },
190
+ "contour:show": { payload: [], composed: true },
191
+ "contour:sort": { payload: ["column", "direction"], composed: true },
192
+ "contour:submit": { payload: ["submitting"], composed: true },
193
+ "contour:stream-state": { payload: ["running"], composed: true },
194
+ "contour:tab-change": { payload: ["index", "label"], composed: true },
195
+ "contour:theme-change": { payload: ["theme"], composed: true },
196
+ "contour:tick": { payload: ["frame"], composed: true },
197
+ "contour:time-change": { payload: ["progress", "value"], composed: true },
198
+ "contour:time-range-change": { payload: ["value"], composed: true },
199
+ "contour:toggle": { payload: ["collapsed", "expanded", "label", "open", "path", "playing"], composed: true },
200
+ "contour:view-enter": { payload: [], composed: true },
201
+ "contour:view-leave": { payload: [], composed: true },
202
+ });
203
+
204
+ // Shared HTML sanitizer (B3-18): allowlist via DOMParser instead of a
205
+ // blacklist regex, so single-quoted, unquoted and javascript: payloads
206
+ // cannot slip through.
207
+ /** Sanitize consumer-provided HTML using a DOM allowlist. */
208
+ export function sanitizeHtml(input) {
209
+ const str = String(input == null ? "" : input);
210
+ // Fail closed when no parser is available (SSR, constrained runtimes):
211
+ // never treat "no parser" as "trusted markup". Return the input as inert
212
+ // text so no tag is interpreted by an innerHTML assignment.
213
+ if (typeof DOMParser === "undefined") {
214
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
215
+ }
216
+ const doc = new DOMParser().parseFromString(str, "text/html");
217
+ const drop = new Set(["script", "iframe", "object", "embed", "style", "link", "meta", "base", "form", "input", "button"]);
218
+ const walk = (node) => {
219
+ const children = Array.from(node.childNodes);
220
+ for (const c of children) {
221
+ if (c.nodeType === 1) {
222
+ const tag = c.tagName.toLowerCase();
223
+ if (drop.has(tag)) { c.remove(); continue; }
224
+ // Strip every on-* attribute and javascript: URLs.
225
+ for (const attr of Array.from(c.attributes)) {
226
+ const name = attr.name.toLowerCase();
227
+ if (name.startsWith("on")) { c.removeAttribute(attr.name); continue; }
228
+ const val = String(attr.value || "").trim().toLowerCase();
229
+ if ((name === "href" || name === "src" || name === "xlink:href") && (val.startsWith("javascript:") || val.startsWith("data:text/html"))) {
230
+ c.removeAttribute(attr.name);
231
+ }
232
+ }
233
+ walk(c);
234
+ }
235
+ }
236
+ };
237
+ walk(doc.body);
238
+ return doc.body.innerHTML;
239
+ }
240
+ /**
241
+ * Validate a CSS colour for use in an inline style.
242
+ *
243
+ * Returns the trimmed value when it is a plain colour (named, hex, or a
244
+ * known colour function) and an empty string otherwise. Anything that could
245
+ * break out of the declaration, load a resource, or run script is rejected,
246
+ * so a consumer-supplied `color` attribute cannot become an injection sink.
247
+ *
248
+ * @param {unknown} value candidate colour
249
+ * @returns {string} the safe colour, or "" when rejected
250
+ */
251
+ export function safeColor(value) {
252
+ const raw = String(value == null ? "" : value).trim();
253
+ if (!raw) return "";
254
+ if (/[;{}<>"'`\\]/.test(raw)) return "";
255
+ if (/url\s*\(/i.test(raw) || /expression\s*\(/i.test(raw)) return "";
256
+ if (/^#[0-9a-f]{3,8}$/i.test(raw)) return raw;
257
+ if (/^(rgb|rgba|hsl|hsla|hwb|lab|lch|oklab|oklch|color)\(/i.test(raw)) return raw;
258
+ if (/^[a-z]+$/i.test(raw)) return raw;
259
+ return "";
260
+ }
261
+ /**
262
+ * Resolve an href candidate to a value that is safe to assign to a sink.
263
+ *
264
+ * Fragments, relative paths and the schemes we can vouch for pass through
265
+ * unchanged; `javascript:`, `data:` and any other scheme collapse to "#".
266
+ * This closes the attribute-to-property path that `sanitizeHtml` does not
267
+ * cover, because assigning `a.href = "javascript:…"` executes on click.
268
+ *
269
+ * @param {unknown} value candidate href
270
+ * @returns {string} the safe href, or "#"
271
+ */
272
+ export function safeHref(value) {
273
+ const raw = String(value == null ? "" : value).trim();
274
+ if (!raw) return "#";
275
+ if (raw.startsWith("#") || raw.startsWith("/") || raw.startsWith("./") || raw.startsWith("../") || raw.startsWith("?")) return raw;
276
+ if (typeof document === "undefined" || !document.baseURI) return "#";
277
+ try {
278
+ const url = new URL(raw, document.baseURI);
279
+ return ["http:", "https:", "mailto:", "tel:"].includes(url.protocol) ? raw : "#";
280
+ } catch (e) {
281
+ return "#";
282
+ }
283
+ }
284
+ /**
285
+ * Read a length token from the document root, in pixels.
286
+ *
287
+ * Virtualized components used to hard-code 36/32/28 px row heights, which
288
+ * disagreed with the rendered row and ignored density. The height is now a
289
+ * token (`--data-grid-row-height`, …) and this reads its computed value.
290
+ *
291
+ * @param {string} name custom-property name
292
+ * @param {number} fallback pixels to use when the token is absent or invalid
293
+ * @returns {number} the resolved length in pixels
294
+ */
295
+ export function cssLength(name, fallback) {
296
+ if (typeof getComputedStyle === "undefined" || typeof document === "undefined") return fallback;
297
+ const v = parseFloat(getComputedStyle(document.documentElement).getPropertyValue(name));
298
+ return Number.isFinite(v) && v > 0 ? v : fallback;
299
+ }
300
+ /**
301
+ * Surface a malformed JSON attribute instead of swallowing it.
302
+ *
303
+ * A bare `catch (e) { /* keep existing *\/ }` turns a typo in a component
304
+ * attribute into a silent no-op: the render keeps whatever was there before
305
+ * and the defect is invisible. This warns once, with the component name and
306
+ * the parser message, so the author can find it.
307
+ *
308
+ * @param {Element|null} host the component that owns the attribute
309
+ * @param {string} label the attribute (or a short description)
310
+ * @param {unknown} error the thrown parse error
311
+ */
312
+ export function warnBadJson(host, label, error) {
313
+ if (typeof console === "undefined" || !console.warn) return;
314
+ const name = host && host.tagName ? host.tagName.toLowerCase() : "component";
315
+ const msg = (error && error.message) || String(error);
316
+ console.warn(`[contour] ${name}: malformed ${label || "attribute"} — ${msg}`);
317
+ }
318
+ // contract: an attribute that is not here cannot ask an element to re-render,
319
+ // and an attribute a component WRITES to itself must never be here, because
320
+ // that write would fire the callback that performs the render.
321
+ //
322
+ // Excluded because the render bodies below set them on the host:
323
+ // role, open, aria-label, aria-valuenow, aria-valuemin, aria-valuemax, tabindex
324
+ // speed — the time-slider writes its committed speed back (R20 T-30);
325
+ // both readers (time-slider, animation-controls) observe it per-class.
326
+ // x, y — the annotation writes its dragged position back (R20 T-11);
327
+ // its only reader observes them per-class.
328
+ // progress — animation-controls writes its playhead back (R20 T-10);
329
+ // both readers (animation-controls, file-upload) observe it per-class.
330
+ // colors — palette-editor writes the edited palette back (R20 T-15);
331
+ // all readers (palette-editor, style-panel, bivariate, bivariate-legend)
332
+ // observe it per-class.
333
+ // Adding one of those back to this list makes that component recurse.
334
+ /** Shared attribute vocabulary used by components that opt into defaults. */
335
+ export const OBSERVED = [
336
+ "accept", "action", "actions", "active", "after", "allow-duplicate", "allow-remove", "allow-rename", "allow-zoom", "alpha", "anchor", "answer", "area", "article", "attribution", "attribution-mark", "audit", "autoplay", "axis", "axis-x", "axis-y", "brownout", "brownout-level", "before", "body", "brand", "bounds", "breakpoint", "breaks", "brush", "brush-end", "brush-max", "brush-min", "brush-start", "cache-key", "canvas", "center", "clearable", "cols", "columns", "color", "command",
337
+ "cells", "checked", "chrome", "confidence", "coverage", "debounce", "closable", "collapsed", "collapsible", "classification", "continuous", "content", "controls", "copyable", "count", "data", "data-table", "date", "delta", "description", "glyphs", "graduated", "demo", "density", "desc", "dir", "direction", "disabled", "distance", "dismissible", "divider", "do", "dont", "dot", "ends", "high", "input", "layer", "low", "mode", "modes", "n", "opacity", "palette", "polarity", "precision", "range", "single",
338
+ "empty", "exclusive", "fallback", "filename", "format", "heading", "help", "hint", "href", "icon", "illustration", "instrument", "interval", "items", "key", "layers", "level", "markers", "range-end", "range-start",
339
+ "label", "labels", "lazy", "lede", "legend", "left-label", "right-label", "line", "limit", "link", "links", "live", "loading", "locale", "loop", "max", "media", "message", "method", "methodology", "menu", "min", "multiple", "name", "needle", "next", "no", "no-cache", "no-data-message", "nodes", "note", "norm", "normalize",
340
+ "options", "orientation", "page-size", "pages", "pause", "paused", "pausable", "persist", "placeholder", "playing", "point", "points", "prev", "presets", "prompt", "question", "recent", "required",
341
+ "quote", "ramp", "refresh", "removable", "resolution", "reverse", "rings", "retry", "results", "rows", "scale", "selectable", "segments", "show-header", "sparkline", "threshold", "thresholds", "selected", "separator", "series", "shortcut", "side", "size", "skeleton", "sort", "sort-dir", "status", "step", "submit", "submitting", "timeout", "trigger", "virtual", "sticky", "cluster-count", "cluster-expanded", "time", "resizable",
342
+ "state", "steps", "style", "subtitle", "summary", "src", "source", "table", "tabs", "tag", "text", "ticks", "title", "type", "unread-only", "unit", "updated", "cluster-items", "row-height",
343
+ "variant", "values", "viewport", "warning", "yes", "zoomable",
344
+ "caption", "current-time", "is-playing", "loop-label", "no-data-color", "no-data-label", "property", "show-loop", "show-thumb", "show-thumb-caption", "speeds", "item-height", "pause-label", "play-label", "speed-label", "time-label", "shimmer",
345
+ "search",
346
+ "numbered",
347
+ "bucket-count", "limit-values",
348
+ "autocomplete", "levels", "submit-label",
349
+ "fields", "gap",
350
+ "controls",
351
+ "flush", "head", "preview", "tags", "url",
352
+ "custom-error",
353
+ ];
354
+
355
+ /** Resolve an authored heading level while keeping the fallback valid. */
356
+ export function headingTag(host, fallback = "h3") {
357
+ const v = host && host.getAttribute ? host.getAttribute("heading") : null;
358
+ return /^h[1-6]$/.test(v || "") ? v : fallback;
359
+ }
360
+
361
+ /**
362
+ * Resolve a localised label for a host (R18-63). A consumer supplies a
363
+ * `labels` JSON attribute (e.g. `labels='{"clear":"Effacer"}'`); it is merged
364
+ * over the English `fallback`, so a partial object localises only the keys it
365
+ * names. A malformed attribute is ignored rather than thrown — a bad label
366
+ * must not take the widget down. Returns `fallback` when no override exists.
367
+ */
368
+ export function labelText(host, key, fallback) {
369
+ const def = fallback !== undefined ? fallback : key;
370
+ const raw = host && host.getAttribute ? host.getAttribute("labels") : null;
371
+ if (!raw) return def;
372
+ try {
373
+ const parsed = JSON.parse(raw);
374
+ if (parsed && typeof parsed === "object" && typeof parsed[key] === "string" && parsed[key]) return parsed[key];
375
+ } catch (e) { /* a malformed labels attribute is ignored, not fatal */ }
376
+ return def;
377
+ }
378
+
379
+ /**
380
+ * Write localised copy onto a node without stealing an author's words (R18-63).
381
+ *
382
+ * `labelText()` resolves the string; this decides whether the node may take it.
383
+ * A node the component generated on an earlier render carries
384
+ * `data-contour-label`, so a `labels` change reaches it. A node the AUTHOR
385
+ * wrote — a `.c-saved-view__apply` button with its own text, a
386
+ * `.c-spatial-filter__clear-all` — has no such mark and keeps its words,
387
+ * because a default must never overwrite copy a consumer chose.
388
+ *
389
+ * This exists because the rule is not obvious and the failure is silent: an
390
+ * unconditional `node.textContent = labelText(...)` looks like the fix and is a
391
+ * regression for every consumer who supplied their own button.
392
+ */
393
+ export function applyLabel(node, host, key, fallback) {
394
+ if (!node) return;
395
+ if (node.dataset && node.dataset.contourLabel === "true") {
396
+ node.textContent = labelText(host, key, fallback);
397
+ } else if (!node.textContent) {
398
+ node.textContent = labelText(host, key, fallback);
399
+ if (node.dataset) node.dataset.contourLabel = "true";
400
+ }
401
+ }
402
+
403
+ /**
404
+ * Base class for all Contour web components.
405
+ *
406
+ * Lifecycle: the first `connectedCallback` snapshots the author's nodes and
407
+ * class attribute, then calls `render()`. On attribute change, the snapshot
408
+ * is restored and `render()` runs again, so subclasses stay reactive.
409
+ *
410
+ * All components use light DOM so that `ds.css` styles apply directly.
411
+ */
412
+ // Base class: the lifecycle belongs here, the markup belongs to the subclass.
413
+ //
414
+ // A render body is written to run more than once, and it is idempotent because
415
+ // of this snapshot rather than because of its own guards. The first
416
+ // connectedCallback records the nodes and the class attribute the AUTHOR
417
+ // wrote; every later render drops everything, re-appends exactly those nodes,
418
+ // and runs again. So a body may keep the natural
419
+ // `if (!this.querySelector(".c-card__title"))` shape: after the reset the
420
+ // generated node is gone, the guard passes, and the changed attribute reaches
421
+ // the page. Without the reset the guard is permanent and reactivity is a lie.
422
+ //
423
+ // The snapshot holds node references, not a re-parsed string, so listeners a
424
+ // consumer put on authored children survive a re-render. The cost is honest:
425
+ // nodes a component generated are rebuilt, so state inside them (a typed
426
+ // value, a focus ring) is lost when a host attribute changes.
427
+ // SSR-safe base (R12-25): in a non-DOM runtime (Node, type-only tooling)
428
+ // HTMLElement is undefined. Fall back to Object so the module can be imported
429
+ // for metadata/type inspection without a DOM shim; components cannot be
430
+ // instantiated there, which is the correct boundary.
431
+ const _ContourBaseParent = (typeof HTMLElement !== "undefined") ? HTMLElement : Object;
432
+ export class ContourBase extends _ContourBaseParent {
433
+ static formAssociated = false;
434
+ constructor() {
435
+ super();
436
+ if (this.constructor.formAssociated && typeof this.attachInternals === "function") {
437
+ this._internals = this.attachInternals();
438
+ }
439
+ }
440
+ // Per-component observed attributes. Subclasses override `static get observed()`
441
+ // with only the attributes they read; the default is the full shared list so
442
+ // a component that does not opt in keeps working.
443
+ static get observed() {
444
+ return OBSERVED;
445
+ }
446
+ /**
447
+ * The attribute list the platform is told about.
448
+ *
449
+ * `labels` is appended here rather than left to each subclass's `observed`,
450
+ * because the reader is a SHARED helper: `labelText()` below resolves copy for
451
+ * whichever component asks, so a per-class list has to remember it once per
452
+ * class or a `labels` change silently does nothing on every host that forgot.
453
+ * That is exactly how it stood — one component listed it and eleven did not.
454
+ * A component that writes `labels` to itself would recurse, and none does.
455
+ */
456
+ static get observedAttributes() {
457
+ const list = this.observed;
458
+ return list.includes("labels") ? list : [...list, "labels"];
459
+ }
460
+
461
+ // Subclasses override to declare reflected properties:
462
+ // static get properties() { return { value: { attribute: "value", type: String } }; }
463
+ // A property with no entry is not reflected. Types: String (default), Number, Boolean.
464
+ static get properties() {
465
+ return {};
466
+ }
467
+
468
+ // Update policy (R12-06): "scaffold" components may rebuild their generated
469
+ // DOM on attribute change (the default lifecycle). High-volume components
470
+ // (table, grid, tree, virtual-list, chart) should override to "keyed" and
471
+ // use ensure()/keyed patching, or expose an imperative update method.
472
+ // Documented here so consumers know which components guarantee identity
473
+ // stability across renders.
474
+ static get updateMode() {
475
+ return "scaffold";
476
+ }
477
+
478
+ // Brownout helpers (G-16): components read their degraded level from the
479
+ // `brownout` / `brownout-level` attribute and shed non-essential chrome
480
+ // above a threshold. Centralised here so a new component does not
481
+ // re-implement the attribute lookup.
482
+ brownoutLevel() {
483
+ const raw = this.getAttribute("brownout-level") || this.getAttribute("brownout") || "0";
484
+ const n = parseInt(raw, 10);
485
+ return Number.isFinite(n) ? n : 0;
486
+ }
487
+ shed(kind, threshold) {
488
+ return this.brownoutLevel() >= (threshold || 1);
489
+ }
490
+ // Read-only and diagnostic: it exists so a page can show that `batch()` did
491
+ // what it claims instead of asking the reader to believe it, and so a test can
492
+ // assert a re-render happened without watching for a specific node. A consumer
493
+ // that never calls `batch()` never needs it, and nothing here reads it.
494
+ get renderCount() {
495
+ return this._contourRenderCount || 0;
496
+ }
497
+
498
+ _countRender() {
499
+ this._contourRenderCount = (this._contourRenderCount || 0) + 1;
500
+ }
501
+
502
+ // Install accessors once per class, so `el.value = 42` writes the attribute
503
+ // and triggers the normal re-render path instead of being a silent no-op.
504
+ static _propsInstalled = false;
505
+ _installProperties() {
506
+ const ctor = this.constructor;
507
+ if (ctor._propsInstalled) return;
508
+ ctor._propsInstalled = true;
509
+ const props = ctor.properties || {};
510
+ const declared = new Set();
511
+ for (const [name, spec] of Object.entries(props)) {
512
+ const attr = (spec && spec.attribute) || name;
513
+ declared.add(attr);
514
+ const type = (spec && spec.type) || String;
515
+ Object.defineProperty(ctor.prototype, name, {
516
+ get() {
517
+ const raw = this.getAttribute(attr);
518
+ if (type === Boolean) return raw !== null;
519
+ if (raw === null) return spec && spec.default !== undefined ? spec.default : null;
520
+ if (type === Number) { const n = Number(raw); return Number.isNaN(n) ? null : n; }
521
+ return raw;
522
+ },
523
+ set(v) {
524
+ if (v === null || v === undefined || v === false) this.removeAttribute(attr);
525
+ else if (type === Boolean) { if (v) this.setAttribute(attr, ""); else this.removeAttribute(attr); }
526
+ else this.setAttribute(attr, String(v));
527
+ },
528
+ configurable: true,
529
+ });
530
+ }
531
+ // Default reflection (R18-54): every observed attribute a component reads
532
+ // but does not declare in properties() still gets an accessor, so
533
+ // `el.allowDuplicate = true` writes `allow-duplicate=""` instead of being
534
+ // a silent no-op. The property name is the camelCase form of the
535
+ // attribute (kebab -> camel); a kebab attribute with no valid identifier
536
+ // form is skipped rather than guessed. Declared properties win.
537
+ //
538
+ // The list is `observedAttributes`, not `observed`, so the reflection
539
+ // surface and the platform's stay the same set — `labels` included.
540
+ const observed = ctor.observedAttributes;
541
+ for (const attr of observed) {
542
+ if (declared.has(attr)) continue;
543
+ const prop = attr.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
544
+ if (!/^[a-zA-Z_$][\w$]*$/.test(prop)) continue;
545
+ if (prop in ctor.prototype) continue; // an inherited accessor already exists
546
+ const isBool = attr === "disabled" || attr === "checked" || attr === "required" || attr === "readonly" || attr === "multiple" || attr === "selected" || attr === "open" || attr === "hidden";
547
+ Object.defineProperty(ctor.prototype, prop, {
548
+ get() {
549
+ const raw = this.getAttribute(attr);
550
+ if (isBool) return raw !== null;
551
+ return raw;
552
+ },
553
+ set(v) {
554
+ if (v === null || v === undefined || v === false) this.removeAttribute(attr);
555
+ else if (isBool) { if (v) this.setAttribute(attr, ""); else this.removeAttribute(attr); }
556
+ else this.setAttribute(attr, String(v));
557
+ },
558
+ configurable: true,
559
+ });
560
+ }
561
+ }
562
+
563
+ connectedCallback() {
564
+ if (this._contourAuthored) { this._wireFormData(); return; } // reconnected, not re-specified
565
+ this._installProperties();
566
+ this._contourAuthored = {
567
+ nodes: Array.from(this.childNodes),
568
+ cls: this.getAttribute("class"),
569
+ };
570
+ const before = Array.from(this.childNodes);
571
+ this._contourRenderGen = (this._contourRenderGen || 0) + 1;
572
+ this._ensureCache = new Map();
573
+ this._ensureCacheGen = this._contourRenderGen;
574
+ this._countRender();
575
+ try { this.render(); }
576
+ catch (e) { console.error("Contour render error:", e); this.textContent = labelText(this, "render-error", "Component failed to render."); }
577
+ this._contourGenerated = Array.from(this.childNodes).filter((n) => !before.includes(n));
578
+ this._applyParts(this);
579
+ this._applyDensity();
580
+ this.enhance();
581
+ this._detachInnerFormControls();
582
+ this._wireFormData();
583
+ this._wireValueTracking();
584
+ }
585
+
586
+ attributeChangedCallback(name, oldValue, newValue) {
587
+ if (oldValue === newValue) return;
588
+ // Fires before connectedCallback during an upgrade: nothing to reset to
589
+ // yet, and connectedCallback will render with the final attributes.
590
+ if (!this.isConnected || !this._contourAuthored) return;
591
+ // Opt-in batching: when inside batch(), attribute changes are coalesced
592
+ // into a single render that fires when the batch ends. This lets a
593
+ // dashboard update value + delta + direction without three rebuilds,
594
+ // without changing the default synchronous contract the gate enforces.
595
+ if (this._batchDepth > 0) {
596
+ this._batchDirty = true;
597
+ return;
598
+ }
599
+ // Re-entrant change (an attribute set while a render is in flight): do
600
+ // not drop it, defer a single re-render to the next microtask so the
601
+ // in-flight render can finish first. Coalesces several such changes.
602
+ if (this._contourRendering) {
603
+ if (!this._pendingRerender) {
604
+ this._pendingRerender = true;
605
+ queueMicrotask(() => {
606
+ this._pendingRerender = false;
607
+ if (!this.isConnected || !this._contourAuthored) return;
608
+ // Re-run with a sentinel old value so the equality guard does not
609
+ // short-circuit; the render reads current attribute values.
610
+ this.attributeChangedCallback("__rerender__", null, "");
611
+ });
612
+ }
613
+ return;
614
+ }
615
+ if (name === "checked") this._checkedAttrChanged = true;
616
+ this._contourRendering = true;
617
+ try {
618
+ // Preserve form control values across a re-render: generated inputs are
619
+ // dropped and rebuilt, so without this a host attribute change wipes
620
+ // whatever the user typed.
621
+ const savedControls = Array.from(this.querySelectorAll("input, textarea, select"));
622
+ const savedValues = savedControls.map((el) => ({
623
+ key: el.name || el.id || null,
624
+ preserveKey: el.getAttribute("data-contour-preserve-key") || null,
625
+ value: el.value,
626
+ checked: el.checked,
627
+ type: el.type,
628
+ // User-dirty tracking (R20 T-02): a control the user edited keeps
629
+ // its value until the host's `value` attribute changes. A
630
+ // multi-select saves its whole selection, not just select.value
631
+ // (which is only the first selected option).
632
+ dirty: !!el._contourUserDirty,
633
+ attrAtDirty: el._contourAttrAtDirty,
634
+ selected: el.tagName === "SELECT" && el.multiple ? Array.from(el.selectedOptions).map((o) => o.value) : null,
635
+ }));
636
+ // Preserve focus, scroll position and <details> open state across the
637
+ // rebuild, so a host attribute change does not yank focus to <body>
638
+ // or collapse an open disclosure.
639
+ const hadFocus = this.contains(document.activeElement) ? document.activeElement : null;
640
+ // Capture a recovery key for unkeyed active elements: an id is the
641
+ // strongest key, then a `data-contour-preserve-key`, then a `name`,
642
+ // then the relative index among all focusable controls inside the host.
643
+ // Without these, an attribute update that rebuilds an unkeyed input
644
+ // drops focus to <body>.
645
+ const _focusableSelector = "button, [href], input, select, textarea, [tabindex]:not([tabindex='-1'])";
646
+ const _focusablesBefore = Array.from(this.querySelectorAll(_focusableSelector));
647
+ const hadFocusIndex = hadFocus ? _focusablesBefore.indexOf(hadFocus) : -1;
648
+ const hadFocusKey = hadFocus ? (hadFocus.id || null) : null;
649
+ const hadFocusPreserveKey = hadFocus ? (hadFocus.getAttribute("data-contour-preserve-key") || null) : null;
650
+ const hadFocusName = hadFocus ? (hadFocus.getAttribute("name") || null) : null;
651
+ const savedScrolls = Array.from(this.querySelectorAll("*")).filter((el) => el.scrollHeight > el.clientHeight || el.scrollWidth > el.clientWidth).map((el) => ({ el, id: el.id || null, preserveKey: el.getAttribute("data-contour-preserve-key") || null, top: el.scrollTop, left: el.scrollLeft }));
652
+ const savedDetails = Array.from(this.querySelectorAll("details")).map((d) => ({ id: d.id || null, preserveKey: d.getAttribute("data-contour-preserve-key") || null, open: d.open }));
653
+ // Unwrap authored content from generated wrappers before dropping them,
654
+ // so an attribute re-render cannot destroy authored light-DOM children
655
+ // that render() moved into a body/pre wrapper (B3-05).
656
+ for (const g of (this._contourGenerated || [])) {
657
+ if (!g || g.parentNode !== this) continue;
658
+ let wrapper = null;
659
+ if (g.classList && (g.classList.contains("c-panel__body") || g.classList.contains("c-dialog__body"))) wrapper = g;
660
+ else if (g.tagName === "PRE") wrapper = g.querySelector("code") || g;
661
+ if (wrapper) {
662
+ while (wrapper.firstChild) this.insertBefore(wrapper.firstChild, g);
663
+ }
664
+ }
665
+ // Drop generated nodes from the previous render.
666
+ for (const g of (this._contourGenerated || [])) {
667
+ if (g.parentNode === this) this.removeChild(g);
668
+ }
669
+ // Refresh the authored snapshot so content added after connect survives.
670
+ const generated = new Set(this._contourGenerated || []);
671
+ const authoredNow = Array.from(this.childNodes).filter((n) => !generated.has(n));
672
+ this._contourAuthored.nodes = authoredNow;
673
+ // Clear and restore authored nodes.
674
+ while (this.firstChild) this.removeChild(this.firstChild);
675
+ for (const node of this._contourAuthored.nodes) this.appendChild(node);
676
+ if (this._contourAuthored.cls === null) this.removeAttribute("class");
677
+ else this.setAttribute("class", this._contourAuthored.cls);
678
+ const before = Array.from(this.childNodes);
679
+ this._contourRenderGen = (this._contourRenderGen || 0) + 1;
680
+ this._ensureCache = new Map();
681
+ this._ensureCacheGen = this._contourRenderGen;
682
+ this._countRender();
683
+ try { this.render(); }
684
+ catch (e) { console.error("Contour render error:", e); this.textContent = labelText(this, "render-error", "Component failed to render."); }
685
+ this._contourGenerated = Array.from(this.childNodes).filter((n) => !before.includes(n));
686
+ this._applyParts(this);
687
+ this._applyDensity();
688
+ // Restore preserved form control values. A re-render that adds or
689
+ // removes a control must not wipe the rest: keyed controls (those with
690
+ // a `name` or `id`) are matched by key first, so a new field inserted
691
+ // between two existing ones leaves both neighbours' values intact.
692
+ // Unkeyed controls fall back to index matching up to the shorter of
693
+ // the two lists, so a field removed at the end does not shift values
694
+ // onto the wrong input.
695
+ const newControls = Array.from(this.querySelectorAll("input, textarea, select"));
696
+ const keyed = savedValues.filter((sv) => sv.key || sv.preserveKey);
697
+ const unkeyed = savedValues.filter((sv) => !sv.key && !sv.preserveKey);
698
+ const used = new Set();
699
+ for (const el of newControls) {
700
+ const key = el.name || el.id || el.getAttribute("data-contour-preserve-key") || null;
701
+ if (!key) continue;
702
+ const match = keyed.find((sv) => (sv.key === key || sv.preserveKey === key) && !used.has(sv));
703
+ if (!match) continue;
704
+ used.add(match);
705
+ if (!this._contourResetting) this._restoreControlValue(el, match);
706
+ if ((el.type === "checkbox" || el.type === "radio") && typeof match.checked === "boolean" && !this._checkedAttrChanged && !this._contourResetting) {
707
+ el.checked = match.checked;
708
+ }
709
+ }
710
+ // Restore unkeyed controls by type-aware index matching: group saved
711
+ // unkeyed controls by type, then match new unkeyed controls by type and
712
+ // index within that type group. This prevents misalignment when elements
713
+ // are inserted or removed between renders (F-R4). A textarea removed
714
+ // from the middle no longer shifts its value onto a following input.
715
+ const savedByType = new Map();
716
+ for (const sv of unkeyed) {
717
+ const group = savedByType.get(sv.type) || [];
718
+ group.push(sv);
719
+ savedByType.set(sv.type, group);
720
+ }
721
+ const usedByType = new Map();
722
+ for (const el of newControls) {
723
+ if (el.name || el.id) continue;
724
+ const type = el.type;
725
+ const group = savedByType.get(type) || [];
726
+ const used = usedByType.get(type) || 0;
727
+ if (used >= group.length) continue;
728
+ const saved = group[used];
729
+ usedByType.set(type, used + 1);
730
+ if (!this._contourResetting) this._restoreControlValue(el, saved);
731
+ if ((el.type === "checkbox" || el.type === "radio") && typeof saved.checked === "boolean" && !this._checkedAttrChanged && !this._contourResetting) {
732
+ el.checked = saved.checked;
733
+ }
734
+ }
735
+ // Restore <details> open state. A disclosure carries an `id` when it is
736
+ // stable across renders (a faq item, a doc section); match those by id
737
+ // so inserting a new disclosure above them does not collapse the ones
738
+ // below. Disclosures without an id fall back to index matching up to
739
+ // the shorter list, which is the behaviour the length guard existed
740
+ // to protect and still protects for the tail of either list.
741
+ const newDetails = Array.from(this.querySelectorAll("details"));
742
+ const keyedDetails = savedDetails.filter((sd) => sd.id || sd.preserveKey);
743
+ const usedIds = new Set();
744
+ for (const d of newDetails) {
745
+ const id = d.id || null;
746
+ const preserveKey = d.getAttribute("data-contour-preserve-key") || null;
747
+ if (!id && !preserveKey) continue;
748
+ const match = keyedDetails.find((sd) => (sd.id === id || sd.preserveKey === preserveKey) && !usedIds.has(sd.id || sd.preserveKey));
749
+ if (!match) continue;
750
+ usedIds.add(match.id || match.preserveKey);
751
+ d.open = match.open;
752
+ }
753
+ let di = 0;
754
+ const plainSaved = savedDetails.filter((sd) => !sd.id);
755
+ for (const d of newDetails) {
756
+ if (d.id) continue;
757
+ const sd = plainSaved[di];
758
+ di += 1;
759
+ if (!sd) break;
760
+ d.open = sd.open;
761
+ }
762
+ // Restore scroll positions. A scroller that carries an `id` is matched by
763
+ // id so inserting another scroller above it does not hand its offset to
764
+ // the wrong container; the rest fall back to index matching up to the
765
+ // shorter list, which is what the old length guard protected.
766
+ const newScrolls = Array.from(this.querySelectorAll("*")).filter((el) => el.scrollHeight > el.clientHeight || el.scrollWidth > el.clientWidth);
767
+ const keyedScrolls = savedScrolls.filter((s) => s.id || s.preserveKey);
768
+ const usedScrolls = new Set();
769
+ for (const el of newScrolls) {
770
+ const id = el.id || null;
771
+ const preserveKey = el.getAttribute("data-contour-preserve-key") || null;
772
+ if (!id && !preserveKey) continue;
773
+ const match = keyedScrolls.find((s) => (s.id === id || s.preserveKey === preserveKey) && !usedScrolls.has(s.el));
774
+ if (!match) continue;
775
+ usedScrolls.add(match.el);
776
+ el.scrollTop = match.top;
777
+ el.scrollLeft = match.left;
778
+ }
779
+ let si = 0;
780
+ const plainScrolls = savedScrolls.filter((s) => !s.id && !s.preserveKey);
781
+ for (const el of newScrolls) {
782
+ if (el.id) continue;
783
+ const s = plainScrolls[si];
784
+ si += 1;
785
+ if (!s) break;
786
+ el.scrollTop = s.top;
787
+ el.scrollLeft = s.left;
788
+ }
789
+ // Restore focus if it was inside the host. Keyed elements (id) are
790
+ // matched first; unkeyed ones fall back to a `name` attribute, then to
791
+ // their relative index among focusable controls, so an attribute update
792
+ // that rebuilds an unkeyed input no longer drops focus to <body>.
793
+ if (hadFocus) {
794
+ let target = null;
795
+ if (hadFocusKey) {
796
+ try { target = this.querySelector("#" + CSS.escape(hadFocusKey)); } catch (e) { target = null; }
797
+ }
798
+ if (!target && hadFocusPreserveKey) {
799
+ try { target = this.querySelector('[data-contour-preserve-key="' + CSS.escape(hadFocusPreserveKey) + '"]'); } catch (e) { target = null; }
800
+ }
801
+ if (!target && hadFocusName) {
802
+ try { target = this.querySelector('[name="' + CSS.escape(hadFocusName) + '"]'); } catch (e) { target = null; }
803
+ }
804
+ if (!target && hadFocusIndex >= 0) {
805
+ const after = Array.from(this.querySelectorAll(_focusableSelector));
806
+ if (after.length) {
807
+ target = after[Math.min(hadFocusIndex, after.length - 1)];
808
+ }
809
+ }
810
+ if (target && typeof target.focus === "function") {
811
+ try { target.focus(); } catch (e) {}
812
+ } else if (document.contains(hadFocus)) {
813
+ try { hadFocus.focus(); } catch (e) {}
814
+ } else {
815
+ const first = this.querySelector(_focusableSelector);
816
+ if (first) try { first.focus(); } catch (e) {}
817
+ else try { this.focus(); } catch (e) {}
818
+ }
819
+ }
820
+ this.enhance();
821
+ this._detachInnerFormControls();
822
+ this._checkedAttrChanged = false;
823
+ this._contourResetting = false;
824
+ } finally {
825
+ this._contourRendering = false;
826
+ }
827
+ }
828
+
829
+ disconnectedCallback() {
830
+ this._pendingRerender = false;
831
+ this._ensureCache = null;
832
+ this._batchDepth = 0;
833
+ this._batchDirty = false;
834
+ // Form listeners were removed by runDisposers below; clear the guard so
835
+ // a reconnected host re-attaches them (connectedCallback re-wires).
836
+ this._wiredFormData = false;
837
+ runDisposers(this);
838
+ // Override in subclasses that attach event listeners or timers.
839
+ }
840
+
841
+ adoptedCallback() {
842
+ // Re-apply parts and the density mirror when the node is moved to a new
843
+ // document.
844
+ if (this._contourAuthored) { this._applyParts(this); this._applyDensity(); }
845
+ }
846
+
847
+ // Default no-op: subclasses with behaviour override this.
848
+ enhance() {}
849
+
850
+ // Form lifecycle (form-associated components only). The platform calls
851
+ // these on <form>.reset(), on disable by a fieldset/form, and on bfcache
852
+ // restore; before this, a reset left the generated control showing its old
853
+ // value and a disabled fieldset reached nothing. The implementations are
854
+ // generic over the host's inner control(s), so a subclass overrides only
855
+ // when its control is not a plain input/textarea/select.
856
+ //
857
+ // The inner-value contract mirrors what each form class's enhance() sync
858
+ // already writes: a boolean control submits its `checked` value (or null),
859
+ // a text-like control submits its raw value, and `required` sets validity.
860
+ _syncFormValue() {
861
+ if (!this._internals) return;
862
+ // A boolean group (a contour-radio-list) submits the *checked* item's
863
+ // value, so prefer the checked control over the first one found.
864
+ const ctl = this.querySelector("input:checked, textarea, select") || this.querySelector("input, textarea, select");
865
+ if (!ctl) return;
866
+ const boolean = ctl.type === "checkbox" || ctl.type === "radio";
867
+ const value = boolean ? (ctl.checked ? (ctl.value || "on") : null) : ctl.value;
868
+ this._internals.setFormValue(value);
869
+ this._syncValidity(this.hasAttribute("required") && !value);
870
+ }
871
+
872
+ // The single validity writer (BY-32). Every form class used to repeat the
873
+ // required-check + setValidity pair; the copies in forms.mjs now call here,
874
+ // and the call ALSO mirrors the host's `data-invalid` custom state
875
+ // (ElementInternals.states → `:state(data-invalid)`), so validity and the
876
+ // state a consumer's CSS can select can never drift apart.
877
+ _syncValidity(valueMissing) {
878
+ if (!this._internals) return;
879
+ if (valueMissing) this._internals.setValidity({ valueMissing: true }, "This field is required.");
880
+ else this._internals.setValidity({});
881
+ this._setCustomState("data-invalid", !!valueMissing);
882
+ }
883
+
884
+ // Custom-state mirror (BY-32). `ElementInternals.states` exposes a host's
885
+ // own boolean to CSS as `:state(name)` — a consumer writes
886
+ // `contour-switch:state(data-checked)` without the layer inventing a data-*
887
+ // attribute. Loader hosts are NOT formAssociated, so the states-only
888
+ // internals are attached lazily into `_stateInternals` — never `_internals`,
889
+ // which every form path uses as its "form-associated" guard (`_wireFormData`
890
+ // reads .form on it, which throws on a non-form host; probing lazy attach
891
+ // into `_internals` broke every src-mounting arm with exactly that error).
892
+ // Where CustomStateSet is absent the mirror is a silent no-op and the
893
+ // ARIA/attribute path remains the announcement. Not a write to OBSERVED,
894
+ // so it can never re-enter render.
895
+ _setCustomState(name, on) {
896
+ let internals = this._internals;
897
+ if (!internals) {
898
+ if (this._stateInternals) internals = this._stateInternals;
899
+ else if (typeof this.attachInternals === "function") {
900
+ try { internals = this._stateInternals = this.attachInternals(); } catch (e) { return; }
901
+ }
902
+ }
903
+ const states = internals && internals.states;
904
+ if (!states) return;
905
+ if (on) { if (!states.has(name)) states.add(name); }
906
+ else if (states.has(name)) states.delete(name);
907
+ }
908
+
909
+ // The form value events (BY-44). §23 promises interactive components emit
910
+ // bubbling contour:* events; the form family had 16 user-interaction
911
+ // listeners and emitted none, so a consumer could not observe a change
912
+ // without polling. This is the ONE value-shape both `contour:input` and
913
+ // `contour:change` carry, derived from the same control state _syncFormValue
914
+ // submits, so the event can never disagree with the entry list.
915
+ _emitForm(type) {
916
+ if (!this._internals) return;
917
+ const ctl = this.querySelector("input:checked, textarea, select") || this.querySelector("input, textarea, select");
918
+ if (!ctl) return;
919
+ const boolean = ctl.type === "checkbox" || ctl.type === "radio";
920
+ this.dispatchEvent(new CustomEvent(type, {
921
+ bubbles: true,
922
+ composed: true,
923
+ detail: {
924
+ name: this.getAttribute("name"),
925
+ value: boolean ? (ctl.checked ? (ctl.value || "on") : null) : ctl.value,
926
+ checked: boolean ? ctl.checked : null,
927
+ },
928
+ }));
929
+ }
930
+ formResetCallback() {
931
+ // Reset synchronously: re-rendering would restore the base class's
932
+ // *preserved* typed value, not the authored default. The authored
933
+ // default is the host's own value/checked attributes, so restore the
934
+ // inner control from them, then re-sync internals. The user-dirty marks
935
+ // go with the reset: a later re-render must not resurrect the typed
936
+ // value the form just discarded.
937
+ for (const ctl of this.querySelectorAll("input, textarea, select")) {
938
+ ctl._contourUserDirty = false;
939
+ if (ctl.type === "checkbox" || ctl.type === "radio") {
940
+ ctl.checked = this.hasAttribute("checked");
941
+ } else if (ctl.tagName === "SELECT") {
942
+ const chosen = ctl.querySelector("option[selected], option:first-of-type");
943
+ ctl.value = chosen ? chosen.value : "";
944
+ } else {
945
+ // The authored default lives on the host (`value` attribute), not
946
+ // necessarily on the generated inner control.
947
+ ctl.value = this.hasAttribute("value") ? this.getAttribute("value") : (ctl.getAttribute("value") || "");
948
+ }
949
+ }
950
+ this._syncFormValue();
951
+ }
952
+ formDisabledCallback(disabled) {
953
+ for (const ctl of this.querySelectorAll("input, textarea, select, button")) {
954
+ if (disabled) ctl.setAttribute("disabled", "");
955
+ else ctl.removeAttribute("disabled");
956
+ }
957
+ }
958
+ formStateRestoreCallback(state) {
959
+ if (!this._internals || state === null || state === undefined) return;
960
+ const controls = Array.from(this.querySelectorAll("input, textarea, select"));
961
+ const str = String(state);
962
+ // The restore state is the value the host last submitted; for a boolean
963
+ // group it names which inner control to check.
964
+ const match = controls.find((c) => (c.type === "checkbox" || c.type === "radio") && c.value === str);
965
+ if (match) {
966
+ match.checked = true;
967
+ for (const other of controls) {
968
+ if (other !== match && other.type === "radio" && other.name === match.name) other.checked = false;
969
+ }
970
+ } else if (controls.length) {
971
+ controls[0].value = str;
972
+ }
973
+ this._syncFormValue();
974
+ }
975
+ checkValidity() {
976
+ return this._internals ? this._internals.checkValidity() : true;
977
+ }
978
+ reportValidity() {
979
+ return this._internals ? this._internals.reportValidity() : true;
980
+ }
981
+
982
+ // Keep internals in step with the group. Checking radio B fires `change` on
983
+ // B only — the deselected host A hears nothing, so its internals keep the
984
+ // stale "a" and the entry list collects both ("g=a","g=b"; measured by the
985
+ // form-lifecycle probe, 2026-10-28). Re-syncing in the `formdata` handler
986
+ // is too late: the entry list has already copied each host's internals
987
+ // before that event fires. `change` bubbles through the shared form, so a
988
+ // same-name host re-derives its value the moment B is checked — before any
989
+ // collection can read it.
990
+ _wireFormData() {
991
+ if (!this._internals || this._wiredFormData) return;
992
+ const form = this._internals.form;
993
+ if (!form) return;
994
+ this._wiredFormData = true;
995
+ const myName = this.getAttribute("name");
996
+ const onFormChange = (e) => {
997
+ const t = e.target;
998
+ if (t && t.type === "radio" && t.name && t.name === myName) this._syncFormValue();
999
+ };
1000
+ form.addEventListener("change", onFormChange);
1001
+ const onFormData = () => this._syncFormValue();
1002
+ form.addEventListener("formdata", onFormData);
1003
+ onDispose(this, () => {
1004
+ form.removeEventListener("change", onFormChange);
1005
+ form.removeEventListener("formdata", onFormData);
1006
+ });
1007
+ }
1008
+
1009
+ // User-dirty value tracking (R20 T-02). The restore path only fills
1010
+ // controls a render left empty, so a host with an authored `value`
1011
+ // attribute overwrote whatever the user typed on every unrelated
1012
+ // attribute change. A control the user actually edited — an `input` or
1013
+ // `change` event, which programmatic `.value` writes do not fire — is
1014
+ // marked dirty together with the host's `value` attribute at that moment;
1015
+ // `_restoreControlValue` keeps the typed value until the author changes
1016
+ // that attribute. Scoped to form-associated hosts: their controls carry
1017
+ // the submission contract, and a non-form widget that clears its own
1018
+ // field on re-render keeps that behaviour. Delegated on the host (rule
1019
+ // 12): the controls are rebuilt on every render.
1020
+ _wireValueTracking() {
1021
+ if (!this._internals || this._wiredValueTracking) return;
1022
+ this._wiredValueTracking = true;
1023
+ const mark = (e) => {
1024
+ const t = e.target;
1025
+ if (!t || !t.matches || !t.matches("input, textarea, select")) return;
1026
+ if (this._ownerBetween(t, this)) return;
1027
+ t._contourUserDirty = true;
1028
+ t._contourAttrAtDirty = this.getAttribute("value");
1029
+ };
1030
+ this.addEventListener("input", mark);
1031
+ this.addEventListener("change", mark);
1032
+ }
1033
+
1034
+ // Restore one control's value from its snapshot (R20 T-02/T-06). A
1035
+ // user-dirty control keeps its typed value — a multi-select its whole
1036
+ // selection, not just the first selected option — until the host's
1037
+ // `value` attribute changes. Otherwise the original rule stands: only a
1038
+ // control the render left empty, with no value attribute of its own,
1039
+ // takes the saved value. The dirty mark is re-applied to the rebuilt
1040
+ // control so the NEXT re-render preserves it too.
1041
+ _restoreControlValue(el, saved) {
1042
+ if (saved.dirty && saved.attrAtDirty === this.getAttribute("value")) {
1043
+ if (saved.selected && el.tagName === "SELECT" && el.multiple) {
1044
+ const wanted = new Set(saved.selected);
1045
+ for (const o of el.options) o.selected = wanted.has(o.value);
1046
+ } else {
1047
+ el.value = saved.value;
1048
+ }
1049
+ el._contourUserDirty = true;
1050
+ el._contourAttrAtDirty = saved.attrAtDirty;
1051
+ return;
1052
+ }
1053
+ if (el.value === "" && el.getAttribute("value") === null) el.value = saved.value;
1054
+ }
1055
+
1056
+ // The inner native control(s) are scaffolding; the host reports through
1057
+ // ElementInternals. A same-name native control inside a <form> would submit
1058
+ // a second entry with the same name — double submission, measured as
1059
+ // ["g=a","g=a"] in a two-entry FormData (2026-10-27, form-lifecycle probe).
1060
+ // form="" (no matching form element) detaches it from the form owner while
1061
+ // keeping native radio-group semantics: same name, same tree, both
1062
+ // form-ownerless → they still share one checked state.
1063
+ _detachInnerFormControls() {
1064
+ if (!this._internals) return;
1065
+ for (const ctl of this.querySelectorAll("input, textarea, select")) {
1066
+ if (ctl.hasAttribute("name") && ctl.getAttribute("form") !== "") ctl.setAttribute("form", "");
1067
+ }
1068
+ }
1069
+
1070
+ // Opt-in batching: coalesce multiple attribute changes into a single
1071
+ // render. Usage: el.batch(() => { el.value = 42; el.delta = "+3"; });
1072
+ // The render fires once when the callback returns, reading all final
1073
+ // attribute values. Nested calls are supported.
1074
+ /** Coalesce synchronous property changes into one render. */
1075
+ batch(fn) {
1076
+ if (typeof fn !== "function") return;
1077
+ this._batchDepth = (this._batchDepth || 0) + 1;
1078
+ this._batchDirty = this._batchDirty || false;
1079
+ try {
1080
+ fn();
1081
+ } finally {
1082
+ this._batchDepth -= 1;
1083
+ if (this._batchDepth === 0 && this._batchDirty) {
1084
+ this._batchDirty = false;
1085
+ // Trigger a single re-render with current attribute values.
1086
+ if (this.isConnected && this._contourAuthored) {
1087
+ this.attributeChangedCallback("__rerender__", null, "");
1088
+ }
1089
+ }
1090
+ }
1091
+ }
1092
+
1093
+ // Ask for a re-render without naming the attribute that changed, for work the
1094
+ // host started itself — a `src` fetch that resolved, a timer, an observer. A
1095
+ // render body must never reach for `attributeChangedCallback` directly: on the
1096
+ // connect path `_contourRendering` is still false, so that call performs a
1097
+ // synchronous nested re-render and the outer body then carries on painting the
1098
+ // node the nested pass already painted. Measured in Chromium (tmp/wc9/probe.mjs,
1099
+ // 2026-10-27): a host with `src` rendered "Loading…Loading…" — two nodes — while
1100
+ // the identical host with an authored `loading` attribute rendered one.
1101
+ //
1102
+ // Deferring to a microtask lets the in-flight render finish before the next one
1103
+ // starts, and the flag coalesces N asks in one pass into one render. It runs
1104
+ // through the same reset/restore path as an attribute change, so a consumer's
1105
+ // authored nodes and focus survive it exactly as they survive a real change.
1106
+ requestRender() {
1107
+ if (this._contourRerenderQueued) return;
1108
+ this._contourRerenderQueued = true;
1109
+ queueMicrotask(() => {
1110
+ this._contourRerenderQueued = false;
1111
+ if (!this.isConnected || !this._contourAuthored) return;
1112
+ this.attributeChangedCallback("__rerender__", null, "");
1113
+ });
1114
+ }
1115
+
1116
+ // Expose ::part() hooks on every generated node whose class follows the
1117
+ // `c-<block>__<element>` convention, so a consumer can theme internals
1118
+ // without shadow DOM. Runs after render() in both connect and re-render.
1119
+ _applyParts(root) {
1120
+ const scope = root || this;
1121
+ const nodes = scope.querySelectorAll ? Array.from(scope.querySelectorAll("[class]")) : [];
1122
+ for (const node of nodes) {
1123
+ if (node.hasAttribute("part")) continue;
1124
+ if (typeof node.className !== "string") continue;
1125
+ for (const c of node.className.split(/\s+/)) {
1126
+ const m = c.match(/^c-[a-z0-9-]+__([a-z0-9-]+)$/);
1127
+ if (m) { node.setAttribute("part", m[1]); break; }
1128
+ }
1129
+ }
1130
+ }
1131
+
1132
+ // Density modifier (BY-48). The sheet hooks on `[data-density]` — the
1133
+ // attribute the token layer ships with (`--density`, `--density-compact`
1134
+ // in tokens.css) — so the wc layer exposes a `density` attribute and
1135
+ // mirrors it to `data-density` on the host. `data-density` is not in
1136
+ // OBSERVED, so the write cannot re-enter the render this runs from.
1137
+ _applyDensity() {
1138
+ const density = this.getAttribute("density");
1139
+ if (density !== null) this.setAttribute("data-density", density);
1140
+ else if (this.hasAttribute("data-density")) this.removeAttribute("data-density");
1141
+ }
1142
+
1143
+ // The closest host above `node` on the way up to `root`, or null when the
1144
+ // path never crosses another host. `ensure()` may only reuse a node its own
1145
+ // host owns: querySelector reaches straight through a nested host's
1146
+ // boundary, so two blocks that both carry a `__title` would share one
1147
+ // element and the outer render would write the inner one's text.
1148
+ _ownerBetween(node, root) {
1149
+ for (let p = node.parentElement; p && p !== root; p = p.parentElement) {
1150
+ if (p instanceof ContourBase) return p;
1151
+ }
1152
+ return null;
1153
+ }
1154
+
1155
+ // Helper for update-or-create reactivity: returns the first node matching
1156
+ // `selector`, creating it via `factory()` and appending it if absent. Render
1157
+ // bodies use this so an attribute change updates the existing node instead
1158
+ // of being blocked by a `!querySelector` guard.
1159
+ //
1160
+ // A per-render cache avoids re-querying the subtree for every ensure() call
1161
+ // in the same render pass (O(k*n) -> O(n+k)). The cache is keyed by the
1162
+ // scope it was read from as well as the selector, because a `parent` that is
1163
+ // not the host survives the next render's node reset while its cached match
1164
+ // does not — a detached element handed back instead of a fresh one appended.
1165
+ ensure(selector, factory, parent) {
1166
+ const root = parent || this;
1167
+ if (!root._ensureCache || root._ensureCacheGen !== this._contourRenderGen) {
1168
+ root._ensureCache = new Map();
1169
+ root._ensureCacheGen = this._contourRenderGen;
1170
+ }
1171
+ const cache = root._ensureCache;
1172
+ const key = root === this ? selector : "\u0000" + root + "\u0000" + selector;
1173
+ let node = cache.get(key);
1174
+ if (node === undefined) {
1175
+ // First match this host owns, skipping anything inside a nested host.
1176
+ node = null;
1177
+ for (const candidate of root.querySelectorAll(selector)) {
1178
+ if (!this._ownerBetween(candidate, root)) { node = candidate; break; }
1179
+ }
1180
+ cache.set(key, node);
1181
+ }
1182
+ if (!node) {
1183
+ node = factory();
1184
+ // Expose a ::part() hook for every generated element, so a consumer
1185
+ // can theme internals without shadow DOM. The part name is the element
1186
+ // name after the block's `__` separator (e.g. .c-card__title -> "title").
1187
+ if (node && node.setAttribute && !node.hasAttribute("part")) {
1188
+ const m = String(selector).match(/\.c-[a-z0-9-]+__([a-z0-9-]+)/);
1189
+ if (m) node.setAttribute("part", m[1]);
1190
+ }
1191
+ root.appendChild(node);
1192
+ cache.set(key, node);
1193
+ }
1194
+ return node;
1195
+ }
1196
+ }
1197
+
1198
+ // Brownout mixin (G-16): opt-in base for components that shed non-essential
1199
+ // chrome under degraded conditions. Merges `brownout` / `brownout-level`
1200
+ // into the subclass observed list and exposes the helpers already on
1201
+ // ContourBase. Usage: `class Foo extends withBrownout(ContourBase) { ... }`.
1202
+ export function withBrownout(Base) {
1203
+ return class extends Base {
1204
+ static get observed() {
1205
+ const base = (super.observed && Array.isArray(super.observed)) ? super.observed : [];
1206
+ const extra = ["brownout", "brownout-level"];
1207
+ return Array.from(new Set(base.concat(extra)));
1208
+ }
1209
+ brownoutLevel() { return super.brownoutLevel ? super.brownoutLevel() : (parseInt(this.getAttribute("brownout-level") || this.getAttribute("brownout") || "0", 10) || 0); }
1210
+ shed(kind, threshold) { return this.brownoutLevel() >= (threshold || 1); }
1211
+ };
1212
+ }
1213
+
1214
+ // Simple component: just adds CSS classes.
1215
+ /** Create a light-DOM component that only applies block and modifier classes. */
1216
+ export const simple = (classes) => class extends ContourBase {
1217
+ render() {
1218
+ classes.forEach((c) => this.classList.add(c));
1219
+ // Remove stale modifier classes first so attribute removal is reflected.
1220
+ for (const c of Array.from(this.classList)) {
1221
+ if (classes.some((base) => c.startsWith(base + "--"))) this.classList.remove(c);
1222
+ }
1223
+ MODS.forEach((attr) => {
1224
+ if (this.hasAttribute(attr)) {
1225
+ const val = this.getAttribute(attr);
1226
+ classes.forEach((c) => {
1227
+ const prefix = c.replace("c-", "");
1228
+ this.classList.add(`c-${prefix}--${val}`);
1229
+ });
1230
+ }
1231
+ });
1232
+ }
1233
+ };
1234
+
1235
+ // ---- Class-only blocks ----
1236
+ //
1237
+ // A block in this list needs nothing but its own class: the element name is
1238
+ // \`contour-<block>\` and the class is \`c-<block>\`, which is why the table holds
1239
+ // the block and not two spellings of it. Blocks that need scaffolding are not
1240
+ // here — they declare a class above, and their presence in this list would be
1241
+ // a fallback that only runs when the real component is broken, so the
1242
+ // registration loop skips a name an explicit component already claimed.
1243
+ /** Blocks whose custom elements need no generated markup. */
1244
+ export const CLASS_ONLY = [
1245
+ "box", "cluster", "container", "row", "scrim", "stack"
1246
+ ];
1247
+
1248
+ // Feature detection for `hidden="until-found"` (BY-51). Browsers that do not
1249
+ // support it treat the value as the boolean hidden attribute, which would
1250
+ // hide the content permanently — so we only upgrade where supported.
1251
+ /** Detect support for the non-destructive `hidden="until-found"` value. */
1252
+ export function supportsUntilFound() {
1253
+ try {
1254
+ const t = document.createElement("div");
1255
+ t.setAttribute("hidden", "until-found");
1256
+ return t.getAttribute("hidden") === "until-found";
1257
+ } catch (e) { return false; }
1258
+ }
1259
+
1260
+ // Value formatting (BY-31/BY-22): opt-in Intl formatting for kpi/stat/readout/coordinate.
1261
+ // `format` is a preset ("number","currency","percent","compact","date","time",
1262
+ // "unit","relative") or a JSON string of Intl.NumberFormat/DateTimeFormat/
1263
+ // RelativeTimeFormat options. `locale` defaults to the runtime locale.
1264
+ // Returns the raw value when formatting fails.
1265
+ /** Format a value with the component's supported Intl presets. */
1266
+ export function formatValue(value, format, locale, unit) {
1267
+ if (!format) return value;
1268
+ const loc = locale || (typeof navigator !== "undefined" && navigator.language) || "en";
1269
+ if (format === "date" || format === "time") {
1270
+ try {
1271
+ const opts = format === "time" ? { timeStyle: "short" } : undefined;
1272
+ return new Intl.DateTimeFormat(loc, opts).format(new Date(value));
1273
+ } catch (e) { return value; }
1274
+ }
1275
+ if (format === "relative") {
1276
+ try {
1277
+ const num = Number(value);
1278
+ // Interpret the value as seconds from now unless it is an ISO date.
1279
+ let seconds = num;
1280
+ if (Number.isNaN(num)) {
1281
+ const then = new Date(value).getTime();
1282
+ if (Number.isFinite(then)) seconds = (then - Date.now()) / 1000;
1283
+ }
1284
+ const rtf = new Intl.RelativeTimeFormat(loc, { numeric: "auto" });
1285
+ if (Math.abs(seconds) < 60) return rtf.format(Math.round(seconds), "second");
1286
+ if (Math.abs(seconds) < 3600) return rtf.format(Math.round(seconds / 60), "minute");
1287
+ if (Math.abs(seconds) < 86400) return rtf.format(Math.round(seconds / 3600), "hour");
1288
+ return rtf.format(Math.round(seconds / 86400), "day");
1289
+ } catch (e) { return value; }
1290
+ }
1291
+ let opts = {};
1292
+ if (format === "currency") opts = { style: "currency", currency: "USD" };
1293
+ else if (format === "percent") opts = { style: "percent" };
1294
+ else if (format === "compact") opts = { notation: "compact" };
1295
+ else if (format === "unit") opts = { style: "unit", unit: unit || "meter" };
1296
+ else if (format !== "number") {
1297
+ try { opts = JSON.parse(format); } catch (e) { return value; }
1298
+ }
1299
+ try { return new Intl.NumberFormat(loc, opts).format(Number(value)); }
1300
+ catch (e) { return value; }
1301
+ }
1302
+
1303
+ // Shared keyboard navigation for roving-tabindex patterns.
1304
+ // `items`: array of focusable elements, `e`: KeyboardEvent.
1305
+ // Options: `{ wrap (default true), enter (default true), homeEnd (false),
1306
+ // onKey(key, idx, item) }` — return truthy to preventDefault.
1307
+ // `onNavigate(newIdx)` — called after focus moves with new index.
1308
+ // `rtl` — if true, ArrowRight/Left swap direction; defaults to dir attribute.
1309
+ /** Navigate a roving-tabindex group with arrow keys, Home/End, Enter/Space. */
1310
+ export function navKey(e, items, { wrap = true, enter = true, homeEnd = false, onKey, onNavigate, rtl } = {}) {
1311
+ const idx = items.indexOf(document.activeElement);
1312
+ if (idx < 0) return;
1313
+ let next = -1;
1314
+ // Determine direction: ArrowRight/Down always advance forward in LTR.
1315
+ // With RTL, ArrowRight goes back and ArrowLeft goes forward.
1316
+ const fwdKey = rtl ? "ArrowLeft" : "ArrowRight";
1317
+ const revKey = rtl ? "ArrowRight" : "ArrowLeft";
1318
+ if (e.key === fwdKey || e.key === "ArrowDown") next = wrap ? (idx + 1) % items.length : Math.min(idx + 1, items.length - 1);
1319
+ else if (e.key === revKey || e.key === "ArrowUp") next = wrap ? (idx - 1 + items.length) % items.length : Math.max(0, idx - 1);
1320
+ else if ((homeEnd || wrap) && e.key === "Home") next = 0;
1321
+ else if ((homeEnd || wrap) && e.key === "End") next = items.length - 1;
1322
+ if (next >= 0 && next !== idx) {
1323
+ e.preventDefault();
1324
+ try { items[next].focus(); } catch (_) {}
1325
+ if (onNavigate) onNavigate(next);
1326
+ if (onKey) onKey(e.key, idx, items[idx]);
1327
+ } else if ((enter || wrap) && (e.key === "Enter" || e.key === " ")) {
1328
+ e.preventDefault();
1329
+ if (onKey) onKey(e.key, idx, items[idx]);
1330
+ }
1331
+ }
1332
+
1333
+ // Resolve RTL direction from element or document. Returns true for RTL layout.
1334
+ /** Check whether the given element uses right-to-left text direction. */
1335
+ export function isRtl(el) {
1336
+ let node = el;
1337
+ while (node && node.nodeType === 1) {
1338
+ const d = node.getAttribute && node.getAttribute("dir");
1339
+ if (d) return d.toLowerCase() === "rtl";
1340
+ node = node.parentElement;
1341
+ }
1342
+ try { return (typeof document !== "undefined" && (document.documentElement.getAttribute("dir") || "").toLowerCase() === "rtl"); }
1343
+ catch (e) { return false; }
1344
+ }
1345
+
1346
+ // Spatial maths (BY-23): pure functions on the host's own attributes.
1347
+ // Haversine distance in meters between two lat/lon points.
1348
+ /** Return the great-circle distance between two latitude/longitude points. */
1349
+ export function haversine(lat1, lon1, lat2, lon2) {
1350
+ const R = 6371000;
1351
+ const toRad = (d) => d * Math.PI / 180;
1352
+ const dLat = toRad(lat2 - lat1);
1353
+ const dLon = toRad(lon2 - lon1);
1354
+ const a = Math.sin(dLat / 2) ** 2 + Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(dLon / 2) ** 2;
1355
+ return 2 * R * Math.asin(Math.sqrt(a));
1356
+ }
1357
+ // Bearing in degrees (clockwise from north) from point 1 to point 2.
1358
+ /** Return the initial bearing from one latitude/longitude point to another. */
1359
+ export function bearing(lat1, lon1, lat2, lon2) {
1360
+ const toRad = (d) => d * Math.PI / 180;
1361
+ const toDeg = (r) => r * 180 / Math.PI;
1362
+ const dLon = toRad(lon2 - lon1);
1363
+ const y = Math.sin(dLon) * Math.cos(toRad(lat2));
1364
+ const x = Math.cos(toRad(lat1)) * Math.sin(toRad(lat2)) - Math.sin(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.cos(dLon);
1365
+ return (toDeg(Math.atan2(y, x)) + 360) % 360;
1366
+ }
1367
+ // Mercator resolution (meters per pixel) at a given latitude and zoom.
1368
+ /** Return meters per pixel for Web Mercator at a latitude and zoom level. */
1369
+ export function mercatorResolution(lat, zoom) {
1370
+ return 156543.03392 * Math.cos(lat * Math.PI / 180) / Math.pow(2, zoom);
1371
+ }
1372
+
1373
+ /* ============================================================================
1374
+ CONTOUR — SVG geometry helpers (pure functions, zero dependencies)
1375
+ ----------------------------------------------------------------------------
1376
+ Lightweight path generators for the spatial chart variants that Contour's
1377
+ CSS already styles (.c-chart--donut, .c-chart--histogram, .c-sparkline).
1378
+ They return strings suitable for an SVG `d` attribute or a list of
1379
+ {x, y, width, height} rectangles, so a consumer never has to hand-compute
1380
+ arc math or bar widths for a basic cartographic control.
1381
+
1382
+ Every function is pure: no DOM, no state, no side effects. They are
1383
+ exported so a consumer can import them directly, and the chart component
1384
+ uses them when its `series` attribute carries structured data rather than
1385
+ a pre-computed path string.
1386
+ ========================================================================= */
1387
+ "use strict";
1388
+
1389
+ /**
1390
+ * Build an SVG arc path for a single donut slice.
1391
+ *
1392
+ * @param {number} cx centre x
1393
+ * @param {number} cy centre y
1394
+ * @param {number} r outer radius
1395
+ * @param {number} inner inner radius (0 for a pie)
1396
+ * @param {number} startAngle start angle in radians
1397
+ * @param {number} endAngle end angle in radians
1398
+ * @returns {string} SVG path `d` attribute
1399
+ */
1400
+ /** Build an SVG arc path string. */
1401
+ export function arcPath(cx, cy, r, inner, startAngle, endAngle) {
1402
+ // Clamp non-finite inputs so a bad value cannot emit NaN/Infinity into the
1403
+ // path string (B3-22). A degenerate slice collapses to a point.
1404
+ cx = Number.isFinite(cx) ? cx : 0;
1405
+ cy = Number.isFinite(cy) ? cy : 0;
1406
+ r = Number.isFinite(r) && r > 0 ? r : 0;
1407
+ inner = Number.isFinite(inner) && inner >= 0 ? inner : 0;
1408
+ startAngle = Number.isFinite(startAngle) ? startAngle : 0;
1409
+ endAngle = Number.isFinite(endAngle) ? endAngle : 0;
1410
+ const largeArc = endAngle - startAngle > Math.PI ? 1 : 0;
1411
+ const x1 = cx + r * Math.cos(startAngle);
1412
+ const y1 = cy + r * Math.sin(startAngle);
1413
+ const x2 = cx + r * Math.cos(endAngle);
1414
+ const y2 = cy + r * Math.sin(endAngle);
1415
+ if (inner <= 0) {
1416
+ return `M ${cx} ${cy} L ${x1} ${y1} A ${r} ${r} 0 ${largeArc} 1 ${x2} ${y2} Z`;
1417
+ }
1418
+ const ix1 = cx + inner * Math.cos(endAngle);
1419
+ const iy1 = cy + inner * Math.sin(endAngle);
1420
+ const ix2 = cx + inner * Math.cos(startAngle);
1421
+ const iy2 = cy + inner * Math.sin(startAngle);
1422
+ return `M ${x1} ${y1} A ${r} ${r} 0 ${largeArc} 1 ${x2} ${y2} L ${ix1} ${iy1} A ${inner} ${inner} 0 ${largeArc} 0 ${ix2} ${iy2} Z`;
1423
+ }
1424
+
1425
+ /**
1426
+ * Convert a list of values into donut slice paths.
1427
+ *
1428
+ * @param {number[]} values
1429
+ * @param {object} [opts]
1430
+ * @param {number} [opts.cx=100]
1431
+ * @param {number} [opts.cy=100]
1432
+ * @param {number} [opts.r=90]
1433
+ * @param {number} [opts.inner=55]
1434
+ * @param {number} [opts.gap=0.02] angular gap between slices in radians
1435
+ * @returns {{path: string, value: number, index: number}[]}
1436
+ */
1437
+ /** Compute donut slice geometry. */
1438
+ export function donutSlices(values, opts) {
1439
+ opts = opts || {};
1440
+ const cx = opts.cx != null ? opts.cx : 100;
1441
+ const cy = opts.cy != null ? opts.cy : 100;
1442
+ const r = opts.r != null ? opts.r : 90;
1443
+ const inner = opts.inner != null ? opts.inner : 55;
1444
+ const gap = opts.gap != null ? opts.gap : 0.02;
1445
+ const total = values.reduce((a, b) => a + (Number(b) || 0), 0) || 1;
1446
+ let angle = -Math.PI / 2;
1447
+ const out = [];
1448
+ values.forEach((v, i) => {
1449
+ const num = Number(v) || 0;
1450
+ const frac = num / total;
1451
+ if (!(num > 0)) { angle += frac * Math.PI * 2; return; }
1452
+ const sweep = frac * Math.PI * 2 - gap;
1453
+ const start = angle + gap / 2;
1454
+ const end = start + Math.max(0, sweep);
1455
+ out.push({ path: arcPath(cx, cy, r, inner, start, end), value: num, index: i });
1456
+ angle += frac * Math.PI * 2;
1457
+ });
1458
+ return out;
1459
+ }
1460
+
1461
+ /**
1462
+ * Compute bar rectangles for a histogram.
1463
+ *
1464
+ * @param {number[]} values
1465
+ * @param {object} [opts]
1466
+ * @param {number} [opts.width=300]
1467
+ * @param {number} [opts.height=120]
1468
+ * @param {number} [opts.gap=2]
1469
+ * @param {number} [opts.max] override max value (defaults to max of values)
1470
+ * @returns {{x:number,y:number,width:number,height:number}[]}
1471
+ */
1472
+ /** Compute bar rectangle geometry. */
1473
+ export function barRects(values, opts) {
1474
+ opts = opts || {};
1475
+ const width = opts.width != null ? opts.width : 300;
1476
+ const height = opts.height != null ? opts.height : 120;
1477
+ const gap = opts.gap != null ? opts.gap : 2;
1478
+ const max = opts.max != null ? opts.max : (Math.max.apply(null, values.map((v) => Number(v) || 0)) || 1);
1479
+ if (!Number.isFinite(max) || max <= 0) return values.map(() => ({ x: 0, y: height, width: 0, height: 0 }));
1480
+ const n = values.length || 1;
1481
+ const slot = width / n;
1482
+ const barW = Math.max(1, slot - gap);
1483
+ return values.map((v, i) => {
1484
+ const h = ((Number(v) || 0) / max) * height;
1485
+ return { x: i * slot + gap / 2, y: height - h, width: barW, height: h };
1486
+ });
1487
+ }
1488
+
1489
+ /**
1490
+ * Build an SVG polyline `points` attribute from a list of numbers.
1491
+ *
1492
+ * @param {number[]} values
1493
+ * @param {object} [opts]
1494
+ * @param {number} [opts.width=300]
1495
+ * @param {number} [opts.height=120]
1496
+ * @param {number} [opts.max] override max
1497
+ * @param {number} [opts.min] override min
1498
+ * @returns {string} "x,y x,y ..."
1499
+ */
1500
+ /** Compute polyline point string. */
1501
+ export function polylinePoints(values, opts) {
1502
+ opts = opts || {};
1503
+ const width = opts.width != null ? opts.width : 300;
1504
+ const height = opts.height != null ? opts.height : 120;
1505
+ const nums = values.map((v) => Number(v) || 0);
1506
+ if (!nums.length) return "";
1507
+ const max = opts.max != null ? opts.max : Math.max.apply(null, nums);
1508
+ const min = opts.min != null ? opts.min : Math.min.apply(null, nums);
1509
+ const range = (Number.isFinite(max - min) && (max - min) !== 0) ? (max - min) : 1;
1510
+ const n = nums.length || 1;
1511
+ return nums.map((v, i) => {
1512
+ const x = (i / Math.max(1, n - 1)) * width;
1513
+ const y = height - ((v - min) / range) * height;
1514
+ return x.toFixed(2) + "," + y.toFixed(2);
1515
+ }).join(" ");
1516
+ }
1517
+
1518
+ /**
1519
+ * Build a smooth (monotone) SVG path through a list of numbers.
1520
+ *
1521
+ * @param {number[]} values
1522
+ * @param {object} [opts] same as polylinePoints
1523
+ * @returns {string} SVG path `d` attribute
1524
+ */
1525
+ /** Compute a smoothed SVG path. */
1526
+ export function smoothPath(values, opts) {
1527
+ const pts = polylinePoints(values, opts).split(" ").map((p) => p.split(",").map(Number));
1528
+ if (!pts.length) return "";
1529
+ let d = `M ${pts[0][0]} ${pts[0][1]}`;
1530
+ for (let i = 1; i < pts.length; i++) {
1531
+ const prev = pts[i - 1];
1532
+ const cur = pts[i];
1533
+ const cpx = (prev[0] + cur[0]) / 2;
1534
+ d += ` C ${cpx} ${prev[1]}, ${cpx} ${cur[1]}, ${cur[0]} ${cur[1]}`;
1535
+ }
1536
+ return d;
1537
+ }
1538
+
1539
+ /**
1540
+ * Build an SVG path for a compass needle pointing at `angleDeg` (clockwise
1541
+ * from north/up). The needle is a thin triangle from the centre to the tip,
1542
+ * with a short tail in the opposite direction.
1543
+ *
1544
+ * @param {number} cx centre x
1545
+ * @param {number} cy centre y
1546
+ * @param {number} length needle length (tip distance from centre)
1547
+ * @param {number} [angleDeg=0] bearing in degrees, clockwise from up
1548
+ * @param {number} [width=3] half-width of the needle at the base
1549
+ * @returns {string} SVG path `d` attribute
1550
+ */
1551
+ /** Compute compass needle geometry. */
1552
+ export function compassNeedle(cx, cy, length, angleDeg, width) {
1553
+ angleDeg = angleDeg == null ? 0 : angleDeg;
1554
+ width = width == null ? 3 : width;
1555
+ const a = (angleDeg - 90) * Math.PI / 180; // 0deg = up
1556
+ const tipX = cx + length * Math.cos(a);
1557
+ const tipY = cy + length * Math.sin(a);
1558
+ const tail = length * 0.25;
1559
+ const tailX = cx - tail * Math.cos(a);
1560
+ const tailY = cy - tail * Math.sin(a);
1561
+ const perpX = Math.cos(a + Math.PI / 2);
1562
+ const perpY = Math.sin(a + Math.PI / 2);
1563
+ const b1x = cx + width * perpX;
1564
+ const b1y = cy + width * perpY;
1565
+ const b2x = cx - width * perpX;
1566
+ const b2y = cy - width * perpY;
1567
+ return `M ${tipX.toFixed(2)} ${tipY.toFixed(2)} L ${b1x.toFixed(2)} ${b1y.toFixed(2)} L ${tailX.toFixed(2)} ${tailY.toFixed(2)} L ${b2x.toFixed(2)} ${b2y.toFixed(2)} Z`;
1568
+ }
1569
+
1570
+ /**
1571
+ * Compute tick values for a scale bar.
1572
+ *
1573
+ * @param {number} value total value (max)
1574
+ * @param {number} [segments=4] number of segments
1575
+ * @returns {number[]} tick values from 0 to value inclusive
1576
+ */
1577
+ /** Compute scale bar tick positions. */
1578
+ export function scaleBarTicks(value, segments) {
1579
+ value = Number(value) || 0;
1580
+ segments = Math.max(1, Math.round(segments || 4));
1581
+ const out = [];
1582
+ for (let i = 0; i <= segments; i++) {
1583
+ out.push((value / segments) * i);
1584
+ }
1585
+ return out;
1586
+ }
1587
+ // Marker shape encoding utility (G-13)
1588
+ /** Supported marker shapes for chart series. */
1589
+ export const MARKER_SHAPES = ["circle", "square", "triangle", "diamond", "star"];
1590
+ /** Return CSS styles for a marker shape. */
1591
+ export function markerStyles(shape) {
1592
+ const map = {
1593
+ circle: "border-radius:50%",
1594
+ square: "border-radius:0",
1595
+ triangle: "clip-path:polygon(50% 0%,0% 100%,100% 100%)",
1596
+ diamond: "transform:rotate(45deg)",
1597
+ star: "clip-path:polygon(50% 0%,61% 35%,98% 35%,68% 57%,79% 91%,50% 70%,21% 91%,32% 57%,2% 35%,39% 35%)",
1598
+ };
1599
+ return map[shape] || "";
1600
+ }
1601
+ /** Assign marker shapes to chart items. */
1602
+ export function assignMarkers(items) {
1603
+ return (items || []).map((it, i) => ({ ...it, marker: MARKER_SHAPES[i % MARKER_SHAPES.length] }));
1604
+ }
1605
+
1606
+ /* ---------------------------------------------------------------------------
1607
+ * Contour lines — marching squares over a 2D field.
1608
+ *
1609
+ * The same algorithm as tools/contour-gen.py, ported to the browser. Iso-lines
1610
+ * of different levels of one continuous field cannot cross; the asymptotic
1611
+ * saddle decider below is what guarantees that, so a hand-drawn path is never
1612
+ * a substitute. Shared by the `contour-contour-plot` element and the guide's
1613
+ * `data-contour-plot` renderer so the two cannot drift.
1614
+ * ------------------------------------------------------------------------- */
1615
+
1616
+ /**
1617
+ * Extract the iso-line segments of a scalar field at one level.
1618
+ *
1619
+ * @param {number[][]} grid row-major field values
1620
+ * @param {number} level iso-level to extract
1621
+ * @returns {Array<[{x:number,y:number},{x:number,y:number}]>} segments in grid space
1622
+ */
1623
+ export function marchingSquares(grid, level) {
1624
+ const rows = grid.length;
1625
+ const cols = rows ? grid[0].length : 0;
1626
+ const segments = [];
1627
+ if (!rows || !cols) return segments;
1628
+
1629
+ const lerp = (a, b, va, vb) => (vb === va ? 0.5 : (level - va) / (vb - va));
1630
+
1631
+ for (let y = 0; y < rows - 1; y++) {
1632
+ for (let x = 0; x < cols - 1; x++) {
1633
+ const tl = grid[y][x];
1634
+ const tr = grid[y][x + 1];
1635
+ const bl = grid[y + 1][x];
1636
+ const br = grid[y + 1][x + 1];
1637
+ const code =
1638
+ (tl >= level ? 8 : 0) |
1639
+ (tr >= level ? 4 : 0) |
1640
+ (br >= level ? 2 : 0) |
1641
+ (bl >= level ? 1 : 0);
1642
+ if (code === 0 || code === 15) continue;
1643
+
1644
+ const top = { x: x + lerp(tl, tr, tl, tr), y };
1645
+ const right = { x: x + 1, y: y + lerp(tr, br, tr, br) };
1646
+ const bottom = { x: x + lerp(bl, br, bl, br), y: y + 1 };
1647
+ const left = { x, y: y + lerp(tl, bl, tl, bl) };
1648
+
1649
+ let connect;
1650
+ if (code === 5) {
1651
+ const center = (tl + tr + bl + br) / 4;
1652
+ connect = center >= level ? "top-bottom" : "left-right";
1653
+ } else if (code === 10) {
1654
+ const center = (tl + tr + bl + br) / 4;
1655
+ connect = center >= level ? "left-right" : "top-bottom";
1656
+ }
1657
+
1658
+ switch (code) {
1659
+ case 1: case 14: segments.push([left, bottom]); break;
1660
+ case 2: case 13: segments.push([bottom, right]); break;
1661
+ case 3: case 12: segments.push([left, right]); break;
1662
+ case 4: case 11: segments.push([top, right]); break;
1663
+ case 6: case 9: segments.push([top, bottom]); break;
1664
+ case 7: case 8: segments.push([left, top]); break;
1665
+ case 5:
1666
+ if (connect === "top-bottom") {
1667
+ segments.push([top, bottom], [left, right]);
1668
+ } else {
1669
+ segments.push([top, right], [left, bottom]);
1670
+ }
1671
+ break;
1672
+ case 10:
1673
+ if (connect === "left-right") {
1674
+ segments.push([left, right], [top, bottom]);
1675
+ } else {
1676
+ segments.push([top, right], [left, bottom]);
1677
+ }
1678
+ break;
1679
+ }
1680
+ }
1681
+ }
1682
+ return segments;
1683
+ }
1684
+
1685
+ /**
1686
+ * Build the SVG `d` path for every level of a field.
1687
+ *
1688
+ * @param {number[][]} grid row-major field values
1689
+ * @param {number[]} levels iso-levels, one path per level
1690
+ * @param {number} width viewBox width in px
1691
+ * @param {number} height viewBox height in px
1692
+ * @returns {Array<{level:number, d:string}>} one entry per level
1693
+ */
1694
+ export function contourPaths(grid, levels, width, height) {
1695
+ const rows = grid.length;
1696
+ const cols = rows ? grid[0].length : 0;
1697
+ if (rows < 2 || cols < 2) return [];
1698
+ const sx = width / (cols - 1);
1699
+ const sy = height / (rows - 1);
1700
+ return (levels || []).map((level) => {
1701
+ const segs = marchingSquares(grid, level);
1702
+ let d = "";
1703
+ for (const [a, b] of segs) {
1704
+ d += `M ${(a.x * sx).toFixed(2)} ${(a.y * sy).toFixed(2)} L ${(b.x * sx).toFixed(2)} ${(b.y * sy).toFixed(2)} `;
1705
+ }
1706
+ return { level, d: d.trim() };
1707
+ });
1708
+ }
1709
+
1710
+ /* ============================================================================
1711
+ CONTOUR — shared behaviour
1712
+ ----------------------------------------------------------------------------
1713
+ One implementation of each interaction, called by both layers: the light-DOM
1714
+ wrappers and the `contour-shadow-*` wrappers.
1715
+
1716
+ Before this file the two layers each carried a copy, and the copies had
1717
+ already drifted in the one direction source review cannot see: the shadow copy
1718
+ queried its own root for nodes the author slots into the light DOM, so it
1719
+ found nothing and wired nothing. Measured against the shipped artifact
1720
+ (tmp/r3/behaviour-baseline.mjs):
1721
+
1722
+ PASS light contour-tabs renders 2 tabs, ArrowRight moves selection
1723
+ PASS light segmented emits contour:change
1724
+ PASS light pagination emits contour:page
1725
+ FAIL shadow tabs: inner query sees slotted tabs [inside shadow root: 0; slotted: 2]
1726
+ FAIL shadow segmented / shadow menu: event reaches the document
1727
+
1728
+ Two rules fall out of that, and they are the whole design of this file:
1729
+ a behaviour looks in BOTH trees, because slotted content lives in the light
1730
+ DOM; and it dispatches on the HOST, because a bubbling event from a node
1731
+ inside a shadow root reaches neither the host nor the document:
1732
+
1733
+ bubbles-only -> reachedHost:false reachedDoc:false
1734
+
1735
+ Names are prefixed where they could collide: `stripWc` concatenates every
1736
+ fragment into one IIFE scope, so `emit`, `on` or `once` as bare top-level
1737
+ consts would silently shadow another module's. Nothing here owns markup or
1738
+ styling; a component decides what to render, this file only what happens when
1739
+ the reader acts on it.
1740
+ ========================================================================= */
1741
+
1742
+ // `contourId` is the shared counter: a generated node that needs an id (a
1743
+ // listbox's options, an aria-controls target) takes it from here rather than
1744
+ // calling Math.random(), which can hand two instances the same id and then point
1745
+ // one control at another's list.
1746
+
1747
+ // A host is wired once per behaviour. Re-entering is normal — the base class
1748
+ // calls enhance() after every render — so the guard lives in a WeakMap keyed on
1749
+ // the node, where a re-render cannot drop it.
1750
+ const WIRED_HOSTS = new WeakMap();
1751
+ /** Reset the wired-host claim for a host, allowing re-wiring after disconnect. */
1752
+ export const wcReset = (host) => { WIRED_HOSTS.delete(host); };
1753
+ const wcClaim = (host, name) => {
1754
+ let set = WIRED_HOSTS.get(host);
1755
+ if (!set) { set = new Set(); WIRED_HOSTS.set(host, set); }
1756
+ if (set.has(name)) return false;
1757
+ set.add(name);
1758
+ return true;
1759
+ };
1760
+
1761
+ // Authored content sits in the light DOM even when a shadow template slots it,
1762
+ // and a template's own parts sit in the root: a behaviour owns both.
1763
+ const wcScopes = (host) => (host.shadowRoot ? [host, host.shadowRoot] : [host]);
1764
+ const wcAll = (host, sel) => {
1765
+ const found = [];
1766
+ for (const scope of wcScopes(host)) {
1767
+ for (const el of scope.querySelectorAll(sel)) if (!found.includes(el)) found.push(el);
1768
+ }
1769
+ return found;
1770
+ };
1771
+ const wcOne = (host, sel) => wcAll(host, sel)[0] || null;
1772
+ // A custom element carries its own block class, and `querySelectorAll` never
1773
+ // returns the node it was called on, so a group element that IS the host has to
1774
+ // be added explicitly or the light wrappers find no group at all.
1775
+ const wcSelfOrAll = (host, sel) => {
1776
+ const found = typeof host.matches === "function" && host.matches(sel) ? [host] : [];
1777
+ for (const el of wcAll(host, sel)) if (!found.includes(el)) found.push(el);
1778
+ return found;
1779
+ };
1780
+ // The flat tree is not the node tree. A group element inside a shadow root and
1781
+ // the nodes slotted into it are in different trees, so `group.contains(node)` is
1782
+ // false for exactly the authored content the group exists to hold. A group's
1783
+ // nodes are therefore its own subtree plus, when the group is template-owned,
1784
+ // the host's light DOM — which is what a reader actually slotted into it.
1785
+ const wcShadowOf = (node) => {
1786
+ const root = node && node.getRootNode ? node.getRootNode() : null;
1787
+ return root && root.host ? root : null;
1788
+ };
1789
+ const wcGroup = (host, group, sel) => {
1790
+ const found = Array.from(group.querySelectorAll(sel));
1791
+ if (wcShadowOf(group) && wcShadowOf(group).host === host) {
1792
+ for (const el of host.querySelectorAll(sel)) if (!found.includes(el)) found.push(el);
1793
+ }
1794
+ return found;
1795
+ };
1796
+ // Both scopes are listened to because retargeting is the asymmetry that decides
1797
+ // where a node is visible from: a listener on the host sees the author's slotted
1798
+ // nodes with their real target, but an event that started inside a shadow tree
1799
+ // arrives there retargeted to the host, so `closest` finds nothing. The root
1800
+ // listener sees those inner nodes unretargeted.
1801
+ //
1802
+ // A composed event is therefore heard twice on its way out, so each handler runs
1803
+ // once per event — but keyed on the handler too. A set of events alone would let
1804
+ // one component swallow the click of a component nested inside it, and each host
1805
+ // owns its own interaction.
1806
+ const HEARD = new WeakMap();
1807
+ const wcListen = (host, type, handler) => {
1808
+ const scoped = (e) => {
1809
+ let seen = HEARD.get(e);
1810
+ if (!seen) { seen = new Set(); HEARD.set(e, seen); }
1811
+ if (seen.has(scoped)) return;
1812
+ seen.add(scoped);
1813
+ handler(e);
1814
+ };
1815
+ for (const scope of wcScopes(host)) scope.addEventListener(type, scoped);
1816
+ };
1817
+ const wcOwned = (host, node) =>
1818
+ !!node && wcScopes(host).some((scope) => scope.contains(node));
1819
+ // `closest` is asked of the event's own target, which is unretargeted inside the
1820
+ // tree that heard it; `wcOwned` then rejects a match outside this host.
1821
+ const wcClosest = (host, target, sel) =>
1822
+ (typeof target?.closest === "function" && wcOwned(host, target)) ? target.closest(sel) : null;
1823
+ // Dispatched on the HOST, so a listener outside this layer hears it whatever the flag
1824
+ // says — which is why an event reaching the document proves nothing about `composed`.
1825
+ // The flag is for a boundary this layer does not own: A/B on a wrapper mounted inside a
1826
+ // foreign component's shadow root, the option pressed in both runs, and the document
1827
+ // heard the event in one of them — `composed: false` arrived 0 times, `composed: true`
1828
+ // once. Consumers that wrap contour inside their own shadow tree are who it serves.
1829
+ const wcEmit = (host, name, detail) => {
1830
+ host.dispatchEvent(new CustomEvent(name, { detail, bubbles: true, composed: true }));
1831
+ };
1832
+
1833
+ /**
1834
+ * Tabs and code-tabs: roving tabindex, Arrow/Home/End, panel show-hide.
1835
+ * The active tab is `[aria-selected="true"]`, which is the rule the sheet
1836
+ * paints, so no state class is ever written — and none is invented either.
1837
+ */
1838
+ /** Wire tab keyboard navigation and selection for a host. */
1839
+ export function wireTabs(host) {
1840
+ if (!wcClaim(host, "tabs")) return;
1841
+ for (const list of wcSelfOrAll(host, ".c-tabs__list, .c-code-tabs__list")) {
1842
+ const isCode = list.classList.contains("c-code-tabs__list");
1843
+ const panelSel = isCode ? ".c-code-tabs__panel" : ".c-tabs__panel";
1844
+ // `list.contains(tab)` is the test that fails on a shadow wrapper: the list
1845
+ // is in the root and the tabs the author wrote are slotted light DOM, so the
1846
+ // node tree says they are unrelated even though the flat tree does not.
1847
+ const tabsOf = () => wcGroup(host, list, "[role='tab']");
1848
+ const activate = (tab, focus) => {
1849
+ const tabs = tabsOf();
1850
+ if (!tab.id) tab.id = contourId("c-tab");
1851
+ tabs.forEach((t) => {
1852
+ const selected = t === tab;
1853
+ t.setAttribute("aria-selected", String(selected));
1854
+ t.tabIndex = selected ? 0 : -1;
1855
+ const ctrl = t.getAttribute("aria-controls");
1856
+ if (!ctrl) return;
1857
+ const panel = wcOne(host, "#" + CSS.escape(ctrl)) || document.getElementById(ctrl);
1858
+ if (panel) {
1859
+ panel.hidden = !selected;
1860
+ // A tabpanel is named by its tab: without this a screen reader
1861
+ // announces the panel with no name.
1862
+ if (selected) panel.setAttribute("aria-labelledby", t.id);
1863
+ }
1864
+ });
1865
+ const panels = wcAll(host, panelSel);
1866
+ if (panels.length) {
1867
+ const index = tabs.indexOf(tab);
1868
+ panels.forEach((p, i) => { p.hidden = i !== index; });
1869
+ }
1870
+ if (focus) try { tab.focus(); } catch (e) { /* detached mid-key */ }
1871
+ // Emit activation so consumers can observe tab changes (B3-10).
1872
+ const name = tab.getAttribute("aria-controls") || tab.textContent || "";
1873
+ host.dispatchEvent(new CustomEvent("contour:tab-change", { bubbles: true, composed: true, detail: { index: tabs.indexOf(tab), label: name } }));
1874
+ };
1875
+ // Same-document View Transitions (BY-24). A tab swap runs inside
1876
+ // document.startViewTransition, so the browser cross-fades the whole
1877
+ // document between the old and new panel. This is a document cross-fade,
1878
+ // not a named-element morph: the component does not set
1879
+ // --view-transition-name, and a consumer who names elements gets the
1880
+ // browser's own morph on top of this. The initial mount activation below
1881
+ // stays direct — a transition on load is a page fade nobody asked for —
1882
+ // and the plain swap is the entire fallback, because the CSS harness
1883
+ // (components.css) is enhancement-only too.
1884
+ const runActivation = (tab, focus) => {
1885
+ // Keyboard activation must update aria-selected synchronously so assistive
1886
+ // tech and keyboard users see the new state immediately; view transitions
1887
+ // are a visual enhancement and must not defer the state change (a deferred
1888
+ // activation leaves the previous tab marked selected until the transition
1889
+ // callback runs, which breaks keyboard roving and any synchronous test).
1890
+ const can = !focus && typeof document.startViewTransition === "function"
1891
+ && !(typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches);
1892
+ if (can) {
1893
+ try { document.startViewTransition(() => activate(tab, focus)); return; }
1894
+ catch (e) { /* an in-flight transition or a private context: plain swap */ }
1895
+ }
1896
+ activate(tab, focus);
1897
+ };
1898
+ wcListen(host, "click", (e) => {
1899
+ const tab = wcClosest(host, e.target, "[role='tab']");
1900
+ if (tab && tabsOf().includes(tab)) {
1901
+ // A button nested inside a tab (a close control, say) is its own
1902
+ // target: activating the tab underneath it would be a surprise.
1903
+ const inner = e.target && e.target.closest ? e.target.closest("button") : null;
1904
+ if (inner && inner !== tab && tab.contains(inner)) return;
1905
+ runActivation(tab, false);
1906
+ }
1907
+ });
1908
+ wcListen(host, "keydown", (e) => {
1909
+ let tab = wcClosest(host, e.target, "[role='tab']");
1910
+ if (!tab && e.target && e.target.getAttribute && e.target.getAttribute("role") === "tab" && wcOwned(host, e.target)) tab = e.target;
1911
+ const tabs = tabsOf();
1912
+ const index = tabs.indexOf(tab);
1913
+ if (index < 0) return;
1914
+ const vertical = host.getAttribute("orientation") === "vertical";
1915
+ const rtl = isRtl(host);
1916
+ const move = vertical
1917
+ ? (rtl
1918
+ ? { ArrowDown: index - 1, ArrowUp: index + 1, Home: tabs.length - 1, End: 0 }
1919
+ : { ArrowDown: index + 1, ArrowUp: index - 1, Home: 0, End: tabs.length - 1 })
1920
+ : (rtl
1921
+ ? { ArrowRight: index - 1, ArrowLeft: index + 1, Home: tabs.length - 1, End: 0 }
1922
+ : { ArrowRight: index + 1, ArrowLeft: index - 1, Home: 0, End: tabs.length - 1 });
1923
+ if (!(e.key in move)) return;
1924
+ e.preventDefault();
1925
+ const next = tabs[(move[e.key] + tabs.length) % tabs.length];
1926
+ if (next) runActivation(next, true);
1927
+ });
1928
+ // Respect an author-marked selected tab; fall back to the first. With
1929
+ // `persist="storage"` (BY-49) the last user choice wins over both, so a
1930
+ // reload lands on the tab the reader left. The key is the host id (a
1931
+ // stable identity the author provides); without one persistence is a
1932
+ // no-op rather than a collision across every unnamed tabs instance.
1933
+ const tabs = tabsOf();
1934
+ const persist = host.getAttribute("persist");
1935
+ let restored = null;
1936
+ if (persist === "storage" && host.id) {
1937
+ try { restored = localStorage.getItem("contour-tabs:" + host.id); } catch (e) { restored = null; }
1938
+ } else if (persist === "url") {
1939
+ try {
1940
+ const params = new URLSearchParams(window.location.search);
1941
+ const v = params.get("c-tabs");
1942
+ if (v !== null) restored = v;
1943
+ } catch (e) { restored = null; }
1944
+ }
1945
+ const marked = tabs.find((t) => t.getAttribute("aria-selected") === "true");
1946
+ let first = marked || tabs[0];
1947
+ if (restored !== null) {
1948
+ const idx = parseInt(restored, 10);
1949
+ if (Number.isFinite(idx) && tabs[idx]) first = tabs[idx];
1950
+ }
1951
+ if (first) activate(first, false);
1952
+ // Persist on every subsequent activation.
1953
+ if (persist === "storage" && host.id) {
1954
+ host.addEventListener("contour:tab-change", (e) => {
1955
+ try { localStorage.setItem("contour-tabs:" + host.id, String(e.detail && e.detail.index)); } catch (err) { /* quota/private mode */ }
1956
+ });
1957
+ } else if (persist === "url") {
1958
+ host.addEventListener("contour:tab-change", (e) => {
1959
+ try {
1960
+ const url = new URL(window.location.href);
1961
+ url.searchParams.set("c-tabs", String(e.detail && e.detail.index));
1962
+ window.history.replaceState(null, "", url.toString());
1963
+ } catch (err) { /* no history API */ }
1964
+ });
1965
+ }
1966
+ }
1967
+ }
1968
+
1969
+ /**
1970
+ * Segmented control: one pressed option, and `contour:change`. The guide's own
1971
+ * markup carries the option value in a `data-*-value` hook, so the event reads
1972
+ * the hook it can see and falls back to the label the reader sees.
1973
+ */
1974
+ /** Wire segmented-control selection for a host. */
1975
+ export function wireSegmented(host) {
1976
+ const groups = wcSelfOrAll(host, ".c-segmented");
1977
+ // The block's contract is the option class, a group role and an explicit
1978
+ // pressed state — that is what the sheet styles (`.c-segmented__option
1979
+ // [aria-pressed="true"]`) and what the guide's raw specimens write by hand. A
1980
+ // wrapper that only classes the host leaves the author's buttons unstyled:
1981
+ // measured in §23, three buttons with no class and no `aria-pressed` at all.
1982
+ // Normalised here, on every pass, so both layers and slotted markup agree.
1983
+ const normalize = () => {
1984
+ // Who owns the pressed state. The author's `value` wins when it CHANGES — an
1985
+ // attribute the author writes again is a new instruction — and the reader's own
1986
+ // click wins in between, because the pressed attribute on the option is that
1987
+ // choice and these buttons are the author's nodes, which survive a re-render.
1988
+ // The one remembered value is what makes both halves hold: without it a click
1989
+ // would move the state and the next re-render would move it back to `value`;
1990
+ // with a bare "reader has picked" flag, an author writing `value` later would
1991
+ // be ignored forever.
1992
+ const authored = host.getAttribute("value");
1993
+ const chosen = authored !== host._segAuthorValue ? authored : null;
1994
+ if (chosen !== null) host._segAuthorValue = authored;
1995
+ let seen = 0;
1996
+ for (const g of groups) {
1997
+ if (!g.hasAttribute("role")) g.setAttribute("role", "group");
1998
+ const label = host.getAttribute("label");
1999
+ if (label && !g.hasAttribute("aria-label")) g.setAttribute("aria-label", label);
2000
+ const opts = wcGroup(host, g, "button");
2001
+ seen += opts.length;
2002
+ opts.forEach((b) => {
2003
+ b.classList.add("c-segmented__option");
2004
+ b.setAttribute("aria-pressed", chosen !== null && chosen !== undefined ? String(b.dataset.value === chosen) : (b.getAttribute("aria-pressed") === "true" ? "true" : "false"));
2005
+ });
2006
+ // One tab stop for the group, on the pressed option — or the first when the
2007
+ // author chose none. Arrow keys then move it along with focus.
2008
+ const chosenOpt = opts.find((b) => b.getAttribute("aria-pressed") === "true") || opts[0];
2009
+ opts.forEach((b) => { b.tabIndex = b === chosenOpt ? 0 : -1; });
2010
+ }
2011
+ return seen;
2012
+ };
2013
+ // A classic `<script src="dist/contour-wc.js">` in `<head>` upgrades the host
2014
+ // while the parser is still inside it, so the author's buttons do not exist yet
2015
+ // and this pass normalises nothing — measured across three arms: head gave 0
2016
+ // option classes, 0 pressed states and 2 tab stops, where the same bundle with
2017
+ // `defer` and the ESM entry (deferred by spec) both gave 2, 2, 1. The listeners
2018
+ // below are unaffected because they delegate on the host, which outlives the
2019
+ // parse. One retry on a later task is all the missing children need; a group
2020
+ // that is genuinely empty just re-runs an idempotent pass once.
2021
+ if (!normalize()) {
2022
+ if (!host._segRetryScheduled) {
2023
+ host._segRetryScheduled = true;
2024
+ setTimeout(() => { host._segRetryScheduled = false; normalize(); }, 0);
2025
+ }
2026
+ }
2027
+ if (!wcClaim(host, "segmented")) return;
2028
+ const activate = (btn) => {
2029
+ const seg = groups.find((g) => wcGroup(host, g, "button").includes(btn));
2030
+ if (!seg) return;
2031
+ // `value` is deliberately not written back to the host here: it sits in the
2032
+ // shared OBSERVED list, so writing it would spend a full re-render on every
2033
+ // click. The pressed attribute on the option is the state, and it survives a
2034
+ // re-render because these buttons are the author's nodes, not generated ones.
2035
+ wcGroup(host, seg, "button").forEach((o) => {
2036
+ const on = o === btn;
2037
+ o.setAttribute("aria-pressed", String(on));
2038
+ o.tabIndex = on ? 0 : -1;
2039
+ });
2040
+ wcEmit(host, "contour:change", { value: btn.dataset.value || btn.textContent.trim() });
2041
+ };
2042
+ wcListen(host, "click", (e) => {
2043
+ const btn = wcClosest(host, e.target, "button");
2044
+ if (!btn) return;
2045
+ activate(btn);
2046
+ });
2047
+ wcListen(host, "keydown", (e) => {
2048
+ const btn = wcClosest(host, e.target, "button");
2049
+ if (!btn) return;
2050
+ const seg = groups.find((g) => wcGroup(host, g, "button").includes(btn));
2051
+ if (!seg) return;
2052
+ const opts = wcGroup(host, seg, "button");
2053
+ navKey(e, opts, { wrap: false, homeEnd: true, rtl: isRtl(host), onNavigate: (i) => activate(opts[i]), onKey: () => activate(btn) });
2054
+ });
2055
+ }
2056
+
2057
+ /**
2058
+ * Combobox: filter, arrow-cursor the visible options, commit, dismiss outside.
2059
+ * Native `<select>` stays native elsewhere — its popup cannot be styled — so the
2060
+ * one list this file drives is the one the system does draw.
2061
+ */
2062
+ /** Wire combobox filtering, keyboard nav and selection for a host. */
2063
+ export function wireCombobox(host) {
2064
+ wireComboboxDocDismiss();
2065
+ const input = wcOne(host, ".c-combobox__input");
2066
+ const list = wcOne(host, ".c-combobox__list");
2067
+ if (!input || !list) return;
2068
+ const optionList = () => wcAll(host, ".c-combobox__option");
2069
+
2070
+ // Roles are re-applied on every pass, not claimed once. A re-render drops the
2071
+ // generated input and list and rebuilds them, so an attribute set on the first
2072
+ // pass is simply gone; the roles also belong to the markup, which the shared
2073
+ // implementation is what both layers have in common. Idempotent, so re-running
2074
+ // it cannot stack anything.
2075
+ if (!list.id) list.id = contourId("c-combobox-list");
2076
+ list.setAttribute("role", "listbox");
2077
+ input.setAttribute("role", "combobox");
2078
+ input.setAttribute("aria-haspopup", "listbox");
2079
+ input.setAttribute("aria-controls", list.id);
2080
+ input.setAttribute("aria-expanded", list.hasAttribute("hidden") ? "false" : "true");
2081
+ if (!input.hasAttribute("aria-autocomplete")) input.setAttribute("aria-autocomplete", "list");
2082
+ optionList().forEach((opt, i) => {
2083
+ if (!opt.id) opt.id = contourId("c-combobox-option");
2084
+ opt.setAttribute("role", "option");
2085
+ if (!opt.hasAttribute("aria-selected")) opt.setAttribute("aria-selected", "false");
2086
+ });
2087
+
2088
+ // Listeners are claimed once, and they are delegated on the HOST for the same
2089
+ // reason the other behaviours are: a listener bound to the generated input died
2090
+ // with it on the next render while the per-host claim was already spent, so a
2091
+ // combobox that changed any attribute stopped opening and stopped answering the
2092
+ // arrow keys. Measured: fresh -> openedOnFocus true, activeOptionCount 1; after
2093
+ // a placeholder change -> false and 0. The host outlives every rebuild, so the
2094
+ // nodes are looked up again per event instead of captured.
2095
+ if (!wcClaim(host, "combobox")) return;
2096
+ const liveInput = () => wcOne(host, ".c-combobox__input");
2097
+ const liveList = () => wcOne(host, ".c-combobox__list");
2098
+ let cursor = -1;
2099
+ const mark = (visible) => {
2100
+ const field = liveInput();
2101
+ visible.forEach((o, i) => {
2102
+ const on = i === cursor;
2103
+ o.classList.toggle("c-combobox__option--active", on);
2104
+ o.setAttribute("aria-selected", String(on));
2105
+ });
2106
+ if (field) {
2107
+ const active = cursor >= 0 ? visible[cursor] : null;
2108
+ if (active) field.setAttribute("aria-activedescendant", active.id);
2109
+ else field.removeAttribute("aria-activedescendant");
2110
+ }
2111
+ };
2112
+ const filter = (query) => {
2113
+ const q = (query || "").toLowerCase();
2114
+ if (host._comboboxVirtual && typeof host._renderComboboxWindow === "function") {
2115
+ host._renderComboboxWindow(q, true);
2116
+ cursor = -1;
2117
+ return;
2118
+ }
2119
+ optionList().forEach((o) => { o.hidden = !!(q && !o.textContent.toLowerCase().includes(q)); });
2120
+ cursor = -1;
2121
+ };
2122
+ const open = () => {
2123
+ const l = liveList();
2124
+ if (!l) return;
2125
+ l.removeAttribute("hidden");
2126
+ const field = liveInput();
2127
+ if (field) field.setAttribute("aria-expanded", "true");
2128
+ };
2129
+ const close = () => {
2130
+ const l = liveList();
2131
+ if (l) l.setAttribute("hidden", "");
2132
+ const field = liveInput();
2133
+ if (field) {
2134
+ field.setAttribute("aria-expanded", "false");
2135
+ field.removeAttribute("aria-activedescendant");
2136
+ }
2137
+ cursor = -1;
2138
+ // Cleared across every option, not the visible subset: an option that was
2139
+ // cursorred and then filtered out would otherwise keep `aria-selected="true"`
2140
+ // into the next open, and a listbox may report only one selected option.
2141
+ optionList().forEach((o) => {
2142
+ o.classList.remove("c-combobox__option--active");
2143
+ o.setAttribute("aria-selected", "false");
2144
+ });
2145
+ };
2146
+ if (host._comboboxVirtual && list && !list._contourVirtualScroll) {
2147
+ list._contourVirtualScroll = true;
2148
+ list.addEventListener("scroll", () => {
2149
+ if (typeof host._renderComboboxWindow === "function") host._renderComboboxWindow(host._comboboxQuery || "");
2150
+ }, { passive: true });
2151
+ }
2152
+ const commit = (opt) => {
2153
+ const field = liveInput();
2154
+ if (!field) return;
2155
+ if (host.hasAttribute("multiple")) {
2156
+ const now = opt.getAttribute("aria-selected") === "true";
2157
+ opt.setAttribute("aria-selected", String(!now));
2158
+ opt.classList.toggle("c-combobox__option--selected", !now);
2159
+ const selected = (host.getAttribute("value") || "").split(",").map((v) => v.trim()).filter(Boolean);
2160
+ const value = host._comboboxVirtual && host._comboboxFiltered
2161
+ ? host._comboboxFiltered.find((item) => item.index === Number(opt.dataset.optionIndex))?.value
2162
+ : (opt.dataset.optionValue != null ? opt.dataset.optionValue : opt.textContent.trim());
2163
+ const position = selected.indexOf(String(value));
2164
+ if (now && position >= 0) selected.splice(position, 1);
2165
+ if (!now && position < 0) selected.push(String(value));
2166
+ host.setAttribute("value", selected.join(","));
2167
+ if (typeof host._syncFormValue === "function") host._syncFormValue();
2168
+ wcEmit(host, "contour:select", { value: selected });
2169
+ field.focus();
2170
+ return;
2171
+ }
2172
+ // Commit the option's value, not its label: the field shows the label, the
2173
+ // form submits the value, and `contour:select` carries the value.
2174
+ const value = opt.dataset.optionValue != null ? opt.dataset.optionValue : opt.textContent.trim();
2175
+ field.value = opt.textContent;
2176
+ host.setAttribute("value", value);
2177
+ if (typeof host._syncFormValue === "function") host._syncFormValue();
2178
+ wcEmit(host, "contour:select", { value });
2179
+ close();
2180
+ field.focus();
2181
+ };
2182
+
2183
+ // `input` and `focus` do not both bubble out of a shadow root in the same way,
2184
+ // so `focusin` is what the focus-driven open listens to, and every handler
2185
+ // checks the event actually came from this host's field.
2186
+ const isField = (target) => wcClosest(host, target, ".c-combobox__input") !== null;
2187
+ wcListen(host, "input", (e) => {
2188
+ if (!isField(e.target)) return;
2189
+ host._comboboxQuery = e.target.value;
2190
+ filter(e.target.value);
2191
+ open();
2192
+ // The form-value event (BY-44) rides on the same interaction; the shadow
2193
+ // wrappers share this behaviour but have no `_emitForm`, so guard it.
2194
+ if (typeof host._emitForm === "function") host._emitForm("contour:input");
2195
+ });
2196
+ wcListen(host, "focusin", (e) => {
2197
+ if (!isField(e.target)) return;
2198
+ filter(e.target.value);
2199
+ open();
2200
+ });
2201
+ wcListen(host, "keydown", (e) => {
2202
+ if (!isField(e.target)) return;
2203
+ const visible = optionList().filter((o) => !o.hidden);
2204
+ if (e.key === "ArrowDown") { e.preventDefault(); cursor = Math.min(cursor + 1, visible.length - 1); mark(visible); }
2205
+ else if (e.key === "ArrowUp") { e.preventDefault(); cursor = Math.max(cursor - 1, 0); mark(visible); }
2206
+ else if (e.key === "Home") { e.preventDefault(); cursor = 0; mark(visible); }
2207
+ else if (e.key === "End") { e.preventDefault(); cursor = Math.max(0, visible.length - 1); mark(visible); }
2208
+ else if (e.key === "Enter" || e.key === " ") { e.preventDefault(); if (cursor >= 0 && visible[cursor]) commit(visible[cursor]); }
2209
+ else if (e.key === "Escape") close();
2210
+ });
2211
+ wcListen(host, "click", (e) => {
2212
+ const opt = wcClosest(host, e.target, ".c-combobox__option");
2213
+ if (opt) { commit(opt); return; }
2214
+ if (!wcOwned(host, e.target) || !host.contains(e.target)) close();
2215
+ });
2216
+ }
2217
+
2218
+ // Outside-click dismissal for comboboxes. A single document listener is cheaper and
2219
+ // leak-free compared to one per instance; it closes every open list whose host
2220
+ // does not contain the click target.
2221
+ let _comboboxDocWired = false;
2222
+ function wireComboboxDocDismiss() {
2223
+ if (_comboboxDocWired) return;
2224
+ _comboboxDocWired = true;
2225
+ document.addEventListener("click", (e) => {
2226
+ for (const host of document.querySelectorAll("contour-combobox, contour-shadow-combobox")) {
2227
+ const list = host.shadowRoot ? host.shadowRoot.querySelector(".c-combobox__list") : host.querySelector(".c-combobox__list");
2228
+ const input = host.shadowRoot ? host.shadowRoot.querySelector(".c-combobox__input") : host.querySelector(".c-combobox__input");
2229
+ if (!list || list.hasAttribute("hidden")) continue;
2230
+ const root = host.shadowRoot || host;
2231
+ if (root.contains(e.target)) continue;
2232
+ list.setAttribute("hidden", "");
2233
+ }
2234
+ });
2235
+ }
2236
+
2237
+ /**
2238
+ * The tree items a keyboard reader can actually reach. A collapsed branch carries
2239
+ * `hidden`, and a hidden element is not focusable, so a tab stop placed on one is
2240
+ * a stop the reader never arrives at — measured when this was missed: ArrowDown
2241
+ * left focus where it was and moved the only stop onto a hidden child.
2242
+ */
2243
+ const visibleStops = (host) => wcAll(host, ".c-tree__toggle, .c-tree__leaf").filter((el) => !el.closest(".c-tree__children[hidden]"));
2244
+
2245
+ /** Tree: one toggle per branch, and `contour:toggle` so a page can persist it. */
2246
+ /** Wire tree toggle and keyboard navigation for a host. */
2247
+ export function wireTree(host) {
2248
+ // The ARIA shape and the tab stop are re-applied on every pass, before the
2249
+ // claim. Two reasons, both measured on the shipped guide: the generated items
2250
+ // carried `role="tree"` on the list and NO `role="treeitem"` anywhere, so the
2251
+ // structure announced nothing to a screen reader; and every toggle and leaf was
2252
+ // stamped `tabindex="-1"` with nothing ever set to 0, so the tree had no tab
2253
+ // stop and a keyboard reader could not reach it at all. Roles cannot be guarded
2254
+ // by a one-shot claim, because a re-render rebuilds the nodes that carry them.
2255
+ const nodes = () => wcAll(host, ".c-tree__node");
2256
+ const rootList = wcSelfOrAll(host, "ul.c-tree")[0];
2257
+ if (rootList && !rootList.hasAttribute("role")) rootList.setAttribute("role", "tree");
2258
+ wcAll(host, ".c-tree__children").forEach((ul) => {
2259
+ if (!ul.hasAttribute("role")) ul.setAttribute("role", "group");
2260
+ });
2261
+ const levelOf = (node) => {
2262
+ let level = 1;
2263
+ for (let p = node.parentElement; p; p = p.parentElement) if (p.classList && p.classList.contains("c-tree__children")) level++;
2264
+ return level;
2265
+ };
2266
+ nodes().forEach((node) => {
2267
+ if (node.getAttribute("role") !== "treeitem") node.setAttribute("role", "treeitem");
2268
+ node.setAttribute("aria-level", String(levelOf(node)));
2269
+ const row = node.querySelector(":scope > .c-tree__row");
2270
+ if (row) node.setAttribute("aria-expanded", row.querySelector(":scope > .c-tree__toggle")?.getAttribute("aria-expanded") || "false");
2271
+ else if (node.hasAttribute("aria-expanded")) node.removeAttribute("aria-expanded");
2272
+ });
2273
+ // Exactly one tab stop. The author's own `tabindex="0"` is the choice, then the
2274
+ // element that already holds focus, then the first item — in that order, so the
2275
+ // invariant (one stop, never none, never N) holds without overriding intent.
2276
+ // Only the VISIBLE items count: a collapsed branch is `hidden`, and a stop on a
2277
+ // node the browser will not focus is a stop the reader never reaches. Measured
2278
+ // when this was missed — ArrowDown left focus on item 0 and moved the stop onto
2279
+ // a hidden child, so the tree reported one tab stop that nothing could hold.
2280
+ const stops = visibleStops(host);
2281
+ const authored = stops.find((el) => el.getAttribute("tabindex") === "0");
2282
+ const active = authored || stops.find((el) => el === document.activeElement) || stops[0];
2283
+ stops.forEach((el) => el.setAttribute("tabindex", el === active ? "0" : "-1"));
2284
+ // Hidden items are taken out of the sequence entirely, not left at whatever
2285
+ // value a previous pass gave them.
2286
+ wcAll(host, ".c-tree__toggle, .c-tree__leaf").forEach((el) => {
2287
+ if (!stops.includes(el)) el.setAttribute("tabindex", "-1");
2288
+ });
2289
+
2290
+ if (!wcClaim(host, "tree")) return;
2291
+ // Checkbox selection (F-08): track checked nodes and emit contour:select.
2292
+ host._selectedTree = host._selectedTree || new Set();
2293
+ let lastTreeIndex = -1;
2294
+ wcListen(host, "change", (e) => {
2295
+ const cb = e.target && e.target.closest ? e.target.closest(".c-tree__select") : null;
2296
+ if (!cb || !host.contains(cb)) return;
2297
+ const cbs = Array.from(host.querySelectorAll(".c-tree__select"));
2298
+ const idx = cbs.indexOf(cb);
2299
+ const label = (cb.parentElement && cb.parentElement.textContent || "").trim().slice(0, 120);
2300
+ if (e.shiftKey && lastTreeIndex >= 0) {
2301
+ const from = Math.min(lastTreeIndex, idx);
2302
+ const to = Math.max(lastTreeIndex, idx);
2303
+ for (let i = from; i <= to; i++) {
2304
+ cbs[i].checked = cb.checked;
2305
+ const lbl = (cbs[i].parentElement && cbs[i].parentElement.textContent || "").trim().slice(0, 120);
2306
+ if (cb.checked) host._selectedTree.add(lbl); else host._selectedTree.delete(lbl);
2307
+ }
2308
+ } else if (!e.ctrlKey && !e.metaKey) {
2309
+ // single select: clear others unless ctrl
2310
+ if (cb.checked) {
2311
+ cbs.forEach((c, i) => {
2312
+ if (i !== idx && c.checked) {
2313
+ c.checked = false;
2314
+ const lbl = (c.parentElement && c.parentElement.textContent || "").trim().slice(0, 120);
2315
+ host._selectedTree.delete(lbl);
2316
+ }
2317
+ });
2318
+ }
2319
+ if (cb.checked) host._selectedTree.add(label); else host._selectedTree.delete(label);
2320
+ } else {
2321
+ if (cb.checked) host._selectedTree.add(label); else host._selectedTree.delete(label);
2322
+ }
2323
+ lastTreeIndex = idx;
2324
+ wcEmit(host, "contour:select", { labels: Array.from(host._selectedTree) });
2325
+ });
2326
+ // Drag-and-drop (F-08): nodes are draggable; drop emits contour:move.
2327
+ wcAll(host, ".c-tree__node, .c-tree__leaf").forEach((n) => { if (!n.hasAttribute("draggable")) n.setAttribute("draggable", "true"); });
2328
+ let dragLabel = null;
2329
+ wcListen(host, "dragstart", (e) => {
2330
+ const node = wcClosest(host, e.target, ".c-tree__node, .c-tree__leaf");
2331
+ if (!node) return;
2332
+ dragLabel = (node.textContent || "").trim().slice(0, 120);
2333
+ if (e.dataTransfer) { e.dataTransfer.effectAllowed = "move"; try { e.dataTransfer.setData("text/plain", dragLabel); } catch (err) {} }
2334
+ });
2335
+ wcListen(host, "dragover", (e) => {
2336
+ const node = wcClosest(host, e.target, ".c-tree__node, .c-tree__leaf");
2337
+ if (!node) return;
2338
+ e.preventDefault();
2339
+ if (e.dataTransfer) e.dataTransfer.dropEffect = "move";
2340
+ });
2341
+ wcListen(host, "drop", (e) => {
2342
+ const node = wcClosest(host, e.target, ".c-tree__node, .c-tree__leaf");
2343
+ if (!node || !dragLabel) return;
2344
+ e.preventDefault();
2345
+ const toLabel = (node.textContent || "").trim().slice(0, 120);
2346
+ if (toLabel && toLabel !== dragLabel) {
2347
+ wcEmit(host, "contour:move", { from: dragLabel, to: toLabel });
2348
+ }
2349
+ dragLabel = null;
2350
+ });
2351
+ // Expanded-state persistence (BY-49), one path per component like tabs:
2352
+ // restore runs once at connect, the write fires from the same handler that
2353
+ // emits contour:toggle. Identity is the emitted label — the row's text
2354
+ // trimmed and sliced to 120 chars — because the generated DOM stamps no node
2355
+ // ids (route table tmp/persist-route-table.md). Storage requires a host id;
2356
+ // url mode is the single `c-tree` search param, never a hash write.
2357
+ const persist = host.getAttribute("persist");
2358
+ if (persist === "storage" && host.id) {
2359
+ try {
2360
+ const saved = localStorage.getItem("contour-tree:" + host.id);
2361
+ if (saved !== null) {
2362
+ const labels = JSON.parse(saved);
2363
+ if (Array.isArray(labels)) {
2364
+ const want = new Set(labels.map((l) => String(l)));
2365
+ wcAll(host, ".c-tree__row").forEach((row) => {
2366
+ const currentToggle = row.querySelector(":scope > .c-tree__toggle");
2367
+ if (currentToggle?.getAttribute("aria-expanded") === "true") return;
2368
+ const label = (row.textContent || "").trim().slice(0, 120);
2369
+ if (!want.has(label)) return;
2370
+ const toggle = row.querySelector(":scope > .c-tree__toggle");
2371
+ if (!toggle) return;
2372
+ const node = row.closest(".c-tree__node");
2373
+ const children = node ? node.querySelector(":scope > .c-tree__children") : null;
2374
+ toggle.setAttribute("aria-expanded", "true");
2375
+ if (node) node.setAttribute("aria-expanded", "true");
2376
+ if (children) children.removeAttribute("hidden");
2377
+ });
2378
+ }
2379
+ }
2380
+ } catch (e) { /* private mode / malformed: keep the authored state */ }
2381
+ } else if (persist === "url") {
2382
+ try {
2383
+ const v = new URLSearchParams(window.location.search).get("c-tree");
2384
+ if (v !== null) {
2385
+ const labels = JSON.parse(v);
2386
+ if (Array.isArray(labels)) {
2387
+ const want = new Set(labels.map((l) => String(l)));
2388
+ wcAll(host, ".c-tree__row").forEach((row) => {
2389
+ const currentToggle = row.querySelector(":scope > .c-tree__toggle");
2390
+ if (currentToggle?.getAttribute("aria-expanded") === "true") return;
2391
+ const label = (row.textContent || "").trim().slice(0, 120);
2392
+ if (!want.has(label)) return;
2393
+ const toggle = row.querySelector(":scope > .c-tree__toggle");
2394
+ if (!toggle) return;
2395
+ const node = row.closest(".c-tree__node");
2396
+ const children = node ? node.querySelector(":scope > .c-tree__children") : null;
2397
+ toggle.setAttribute("aria-expanded", "true");
2398
+ if (node) node.setAttribute("aria-expanded", "true");
2399
+ if (children) children.removeAttribute("hidden");
2400
+ });
2401
+ }
2402
+ }
2403
+ } catch (e) { /* malformed param: keep the authored state */ }
2404
+ }
2405
+ const toggleNode = (toggle) => {
2406
+ const wasOpen = toggle.getAttribute("aria-expanded") === "true";
2407
+ toggle.setAttribute("aria-expanded", String(!wasOpen));
2408
+ const row = toggle.closest(".c-tree__row") || toggle.parentElement;
2409
+ const node = toggle.closest(".c-tree__node");
2410
+ const children = node ? node.querySelector(":scope > .c-tree__children") : null;
2411
+ if (children) {
2412
+ if (wasOpen) {
2413
+ if (supportsUntilFound()) children.setAttribute("hidden", "until-found");
2414
+ else children.hidden = true;
2415
+ } else {
2416
+ children.removeAttribute("hidden");
2417
+ }
2418
+ }
2419
+ if (node) node.setAttribute("aria-expanded", String(!wasOpen));
2420
+ wcEmit(host, "contour:toggle", { open: !wasOpen, label: (row ? row.textContent : "").trim().slice(0, 120) });
2421
+ // Persist expanded state (BY-49): collect all currently-open rows.
2422
+ if (persist === "storage" && host.id) {
2423
+ try {
2424
+ const open = [];
2425
+ wcAll(host, ".c-tree__row").forEach((r) => {
2426
+ const toggle = r.querySelector(":scope > .c-tree__toggle");
2427
+ if (toggle?.getAttribute("aria-expanded") === "true") open.push((r.textContent || "").trim().slice(0, 120));
2428
+ });
2429
+ localStorage.setItem("contour-tree:" + host.id, JSON.stringify(open));
2430
+ } catch (e) {}
2431
+ } else if (persist === "url") {
2432
+ try {
2433
+ const open = [];
2434
+ wcAll(host, ".c-tree__row").forEach((r) => {
2435
+ const toggle = r.querySelector(":scope > .c-tree__toggle");
2436
+ if (toggle?.getAttribute("aria-expanded") === "true") open.push((r.textContent || "").trim().slice(0, 120));
2437
+ });
2438
+ const url = new URL(window.location.href);
2439
+ url.searchParams.set("c-tree", JSON.stringify(open));
2440
+ window.history.replaceState(null, "", url.toString());
2441
+ } catch (e) {}
2442
+ }
2443
+ };
2444
+ const branchOf = (el) => (el.classList && el.classList.contains("c-tree__toggle") ? el : null);
2445
+ const stopsOf = () => visibleStops(host);
2446
+ // The kept element takes the single stop; every other item — visible or hidden —
2447
+ // is dropped to -1, so opening a branch cannot leave two stops behind.
2448
+ const rove = (keep) => {
2449
+ wcAll(host, ".c-tree__toggle, .c-tree__leaf").forEach((el) => el.setAttribute("tabindex", el === keep ? "0" : "-1"));
2450
+ };
2451
+ wcListen(host, "click", (e) => {
2452
+ let toggle = wcClosest(host, e.target, ".c-tree__toggle");
2453
+ if (!toggle) {
2454
+ const row = wcClosest(host, e.target, ".c-tree__row");
2455
+ if (row) toggle = row.querySelector(":scope > .c-tree__toggle");
2456
+ }
2457
+ if (!toggle) return;
2458
+ e.preventDefault();
2459
+ e.stopPropagation();
2460
+ toggleNode(toggle);
2461
+ });
2462
+ wcListen(host, "focusin", (e) => {
2463
+ // Roving the tab stop with focus, so the tree is one Tab and not N.
2464
+ if (!wcClosest(host, e.target, ".c-tree__toggle, .c-tree__leaf")) return;
2465
+ rove(e.target);
2466
+ });
2467
+ wcListen(host, "keydown", (e) => {
2468
+ const toggle = wcClosest(host, e.target, ".c-tree__toggle, .c-tree__leaf");
2469
+ if (!toggle) return;
2470
+ const items = stopsOf();
2471
+ const idx = items.indexOf(toggle);
2472
+ if (e.key === "Enter" || e.key === " ") {
2473
+ if (branchOf(toggle)) { e.preventDefault(); toggleNode(toggle); }
2474
+ return;
2475
+ }
2476
+ // Right opens a branch, Left closes it — the pair a tree reader expects, and
2477
+ // the only way to reach a collapsed branch's children without a mouse.
2478
+ if (e.key === "ArrowRight") {
2479
+ const branch = branchOf(toggle);
2480
+ const closed = branch && branch.getAttribute("aria-expanded") === "false";
2481
+ e.preventDefault();
2482
+ if (closed) { toggleNode(branch); rove(toggle); }
2483
+ else { const next = items[idx + 1]; if (next) { next.focus(); rove(next); } }
2484
+ return;
2485
+ }
2486
+ if (e.key === "ArrowLeft") {
2487
+ const branch = branchOf(toggle);
2488
+ if (branch && branch.getAttribute("aria-expanded") === "true") {
2489
+ e.preventDefault();
2490
+ toggleNode(branch);
2491
+ rove(toggle);
2492
+ } else {
2493
+ const parent = toggle.closest(".c-tree__children");
2494
+ const owner = parent ? parent.closest(".c-tree__node") : null;
2495
+ const up = owner ? owner.querySelector(":scope > .c-tree__row > .c-tree__toggle") : null;
2496
+ if (up) { e.preventDefault(); up.focus(); rove(up); }
2497
+ }
2498
+ return;
2499
+ }
2500
+ navKey(e, items, { wrap: false, homeEnd: true, onNavigate: (i) => rove(items[i]) });
2501
+ });
2502
+ }
2503
+
2504
+ /** Menu: roving focus over items, `contour:select` from key or pointer. */
2505
+ /** Wire menu keyboard navigation and selection for a host. */
2506
+ export function wireMenu(host) {
2507
+ wcAll(host, "[role='menuitem']").forEach((it) => { if (!it.hasAttribute("tabindex")) it.setAttribute("tabindex", it.getAttribute("aria-disabled") === "true" ? "-1" : "-1"); });
2508
+ const all = () => wcAll(host, "[role='menuitem']");
2509
+ if (!all().some((it) => it.getAttribute("tabindex") === "0") && all().length) {
2510
+ const first = all().find((it) => it.getAttribute("aria-disabled") !== "true");
2511
+ if (first) first.setAttribute("tabindex", "0");
2512
+ }
2513
+ if (!wcClaim(host, "menu")) return;
2514
+
2515
+ const submenusOf = (item) => item.querySelector(":scope > ul.c-menu, :scope > .c-menu");
2516
+ const closeAllSubmenus = () => {
2517
+ wcAll(host, "[aria-haspopup='menu']").forEach((it) => it.setAttribute("aria-expanded", "false"));
2518
+ };
2519
+
2520
+ wcListen(host, "keydown", (e) => {
2521
+ const its = all().filter((it) => it.getAttribute("aria-disabled") !== "true");
2522
+ if (!its.length) return;
2523
+ const index = its.indexOf(e.target);
2524
+ const target = index >= 0 ? its[index] : null;
2525
+ const sub = target ? submenusOf(target) : null;
2526
+
2527
+ // Submenu open (F-02): ArrowRight / Enter on a haspopup item opens it.
2528
+ if (target && target.getAttribute("aria-haspopup") === "menu" && (e.key === "ArrowRight" || e.key === "Enter" || e.key === " ")) {
2529
+ if (sub) {
2530
+ e.preventDefault();
2531
+ closeAllSubmenus();
2532
+ target.setAttribute("aria-expanded", "true");
2533
+ const firstSub = sub.querySelector("[role='menuitem']");
2534
+ if (firstSub) { firstSub.setAttribute("tabindex", "0"); try { firstSub.focus(); } catch (err) {} }
2535
+ return;
2536
+ }
2537
+ }
2538
+ // Submenu close: ArrowLeft / Escape.
2539
+ if (e.key === "ArrowLeft" || e.key === "Escape") {
2540
+ const parent = target ? target.closest("ul.c-menu") : null;
2541
+ // find the haspopup ancestor item
2542
+ let ancestor = null;
2543
+ if (target) {
2544
+ const ul = target.parentElement && target.parentElement.tagName === "UL" ? target.parentElement : null;
2545
+ // walk up to find a li with aria-haspopup whose submenu contains target
2546
+ let node = target.parentElement;
2547
+ while (node && node !== host) {
2548
+ if (node.getAttribute && node.getAttribute("aria-haspopup") === "menu" && node.contains(target) && node !== target) { ancestor = node; break; }
2549
+ node = node.parentElement;
2550
+ }
2551
+ }
2552
+ if (ancestor) {
2553
+ e.preventDefault();
2554
+ ancestor.setAttribute("aria-expanded", "false");
2555
+ try { ancestor.focus(); } catch (err) {}
2556
+ return;
2557
+ }
2558
+ if (e.key === "Escape") {
2559
+ closeAllSubmenus();
2560
+ }
2561
+ }
2562
+
2563
+ navKey(e, its, { wrap: true, homeEnd: true, onKey: () => { if (e.key === "Enter" || e.key === " ") { const idx = its.indexOf(document.activeElement); if (idx >= 0 && !(target && target.getAttribute("aria-haspopup") === "menu")) { wcEmit(host, "contour:select", { index: idx, label: its[idx].textContent.trim() }); closeAllSubmenus(); } } } });
2564
+ // Typeahead (F-21): printable char jumps to the first item whose label
2565
+ // starts with the typed character.
2566
+ if (e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey) {
2567
+ const ch = e.key.toLowerCase();
2568
+ const match = its.findIndex((it) => (it.textContent || "").trim().toLowerCase().startsWith(ch));
2569
+ if (match >= 0) { e.preventDefault(); its[match].focus(); }
2570
+ }
2571
+ });
2572
+ wcListen(host, "click", (e) => {
2573
+ const item = wcClosest(host, e.target, "[role='menuitem']");
2574
+ if (!item) return;
2575
+ if (item.getAttribute("aria-disabled") === "true") return;
2576
+ // Toggle submenu on click for haspopup items.
2577
+ if (item.getAttribute("aria-haspopup") === "menu") {
2578
+ const sub = submenusOf(item);
2579
+ if (sub) {
2580
+ const open = item.getAttribute("aria-expanded") === "true";
2581
+ closeAllSubmenus();
2582
+ item.setAttribute("aria-expanded", open ? "false" : "true");
2583
+ return;
2584
+ }
2585
+ }
2586
+ const index = all().indexOf(item);
2587
+ if (index >= 0) {
2588
+ wcEmit(host, "contour:select", { index, label: item.textContent.trim() });
2589
+ closeAllSubmenus();
2590
+ // close-on-select: if the menu is a popover, hide it.
2591
+ if (typeof host.hidePopover === "function") { try { host.hidePopover(); } catch (e) {} }
2592
+ }
2593
+ });
2594
+ }
2595
+
2596
+ /** Pagination: `[aria-current="page"]` is the state the sheet paints. */
2597
+ /** Wire pagination controls for a host. */
2598
+ export function wirePagination(host) {
2599
+ wcAll(host, ".c-pagination__link").forEach((b) => { if (!b.hasAttribute("tabindex")) b.setAttribute("tabindex", "0"); });
2600
+ if (!wcClaim(host, "pagination")) return;
2601
+ const activate = (btn) => {
2602
+ const page = parseInt(btn.textContent, 10);
2603
+ if (!Number.isFinite(page)) return;
2604
+ wcAll(host, ".c-pagination__link").forEach((b) => {
2605
+ if (parseInt(b.textContent, 10) === page) b.setAttribute("aria-current", "page");
2606
+ else b.removeAttribute("aria-current");
2607
+ });
2608
+ host.setAttribute("page", String(page));
2609
+ wcEmit(host, "contour:page", { page });
2610
+ if (host.getAttribute("persist") === "storage" && host.id) {
2611
+ try { localStorage.setItem("contour-pagination:" + host.id, String(page)); } catch (e) {}
2612
+ } else if (host.getAttribute("persist") === "url") {
2613
+ try { const url = new URL(window.location.href); url.searchParams.set("c-pagination", String(page)); window.history.replaceState(null, "", url.toString()); } catch (e) {}
2614
+ }
2615
+ };
2616
+ wcListen(host, "click", (e) => {
2617
+ const btn = wcClosest(host, e.target, ".c-pagination__link");
2618
+ if (!btn) return;
2619
+ e.preventDefault();
2620
+ const action = btn.getAttribute("data-action");
2621
+ if (action === "prev" || action === "next") {
2622
+ const links = wcAll(host, ".c-pagination__link").filter((b) => !b.getAttribute("data-action"));
2623
+ const cur = links.find((b) => b.getAttribute("aria-current") === "page");
2624
+ const curPage = cur ? (parseInt(cur.textContent, 10) || 1) : 1;
2625
+ const page = action === "prev" ? Math.max(1, curPage - 1) : Math.min(links.length, curPage + 1);
2626
+ const target = links.find((b) => parseInt(b.textContent, 10) === page);
2627
+ if (target) { activate(target); return; }
2628
+ }
2629
+ activate(btn);
2630
+ });
2631
+ wcListen(host, "keydown", (e) => {
2632
+ const btn = wcClosest(host, e.target, ".c-pagination__link");
2633
+ if (!btn) return;
2634
+ const links = wcAll(host, ".c-pagination__link");
2635
+ const idx = links.indexOf(btn);
2636
+ let next = -1;
2637
+ const rtl = isRtl(host);
2638
+ if (e.key === "ArrowRight") next = rtl ? Math.max(idx - 1, 0) : Math.min(idx + 1, links.length - 1);
2639
+ else if (e.key === "ArrowLeft") next = rtl ? Math.min(idx + 1, links.length - 1) : Math.max(idx - 1, 0);
2640
+ else if (e.key === "Home") next = 0;
2641
+ else if (e.key === "End") next = links.length - 1;
2642
+ else if (e.key === "Enter" || e.key === " ") { e.preventDefault(); activate(btn); return; }
2643
+ if (next >= 0 && next !== idx) { e.preventDefault(); links[next].focus(); }
2644
+ });
2645
+ }
2646
+
2647
+ /**
2648
+ * Copy. `.c-code__copy` copies its block, `.c-install__copy` its command — one
2649
+ * handler because both need the same three things: the text, the clipboard, and
2650
+ * a `contour:copy` a page can toast from when the clipboard is denied.
2651
+ */
2652
+ /** Wire copy-to-clipboard behaviour for a host. */
2653
+ export function wireCopy(host) {
2654
+ if (!wcClaim(host, "copy")) return;
2655
+ wcListen(host, "click", (e) => {
2656
+ const btn = wcClosest(host, e.target, ".c-code__copy, .c-install__copy");
2657
+ if (!btn) return;
2658
+ const owner = wcClosest(host, btn, ".c-code") || wcClosest(host, btn, ".c-install") || host;
2659
+ const src = owner.querySelector("code, .c-install__command");
2660
+ // A numbered block carries its gutter as elements inside the <code>, so
2661
+ // `textContent` would copy the numbers and lose the line breaks between the
2662
+ // line spans. Read the lines back instead: the gutter is dropped, the breaks
2663
+ // are restored, and the clipboard gets the code the reader sees.
2664
+ const readSource = (el) => {
2665
+ const lines = el && el.querySelectorAll ? el.querySelectorAll(".c-code__line") : null;
2666
+ if (!lines || !lines.length) return el ? el.textContent || "" : "";
2667
+ return Array.from(lines).map((l) => Array.from(l.childNodes)
2668
+ .filter((n) => !(n.classList && n.classList.contains("c-code__line-number")))
2669
+ .map((n) => n.textContent).join("")).join("\n");
2670
+ };
2671
+ const text = readSource(src) || (src ? "" : owner.textContent) || "";
2672
+ // The confirmation is the one the system script paints for the guide's own
2673
+ // copy buttons: a label swap, `data-copied` (which the shipped CSS styles)
2674
+ // and an icon check on the trigger, reverted after the same beat. The
2675
+ // trigger keeps focus, so the label change is what a screen reader hears.
2676
+ const confirm = (ok) => {
2677
+ const icon = btn.querySelector("use");
2678
+ const originalHref = icon && icon.getAttribute("href");
2679
+ const originalLabel = btn.getAttribute("aria-label") || btn.title || "";
2680
+ if (ok && icon) icon.setAttribute("href", "#i-check");
2681
+ btn.setAttribute("aria-label", ok ? "Copied" : "Copy failed");
2682
+ btn.dataset.copied = String(ok);
2683
+ const timer = setTimeout(() => {
2684
+ if (!btn.isConnected) return;
2685
+ if (icon && originalHref) icon.setAttribute("href", originalHref);
2686
+ btn.setAttribute("aria-label", originalLabel);
2687
+ delete btn.dataset.copied;
2688
+ }, 1600);
2689
+ onDispose(host, () => clearTimeout(timer));
2690
+ };
2691
+ const doCopy = async () => {
2692
+ try {
2693
+ if (navigator.clipboard && navigator.clipboard.writeText) {
2694
+ await navigator.clipboard.writeText(text);
2695
+ return true;
2696
+ }
2697
+ } catch (e) { /* fall through */ }
2698
+ try {
2699
+ const ta = document.createElement("textarea");
2700
+ ta.value = text;
2701
+ ta.setAttribute("readonly", "");
2702
+ ta.style.position = "fixed";
2703
+ ta.style.top = "-9999px";
2704
+ ta.style.opacity = "0";
2705
+ document.body.append(ta);
2706
+ ta.select();
2707
+ const ok = document.execCommand("copy");
2708
+ ta.remove();
2709
+ return ok;
2710
+ } catch (e) {
2711
+ return false;
2712
+ }
2713
+ };
2714
+ doCopy().then((ok) => confirm(ok));
2715
+ wcEmit(host, "contour:copy", { text });
2716
+ });
2717
+ }
2718
+
2719
+ /**
2720
+ * Removable things: a tag, a filter pill, and the empty state's retry. The
2721
+ * affordance is the control's job to remove and to say so; keeping the node in
2722
+ * sync with the event is what makes the two copies of this rule agree.
2723
+ */
2724
+ /** Wire removable-item (chip/tag) dismissal for a host. */
2725
+ export function wireRemovable(host) {
2726
+ if (!wcClaim(host, "removable")) return;
2727
+ wcListen(host, "click", (e) => {
2728
+ const drop = (node) => { if (node && node.parentNode) node.parentNode.removeChild(node); };
2729
+ const tagBtn = wcClosest(host, e.target, ".c-tag__remove");
2730
+ if (tagBtn) {
2731
+ e.preventDefault();
2732
+ const tag = wcClosest(host, tagBtn, ".c-tag");
2733
+ wcEmit(host, "contour:remove", { label: (tag && tag.getAttribute("label")) || (tag ? tag.textContent.trim() : "") });
2734
+ drop(tag);
2735
+ return;
2736
+ }
2737
+ const pillBtn = wcClosest(host, e.target, ".c-filter-pill__remove");
2738
+ if (pillBtn) {
2739
+ e.preventDefault();
2740
+ const pill = wcClosest(host, pillBtn, ".c-filter-pill");
2741
+ wcEmit(host, "contour:remove", { key: pill && pill.getAttribute("key"), value: pill && pill.getAttribute("value") });
2742
+ drop(pill);
2743
+ return;
2744
+ }
2745
+ if (wcClosest(host, e.target, "[data-empty-action]")) {
2746
+ wcEmit(host, "contour:empty-action", { state: host.getAttribute("state") || "empty" });
2747
+ }
2748
+ const alertClose = wcClosest(host, e.target, ".c-alert__close");
2749
+ if (alertClose) {
2750
+ e.preventDefault();
2751
+ wcEmit(host, "contour:close", {});
2752
+ if (host.shadowRoot ? host.shadowRoot.contains(alertClose) : true) {
2753
+ try { host.remove(); } catch (err) {}
2754
+ }
2755
+ return;
2756
+ }
2757
+ const calloutClose = wcClosest(host, e.target, ".c-callout__close");
2758
+ if (calloutClose) {
2759
+ e.preventDefault();
2760
+ wcEmit(host, "contour:close", {});
2761
+ try { host.remove(); } catch (err) {}
2762
+ return;
2763
+ }
2764
+ });
2765
+ }
2766
+
2767
+ // Modal containment for the light dialog family (BY-46). A native <dialog> in
2768
+ // showModal() modalises the page for free — top layer, backdrop, background
2769
+ // inert — but the light contour-dialog/drawer/sheet have no platform modal, so
2770
+ // opening one must lock the document scroll and inert the background or the
2771
+ // page behind it stays reachable. Stacked: two open surfaces must not unlock
2772
+ // the page on the first close. The guide's own modalise() is the pattern; this
2773
+ // is the system's copy, since a rule that only works inside the guide does not
2774
+ // ship.
2775
+ const modalDepth = { n: 0 };
2776
+ let modalSavedOverflow = null;
2777
+ let modalSavedX = 0;
2778
+ let modalSavedY = 0;
2779
+ const modalInerted = new Set();
2780
+ const modalStack = [];
2781
+ let modalTrapWired = false;
2782
+
2783
+ function modalFocusables(host) {
2784
+ return Array.from(host.querySelectorAll("button, [href], input, select, textarea, [tabindex]:not([tabindex='-1'])"))
2785
+ .filter((el) => !el.hasAttribute("disabled") && el.getAttribute("aria-hidden") !== "true");
2786
+ }
2787
+
2788
+ function modalTrapHandler(e) {
2789
+ if (e.key !== "Tab") return;
2790
+ const host = modalStack[modalStack.length - 1];
2791
+ if (!host) return;
2792
+ const f = modalFocusables(host);
2793
+ if (!f.length) { e.preventDefault(); return; }
2794
+ const first = f[0];
2795
+ const last = f[f.length - 1];
2796
+ const active = document.activeElement;
2797
+ if (e.shiftKey) {
2798
+ if (active === first || !host.contains(active)) { e.preventDefault(); last.focus(); }
2799
+ } else {
2800
+ if (active === last) { e.preventDefault(); first.focus(); }
2801
+ }
2802
+ }
2803
+
2804
+ /** Contain focus within a modal host while open. */
2805
+ export function modalContain(host, open) {
2806
+ if (open) {
2807
+ if (modalDepth.n === 0) {
2808
+ // The lock itself clamps the scroll (overflow:hidden on the scroller),
2809
+ // so the position must be captured BEFORE it is applied or the restore
2810
+ // puts a clamped 0 back (measured: open-after-scrollTo read scrollY 0).
2811
+ modalSavedX = window.scrollX;
2812
+ modalSavedY = window.scrollY;
2813
+ modalSavedOverflow = document.documentElement.style.overflow;
2814
+ document.documentElement.style.overflow = "hidden";
2815
+ }
2816
+ modalDepth.n += 1;
2817
+ modalStack.push(host);
2818
+ if (modalDepth.n === 1 && !modalTrapWired) {
2819
+ modalTrapWired = true;
2820
+ document.addEventListener("keydown", modalTrapHandler);
2821
+ }
2822
+ // An ancestor cannot be inert (it would inert the whole subtree); the
2823
+ // background is therefore each ancestor's SIBLINGS, walked out to the body.
2824
+ for (let el = host; el && el !== document.body; el = el.parentElement) {
2825
+ for (const sib of el.parentElement.children) {
2826
+ if (sib === el || sib.inert || modalInerted.has(sib)) continue;
2827
+ sib.inert = true;
2828
+ modalInerted.add(sib);
2829
+ }
2830
+ }
2831
+ } else {
2832
+ const idx = modalStack.lastIndexOf(host);
2833
+ if (idx >= 0) modalStack.splice(idx, 1);
2834
+ modalDepth.n = Math.max(0, modalDepth.n - 1);
2835
+ if (modalDepth.n === 0) {
2836
+ for (const el of modalInerted) el.inert = false;
2837
+ modalInerted.clear();
2838
+ document.documentElement.style.overflow = modalSavedOverflow || "";
2839
+ window.scrollTo(modalSavedX, modalSavedY);
2840
+ if (modalTrapWired) {
2841
+ document.removeEventListener("keydown", modalTrapHandler);
2842
+ modalTrapWired = false;
2843
+ }
2844
+ }
2845
+ }
2846
+ }
2847
+
2848
+ /* ============================================================================
2849
+ CONTOUR — data state and remote loading
2850
+ ----------------------------------------------------------------------------
2851
+ One implementation of the four data states (`empty`, `loading`, `error`,
2852
+ `skeleton`) and of the remote source (`src`, plus `lazy`, `refresh`,
2853
+ `timeout`).
2854
+
2855
+ Before this file the same forty-line block was written into eight fragments by
2856
+ hand — 6 copies in `content.mjs`, 8 in `data.mjs`, 20 in `map.mjs`, 14 in
2857
+ `navigation.mjs` — and every copy carried the same defects, measured in
2858
+ Chromium against `dist/contour-wc.js` built at 7d75b3d (probe
2859
+ `tmp/wc9/probe.mjs`, 2026-10-27):
2860
+
2861
+ 1. a host with `src` painted `"Loading…Loading…"` — two nodes — because the
2862
+ copy re-rendered by calling `attributeChangedCallback` from inside
2863
+ `render()`, which on the connect path is a synchronous nested render;
2864
+ 2. a 404 and a malformed body both landed on the EMPTY state
2865
+ (`{"empty":1,"error":0,"text":"No data"}`), so the component claimed it had
2866
+ no data when in fact it had failed to fetch it;
2867
+ 3. nothing aborted the request: a host removed mid-flight kept
2868
+ `loadingAfterDetach: 2` stale nodes and was still written to;
2869
+ 4. the state was styled by an inline `style.color`, which beat the CSS rule
2870
+ written beside it in the same commit, so the rule was dead — and 33
2871
+ generated `c-*__skeleton` names had no rule anywhere.
2872
+
2873
+ Three rules fall out of that, and they are the whole design here.
2874
+
2875
+ Presentation belongs to the sheet. Nothing in this file writes a `style`
2876
+ attribute; a state node carries the block-scoped element class the system
2877
+ already defines (`c-readout__loading` — 102 of those exist in `src/css/`), so a
2878
+ generated class is never one the system cannot style.
2879
+
2880
+ A state is not a live region. `role="alert"` on a node that is inserted already
2881
+ carrying text is exactly what `tools/audit/contrast-and-aria.mjs` refuses: it
2882
+ scans every `[role="status"],[role="alert"],[aria-live]` whose text is non-empty
2883
+ at load, because such a region has no change left to announce. So the widget
2884
+ says `aria-busy` while it works and nothing at all when it has failed. A
2885
+ consumer that wants the failure spoken routes `contour:error` to the page's own
2886
+ `#toast-host`, which is present and empty for that purpose.
2887
+
2888
+ The loader is shared per URL, not per host: a dashboard that mounts forty
2889
+ chrome widgets against one endpoint should ask it once. That is also why the
2890
+ abort belongs to the last host out, not the first — see `leaveRequest`.
2891
+ ========================================================================= */
2892
+
2893
+ // Copy. A component overrides any of these through its own attribute, because a
2894
+ // legend and a table should not both say "No data" — but a default must exist,
2895
+ // because a state with no text is a state the reader cannot see.
2896
+ /** Fallback state copy used when remote data is unavailable. */
2897
+ export const STATE_FALLBACK = {
2898
+ empty: "No data",
2899
+ loading: "Loading…",
2900
+ error: "Could not load.",
2901
+ };
2902
+
2903
+ /**
2904
+ * Resolve a state label for a host (R18-63). A consumer supplies a `labels`
2905
+ * JSON attribute (e.g. `labels='{"loading":"Chargement…"}'`); it is merged over
2906
+ * the English default, so a partial object localises only the keys it names.
2907
+ * A malformed attribute is ignored rather than thrown — a bad label must not
2908
+ * take the widget down. Returns the default when no override is present.
2909
+ */
2910
+ export function stateLabel(host, key) {
2911
+ const fallback = STATE_FALLBACK[key] || key;
2912
+ const raw = host && host.getAttribute ? host.getAttribute("labels") : null;
2913
+ if (!raw) return fallback;
2914
+ try {
2915
+ const parsed = JSON.parse(raw);
2916
+ if (parsed && typeof parsed === "object" && typeof parsed[key] === "string" && parsed[key]) return parsed[key];
2917
+ } catch (e) { /* a malformed labels attribute is ignored, not fatal */ }
2918
+ return fallback;
2919
+ }
2920
+
2921
+ // One in-flight request per URL, shared by every host that asked for it.
2922
+ const remoteInflight = new Map();
2923
+ // The last result per URL, so a re-mounted host paints instead of re-asking. A
2924
+ // refused URL is never cached: one blip must not black out a widget until reload.
2925
+ // Bounded, because a page that routes through a hundred tile URLs is not going to
2926
+ // re-ask the first ten, and an unbounded Map is a leak with a cache's vocabulary.
2927
+ const REMOTE_CACHE_MAX = 64;
2928
+ const remoteCache = new Map();
2929
+
2930
+ function cacheResult(src, data) {
2931
+ if (remoteCache.size >= REMOTE_CACHE_MAX) remoteCache.delete(remoteCache.keys().next().value);
2932
+ remoteCache.set(src, data);
2933
+ }
2934
+
2935
+ function setStatus(host, status) {
2936
+ host._remoteStatus = status;
2937
+ if (status !== "error") host._remoteError = null;
2938
+ // `aria-busy` is the platform's own word for "this region is mid-update", it is
2939
+ // not in OBSERVED, so writing it cannot re-enter this render, and it is cleared
2940
+ // the moment a request is not open.
2941
+ if (status === "loading") host.setAttribute("aria-busy", "true");
2942
+ else host.removeAttribute("aria-busy");
2943
+ // The same status drives the `:state(data-loading)` custom state (BY-32): a
2944
+ // consumer's CSS can select a mid-request host without an attribute round
2945
+ // trip. Loader hosts are not formAssociated, so the base mirrors internals
2946
+ // lazily (probed legal in the gate's Chromium); a host without internals or
2947
+ // without CustomStateSet simply keeps the attribute path.
2948
+ if (typeof host._setCustomState === "function") host._setCustomState("data-loading", status === "loading");
2949
+ }
2950
+
2951
+ function emitState(host, name, detail) {
2952
+ host.dispatchEvent(new CustomEvent(name, { detail, bubbles: true, composed: true }));
2953
+ }
2954
+
2955
+ function countOf(data) {
2956
+ if (Array.isArray(data)) return data.length;
2957
+ if (data && typeof data === "object") return Object.keys(data).length;
2958
+ return data === null || data === undefined ? 0 : 1;
2959
+ }
2960
+
2961
+ /**
2962
+ * Leave a shared request. The host stops listening, and if it was the last host
2963
+ * that cared, the request itself is cancelled.
2964
+ *
2965
+ * This is why the abort is not simply `onDispose(host, () => controller.abort())`:
2966
+ * with a shared URL, the first widget to be removed from the page would cancel the
2967
+ * request its nine siblings are still waiting on, and the defect would look like a
2968
+ * network failure that only happens on a dashboard.
2969
+ */
2970
+ function leaveRequest(host) {
2971
+ const entry = host._remoteEntry;
2972
+ host._remoteEntry = null;
2973
+ if (!entry) return;
2974
+ entry.hosts.delete(host);
2975
+ if (entry.hosts.size === 0 && entry.controller) entry.controller.abort();
2976
+ }
2977
+
2978
+ /**
2979
+ * Ask for `src`, and report whether the host is waiting on it.
2980
+ *
2981
+ * `fields` are the attributes the payload may feed, in the order the component
2982
+ * prefers them. Reads nothing and writes nothing the component paints — the
2983
+ * values come back through `remoteData`.
2984
+ */
2985
+ /** Load remote data for the given fields on a host. */
2986
+ export function loadRemote(host, fields) {
2987
+ const src = host.getAttribute("src");
2988
+ if (!src) {
2989
+ leaveRequest(host);
2990
+ setStatus(host, host._remoteData !== undefined ? "ready" : "idle");
2991
+ return;
2992
+ }
2993
+ remoteRefresh(host);
2994
+ const wanted = typeof fields === "string" ? [fields] : fields;
2995
+ // An authored attribute wins outright: the component must not fetch over the top
2996
+ // of markup the author wrote.
2997
+ if (wanted.every((f) => host.getAttribute(f) !== null)) {
2998
+ leaveRequest(host);
2999
+ setStatus(host, "ready");
3000
+ return;
3001
+ }
3002
+ // A host below the fold must not compete with the forty above it for the same
3003
+ // connection. It reports `loading` while it waits, because that is what it is —
3004
+ // painting "No data" here would claim an empty dataset for data that has not
3005
+ // been asked for yet.
3006
+ if (!remoteVisible(host)) {
3007
+ setStatus(host, "loading");
3008
+ return;
3009
+ }
3010
+ // The shared cache is keyed by `cache-key` when the author names one,
3011
+ // otherwise by the URL itself. `no-cache` opts a host OUT of the shared
3012
+ // read: it always asks the network fresh, and the fresh bytes it received
3013
+ // are its own for this mount (the guard below re-reads `_remoteData`, so a
3014
+ // re-render must not fire a second request). The settle still writes the
3015
+ // fresh result to the shared cache — "don't reuse" and "don't store" are
3016
+ // different policies, and this is the former; `remoteInvalidate` gives the
3017
+ // page the latter.
3018
+ const noCache = host.hasAttribute("no-cache");
3019
+ const cacheKey = host.getAttribute("cache-key") || src;
3020
+ if (noCache) {
3021
+ if (host._remoteSrc === src && host._remoteData !== undefined) {
3022
+ setStatus(host, "ready");
3023
+ return;
3024
+ }
3025
+ } else {
3026
+ const cached = remoteCache.get(cacheKey);
3027
+ if (cached !== undefined) {
3028
+ host._remoteSrc = src;
3029
+ host._remoteData = cached;
3030
+ setStatus(host, "ready");
3031
+ return;
3032
+ }
3033
+ }
3034
+ // Already asked: a host still waiting, or one whose last ask settled in
3035
+ // error, must not re-ask on its own. The retry button (wireStates) and the
3036
+ // refresh timer are the only re-askers, and both clear `_remoteSrc` first —
3037
+ // without this guard, an errored host re-fetched on every settle's re-render,
3038
+ // so a permanent 404 looped forever painting `loading`, and a flaky endpoint
3039
+ // "recovered" to rows without the user ever clicking retry (both measured by
3040
+ // the state-contract arm in wc-contract, which is the first lane to mount src).
3041
+ if (host._remoteSrc === src && (host._remoteStatus === "loading" || host._remoteStatus === "error")) return; // already asked
3042
+
3043
+ leaveRequest(host);
3044
+ host._remoteSrc = src;
3045
+ setStatus(host, "loading");
3046
+
3047
+ let entry = remoteInflight.get(src);
3048
+ if (!entry) {
3049
+ entry = { hosts: new Set(), controller: new AbortController(), cacheKey };
3050
+ remoteInflight.set(src, entry);
3051
+ // All three arguments: `host` carries the timeout attribute and owns the
3052
+ // disposer, `src` is the URL to ask, `entry` holds the shared controller.
3053
+ // Dropping `host` (as the call did between 8cde6ba and 566b85a) shifts
3054
+ // `entry` into its slot, so `host.getAttribute` runs against the URL
3055
+ // string and every fetch throws before it starts — caught by the
3056
+ // state-contract arm in wc-contract, which is the first lane to mount src.
3057
+ entry.promise = startFetch(host, src, entry).then(
3058
+ (data) => {
3059
+ if (remoteInflight.get(src) === entry) remoteInflight.delete(src);
3060
+ // The entry is keyed by URL, but a host that named a cache-key must be
3061
+ // able to paint from cache on a re-mount: the fresh result is filed
3062
+ // under both the URL and its named key, so the key is not a private
3063
+ // lane that only ever misses.
3064
+ cacheResult(src, data);
3065
+ const namedKey = entry.cacheKey;
3066
+ if (namedKey && namedKey !== src) cacheResult(namedKey, data);
3067
+ for (const h of entry.hosts) {
3068
+ h._remoteData = data;
3069
+ h._remoteEntry = null;
3070
+ setStatus(h, "ready");
3071
+ emitState(h, "contour:load", { src, count: countOf(data) });
3072
+ }
3073
+ },
3074
+ (err) => {
3075
+ if (remoteInflight.get(src) === entry) remoteInflight.delete(src);
3076
+ for (const h of entry.hosts) {
3077
+ h._remoteEntry = null;
3078
+ setStatus(h, "error");
3079
+ h._remoteError = err && err.name === "HttpError" ? `Could not load (${err.status})` : STATE_FALLBACK.error;
3080
+ emitState(h, "contour:error", {
3081
+ src,
3082
+ message: h._remoteError,
3083
+ name: err && err.name,
3084
+ status: err && err.status,
3085
+ });
3086
+ }
3087
+ }
3088
+ ).finally(() => {
3089
+ for (const h of entry.hosts) if (h.isConnected) h.requestRender();
3090
+ entry.hosts.clear();
3091
+ });
3092
+ }
3093
+ entry.hosts.add(host);
3094
+ host._remoteEntry = entry;
3095
+ // Leaving the page is not failing the request; the host simply stops caring.
3096
+ // Registered once per mount, because `loadRemote` runs from `render()` and a
3097
+ // disposers list that grows with the render count is the leak this file exists
3098
+ // to stop. The flag is cleared inside the disposer, so a reconnect re-registers.
3099
+ if (!host._remoteDisposeRegistered) {
3100
+ host._remoteDisposeRegistered = true;
3101
+ onDispose(host, () => {
3102
+ host._remoteDisposeRegistered = false;
3103
+ leaveRequest(host);
3104
+ });
3105
+ }
3106
+ }
3107
+
3108
+ /**
3109
+ * Drop a URL's cached result so the next host that asks for it re-fetches.
3110
+ * The refresh timer and the retry button already clear the entry themselves;
3111
+ * this is the page-side handle for the same job (an admin action, a
3112
+ * websocket that says the tiles changed) without forcing a remount.
3113
+ * @param {string} srcOrKey the URL — or the cache-key a host asked under
3114
+ */
3115
+ /** Invalidate cached remote data by source or key. */
3116
+ export function remoteInvalidate(srcOrKey) {
3117
+ remoteCache.delete(srcOrKey);
3118
+ }
3119
+
3120
+ // `AbortSignal.timeout` is the platform's own deadline; where it is missing, the
3121
+ // same thing is a timer and an abort. Either way an unreachable internal tile
3122
+ // server cannot leave a widget in `loading` for the life of the page.
3123
+ function startFetch(host, src, entry) {
3124
+ const ms = parseInt(host.getAttribute("timeout") || "", 10);
3125
+ let timer = null;
3126
+ let signal = entry.controller.signal;
3127
+ if (Number.isFinite(ms) && ms > 0) {
3128
+ if (typeof AbortSignal !== "undefined" && AbortSignal.timeout) {
3129
+ // `AbortSignal.any` needs no guard: it ships with `AbortSignal.timeout`, and
3130
+ // a host on an engine without the former has no use for the latter either.
3131
+ signal = AbortSignal.any([signal, AbortSignal.timeout(ms)]);
3132
+ } else {
3133
+ timer = setTimeout(() => entry.controller.abort(), ms);
3134
+ }
3135
+ }
3136
+ // The deadline belongs to the request, so the last host out already aborts it;
3137
+ // the timer is cleared on any settle so a cached answer costs nothing later.
3138
+ onDispose(host, () => { if (timer) clearTimeout(timer); });
3139
+
3140
+ return fetch(src, { signal })
3141
+ .then((res) => {
3142
+ if (timer) clearTimeout(timer);
3143
+ // The status line is the boundary. `fetch` resolves on 404 and on 500, so
3144
+ // without this test a failed request became an empty dataset and the
3145
+ // component told the reader there was nothing to show.
3146
+ if (!res.ok) {
3147
+ const e = new Error(`Could not load (${res.status})`);
3148
+ e.name = "HttpError";
3149
+ e.status = res.status;
3150
+ throw e;
3151
+ }
3152
+ return res.text();
3153
+ })
3154
+ .then((text) => {
3155
+ try { return JSON.parse(text); }
3156
+ catch (err) {
3157
+ const e = new Error(STATE_FALLBACK.error);
3158
+ e.name = "ParseError";
3159
+ e.cause = err;
3160
+ throw e;
3161
+ }
3162
+ });
3163
+ }
3164
+
3165
+ /**
3166
+ * The value a component should render for one field: the attribute the author
3167
+ * wrote, else the matching key of the remote payload, else nothing.
3168
+ *
3169
+ * An array payload feeds the field the component asked for, so
3170
+ * `<contour-readout src="/rows.json">` works with a bare list; an object payload
3171
+ * is matched by key, so one endpoint can serve several fields of one component.
3172
+ * The return is always the string the render body already parses, so adopting this
3173
+ * changes no component's parsing.
3174
+ */
3175
+ /** Read the cached remote data for a field. */
3176
+ export function remoteData(host, field) {
3177
+ const authored = host.getAttribute(field);
3178
+ if (authored !== null) return authored;
3179
+ const data = host._remoteData;
3180
+ if (data === undefined || data === null) return null;
3181
+ if (Array.isArray(data)) return JSON.stringify(data);
3182
+ if (typeof data === "object") {
3183
+ const keys = typeof field === "string" ? [field] : field;
3184
+ for (const k of keys) {
3185
+ if (data[k] === undefined) continue;
3186
+ return typeof data[k] === "string" ? data[k] : JSON.stringify(data[k]);
3187
+ }
3188
+ return null;
3189
+ }
3190
+ return String(data);
3191
+ }
3192
+
3193
+ /**
3194
+ * `refresh="<seconds>"`: revalidate the source on a timer. The loop pauses while
3195
+ * the tab is hidden and stops when the host leaves the page, because a dashboard
3196
+ * left open in a background tab is the common way a design system becomes the
3197
+ * reason a laptop is warm.
3198
+ *
3199
+ * Registered once per mount: `remoteRefresh` is called from `render()`, and a
3200
+ * timer scheduled here fires and clears `_remoteTimer`, so the guard has to be a
3201
+ * flag that survives the tick or every re-render adds another loop.
3202
+ */
3203
+ /** Refresh remote data for a host. */
3204
+ export function remoteRefresh(host) {
3205
+ const seconds = parseFloat(host.getAttribute("refresh") || "");
3206
+ const want = host.hasAttribute("src") && Number.isFinite(seconds) && seconds > 0;
3207
+ if (!want) {
3208
+ if (host._remoteTimer !== undefined) { clearTimeout(host._remoteTimer); host._remoteTimer = undefined; }
3209
+ host._remoteLoop = false;
3210
+ return;
3211
+ }
3212
+ if (host._remoteLoop) return;
3213
+ host._remoteLoop = true;
3214
+ const tick = () => {
3215
+ host._remoteTimer = undefined;
3216
+ if (!host.isConnected || !host.hasAttribute("refresh")) { host._remoteLoop = false; return; }
3217
+ if (document.hidden) { host._remoteTimer = setTimeout(tick, 1000); return; }
3218
+ const src = host.getAttribute("src");
3219
+ const namedKey = host.getAttribute("cache-key");
3220
+ if (namedKey) remoteCache.delete(namedKey);
3221
+ remoteCache.delete(src);
3222
+ host._remoteSrc = null;
3223
+ host._remoteLoop = false;
3224
+ host.requestRender();
3225
+ };
3226
+ host._remoteTimer = setTimeout(tick, Math.max(1000, seconds * 1000));
3227
+ onDispose(host, () => {
3228
+ clearTimeout(host._remoteTimer);
3229
+ host._remoteTimer = undefined;
3230
+ host._remoteLoop = false;
3231
+ });
3232
+ }
3233
+
3234
+ // `loading="lazy"` belongs to the markup, not to the platform: an element below
3235
+ // the fold must not compete with the forty above it. Where IntersectionObserver
3236
+ // is missing the host simply asks, which is the honest fallback rather than never
3237
+ // asking at all.
3238
+ // One shared IntersectionObserver for every lazy host (B3-22): the previous
3239
+ // shape opened a fresh observer per host, so a dashboard with N lazy blocks
3240
+ // paid N observers for a single viewport. The shared observer fans entries out
3241
+ // to the host that owns each target; a host is unobserved (not the whole
3242
+ // observer disconnected) once it enters, so siblings keep watching.
3243
+ let _sharedLazyIO = null;
3244
+ const _sharedLazyTargets = new Map();
3245
+ /** Whether remote data is currently visible. */
3246
+ export function remoteVisible(host) {
3247
+ if (!host.hasAttribute("lazy")) return true;
3248
+ if (typeof IntersectionObserver !== "function") return true;
3249
+ if (host._remoteVisible) return true;
3250
+ if (host._lazyRegistered) return false;
3251
+ if (!_sharedLazyIO) {
3252
+ _sharedLazyIO = new IntersectionObserver((records) => {
3253
+ for (const r of records) {
3254
+ const activate = _sharedLazyTargets.get(r.target);
3255
+ if (!activate || !r.isIntersecting) continue;
3256
+ _sharedLazyTargets.delete(r.target);
3257
+ _sharedLazyIO.unobserve(r.target);
3258
+ activate();
3259
+ }
3260
+ }, { rootMargin: "200px" });
3261
+ }
3262
+ const activate = () => {
3263
+ host._remoteVisible = true;
3264
+ host._lazyRegistered = false;
3265
+ host.requestRender();
3266
+ };
3267
+ host._lazyRegistered = true;
3268
+ _sharedLazyTargets.set(host, activate);
3269
+ _sharedLazyIO.observe(host);
3270
+ onDispose(host, () => {
3271
+ _sharedLazyIO.unobserve(host);
3272
+ _sharedLazyTargets.delete(host);
3273
+ host._lazyRegistered = false;
3274
+ });
3275
+ return false;
3276
+ }
3277
+
3278
+ /**
3279
+ * Page-side visibility events (BY-42). The loader's `remoteVisible` is one-shot
3280
+ * and loader-internal: it exists to gate a single fetch. A dashboard that does
3281
+ * its own ink work (a non-loader animation, a slow layout) needs the same
3282
+ * signal exported, with both halves — enter AND leave — because "paused until
3283
+ * it enters" is only useful if the pause lifts. Events are the loader's own
3284
+ * convention: bubbles + composed, on the host.
3285
+ *
3286
+ * The returned disposer stops the observer; it is also wired to onDispose so a
3287
+ * host removed from the DOM stops observing without the caller tracking it.
3288
+ * Where IntersectionObserver is missing the honest fallback is to report the
3289
+ * element as entered once and stop: an unobserved element is not "never seen",
3290
+ * and a dashboard that waits for leave that can never come is a dashboard that
3291
+ * never resumes.
3292
+ */
3293
+ /** Watch viewport intersection for lazy loading. */
3294
+ export function watchViewport(host) {
3295
+ if (host._contourViewWired) return () => {};
3296
+ host._contourViewWired = true;
3297
+ const emit = (type) => host.dispatchEvent(new CustomEvent(type, { bubbles: true, composed: true }));
3298
+ if (typeof IntersectionObserver !== "function") {
3299
+ emit("contour:view-enter");
3300
+ return () => {};
3301
+ }
3302
+ const io = new IntersectionObserver((records) => {
3303
+ for (const r of records) {
3304
+ if (r.isIntersecting) emit("contour:view-enter");
3305
+ else emit("contour:view-leave");
3306
+ }
3307
+ });
3308
+ io.observe(host);
3309
+ onDispose(host, () => io.disconnect());
3310
+ return () => io.disconnect();
3311
+ }
3312
+
3313
+ // ---------------------------------------------------------------------------
3314
+ // The states themselves
3315
+ // ---------------------------------------------------------------------------
3316
+
3317
+ // A state node carries the block-scoped element class the sheet already defines
3318
+ // (`c-readout__loading`, `c-tree__empty`, …) so an author can theme one block's
3319
+ // state without reaching for the whole system, and never carries a `style`
3320
+ // attribute — which is the defect that made the matching CSS rule dead.
3321
+ //
3322
+ // It also carries `data-contour-state`, the only new hook here. The error state has
3323
+ // to read as a failure, but the per-block rules group `__error` with `__empty` and
3324
+ // `__loading` as muted text, so a failure looks exactly like a placeholder that
3325
+ // simply has not arrived yet. Colouring it by name would mean editing 34 rules in
3326
+ // the four sheets another writer is landing changes into; one rule on this
3327
+ // attribute does it, and an attribute is a host-set input rather than a published
3328
+ // class — no specimen, no inventory entry, nothing to deprecate.
3329
+ function stateNode(block, kind, text) {
3330
+ const node = document.createElement("div");
3331
+ node.className = "c-" + block + "__" + kind;
3332
+ node.dataset.contourState = kind;
3333
+ node.textContent = text;
3334
+ return node;
3335
+ }
3336
+
3337
+ function skeletonRow(i, total) {
3338
+ // The system's own skeleton block and its own modifiers: `--title` for the first
3339
+ // line so a placeholder has a shape instead of a uniform stack of bars, `--text`
3340
+ // for the rest. No per-block name is invented here, which is how the 33
3341
+ // undefined `c-*__skeleton` classes stop being generated at all.
3342
+ const node = document.createElement("div");
3343
+ node.className = "c-skeleton " + (i === 0 && total > 1 ? "c-skeleton--title" : "c-skeleton--text");
3344
+ node.dataset.contourState = "skeleton";
3345
+ return node;
3346
+ }
3347
+
3348
+ /**
3349
+ * Paint the host's data state, if it has one. Returns true when a state took over
3350
+ * the render, so the caller returns before building content it would discard.
3351
+ *
3352
+ * The order is deliberate: `loading` (attribute or open request) wins over `error`,
3353
+ * because a retry in flight is not a failure, and either wins over `skeleton`,
3354
+ * which is a placeholder for a state the host may already be in.
3355
+ */
3356
+ /** Render loading/empty/error states for a block. */
3357
+ export function renderStates(host, block, opts) {
3358
+ const options = opts || {};
3359
+ const loading = host.getAttribute("loading");
3360
+ if (loading !== null || host._remoteStatus === "loading") {
3361
+ host.appendChild(stateNode(block, "loading", loading || stateLabel(host, "loading")));
3362
+ return true;
3363
+ }
3364
+ const error = host.getAttribute("error");
3365
+ if (error !== null || host._remoteStatus === "error") {
3366
+ const message = (error !== null && error !== "") ? error : (host._remoteError || stateLabel(host, "error"));
3367
+ const node = stateNode(block, "error", message);
3368
+ // `retry` is the actionable half of an error. It reuses the button the system
3369
+ // already ships and the `contour:retry` event three components already emit,
3370
+ // rather than inventing a control for the same job.
3371
+ if (host.hasAttribute("retry")) {
3372
+ const btn = document.createElement("button");
3373
+ btn.type = "button";
3374
+ btn.className = "c-btn c-btn--ghost c-btn--sm";
3375
+ btn.textContent = host.getAttribute("retry") || "Retry";
3376
+ btn.dataset.action = "retry";
3377
+ node.appendChild(btn);
3378
+ }
3379
+ host.appendChild(node);
3380
+ return true;
3381
+ }
3382
+ if (host.hasAttribute("skeleton")) {
3383
+ const asked = parseInt(host.getAttribute("skeleton") || "3", 10);
3384
+ const count = Math.min(options.max || 6, Math.max(1, Number.isFinite(asked) ? asked : 3));
3385
+ for (let i = 0; i < count; i++) host.appendChild(skeletonRow(i, count));
3386
+ return true;
3387
+ }
3388
+ return false;
3389
+ }
3390
+
3391
+ /** Paint the empty state — for a host with no data and no authored content. */
3392
+ /** Render the empty state for a block. */
3393
+ export function renderEmpty(host, block) {
3394
+ host.appendChild(stateNode(block, "empty", host.getAttribute("empty") || stateLabel(host, "empty")));
3395
+ }
3396
+
3397
+ // Delegated on the host (AGENTS.md rule 12): the retry button is regenerated on
3398
+ // every render, so a listener bound to the node would be dropped by the next pass.
3399
+ /** Wire state (loading/empty/error) interactions for a host. */
3400
+ export function wireStates(host) {
3401
+ if (host._contourStatesWired) return;
3402
+ host._contourStatesWired = true;
3403
+ host.addEventListener("click", (e) => {
3404
+ const btn = e.target && e.target.closest ? e.target.closest('[data-action="retry"]') : null;
3405
+ if (!btn || !host.contains(btn)) return;
3406
+ e.preventDefault();
3407
+ const src = host.getAttribute("src");
3408
+ const namedKey = host.getAttribute("cache-key");
3409
+ if (namedKey) remoteCache.delete(namedKey);
3410
+ if (src) remoteCache.delete(src);
3411
+ leaveRequest(host);
3412
+ host._remoteSrc = null;
3413
+ host._remoteData = undefined;
3414
+ setStatus(host, "idle");
3415
+ emitState(host, "contour:retry", { src });
3416
+ host.requestRender();
3417
+ });
3418
+ }
3419
+
3420
+
3421
+ // ---- Registration: the class-only wrappers run last ------------------
3422
+ //
3423
+ // Order is the contract. Every complex component above claims its own name and
3424
+ // define() skips a name already claimed -- which is why
3425
+ // <contour-menu items='["Cut"]'> builds a <ul> instead of only gaining a class.
3426
+ // Move this loop back above the complex components and the scaffolding half of
3427
+ // this file becomes dead code again: it did, and no gate noticed.
3428
+ // Explicit defines (not a loop) so the coverage gate and tooling can see them.
3429
+ define("contour-box", simple(["c-box"]));
3430
+ define("contour-cluster", simple(["c-cluster"]));
3431
+ define("contour-container", simple(["c-container"]));
3432
+ define("contour-row", simple(["c-row"]));
3433
+ define("contour-scrim", simple(["c-scrim"]));
3434
+ define("contour-stack", simple(["c-stack"]));
3435
+
3436
+
3437
+
3438
+
3439
+ // ---- Shadow DOM wrappers (opt-in) ------------------------------------
3440
+ //
3441
+ // Every block below already ships a light-DOM element; a shadow wrapper is not
3442
+ // extra capability, it is the same block handed to a consumer who wants an
3443
+ // isolated root and named parts to style through ::part(). So the two tables
3444
+ // name the same blocks and must stay in step with each other, which is what
3445
+ // the contract gate checks.
3446
+ //
3447
+ // A CSSStyleSheet is adoptable by any number of roots, so the document's
3448
+ // same-origin sheets are serialised and parsed ONCE and shared. Rebuilding
3449
+ // them per instance re-parsed the whole 190 kB sheet for every element a page
3450
+ // mounted. The cache is keyed on the sheet list, so a stylesheet linked after
3451
+ // load is still picked up by the next element.
3452
+ //
3453
+ // The key counts what each sheet holds, not just how many sheets there are and
3454
+ // what they are called: an inline <style> replaced by another inline <style>
3455
+ // leaves both unchanged, and a cache keyed on identity alone would hand the
3456
+ // next instance a parse of the sheet that is no longer on the page.
3457
+ let ADOPTED = null;
3458
+ let ADOPTED_KEY = "";
3459
+ const adoptedSheets = () => {
3460
+ let key = document.styleSheets.length + ":";
3461
+ for (const sheet of document.styleSheets) {
3462
+ let rules = -1;
3463
+ try { rules = sheet.cssRules.length; } catch (e) { /* cross-origin: unreadable */ }
3464
+ key += (sheet.href || "") + "~" + rules + "|";
3465
+ }
3466
+ if (ADOPTED && key === ADOPTED_KEY) return ADOPTED;
3467
+ ADOPTED_KEY = key;
3468
+ ADOPTED = [];
3469
+ // Collect every rule a sheet carries, descending into @imported sheets,
3470
+ // because adoptedStyleSheets cannot hold @import rules (the platform
3471
+ // rejects them) and the imported sheets are not separate top-level entries
3472
+ // in document.styleSheets. Skipping them would hand the shadow root an
3473
+ // empty sheet.
3474
+ const collect = (sheet, out) => {
3475
+ let rules;
3476
+ try { rules = sheet.cssRules; } catch (e) { return; }
3477
+ if (!rules) return;
3478
+ for (const r of rules) {
3479
+ if (r instanceof CSSImportRule) {
3480
+ if (r.styleSheet) collect(r.styleSheet, out);
3481
+ } else {
3482
+ try { out.push(r.cssText); } catch (e) { /* unreadable */ }
3483
+ }
3484
+ }
3485
+ };
3486
+ for (const sheet of document.styleSheets) {
3487
+ try {
3488
+ if (sheet.href && new URL(sheet.href).origin === location.origin) {
3489
+ const collected = [];
3490
+ collect(sheet, collected);
3491
+ const built = new CSSStyleSheet();
3492
+ if (collected.length) built.replaceSync(collected.join("\n"));
3493
+ ADOPTED.push(built);
3494
+ }
3495
+ } catch (e) { /* cross-origin or unreadable */ }
3496
+ }
3497
+ return ADOPTED;
3498
+ };
3499
+
3500
+ // One base for every wrapper: adopt the sheets, clone the subclass template,
3501
+ // then keep the root's modifier classes in step with MODS on the host. The
3502
+ // base classes are snapshotted at construction, so a re-render cannot
3503
+ // accumulate a stale modifier the way an additive classList would.
3504
+ const _ShadowParent = (typeof HTMLElement !== "undefined") ? HTMLElement : Object;
3505
+ class ContourShadow extends _ShadowParent {
3506
+ static get observedAttributes() { return MODS; }
3507
+ constructor() {
3508
+ super();
3509
+ // Reuse a Declarative Shadow Root when the platform already attached one
3510
+ // (SSR/DSD hydration); otherwise create and populate the shadow root.
3511
+ let root = this.shadowRoot;
3512
+ if (!root) {
3513
+ root = this.attachShadow({ mode: "open" });
3514
+ if (this.constructor.contourTemplate) {
3515
+ root.appendChild(this.constructor.contourTemplate.content.cloneNode(true));
3516
+ }
3517
+ }
3518
+ const sheets = adoptedSheets();
3519
+ if (sheets.length) {
3520
+ try { root.adoptedStyleSheets = sheets; } catch (e) { /* unsupported or read-only */ }
3521
+ }
3522
+ this._shadowBase = root.firstElementChild ? root.firstElementChild.className : "";
3523
+ }
3524
+ // Subclasses with behaviour beyond the template override this.
3525
+ // Lifecycle note: listeners are attached to nodes inside the shadow root
3526
+ // (root-owned), not to the host, so they are collected when the root is
3527
+ // discarded on disconnect. No host-level disposers are required; the
3528
+ // root-owner invariant is what keeps this leak-free (R11-08).
3529
+ enhance(root) {
3530
+ if (!root) root = this.shadowRoot;
3531
+ if (!root) return;
3532
+ // ARIA setup is idempotent (guards on hasAttribute), so it re-runs on
3533
+ // slotchange to cover slotted content. Behaviour wiring is guarded by
3534
+ // wcClaim inside each wire* function, so it stays one-shot.
3535
+ // Native <button> already has an implicit role of "button"; do not
3536
+ // inject a redundant role (WAI-ARIA Rule 1).
3537
+ // ARIA: sync aria-expanded on disclosure/expandable details
3538
+ root.querySelectorAll("details").forEach((d) => {
3539
+ const summary = d.querySelector("summary");
3540
+ if (summary && !summary.hasAttribute("aria-expanded")) {
3541
+ summary.setAttribute("aria-expanded", String(d.open));
3542
+ d.addEventListener("toggle", () => {
3543
+ summary.setAttribute("aria-expanded", String(d.open));
3544
+ });
3545
+ }
3546
+ });
3547
+ // ARIA: ensure live regions have proper roles
3548
+ root.querySelectorAll("[data-live]").forEach((el) => {
3549
+ if (!el.hasAttribute("role")) el.setAttribute("role", "status");
3550
+ if (!el.hasAttribute("aria-live")) el.setAttribute("aria-live", "polite");
3551
+ });
3552
+ // ARIA: spinners and toasts get live region roles (opt-in: an author-set role wins)
3553
+ root.querySelectorAll(".c-spinner").forEach((el) => {
3554
+ if (!el.hasAttribute("role")) el.setAttribute("role", "status");
3555
+ if (!el.hasAttribute("aria-live")) el.setAttribute("aria-live", "polite");
3556
+ });
3557
+ // ARIA: toast elements get live region roles
3558
+ root.querySelectorAll(".c-toast, .c-toast-host").forEach((el) => {
3559
+ if (!el.hasAttribute("role")) el.setAttribute("role", "status");
3560
+ if (!el.hasAttribute("aria-live")) el.setAttribute("aria-live", "polite");
3561
+ if (!el.hasAttribute("aria-atomic")) el.setAttribute("aria-atomic", "true");
3562
+ });
3563
+ // ARIA: link tabs to panels via aria-controls
3564
+ root.querySelectorAll("[role='tab']").forEach((tab) => {
3565
+ const ctrl = tab.getAttribute("aria-controls");
3566
+ if (ctrl) {
3567
+ const panel = root.querySelector("#" + CSS.escape(ctrl)) || document.getElementById(ctrl);
3568
+ if (panel && !panel.hasAttribute("aria-labelledby")) {
3569
+ if (!tab.id) tab.id = contourId("tab");
3570
+ panel.setAttribute("aria-labelledby", tab.id);
3571
+ }
3572
+ }
3573
+ });
3574
+ // ARIA: link inputs to their labels/hints via aria-describedby
3575
+ root.querySelectorAll("input, textarea, select").forEach((input) => {
3576
+ if (input.hasAttribute("aria-describedby")) return;
3577
+ const field = input.closest(".c-field");
3578
+ if (field) {
3579
+ const hint = field.querySelector(".c-field__hint");
3580
+ if (hint) {
3581
+ if (!hint.id) hint.id = contourId("hint");
3582
+ input.setAttribute("aria-describedby", hint.id);
3583
+ }
3584
+ const err = field.querySelector(".c-field__error");
3585
+ if (err) {
3586
+ if (!err.id) err.id = contourId("err");
3587
+ const existing = input.getAttribute("aria-describedby") || "";
3588
+ input.setAttribute("aria-describedby", (existing + " " + err.id).trim());
3589
+ }
3590
+ }
3591
+ });
3592
+ // ARIA: alert elements are live regions, and the variant sets the volume.
3593
+ // A warning/danger interrupts; info/success/accent speaks politely. An
3594
+ // information alert that asserts itself on load talks over the reader.
3595
+ root.querySelectorAll(".c-alert").forEach((el) => {
3596
+ const urgent = el.classList.contains("c-alert--warning") || el.classList.contains("c-alert--danger");
3597
+ const role = urgent ? "alert" : "status";
3598
+ const live = urgent ? "assertive" : "polite";
3599
+ if (!el.hasAttribute("role") || el.dataset.contourAutoRole) {
3600
+ el.setAttribute("role", role);
3601
+ el.dataset.contourAutoRole = role;
3602
+ }
3603
+ if (!el.hasAttribute("aria-live") || el.dataset.contourAutoLive) {
3604
+ el.setAttribute("aria-live", live);
3605
+ el.dataset.contourAutoLive = live;
3606
+ }
3607
+ });
3608
+ // ARIA: required form fields
3609
+ root.querySelectorAll("input[required], textarea[required], select[required]").forEach((el) => {
3610
+ if (!el.hasAttribute("aria-required")) el.setAttribute("aria-required", "true");
3611
+ });
3612
+ // Interaction is delegated to the implementation the light-DOM wrappers
3613
+ // call too. This file used to carry its own copy of every behaviour, and the
3614
+ // copy queried the root for nodes the author slots into the light DOM, so it
3615
+ // found none and wired nothing: measured against the shipped bundle, slotted
3616
+ // tabs reported 2 such nodes outside the root and 0 inside it. The shared
3617
+ // module looks in both trees and dispatches on the host, the only node an
3618
+ // outside listener can reach across a shadow boundary.
3619
+ // Behaviour wiring lives in connectedCallback (slotted content present)
3620
+ // and is re-run on slotchange; see connectedCallback.
3621
+ }
3622
+ connectedCallback() {
3623
+ this.applyMods();
3624
+ try { this.enhance(this.shadowRoot); } catch (e) { /* ignore */ }
3625
+ // Wire behaviours now that slotted content is present.
3626
+ try {
3627
+ wcReset(this);
3628
+ wireTabs(this); wireSegmented(this); wireCombobox(this); wireTree(this);
3629
+ wireMenu(this); wirePagination(this); wireCopy(this); wireRemovable(this);
3630
+ } catch (e) { /* ignore */ }
3631
+ // Re-wire behaviour when slotted content changes. Reset the wired set so
3632
+ // behaviours can claim again now that slotted nodes exist.
3633
+ //
3634
+ // Guarded: this callback runs again whenever the host is moved in the
3635
+ // DOM, and attaching the listener unconditionally accumulated one per
3636
+ // move until a panel shuffled inside a tab re-wired on every slotchange
3637
+ // it had already handled.
3638
+ if (this.shadowRoot && !this._wiredSlotchange) {
3639
+ this._wiredSlotchange = true;
3640
+ this.shadowRoot.addEventListener("slotchange", () => {
3641
+ try { this.enhance(this.shadowRoot);
3642
+ wireTabs(this); wireSegmented(this); wireCombobox(this); wireTree(this);
3643
+ wireMenu(this); wirePagination(this); wireCopy(this); wireRemovable(this);
3644
+ } catch (e) { /* ignore */ }
3645
+ });
3646
+ }
3647
+ }
3648
+ attributeChangedCallback() { this.applyMods(); }
3649
+ applyMods() {
3650
+ const el = this.shadowRoot.firstElementChild;
3651
+ if (!el || !this._shadowBase) return;
3652
+ const mods = [];
3653
+ for (const attr of MODS) {
3654
+ const val = this.getAttribute(attr);
3655
+ if (!val) continue;
3656
+ for (const cls of this._shadowBase.split(/\s+/)) {
3657
+ if (cls) mods.push("c-" + cls.replace(/^c-/, "") + "--" + val);
3658
+ }
3659
+ }
3660
+ el.className = (this._shadowBase + " " + mods.join(" ")).trim();
3661
+ // An alert's live region follows its variant, and rewriting the class above
3662
+ // is the only signal a variant change produces. `dataset.contourAutoRole`
3663
+ // marks a role this code set, so an authored one is never overwritten.
3664
+ if (el.classList.contains("c-alert")) {
3665
+ const urgent = el.classList.contains("c-alert--warning") || el.classList.contains("c-alert--danger");
3666
+ const role = urgent ? "alert" : "status";
3667
+ const live = urgent ? "assertive" : "polite";
3668
+ if (!el.hasAttribute("role") || el.dataset.contourAutoRole) {
3669
+ el.setAttribute("role", role);
3670
+ el.dataset.contourAutoRole = role;
3671
+ }
3672
+ if (!el.hasAttribute("aria-live") || el.dataset.contourAutoLive) {
3673
+ el.setAttribute("aria-live", live);
3674
+ el.dataset.contourAutoLive = live;
3675
+ }
3676
+ }
3677
+ }
3678
+ }
3679
+
3680
+ // Registers a wrapper. The template markup is always recorded so Node/SSR
3681
+ // tooling can emit Declarative Shadow DOM strings; in a browser the template
3682
+ // is also parsed once into a <template> and cloned per instance.
3683
+ const SHADOW_PARTS_PUBLIC = {};
3684
+ const SHADOW_MARKUP = {};
3685
+ const recordParts = (name, markup) => {
3686
+ SHADOW_PARTS_PUBLIC[name] = [...markup.matchAll(/part="([^"]+)"/g)]
3687
+ .flatMap((m) => m[1].split(/\s+/))
3688
+ .filter(Boolean);
3689
+ };
3690
+ const shadow = (name, markup) => {
3691
+ SHADOW_MARKUP[name] = markup;
3692
+ recordParts(name, markup);
3693
+ if (typeof document === "undefined") return;
3694
+ const tpl = document.createElement("template");
3695
+ tpl.innerHTML = markup;
3696
+ const cls = class extends ContourShadow {};
3697
+ cls.contourTemplate = tpl;
3698
+ define(name, cls);
3699
+ };
3700
+
3701
+ // A wrapper that is one default slot needs no markup of its own: the element,
3702
+ // the class, the part and the name all follow from the block, so the table
3703
+ // holds the block and the tag.
3704
+ const slotWrapper = (tag, block, part) =>
3705
+ "<" + tag + ' class="c-' + block + '" part="' + (part || block) + '"' + (tag === "button" ? ' type="button"' : "") + "><slot></slot></" + tag + ">";
3706
+ const SHADOW_SLOTS = {
3707
+ div: [
3708
+ "accordion", "activity", "advanced", "affordance", "affordances", "anchor", "app", "app-body", "box", "btn-group", "chart-grid",
3709
+ "catchment", "cluster", "command", "compare", "comparison", "compass",
3710
+ "contour-plot", "cta", "dash-freshness", "dash-kpi-row", "dash-shell", "dash-toolbar", "datamark", "delta", "draggable", "drag-handle", "drop-indicator", "drop-zone",
3711
+ "destructive-hint", "docs-shell", "drawer", "elevation",
3712
+ "filter-bar", "flow-map", "heatmap", "hexbin", "icon-badge", "input-group", "instrument", "range-scale", "resizable", "table-wrap", "time-range", "toast-host", "scroll-area",
3713
+ "isochrone", "landing-features", "landing-hero", "layer-panel", "layer-switch", "legend", "logos", "map-area",
3714
+ "map-footer", "map-panel", "map-slot", "measure", "metrics", "minimap", "pager", "pagination",
3715
+ "panel", "plate", "price", "pricing", "progress", "prose", "pullquote", "radio-list",
3716
+ "range", "readout", "recipe", "reserved", "resize-handle", "row",
3717
+ "row-action", "scale-bar", "scrim", "segmented", "sheet", "shortcut-list", "shortcut-overlay", "shortcut-panel",
3718
+ "shortcut-row", "showcase", "sidebar", "skeleton", "sparkline", "stack", "steps", "streaming-chart",
3719
+ "survey", "theme-scope", "time-slider", "timeline", "toast",
3720
+ "toolbar", "tooltip", "tree", "version", "version-banner"
3721
+ ],
3722
+ button: [
3723
+ "btn", "pressable", "scheme-toggle"
3724
+ ],
3725
+ span: [
3726
+ "avatar", "badge", "chip", "dot", "flag", "live-badge", "mark", "pill"
3727
+ ],
3728
+ a: [
3729
+ "link", "linkish"
3730
+ ],
3731
+ kbd: [
3732
+ "kbd"
3733
+ ],
3734
+ label: [
3735
+ "check", "radio", "switch"
3736
+ ],
3737
+ select: [
3738
+ "select"
3739
+ ],
3740
+ nav: [
3741
+ "docs-nav"
3742
+ ],
3743
+ };
3744
+
3745
+ // Two wrappers name their part after the region it holds rather than after
3746
+ // the block, and one names it after the banner. Pinned here because the part
3747
+ // is the contract a consumer styles against. Declared before the loop that
3748
+ // reads it: a const in a temporal dead zone throws at load and takes the
3749
+ // whole file down with it.
3750
+ const SHADOW_PARTS = {
3751
+ "version-banner": "banner",
3752
+ "contour-plot": "plot",
3753
+ };
3754
+
3755
+ // The slot wrappers are recorded wherever this module runs. `shadow()` already
3756
+ // returns before touching `document` when there is none, so the markup is
3757
+ // available to Node/SSR either way — which is the whole point of recording it.
3758
+ // This loop used to sit inside the browser guard, so `renderShadowDSD` could
3759
+ // only resolve the 50 hand-written wrappers in Node and returned null for the
3760
+ // 121 slot wrappers, i.e. it failed in the one environment it exists for.
3761
+ for (const [tag, blocks] of Object.entries(SHADOW_SLOTS)) {
3762
+ for (const block of blocks) {
3763
+ const part = SHADOW_PARTS[block] || block;
3764
+ shadow("contour-shadow-" + block, slotWrapper(tag, block, part));
3765
+ }
3766
+ }
3767
+
3768
+ // Structured templates: more than one slot, or a class that is not the block's
3769
+ // own, so the markup is the definition and is written out.
3770
+ shadow("contour-shadow-callout", `<div class="c-callout" part="callout"><div class="c-callout__title" part="title"><slot name="title"></slot></div><div class="c-callout__body" part="body"><slot></slot></div><button class="c-callout__close" part="close" type="button" aria-label="Close">×</button></div>`);
3771
+ shadow("contour-shadow-empty", `<div class="c-empty" part="empty"><div class="c-empty__illustration" part="illustration"><slot name="illustration"></slot></div><div class="c-empty__title" part="title"><slot name="title"></slot></div><div class="c-empty__text" part="body"><slot></slot></div><div><slot name="action"></slot></div></div>`);
3772
+ shadow("contour-shadow-feature", `<div class="c-feature" part="feature"><span class="c-feature__index" part="index"><slot name="index"></slot></span><div class="c-feature__title" part="title"><slot name="title"></slot></div><div class="c-feature__body" part="body"><slot></slot></div></div>`);
3773
+ shadow("contour-shadow-kpi", `<div class="c-kpi" part="kpi"><div class="c-kpi__value" part="value"><slot name="value"></slot></div><div class="c-kpi__label" part="label"><slot name="label"></slot></div><div class="c-kpi__foot" part="foot"><slot name="delta"></slot><slot name="note"></slot></div></div>`);
3774
+ shadow("contour-shadow-stat", `<div class="c-stat" part="stat"><div class="c-stat__value" part="value"><slot name="value"></slot></div><div class="c-stat__label" part="label"><slot name="label"></slot></div><div class="c-stat__delta" part="delta"><slot name="delta"></slot></div></div>`);
3775
+ shadow("contour-shadow-meter", `<div class="c-meter" part="meter"><span class="c-meter__core" part="core"><span class="c-meter__value" part="value"><slot name="value"></slot></span><span class="c-meter__label" part="label"><slot name="label"></slot></span></span></div>`);
3776
+ shadow("contour-shadow-brownout", `<div class="c-brownout" part="brownout" data-level="0"><slot></slot></div>`);
3777
+ shadow("contour-shadow-widget-state", `<div class="c-widget-state" part="widget-state"><slot></slot></div>`);
3778
+ shadow("contour-shadow-donut", `<div class="c-donut" part="donut"><svg class="c-donut__ring" part="ring" viewBox="0 0 32 32"></svg><div class="c-donut__center" part="center"><slot name="value"></slot></div><div class="c-donut__list" part="list"><slot></slot></div></div>`);
3779
+ shadow("contour-shadow-axis", `<div class="c-axis" part="axis"><slot></slot></div>`);
3780
+ shadow("contour-shadow-brush", `<div class="c-brush" part="brush"><div class="c-brush__selection" part="selection"></div></div>`);
3781
+ shadow("contour-shadow-stacked-bar", `<div class="c-stacked-bar" part="bar"><slot></slot></div>`);
3782
+ shadow("contour-shadow-category", `<div class="c-category" part="category" role="listbox"><slot></slot></div>`);
3783
+ shadow("contour-shadow-gauge", `<div class="c-gauge" part="gauge"><svg class="c-gauge__dial" part="dial" aria-hidden="true" viewBox="0 0 100 100"><path class="c-gauge__track" part="track" d="M 10 90 A 40 40 0 0 1 90 90"></path><g class="c-gauge__zones"></g><line class="c-gauge__needle" part="needle" x1="50" y1="50" x2="50" y2="15"></line><circle class="c-gauge__hub" part="hub" cx="50" cy="50" r="4"></circle></svg><div class="c-gauge__value" part="value"><slot name="value"></slot></div><div class="c-gauge__band" part="band"><slot name="band"></slot></div></div>`);
3784
+ shadow("contour-shadow-diff", `<div class="c-diff" part="diff"><div class="c-diff__line c-diff__line--del" part="before"><span class="c-diff__sign">−</span><span><slot name="before"></slot></span></div><div class="c-diff__line c-diff__line--add" part="after"><span class="c-diff__sign">+</span><span><slot name="after"></slot></span></div></div>`);
3785
+ shadow("contour-shadow-do-dont", `<div class="c-do-dont" part="do-dont"><div class="c-do-dont__item c-do-dont__item--do" part="do"><slot name="do"></slot></div><div class="c-do-dont__item c-do-dont__item--dont" part="dont"><slot name="dont"></slot></div></div>`);
3786
+ shadow("contour-shadow-threshold", `<div class="c-threshold" part="threshold"><span class="c-threshold__fill" part="value"></span><span class="c-threshold__target" part="target"></span></div>`);
3787
+ shadow("contour-shadow-coordinate", `<div class="c-coordinate" part="coordinate"><span class="c-coordinate__value" part="value"><slot name="value"></slot></span></div>`);
3788
+ shadow("contour-shadow-install", `<div class="c-install" part="install"><span class="c-install__prompt" part="prompt"><slot name="prompt"></slot></span><span class="c-install__command" part="command"><slot name="command"></slot></span><button class="c-btn c-btn--ghost c-btn--sm c-install__copy" part="copy" type="button" aria-label="Copy command">Copy</button></div>`);
3789
+ shadow("contour-shadow-toc", `<div class="c-toc" part="toc"><div class="c-toc__title" part="title"><slot name="title"></slot></div><nav class="c-toc__list" part="list"><slot></slot></nav></div>`);
3790
+ shadow("contour-shadow-testimonial", `<div class="c-testimonial" part="testimonial"><blockquote class="c-testimonial__quote" part="quote"><slot name="quote"></slot></blockquote><div class="c-testimonial__byline" part="byline"><span class="c-testimonial__name" part="name"><slot name="name"></slot></span><span class="c-testimonial__role" part="role"><slot name="role"></slot></span></div></div>`);
3791
+ shadow("contour-shadow-search-trigger", `<button class="c-search-trigger" part="trigger"><span><slot name="label"></slot></span><kbd class="c-search-trigger__kbd"><slot name="shortcut"></slot></kbd></button>`);
3792
+ shadow("contour-shadow-brand", `<a class="c-brand" part="brand"><span class="c-mark" part="mark"><slot name="mark"></slot></span><span class="c-brand__name" part="name"><slot name="name"></slot></span></a>`);
3793
+ shadow("contour-shadow-section-head", `<div class="c-section-head" part="head"><h2 class="c-section-head__title" part="title"><slot name="title"></slot></h2><p class="c-section-head__desc" part="desc"><slot name="desc"></slot></p></div>`);
3794
+ shadow("contour-shadow-loading", `<div class="c-loading" part="loading"><span class="c-spinner" part="spinner"></span><slot></slot></div>`);
3795
+ // Shadow tabs are a styling shell: panels are authored by the consumer
3796
+ // (the light layer generates them from a `tabs` attribute). The default
3797
+ // slot below is the panel container; consumers place `c-tabs__panel`
3798
+ // elements (or any content) there. See §23 shadow-parity note.
3799
+ shadow("contour-shadow-tabs", `<div class="c-tabs" part="tabs"><div class="c-tabs__list" part="list" role="tablist"><slot name="tabs"></slot></div><div class="c-tabs__panels" role="presentation"><slot></slot></div></div>`);
3800
+ shadow("contour-shadow-breadcrumb", `<nav class="c-breadcrumb" part="breadcrumb" aria-label="Breadcrumb"><ol><slot></slot></ol></nav>`);
3801
+ shadow("contour-shadow-menu", `<div class="c-menu" part="menu" role="menu"><slot></slot></div>`);
3802
+ shadow("contour-shadow-combobox", `<div class="c-combobox" part="combobox"><input class="c-combobox__input" part="input" type="text" /><ul class="c-combobox__list" part="list" hidden><slot></slot></ul></div>`);
3803
+ shadow("contour-shadow-table", `<div class="c-table-wrap" part="wrap"><table class="c-table" part="table"><thead><slot name="head"></slot></thead><tbody><slot></slot></tbody></table></div>`);
3804
+ shadow("contour-shadow-chart", `<div class="c-chart" part="chart"><div class="c-chart__plot" part="plot"><slot></slot></div></div>`);
3805
+ shadow("contour-shadow-bivariate", `<div class="c-bivariate" part="bivariate"><div class="c-bivariate__matrix" part="matrix"><slot></slot></div></div>`);
3806
+ shadow("contour-shadow-bivariate-legend", `<div class="c-bivariate-legend" part="legend"><div class="c-bivariate-legend__matrix" part="matrix"><slot></slot></div></div>`);
3807
+ shadow("contour-shadow-expandable", `<details class="c-expandable" part="expandable"><summary class="c-expandable__summary"><slot name="summary"></slot></summary><div class="c-expandable__body" part="body"><slot></slot></div></details>`);
3808
+ shadow("contour-shadow-disclosure", `<details class="c-disclosure" part="disclosure"><summary><slot name="summary"></slot></summary><div class="c-disclosure__body" part="body"><slot></slot></div></details>`);
3809
+ shadow("contour-shadow-faq", `<div class="c-faq" part="faq"><div class="c-faq__question" part="question"><slot name="question"></slot></div><div class="c-faq__answer" part="answer"><slot name="answer"></slot></div></div>`);
3810
+ shadow("contour-shadow-code-tabs", `<div class="c-code-tabs" part="code-tabs"><div class="c-code-tabs__list" part="list" role="tablist"><slot name="tabs"></slot></div><div class="c-code-tabs__panels"><slot></slot></div></div>`);
3811
+ shadow("contour-shadow-header", `<header class="c-header" part="header"><div class="container c-header__inner" part="inner"><a class="c-brand" part="brand"><slot name="brand"></slot></a><nav class="c-header__nav" part="nav"><slot name="nav"></slot></nav><div class="c-header__actions" part="actions"><slot name="actions"></slot></div></div></header>`);
3812
+ shadow("contour-shadow-footer", `<footer class="c-footer" part="footer"><div class="container c-footer__grid" part="grid"><div class="c-footer__brand" part="brand"><slot name="brand"></slot></div><div class="c-footer__links" part="links"><slot name="links"></slot></div></div></footer>`);
3813
+ shadow("contour-shadow-container", `<div class="container" part="container"><slot></slot></div>`);
3814
+ shadow("contour-shadow-input", `<input class="c-input" part="input" />`);
3815
+ shadow("contour-shadow-spinner", `<span class="c-spinner" part="spinner" aria-label="Loading"></span>`);
3816
+ shadow("contour-shadow-textarea", `<textarea class="c-textarea" part="textarea"></textarea>`);
3817
+ shadow("contour-shadow-code", `<pre class="c-code" part="code"><code><slot></slot></code><button class="c-code__copy" part="copy" type="button">Copy</button></pre>`);
3818
+ // (folded in from the hand-written component that used to carry its own copy of the sheet logic)
3819
+ shadow("contour-shadow-card", `<div class="c-card" part="card"> <div class="c-card__title" part="head"><slot name="title">Untitled</slot></div> <div class="c-card__body" part="body"><slot></slot></div> <div class="c-card__foot" part="foot"><slot name="foot"></slot></div> </div>`);
3820
+ // (folded in from the hand-written component that used to carry its own copy of the sheet logic)
3821
+ // (folded in from the hand-written component that used to carry its own copy of the sheet logic)
3822
+ shadow("contour-shadow-field", `<div class="c-field" part="field"> <label class="c-field__label" part="label"><slot name="label">Label</slot></label> <slot name="input"></slot> <span class="c-field__hint" part="hint"><slot name="hint"></slot></span> </div>`);
3823
+ // (folded in from the hand-written component that used to carry its own copy of the sheet logic)
3824
+ shadow("contour-shadow-alert", `<div class="c-alert" part="alert"> <div class="c-alert__title" part="title"><slot name="title"></slot></div> <div class="c-alert__body" part="body"><slot></slot></div> <div class="c-alert__actions" part="actions"><slot name="action"></slot></div> <button class="c-alert__close" part="close" type="button" aria-label="Close">×</button> </div>`);
3825
+ shadow("contour-shadow-tag", `<span class="c-tag" part="tag"><slot></slot><button class="c-tag__remove" part="remove" type="button" aria-label="Remove">×</button></span>`);
3826
+ shadow("contour-shadow-filter-pill", `<span class="c-filter-pill" part="filter-pill"><slot></slot><button class="c-filter-pill__remove" part="remove" type="button" aria-label="Remove filter">×</button></span>`);
3827
+
3828
+ // The dialog is the one wrapper with behaviour, because a close button that
3829
+ // does not close is a control the reader cannot use.
3830
+ const DIALOG_MARKUP = "<dialog class=\"c-dialog\" part=\"dialog\"> <div class=\"c-dialog__head\" part=\"head\"> <slot name=\"title\"></slot> <button class=\"c-btn c-btn--icon c-btn--ghost\" part=\"close\" type=\"button\" aria-label=\"Close\"> <svg aria-hidden=\"true\"><use href=\"#i-x\" /></svg> </button> </div> <div class=\"c-dialog__body\" part=\"body\"><slot></slot></div> <div class=\"c-dialog__foot\" part=\"foot\"><slot name=\"foot\"></slot></div> </dialog>";
3831
+ SHADOW_MARKUP["contour-shadow-dialog"] = DIALOG_MARKUP;
3832
+ recordParts("contour-shadow-dialog", DIALOG_MARKUP);
3833
+ class ContourShadowDialog extends ContourShadow {
3834
+ static contourTemplate = (typeof document !== "undefined") ? (() => {
3835
+ const tpl = document.createElement("template");
3836
+ tpl.innerHTML = DIALOG_MARKUP;
3837
+ return tpl;
3838
+ })() : null;
3839
+ enhance(root) {
3840
+ super.enhance(root);
3841
+ // The base constructor AND connectedCallback both call enhance; the base's
3842
+ // own edits are idempotent by guard, so this override must guard as well
3843
+ // or one native beforetoggle dispatches contour:open/close twice (measured
3844
+ // open:2/close:2 for a single show()/close(), shadow-dialog-events probe).
3845
+ if (this._wiredShadowDialog) return;
3846
+ this._wiredShadowDialog = true;
3847
+ const dlg = root.querySelector("dialog");
3848
+ const close = root.querySelector('[part="close"]');
3849
+ if (close) close.addEventListener("click", () => dlg?.close());
3850
+ if (dlg) {
3851
+ let lastFocus = null;
3852
+ // `<dialog>` fires no `show` or `close` events in this engine (measured
3853
+ // bare-dialog probe, 2026-10-28): the only open/close signal is
3854
+ // `beforetoggle` with a `newState`. The earlier `show`/`close` listeners
3855
+ // were dead code, so the shadow twin's contour:open/contour:close never
3856
+ // fired while the light twin's did — a parity break the dialog-family
3857
+ // probe caught at opened:0, closed:0.
3858
+ dlg.addEventListener("beforetoggle", (e) => {
3859
+ if (e.newState === "open") {
3860
+ lastFocus = document.activeElement;
3861
+ this.dispatchEvent(new CustomEvent("contour:open", { bubbles: true, composed: true }));
3862
+ // Focus the close button or first focusable element
3863
+ const focusable = dlg.querySelector("button, [href], input, select, textarea, [tabindex]:not([tabindex='-1'])");
3864
+ if (focusable) try { focusable.focus(); } catch (e) {}
3865
+ } else if (e.newState === "closed") {
3866
+ this.dispatchEvent(new CustomEvent("contour:close", { bubbles: true, composed: true }));
3867
+ // Restore focus
3868
+ if (lastFocus && typeof lastFocus.focus === "function") {
3869
+ try { lastFocus.focus(); } catch (e) {}
3870
+ }
3871
+ }
3872
+ });
3873
+ // Focus trap: keep Tab within the dialog
3874
+ dlg.addEventListener("keydown", (e) => {
3875
+ if (e.key !== "Tab") return;
3876
+ const focusables = Array.from(dlg.querySelectorAll("button, [href], input, select, textarea, [tabindex]:not([tabindex='-1'])"));
3877
+ if (!focusables.length) return;
3878
+ const first = focusables[0];
3879
+ const last = focusables[focusables.length - 1];
3880
+ if (e.shiftKey && document.activeElement === first) {
3881
+ e.preventDefault();
3882
+ last.focus();
3883
+ } else if (!e.shiftKey && document.activeElement === last) {
3884
+ e.preventDefault();
3885
+ first.focus();
3886
+ }
3887
+ });
3888
+ }
3889
+ }
3890
+ show() { this.shadowRoot?.querySelector("dialog")?.showModal(); }
3891
+ close() { this.shadowRoot?.querySelector("dialog")?.close(); }
3892
+ // Native-dialog parity with the light family (R20 T-32): showModal() is
3893
+ // the same modal open path under its native name, open routes through
3894
+ // show()/close(), and returnValue delegates to the platform's own.
3895
+ showModal() { this.show(); }
3896
+ get open() { return !!this.shadowRoot?.querySelector("dialog")?.open; }
3897
+ set open(v) { if (v) this.show(); else this.close(); }
3898
+ get returnValue() { return this.shadowRoot?.querySelector("dialog")?.returnValue ?? ""; }
3899
+ set returnValue(v) { const d = this.shadowRoot?.querySelector("dialog"); if (d) d.returnValue = String(v); }
3900
+ }
3901
+ define("contour-shadow-dialog", ContourShadowDialog);
3902
+
3903
+ /**
3904
+ * Render a Declarative Shadow DOM string for a registered contour-shadow-* element.
3905
+ * Intended for SSR/string emission; returns null for unknown tags.
3906
+ */
3907
+ const renderShadowDSD = (tag, attrs = "", light = "") => {
3908
+ const markup = SHADOW_MARKUP[tag];
3909
+ if (typeof markup !== "string") return null;
3910
+ const attrStr = attrs ? (attrs.startsWith(" ") ? attrs : " " + attrs) : "";
3911
+ return `<${tag}${attrStr}><template shadowrootmode="open">${markup}</template>${light}</${tag}>`;
3912
+ };
3913
+
3914
+ // Published once, at the end, so the array holds what the browser was actually
3915
+ // handed rather than what the source appears to say. Frozen: a page that
3916
+ // reshapes it would make the next reader's count wrong, which is the failure
3917
+ // this array exists to prevent.
3918
+ const FROZEN_SHADOW_MARKUP = Object.freeze({ ...SHADOW_MARKUP });
3919
+ if (typeof globalThis !== "undefined") {
3920
+ globalThis.ContourShadowTemplates = FROZEN_SHADOW_MARKUP;
3921
+ }
3922
+ if (typeof window !== "undefined") {
3923
+ window.ContourElements = Object.freeze(REGISTERED.slice());
3924
+ window.ContourShadowParts = Object.freeze(Object.fromEntries(
3925
+ Object.entries(SHADOW_PARTS_PUBLIC).map(([name, parts]) => [name, Object.freeze([...new Set(parts)])]),
3926
+ ));
3927
+ // Same rule for the event vocabulary: the manifest is frozen at publish so a
3928
+ // page cannot add names the source never emitted, which would make the gate's
3929
+ // "every dispatchEvent name has an entry" read meaningless.
3930
+ window.ContourEvents = Object.freeze(CONTOUR_EVENTS);
3931
+ if (!window.Contour) window.Contour = {};
3932
+ try { window.Contour.shadowTemplates = FROZEN_SHADOW_MARKUP; } catch {}
3933
+ }
3934
+
3935
+ export { SHADOW_MARKUP, renderShadowDSD };
3936
+
3937
+ class ContourResizeObserver extends ContourBase {
3938
+ static get observed() { return ["debounce"]; }
3939
+ static get properties() { return { debounce: { attribute: "debounce" } }; }
3940
+ render() {
3941
+ this.classList.add("c-resize-observer");
3942
+ this.setAttribute("aria-hidden", "true");
3943
+ }
3944
+ enhance() {
3945
+ if (this._wiredResizeObserver) return;
3946
+ this._wiredResizeObserver = true;
3947
+ if (typeof ResizeObserver !== "function") return;
3948
+ const debounce = parseInt(this.getAttribute("debounce") || "0", 10) || 0;
3949
+ let timer = null;
3950
+ const ro = new ResizeObserver((entries) => {
3951
+ const fire = () => {
3952
+ const e = entries[entries.length - 1];
3953
+ const cr = e && e.contentRect ? e.contentRect : this.getBoundingClientRect();
3954
+ this.dispatchEvent(new CustomEvent("contour:resize", { bubbles: true, composed: true, detail: { width: cr.width, height: cr.height } }));
3955
+ };
3956
+ if (debounce > 0) { clearTimeout(timer); timer = setTimeout(fire, debounce); }
3957
+ else fire();
3958
+ });
3959
+ ro.observe(this);
3960
+ onDispose(this, () => { ro.disconnect(); clearTimeout(timer); });
3961
+ }
3962
+ }
3963
+ define("contour-resize-observer", ContourResizeObserver);
3964
+
3965
+
3966
+ class ContourReservedFull extends ContourBase {
3967
+ static get observed() { return ["title"]; }
3968
+ static get properties() { return { title: { attribute: "title" } }; }
3969
+ render() {
3970
+ this.classList.add("c-reserved");
3971
+ const title = this.getAttribute("title");
3972
+ if (title) {
3973
+ const t = this.ensure(".c-reserved__title", () => { const el = document.createElement("div"); el.className = "c-reserved__title"; return el; });
3974
+ t.textContent = title;
3975
+ }
3976
+ }
3977
+ }
3978
+ define("contour-reserved", ContourReservedFull);
3979
+ class ContourThemeScopeFull extends ContourBase {
3980
+ static get observed() { return ["title"]; }
3981
+ static get properties() { return { title: { attribute: "title" } }; }
3982
+ render() {
3983
+ this.classList.add("c-theme-scope");
3984
+ const title = this.getAttribute("title");
3985
+ if (title) {
3986
+ const t = this.ensure(".c-theme-scope__title", () => { const el = document.createElement("div"); el.className = "c-theme-scope__title"; el.style.padding = "var(--space-sm)"; el.style.fontWeight = "var(--weight-semibold)"; return el; });
3987
+ t.textContent = title;
3988
+ }
3989
+ }
3990
+ }
3991
+ define("contour-theme-scope", ContourThemeScopeFull);
3992
+ class ContourActivity extends ContourBase {
3993
+ static get observed() { return ["items", "empty", "loading", "error", "retry", "src", "lazy", "refresh", "timeout", "skeleton"]; }
3994
+ static get properties() { return { items: { attribute: "items" }, src: { attribute: "src" } }; }
3995
+ render() {
3996
+ this.classList.add("c-activity");
3997
+ this.setAttribute("role", "list");
3998
+ wireStates(this);
3999
+ loadRemote(this, "items");
4000
+ if (renderStates(this, "activity")) return;
4001
+ const items = remoteData(this, "items");
4002
+ if (items) {
4003
+ try {
4004
+ const parsed = JSON.parse(items);
4005
+ Array.from(this.querySelectorAll(".c-activity__item")).forEach((n) => n.remove());
4006
+ parsed.forEach((it, i) => {
4007
+ const item = document.createElement("div");
4008
+ item.className = "c-activity__item";
4009
+ item.setAttribute("role", "button");
4010
+ // The first item is the list's tab stop; otherwise the roving
4011
+ // keydown handler never receives focus from the keyboard.
4012
+ item.setAttribute("tabindex", i === 0 ? "0" : "-1");
4013
+ const dot = document.createElement("span");
4014
+ dot.className = "c-activity__dot c-activity__dot--" + (it.variant || "primary");
4015
+ dot.setAttribute("aria-hidden", "true");
4016
+ item.appendChild(dot);
4017
+ const text = document.createElement("span");
4018
+ text.className = "c-activity__text";
4019
+ text.textContent = typeof it === "string" ? it : (it.text || it.label || "");
4020
+ if (!item.hasAttribute("aria-label")) item.setAttribute("aria-label", text.textContent);
4021
+ item.appendChild(text);
4022
+ if (it.time) {
4023
+ const time = document.createElement("span");
4024
+ time.className = "c-activity__time";
4025
+ time.textContent = it.time;
4026
+ item.appendChild(time);
4027
+ }
4028
+ this.appendChild(item);
4029
+ });
4030
+ } catch (e) { warnBadJson(this, "attribute", e); }
4031
+ } else {
4032
+ renderEmpty(this, "activity");
4033
+ }
4034
+ }
4035
+ enhance() {
4036
+ if (this._wiredActivity) return;
4037
+ this._wiredActivity = true;
4038
+ this.addEventListener("click", (e) => {
4039
+ const item = e.target && e.target.closest ? e.target.closest(".c-activity__item") : null;
4040
+ if (item && this.contains(item)) {
4041
+ const items = Array.from(this.querySelectorAll(".c-activity__item"));
4042
+ const index = items.indexOf(item);
4043
+ const text = item.querySelector(".c-activity__text")?.textContent || "";
4044
+ this.dispatchEvent(new CustomEvent("contour:activity-select", { bubbles: true, composed: true, detail: { index, text } }));
4045
+ }
4046
+ });
4047
+ this.addEventListener("keydown", (e) => {
4048
+ const items = Array.from(this.querySelectorAll(".c-activity__item"));
4049
+ if (!items.length) return;
4050
+ navKey(e, items, { wrap: false, homeEnd: true, onNavigate: (i) => { items.forEach((it, j) => it.tabIndex = j === i ? 0 : -1); }, onKey: () => { if (e.key === "Enter" || e.key === " ") { const idx = items.indexOf(document.activeElement); this.dispatchEvent(new CustomEvent("contour:activity-select", { bubbles: true, composed: true, detail: { index: idx, text: document.activeElement.querySelector(".c-activity__text")?.textContent || "" } })); } } });
4051
+ });
4052
+ }
4053
+ }
4054
+ define("contour-activity", ContourActivity);
4055
+ class ContourActivityFeed extends ContourBase {
4056
+ static get observed() { return ["items", "filter", "unread-only", "empty", "loading", "error", "labels", "src", "lazy", "refresh", "timeout", "skeleton"]; }
4057
+ static get properties() { return { items: { attribute: "items" }, filter: { attribute: "filter" }, "unread-only": { attribute: "unread-only", type: Boolean } }; }
4058
+ render() {
4059
+ this.classList.add("c-activity-feed");
4060
+ if (!this.hasAttribute("role")) this.setAttribute("role", "region");
4061
+ if (!this.hasAttribute("aria-label")) this.setAttribute("aria-label", labelText(this, "title", "Activity feed"));
4062
+ wireStates(this);
4063
+ loadRemote(this, "items");
4064
+ if (renderStates(this, "activity-feed")) return;
4065
+ const items = remoteData(this, "items");
4066
+ const filter = this.getAttribute("filter");
4067
+ const unreadOnly = this.hasAttribute("unread-only");
4068
+ let header = this.querySelector(".c-activity-feed__header");
4069
+ if (!header) { header = document.createElement("div"); header.className = "c-activity-feed__header"; this.insertBefore(header, this.firstChild); }
4070
+ let title = header.querySelector(".c-activity-feed__title");
4071
+ if (!title) { title = document.createElement("div"); title.className = "c-activity-feed__title"; header.appendChild(title); }
4072
+ title.textContent = labelText(this, "title", "Activity feed");
4073
+ let toolbar = this.querySelector(".c-activity-feed__toolbar");
4074
+ if (!toolbar) { toolbar = document.createElement("div"); toolbar.className = "c-activity-feed__toolbar"; this.appendChild(toolbar); }
4075
+ const clear = toolbar.querySelector("[data-activity-clear]") || (() => { const b = document.createElement("button"); b.type = "button"; b.className = "c-btn c-btn--ghost c-btn--sm"; b.setAttribute("data-activity-clear", ""); b.textContent = labelText(this, "clear", "Clear all"); toolbar.appendChild(b); return b; })();
4076
+ const unreadBtn = toolbar.querySelector("[data-activity-unread]") || (() => { const b = document.createElement("button"); b.type = "button"; b.className = "c-btn c-btn--ghost c-btn--sm"; b.setAttribute("data-activity-unread", ""); b.textContent = labelText(this, "unread", "Unread only"); toolbar.appendChild(b); return b; })();
4077
+ if (unreadOnly) unreadBtn.setAttribute("aria-pressed", "true");
4078
+ let list = this.querySelector(".c-activity-feed__list");
4079
+ if (!list) { list = document.createElement("ol"); list.className = "c-activity-feed__list"; this.appendChild(list); }
4080
+ if (items) {
4081
+ try {
4082
+ const parsed = JSON.parse(items);
4083
+ let filtered = parsed;
4084
+ if (filter) filtered = filtered.filter((it) => String(it.severity || it.type || "").toLowerCase() === filter.toLowerCase());
4085
+ if (unreadOnly) filtered = filtered.filter((it) => !it.read);
4086
+ Array.from(list.querySelectorAll(".c-activity-feed__item")).forEach((n) => n.remove());
4087
+ if (filtered.length === 0) {
4088
+ let empty = list.querySelector(".c-activity-feed__empty");
4089
+ if (!empty) { empty = document.createElement("div"); empty.className = "c-activity-feed__empty"; empty.textContent = labelText(this, "empty", "No activity"); list.appendChild(empty); }
4090
+ } else {
4091
+ const empty = list.querySelector(".c-activity-feed__empty");
4092
+ if (empty) empty.remove();
4093
+ filtered.forEach((it, idx) => {
4094
+ const item = document.createElement("li");
4095
+ item.className = "c-activity-feed__item" + (it.read ? "" : " c-activity-feed__item--unread");
4096
+ item.setAttribute("role", "button");
4097
+ // The first item is the list's tab stop. With every item at -1 the
4098
+ // keydown handler never saw focus inside the list, so arrows and
4099
+ // Enter did nothing for a keyboard user.
4100
+ item.setAttribute("tabindex", idx === 0 ? "0" : "-1");
4101
+ const dot = document.createElement("span");
4102
+ dot.className = "c-activity-feed__dot c-activity-feed__dot--" + (it.severity || "info");
4103
+ dot.setAttribute("aria-hidden", "true");
4104
+ item.appendChild(dot);
4105
+ const text = document.createElement("span");
4106
+ text.className = "c-activity-feed__text";
4107
+ text.textContent = typeof it === "string" ? it : (it.text || it.label || "");
4108
+ item.appendChild(text);
4109
+ const time = document.createElement("time");
4110
+ time.className = "c-activity-feed__time";
4111
+ if (it.time) time.setAttribute("datetime", String(it.time));
4112
+ time.textContent = it.time || "";
4113
+ item.appendChild(time);
4114
+ const sev = document.createElement("span");
4115
+ sev.className = "c-activity-feed__severity";
4116
+ sev.textContent = it.severity || "";
4117
+ item.appendChild(sev);
4118
+ list.appendChild(item);
4119
+ });
4120
+ }
4121
+ } catch (e) { warnBadJson(this, "attribute", e); }
4122
+ }
4123
+ }
4124
+ enhance() {
4125
+ if (this._wiredActivityFeed) return;
4126
+ this._wiredActivityFeed = true;
4127
+ this.addEventListener("click", (e) => {
4128
+ const btn = e.target && e.target.closest ? e.target.closest("button") : null;
4129
+ if (!btn || !this.contains(btn)) return;
4130
+ // Match the control, not its text: a localised `labels` value changes
4131
+ // the words, and an equality test on "Clear all" then matched nothing.
4132
+ if (btn.hasAttribute("data-activity-clear")) {
4133
+ this.dispatchEvent(new CustomEvent("contour:activity-clear", { bubbles: true, composed: true, detail: {} }));
4134
+ } else if (btn.hasAttribute("data-activity-unread")) {
4135
+ this.toggleAttribute("unread-only");
4136
+ this.dispatchEvent(new CustomEvent("contour:activity-filter", { bubbles: true, composed: true, detail: { unread: this.hasAttribute("unread-only") } }));
4137
+ } else {
4138
+ const item = e.target.closest(".c-activity-feed__item");
4139
+ if (item && this.contains(item)) {
4140
+ const items = Array.from(this.querySelectorAll(".c-activity-feed__item"));
4141
+ const index = items.indexOf(item);
4142
+ const text = item.querySelector(".c-activity-feed__text")?.textContent || "";
4143
+ item.classList.remove("c-activity-feed__item--unread");
4144
+ this.dispatchEvent(new CustomEvent("contour:activity-select", { bubbles: true, composed: true, detail: { index, text } }));
4145
+ }
4146
+ }
4147
+ });
4148
+ this.addEventListener("keydown", (e) => {
4149
+ const items = Array.from(this.querySelectorAll(".c-activity-feed__item"));
4150
+ if (!items.length) return;
4151
+ navKey(e, items, { wrap: false, homeEnd: true, onNavigate: (i) => { items.forEach((it, j) => it.tabIndex = j === i ? 0 : -1); }, onKey: () => { if (e.key === "Enter" || e.key === " ") { const idx = items.indexOf(document.activeElement); this.dispatchEvent(new CustomEvent("contour:activity-select", { bubbles: true, composed: true, detail: { index: idx, text: document.activeElement.querySelector(".c-activity-feed__text")?.textContent || "" } })); } } });
4152
+ });
4153
+ }
4154
+ }
4155
+ define("contour-activity-feed", ContourActivityFeed);
4156
+ class ContourAdvanced extends ContourBase {
4157
+ static get observed() { return ["title"]; }
4158
+ static get properties() { return { title: { attribute: "title" } }; }
4159
+ render() {
4160
+ this.classList.add("c-advanced");
4161
+ this.setAttribute("role", "region");
4162
+ const title = this.getAttribute("title");
4163
+ if (title) {
4164
+ const t = this.ensure(".c-advanced__title", () => { const el = document.createElement("div"); el.className = "c-advanced__title"; return el; });
4165
+ t.textContent = title;
4166
+ this.setAttribute("aria-label", title);
4167
+ }
4168
+ }
4169
+ enhance() {
4170
+ if (this._wiredAdvanced) return;
4171
+ this._wiredAdvanced = true;
4172
+ this.addEventListener("click", (e) => {
4173
+ // Only the title row toggles. A click anywhere used to fire the event,
4174
+ // including on a nested button or input, so using the section toggled it.
4175
+ const t = e.target && e.target.closest ? e.target.closest(".c-advanced__title") : null;
4176
+ if (!t || !this.contains(t)) return;
4177
+ const title = this.getAttribute("title") || "";
4178
+ this.dispatchEvent(new CustomEvent("contour:advanced-toggle", { bubbles: true, composed: true, detail: { title } }));
4179
+ });
4180
+ this.addEventListener("keydown", (e) => {
4181
+ // A key pressed inside an authored control belongs to that control.
4182
+ if (e.target !== this) return;
4183
+ if (e.key === "Enter" || e.key === " ") {
4184
+ e.preventDefault();
4185
+ const title = this.getAttribute("title") || "";
4186
+ this.dispatchEvent(new CustomEvent("contour:advanced-toggle", { bubbles: true, composed: true, detail: { title } }));
4187
+ }
4188
+ });
4189
+ }
4190
+ }
4191
+ define("contour-advanced", ContourAdvanced);
4192
+ class ContourAffordance extends ContourBase {
4193
+ static get observed() { return ["name", "note", "demo"]; }
4194
+ static get properties() { return { name: { attribute: "name" }, note: { attribute: "note" }, demo: { attribute: "demo" } }; }
4195
+ render() {
4196
+ this.classList.add("c-affordance");
4197
+ this.setAttribute("role", "group");
4198
+ const name = this.getAttribute("name");
4199
+ if (name) {
4200
+ const n = this.ensure(".c-affordance__name", () => { const el = document.createElement("div"); el.className = "c-affordance__name"; return el; });
4201
+ n.textContent = name;
4202
+ this.setAttribute("aria-label", name);
4203
+ } else {
4204
+ const n = this.querySelector(".c-affordance__name");
4205
+ if (n) n.remove();
4206
+ }
4207
+ const note = this.getAttribute("note");
4208
+ if (note) {
4209
+ const nt = this.ensure(".c-affordance__note", () => { const el = document.createElement("div"); el.className = "c-affordance__note"; return el; });
4210
+ nt.textContent = note;
4211
+ } else {
4212
+ const nt = this.querySelector(".c-affordance__note");
4213
+ if (nt) nt.remove();
4214
+ }
4215
+ const demo = this.getAttribute("demo");
4216
+ if (demo) {
4217
+ const d = this.ensure(".c-affordance__demo", () => { const el = document.createElement("div"); el.className = "c-affordance__demo"; return el; });
4218
+ d.textContent = demo;
4219
+ } else {
4220
+ const d = this.querySelector(".c-affordance__demo");
4221
+ if (d) d.remove();
4222
+ }
4223
+ }
4224
+ enhance() {
4225
+ if (this._wiredAffordance) return;
4226
+ this._wiredAffordance = true;
4227
+ this.addEventListener("click", (e) => {
4228
+ const name = this.getAttribute("name") || "";
4229
+ this.dispatchEvent(new CustomEvent("contour:affordance-activate", { bubbles: true, composed: true, detail: { name } }));
4230
+ });
4231
+ this.addEventListener("keydown", (e) => {
4232
+ if (e.key === "Enter" || e.key === " ") {
4233
+ e.preventDefault();
4234
+ const name = this.getAttribute("name") || "";
4235
+ this.dispatchEvent(new CustomEvent("contour:affordance-activate", { bubbles: true, composed: true, detail: { name } }));
4236
+ }
4237
+ });
4238
+ }
4239
+ }
4240
+ define("contour-affordance", ContourAffordance);
4241
+ class ContourAffordances extends ContourBase {
4242
+ static get observed() { return ["name", "title"]; }
4243
+ static get properties() { return { name: { attribute: "name" }, title: { attribute: "title" } }; }
4244
+ render() {
4245
+ this.classList.add("c-affordances");
4246
+ this.setAttribute("role", "group");
4247
+ if (!this.querySelector(".c-affordance")) {
4248
+ const aff = document.createElement("div");
4249
+ aff.className = "c-affordance";
4250
+ const name = this.getAttribute("name") || this.getAttribute("title") || labelText(this, "affordance", "Affordance");
4251
+ const n = document.createElement("div");
4252
+ n.className = "c-affordance__name";
4253
+ n.textContent = name;
4254
+ aff.appendChild(n);
4255
+ const demo = document.createElement("div");
4256
+ demo.className = "c-affordance__demo";
4257
+ demo.textContent = labelText(this, "demo", "Demo");
4258
+ aff.appendChild(demo);
4259
+ this.appendChild(aff);
4260
+ }
4261
+ }
4262
+ }
4263
+ define("contour-affordances", ContourAffordances);
4264
+