contour-ds 1.8.1 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/README.md +227 -378
  2. package/dist/agent-cookbook.json +960 -0
  3. package/dist/agent-examples.json +65 -0
  4. package/dist/agent-map-wiring.json +152 -0
  5. package/dist/build-manifest.json +320 -179
  6. package/dist/contour-wc-content.esm.js +479 -3665
  7. package/dist/contour-wc-content.esm.min.js +1 -1
  8. package/dist/contour-wc-core.esm.js +3724 -0
  9. package/dist/contour-wc-core.esm.min.js +1 -0
  10. package/dist/contour-wc-dashboard.esm.js +2713 -4381
  11. package/dist/contour-wc-dashboard.esm.min.js +1 -1
  12. package/dist/contour-wc-data.esm.js +2658 -4346
  13. package/dist/contour-wc-data.esm.min.js +1 -1
  14. package/dist/contour-wc-docs.esm.js +218 -3547
  15. package/dist/contour-wc-docs.esm.min.js +1 -1
  16. package/dist/contour-wc-feedback.esm.js +483 -3658
  17. package/dist/contour-wc-feedback.esm.min.js +1 -1
  18. package/dist/contour-wc-forms.esm.js +503 -3754
  19. package/dist/contour-wc-forms.esm.min.js +1 -1
  20. package/dist/contour-wc-interaction.esm.js +379 -3616
  21. package/dist/contour-wc-interaction.esm.min.js +1 -1
  22. package/dist/contour-wc-layout.esm.js +234 -3563
  23. package/dist/contour-wc-layout.esm.min.js +1 -1
  24. package/dist/contour-wc-map.esm.js +949 -3743
  25. package/dist/contour-wc-map.esm.min.js +1 -1
  26. package/dist/contour-wc-misc.esm.js +237 -3556
  27. package/dist/contour-wc-misc.esm.min.js +1 -1
  28. package/dist/contour-wc-navigation.esm.js +2235 -5237
  29. package/dist/contour-wc-navigation.esm.min.js +1 -1
  30. package/dist/contour-wc-ui.esm.js +4638 -7128
  31. package/dist/contour-wc-ui.esm.min.js +1 -1
  32. package/dist/contour-wc.esm.js +11971 -7727
  33. package/dist/contour-wc.esm.min.js +1 -1
  34. package/dist/contour-wc.js +11971 -7727
  35. package/dist/contour-wc.min.js +1 -1
  36. package/dist/contour.a11y.json +402 -0
  37. package/dist/contour.code-snippets +96 -74
  38. package/dist/contour.components.json +2591 -741
  39. package/dist/contour.css +2624 -1888
  40. package/dist/contour.d.ts +421 -228
  41. package/dist/contour.esm.js +433 -18
  42. package/dist/contour.esm.min.js +1 -1
  43. package/dist/contour.html-data.json +1231 -199
  44. package/dist/contour.js +433 -18
  45. package/dist/contour.min.css +1 -1
  46. package/dist/contour.min.js +1 -1
  47. package/dist/contour.react.d.ts +100 -98
  48. package/dist/contour.single.html +2 -2
  49. package/dist/contour.single.min.css +1 -1
  50. package/dist/contour.themes.json +56 -12
  51. package/dist/contour.tokens.json +482 -255
  52. package/dist/contour.vue.d.ts +100 -98
  53. package/dist/contour.web-types.json +1226 -226
  54. package/dist/custom-elements.json +7649 -2237
  55. package/dist/docs/actions.md +15 -6
  56. package/dist/docs/affordances.md +18 -96
  57. package/dist/docs/apireference.md +9 -5
  58. package/dist/docs/colour.md +10 -4
  59. package/dist/docs/componentindex.md +9 -26
  60. package/dist/docs/data.md +36 -60
  61. package/dist/docs/docs.md +10 -12
  62. package/dist/docs/feedback.md +30 -12
  63. package/dist/docs/field.md +28 -13
  64. package/dist/docs/forms.md +35 -19
  65. package/dist/docs/index.json +63 -56
  66. package/dist/docs/install.md +12 -7
  67. package/dist/docs/landing.md +7 -4
  68. package/dist/docs/mapengine.md +18 -13
  69. package/dist/docs/motion.md +12 -6
  70. package/dist/docs/navigation.md +31 -7
  71. package/dist/docs/overlays.md +32 -25
  72. package/dist/docs/overview.md +3 -2
  73. package/dist/docs/patterns.md +19 -9
  74. package/dist/docs/playground.md +9 -22
  75. package/dist/docs/principles.md +8 -6
  76. package/dist/docs/recipes.md +113 -14
  77. package/dist/docs/space.md +10 -6
  78. package/dist/docs/status.md +12 -25
  79. package/dist/docs/surfaces.md +17 -22
  80. package/dist/docs/theming.md +18 -32
  81. package/dist/docs/type.md +12 -5
  82. package/dist/docs/webcomponents.md +66 -38
  83. package/dist/hljs.css +1 -20
  84. package/dist/map-chrome.mapbox.css +68 -92
  85. package/dist/map-chrome.maplibre.css +68 -92
  86. package/dist/registry/items/contour-core.json +2 -2
  87. package/dist/registry/items/contour-data.json +2 -2
  88. package/dist/registry/items/contour-docs.json +2 -2
  89. package/dist/registry/items/contour-landing.json +2 -2
  90. package/dist/registry/registry.json +8 -8
  91. package/dist/surfaces/contour-core.min.css +1 -1
  92. package/dist/surfaces/contour-data.min.css +1 -1
  93. package/dist/surfaces/contour-docs.min.css +1 -1
  94. package/dist/surfaces/contour-landing.min.css +1 -1
  95. package/dist/svg/icons.svg +367 -0
  96. package/dist/wc/behaviours.mjs +190 -148
  97. package/dist/wc/content.mjs +273 -129
  98. package/dist/wc/core.mjs +598 -395
  99. package/dist/wc/dashboard.mjs +64 -44
  100. package/dist/wc/data-chart.mjs +1333 -0
  101. package/dist/wc/data-export.mjs +391 -0
  102. package/dist/wc/data-gauge.mjs +779 -0
  103. package/dist/wc/data-geo.mjs +696 -0
  104. package/dist/wc/data-glyphs.mjs +133 -0
  105. package/dist/wc/data-legend.mjs +431 -0
  106. package/dist/wc/data-readout.mjs +227 -0
  107. package/dist/wc/data-series.mjs +1004 -0
  108. package/dist/wc/data-table.mjs +751 -0
  109. package/dist/wc/data.mjs +15 -4322
  110. package/dist/wc/docs.mjs +12 -11
  111. package/dist/wc/feedback.mjs +277 -122
  112. package/dist/wc/forms-controls.mjs +635 -0
  113. package/dist/wc/forms-field.mjs +547 -0
  114. package/dist/wc/forms-groups.mjs +347 -0
  115. package/dist/wc/forms-input.mjs +292 -0
  116. package/dist/wc/forms.mjs +10 -1751
  117. package/dist/wc/glyph.mjs +204 -0
  118. package/dist/wc/index.mjs +11 -9
  119. package/dist/wc/interaction.mjs +173 -80
  120. package/dist/wc/layout.mjs +28 -27
  121. package/dist/wc/map.mjs +743 -207
  122. package/dist/wc/misc.mjs +31 -20
  123. package/dist/wc/navigation-menu.mjs +735 -0
  124. package/dist/wc/navigation-shell.mjs +495 -0
  125. package/dist/wc/navigation-tree.mjs +995 -0
  126. package/dist/wc/navigation.mjs +9 -1905
  127. package/dist/wc/registration.mjs +1 -8
  128. package/dist/wc/shadow.mjs +206 -110
  129. package/dist/wc/states.mjs +54 -75
  130. package/dist/wc/svg.mjs +118 -47
  131. package/dist/wc/ui-atoms.mjs +608 -0
  132. package/dist/wc/ui-data.mjs +1404 -0
  133. package/dist/wc/ui-feedback.mjs +419 -0
  134. package/dist/wc/ui-inputs.mjs +1570 -0
  135. package/dist/wc/ui-menus.mjs +307 -0
  136. package/dist/wc/ui-overlays.mjs +1605 -0
  137. package/integrations/README.md +23 -5
  138. package/integrations/ai/CLAUDE.md +3 -0
  139. package/integrations/ai/COPILOT.md +14 -0
  140. package/integrations/ai/GEMINI.md +14 -0
  141. package/integrations/ai/WINDSURF.md +14 -0
  142. package/integrations/ai/v0-prompt.md +13 -1
  143. package/integrations/native/README.md +0 -3
  144. package/integrations/tailwind/contour-theme.css +66 -7
  145. package/integrations/validate-markup.mjs +172 -0
  146. package/package.json +77 -42
  147. package/dist/wc/ui.mjs +0 -5072
@@ -1,3431 +1,6 @@
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.
1
+ import { CLASS_ONLY, CONTOUR_EVENTS, ContourBase, MERCATOR_MAX_LAT, MODS, OBSERVED, REGISTERED, applyLabel, bearing, clampLat, contourId, cssLength, define, flagOn, flagOnValue, formatValue, haversine, headingTag, iconMarkup, isRtl, labelText, levelFromAttributes, mercatorResolution, navKey, normaliseLng, onDispose, safeColor, safeHref, sanitizeHtml, setHTML, simple, statusIcon, supportsUntilFound, unwrapBounds, warnBadJson, wcEmitOverlay, withBrownout, MARKER_SHAPES, arcPath, assignMarkers, barRects, compassNeedle, contourPaths, donutSlices, isMissing, marchingSquares, markerStyles, niceTicks, polylinePoints, scaleBarTicks, smoothPath, modalContain, wcReset, wireCombobox, wireCopy, wireMenu, wirePagination, wireRemovable, wireSegmented, wireTabs, wireTree, STATE_FALLBACK, loadRemote, parseArrayAttr, remoteData, remoteInvalidate, remoteRefresh, remoteVisible, renderEmpty, renderStates, stateLabel, watchViewport, wireStates } from "./contour-wc-core.esm.js";
11
2
 
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.
3
+ // ---- Registration: class-only wrappers run last (define() skips claimed names) ----
3429
4
  define("contour-box", simple(["c-box"]));
3430
5
  define("contour-cluster", simple(["c-cluster"]));
3431
6
  define("contour-container", simple(["c-container"]));
@@ -3436,41 +11,41 @@ export function wireStates(host) {
3436
11
 
3437
12
 
3438
13
 
14
+ // R31-19: the text a shadow <label> shows through its <slot>, read from the
15
+ // light-tree assigned nodes (the shadow label's own textContent is empty).
16
+ const assignedText = (label) => {
17
+ const slot = label.querySelector("slot");
18
+ const nodes = slot ? slot.assignedElements({ flatten: true }) : [];
19
+ const text = nodes.map((n) => (n.textContent || "").trim()).join(" ").trim();
20
+ return text || (label.textContent || "").trim();
21
+ };
3439
22
  // ---- 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
23
  let ADOPTED = null;
3458
24
  let ADOPTED_KEY = "";
3459
- const adoptedSheets = () => {
25
+ const _hashCss = (str) => {
26
+ let h = 2166136261;
27
+ for (let i = 0; i < str.length; i++) {
28
+ h ^= str.charCodeAt(i);
29
+ h = Math.imul(h, 16777619);
30
+ }
31
+ return (h >>> 0).toString(36);
32
+ };
33
+ export const adoptedSheets = () => {
3460
34
  let key = document.styleSheets.length + ":";
3461
35
  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 + "|";
36
+ let sig = "-1";
37
+ try {
38
+ const rules = sheet.cssRules;
39
+ let text = "";
40
+ for (let i = 0; i < rules.length; i++) text += rules[i].cssText + "\n";
41
+ sig = rules.length + ":" + _hashCss(text);
42
+ } catch (e) { /* cross-origin: unreadable */ }
43
+ key += (sheet.href || "inline") + "~" + sig + "|";
3465
44
  }
3466
45
  if (ADOPTED && key === ADOPTED_KEY) return ADOPTED;
3467
46
  ADOPTED_KEY = key;
3468
47
  ADOPTED = [];
3469
48
  // 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
49
  const collect = (sheet, out) => {
3475
50
  let rules;
3476
51
  try { rules = sheet.cssRules; } catch (e) { return; }
@@ -3485,7 +60,8 @@ export function wireStates(host) {
3485
60
  };
3486
61
  for (const sheet of document.styleSheets) {
3487
62
  try {
3488
- if (sheet.href && new URL(sheet.href).origin === location.origin) {
63
+ // Include same-origin linked sheets AND same-origin inline <style> sheets (!sheet.href).
64
+ if (!sheet.href || new URL(sheet.href).origin === location.origin) {
3489
65
  const collected = [];
3490
66
  collect(sheet, collected);
3491
67
  const built = new CSSStyleSheet();
@@ -3498,12 +74,12 @@ export function wireStates(host) {
3498
74
  };
3499
75
 
3500
76
  // 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
77
  const _ShadowParent = (typeof HTMLElement !== "undefined") ? HTMLElement : Object;
3505
78
  class ContourShadow extends _ShadowParent {
3506
- static get observedAttributes() { return MODS; }
79
+ // R30-33: observe `labels` alongside the modifier attributes so a labels
80
+ // change re-runs _applyLabels(). applyMods() ignores it (it only maps MODS),
81
+ // so adding it here does not create a bogus modifier class.
82
+ static get observedAttributes() { return MODS.concat("labels"); }
3507
83
  constructor() {
3508
84
  super();
3509
85
  // Reuse a Declarative Shadow Root when the platform already attached one
@@ -3522,19 +98,10 @@ export function wireStates(host) {
3522
98
  this._shadowBase = root.firstElementChild ? root.firstElementChild.className : "";
3523
99
  }
3524
100
  // 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
101
  enhance(root) {
3530
102
  if (!root) root = this.shadowRoot;
3531
103
  if (!root) return;
3532
104
  // 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
105
  root.querySelectorAll("details").forEach((d) => {
3539
106
  const summary = d.querySelector("summary");
3540
107
  if (summary && !summary.hasAttribute("aria-expanded")) {
@@ -3590,8 +157,6 @@ export function wireStates(host) {
3590
157
  }
3591
158
  });
3592
159
  // 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
160
  root.querySelectorAll(".c-alert").forEach((el) => {
3596
161
  const urgent = el.classList.contains("c-alert--warning") || el.classList.contains("c-alert--danger");
3597
162
  const role = urgent ? "alert" : "status";
@@ -3610,18 +175,85 @@ export function wireStates(host) {
3610
175
  if (!el.hasAttribute("aria-required")) el.setAttribute("aria-required", "true");
3611
176
  });
3612
177
  // 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.
178
+ this._wireLabels(root);
179
+ this._wireClose(root);
180
+ }
181
+ // R31-22: the shadow callout/alert/tag/filter-pill close/remove buttons were
182
+ // inert — a control the reader could focus and never use. Wire them to
183
+ // dismiss the host (hide + emit contour:close/dismiss), once per host.
184
+ _wireClose(root) {
185
+ if (!root || this._wiredShadowClose) return;
186
+ const btns = root.querySelectorAll(".c-callout__close, .c-alert__close, .c-tag__remove, .c-filter-pill__remove");
187
+ if (!btns.length) return;
188
+ this._wiredShadowClose = true;
189
+ for (const b of btns) {
190
+ b.addEventListener("click", () => {
191
+ this.hidden = true;
192
+ this.dispatchEvent(new CustomEvent("contour:close", { bubbles: true, composed: true }));
193
+ });
194
+ }
195
+ }
196
+ // R31-03: a shadow <label> wrapping a <slot> does not label a slotted input.
197
+ // The input is in the light tree, the label in the shadow tree, and HTML's
198
+ // label/for association does not cross the boundary. Give the slotted
199
+ // control an id and point the shadow label's `for` at it, and mirror the
200
+ // field hint/error into aria-describedby. Idempotent.
201
+ _wireLabels(root) {
202
+ if (!root) return;
203
+ root.querySelectorAll("label").forEach((label) => {
204
+ const slot = label.querySelector("slot");
205
+ const field = label.closest(".c-field") || label.parentElement;
206
+ const host = this;
207
+ const controls = [];
208
+ if (slot) {
209
+ for (const n of slot.assignedElements({ flatten: true })) {
210
+ if (n.matches("input, textarea, select")) controls.push(n);
211
+ }
212
+ }
213
+ // A field's input lives in a named "input" slot, not inside the label.
214
+ if (!controls.length && field) {
215
+ const inputSlot = field.querySelector('slot[name="input"]');
216
+ if (inputSlot) {
217
+ for (const n of inputSlot.assignedElements({ flatten: true })) {
218
+ if (n.matches("input, textarea, select")) controls.push(n);
219
+ }
220
+ }
221
+ }
222
+ for (const input of controls) {
223
+ if (!input.id) input.id = contourId("shadow-input");
224
+ if (!label.hasAttribute("for")) label.setAttribute("for", input.id);
225
+ // R31-19: `for` does not cross the shadow boundary — the label is in
226
+ // the shadow tree, the input in the light tree, so `label.control`
227
+ // is null and `input.labels` is empty. Give the input an explicit
228
+ // accessible name from the label's slotted text, and forward a label
229
+ // click to the control, so the visible label actually toggles it.
230
+ if (!input.hasAttribute("aria-label") && !input.hasAttribute("aria-labelledby")) {
231
+ const text = assignedText(label);
232
+ if (text) input.setAttribute("aria-label", text);
233
+ }
234
+ if (!input._contourLabelWired) {
235
+ input._contourLabelWired = true;
236
+ label.addEventListener("click", (e) => {
237
+ if (e.target.closest("a, button, input, textarea, select")) return;
238
+ try { input.click(); } catch (err) { /* control without click */ }
239
+ });
240
+ }
241
+ // Mirror the field hint/error into aria-describedby (once).
242
+ if (field && !input.hasAttribute("aria-describedby")) {
243
+ const hint = field.querySelector(".c-field__hint");
244
+ const err = field.querySelector(".c-field__error");
245
+ const ids = [];
246
+ if (hint) { if (!hint.id) hint.id = contourId("hint"); ids.push(hint.id); }
247
+ if (err) { if (!err.id) err.id = contourId("err"); ids.push(err.id); }
248
+ if (ids.length) input.setAttribute("aria-describedby", ids.join(" "));
249
+ }
250
+ }
251
+ });
3621
252
  }
3622
- connectedCallback() {
253
+ connectedCallback() {
3623
254
  this.applyMods();
3624
255
  try { this.enhance(this.shadowRoot); } catch (e) { /* ignore */ }
256
+ this._applyLabels();
3625
257
  // Wire behaviours now that slotted content is present.
3626
258
  try {
3627
259
  wcReset(this);
@@ -3629,23 +261,47 @@ connectedCallback() {
3629
261
  wireMenu(this); wirePagination(this); wireCopy(this); wireRemovable(this);
3630
262
  } catch (e) { /* ignore */ }
3631
263
  // 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
264
  if (this.shadowRoot && !this._wiredSlotchange) {
3639
265
  this._wiredSlotchange = true;
3640
266
  this.shadowRoot.addEventListener("slotchange", () => {
3641
267
  try { this.enhance(this.shadowRoot);
268
+ this._applyLabels();
3642
269
  wireTabs(this); wireSegmented(this); wireCombobox(this); wireTree(this);
3643
270
  wireMenu(this); wirePagination(this); wireCopy(this); wireRemovable(this);
3644
271
  } catch (e) { /* ignore */ }
3645
272
  });
3646
273
  }
3647
274
  }
3648
- attributeChangedCallback() { this.applyMods(); }
275
+ attributeChangedCallback() { this.applyMods(); this._applyLabels(); }
276
+ // R30-33: localise the static aria-labels/copy baked into shadow templates.
277
+ // The light-DOM sweep (R30-13) routes literals through labelText(); the
278
+ // shadow layer has no such path because its markup is a static template
279
+ // string. This post-processes the rendered shadowRoot, replacing the
280
+ // English defaults with the host's `labels` overrides where present. It is
281
+ // idempotent and only touches nodes that still carry the default text, so
282
+ // an author's own shadow content (slotted) is never overwritten.
283
+ _applyLabels() {
284
+ const root = this.shadowRoot;
285
+ if (!root) return;
286
+ const set = (selector, key, fallback) => {
287
+ const node = root.querySelector(selector);
288
+ if (node) node.setAttribute("aria-label", labelText(this, key, fallback));
289
+ };
290
+ set(".c-callout__close", "close", "Close");
291
+ set(".c-alert__close", "close", "Close");
292
+ set(".c-tag__remove", "remove", "Remove");
293
+ set(".c-filter-pill__remove", "remove-filter", "Remove filter");
294
+ set(".c-breadcrumb", "breadcrumb", "Breadcrumb");
295
+ set(".c-spinner", "loading", "Loading");
296
+ set(".c-install__copy", "copy-command", "Copy command");
297
+ // The install/code copy buttons carry visible "Copy" text as well as an
298
+ // aria-label; localise both, but only while they still read "Copy" so a
299
+ // consumer who set their own label keeps it.
300
+ const copyBtn = root.querySelector(".c-install__copy, .c-code__copy");
301
+ if (copyBtn && copyBtn.textContent.trim() === "Copy") {
302
+ copyBtn.textContent = labelText(this, "copy", "Copy");
303
+ }
304
+ }
3649
305
  applyMods() {
3650
306
  const el = this.shadowRoot.firstElementChild;
3651
307
  if (!el || !this._shadowBase) return;
@@ -3659,8 +315,6 @@ connectedCallback() {
3659
315
  }
3660
316
  el.className = (this._shadowBase + " " + mods.join(" ")).trim();
3661
317
  // 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
318
  if (el.classList.contains("c-alert")) {
3665
319
  const urgent = el.classList.contains("c-alert--warning") || el.classList.contains("c-alert--danger");
3666
320
  const role = urgent ? "alert" : "status";
@@ -3678,8 +332,6 @@ connectedCallback() {
3678
332
  }
3679
333
 
3680
334
  // 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
335
  const SHADOW_PARTS_PUBLIC = {};
3684
336
  const SHADOW_MARKUP = {};
3685
337
  const recordParts = (name, markup) => {
@@ -3692,15 +344,13 @@ connectedCallback() {
3692
344
  recordParts(name, markup);
3693
345
  if (typeof document === "undefined") return;
3694
346
  const tpl = document.createElement("template");
3695
- tpl.innerHTML = markup;
347
+ setHTML(tpl, markup);
3696
348
  const cls = class extends ContourShadow {};
3697
349
  cls.contourTemplate = tpl;
3698
350
  define(name, cls);
3699
351
  };
3700
352
 
3701
353
  // 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
354
  const slotWrapper = (tag, block, part) =>
3705
355
  "<" + tag + ' class="c-' + block + '" part="' + (part || block) + '"' + (tag === "button" ? ' type="button"' : "") + "><slot></slot></" + tag + ">";
3706
356
  const SHADOW_SLOTS = {
@@ -3720,7 +370,7 @@ connectedCallback() {
3720
370
  "toolbar", "tooltip", "tree", "version", "version-banner"
3721
371
  ],
3722
372
  button: [
3723
- "btn", "pressable", "scheme-toggle"
373
+ "btn", "pressable"
3724
374
  ],
3725
375
  span: [
3726
376
  "avatar", "badge", "chip", "dot", "flag", "live-badge", "mark", "pill"
@@ -3734,30 +384,18 @@ connectedCallback() {
3734
384
  label: [
3735
385
  "check", "radio", "switch"
3736
386
  ],
3737
- select: [
3738
- "select"
3739
- ],
3740
387
  nav: [
3741
388
  "docs-nav"
3742
389
  ],
3743
390
  };
3744
391
 
3745
392
  // 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
393
  const SHADOW_PARTS = {
3751
394
  "version-banner": "banner",
3752
395
  "contour-plot": "plot",
3753
396
  };
3754
397
 
3755
398
  // 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
399
  for (const [tag, blocks] of Object.entries(SHADOW_SLOTS)) {
3762
400
  for (const block of blocks) {
3763
401
  const part = SHADOW_PARTS[block] || block;
@@ -3793,14 +431,10 @@ connectedCallback() {
3793
431
  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
432
  shadow("contour-shadow-loading", `<div class="c-loading" part="loading"><span class="c-spinner" part="spinner"></span><slot></slot></div>`);
3795
433
  // 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
434
  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
435
  shadow("contour-shadow-breadcrumb", `<nav class="c-breadcrumb" part="breadcrumb" aria-label="Breadcrumb"><ol><slot></slot></ol></nav>`);
3801
436
  shadow("contour-shadow-menu", `<div class="c-menu" part="menu" role="menu"><slot></slot></div>`);
3802
437
  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
438
  shadow("contour-shadow-chart", `<div class="c-chart" part="chart"><div class="c-chart__plot" part="plot"><slot></slot></div></div>`);
3805
439
  shadow("contour-shadow-bivariate", `<div class="c-bivariate" part="bivariate"><div class="c-bivariate__matrix" part="matrix"><slot></slot></div></div>`);
3806
440
  shadow("contour-shadow-bivariate-legend", `<div class="c-bivariate-legend" part="legend"><div class="c-bivariate-legend__matrix" part="matrix"><slot></slot></div></div>`);
@@ -3811,9 +445,13 @@ connectedCallback() {
3811
445
  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
446
  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
447
  shadow("contour-shadow-container", `<div class="container" part="container"><slot></slot></div>`);
3814
- shadow("contour-shadow-input", `<input class="c-input" part="input" />`);
448
+ // R31-03: contour-shadow-input / -textarea / -select / -table / -scheme-toggle
449
+ // were removed. Each was a control shell that could not hold the state its
450
+ // light twin holds (no value, no options, no rows, no toggle), so it was a
451
+ // trap rather than a styling seam. Use the light <contour-input>,
452
+ // <contour-select>, <contour-table> and <contour-scheme-toggle>, or style a
453
+ // native control with the `.c-input` / `.c-table` classes directly.
3815
454
  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
455
  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
456
  // (folded in from the hand-written component that used to carry its own copy of the sheet logic)
3819
457
  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>`);
@@ -3827,21 +465,18 @@ shadow("contour-shadow-filter-pill", `<span class="c-filter-pill" part="filter-p
3827
465
 
3828
466
  // The dialog is the one wrapper with behaviour, because a close button that
3829
467
  // 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>";
468
+ 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\" viewBox=\"0 0 24 24\"><path d=\"m18 6-12 12M6 6l12 12\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.7\" stroke-linecap=\"round\"/></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
469
  SHADOW_MARKUP["contour-shadow-dialog"] = DIALOG_MARKUP;
3832
470
  recordParts("contour-shadow-dialog", DIALOG_MARKUP);
3833
471
  class ContourShadowDialog extends ContourShadow {
3834
472
  static contourTemplate = (typeof document !== "undefined") ? (() => {
3835
473
  const tpl = document.createElement("template");
3836
- tpl.innerHTML = DIALOG_MARKUP;
474
+ setHTML(tpl, DIALOG_MARKUP);
3837
475
  return tpl;
3838
476
  })() : null;
3839
477
  enhance(root) {
3840
478
  super.enhance(root);
3841
479
  // 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
480
  if (this._wiredShadowDialog) return;
3846
481
  this._wiredShadowDialog = true;
3847
482
  const dlg = root.querySelector("dialog");
@@ -3850,19 +485,22 @@ shadow("contour-shadow-filter-pill", `<span class="c-filter-pill" part="filter-p
3850
485
  if (dlg) {
3851
486
  let lastFocus = null;
3852
487
  // `<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
488
  dlg.addEventListener("beforetoggle", (e) => {
3859
489
  if (e.newState === "open") {
3860
490
  lastFocus = document.activeElement;
491
+ // beforetoggle fires BEFORE dialog.open flips, so the attribute
492
+ // write must not re-enter attributeChangedCallback's show() path.
493
+ this._syncingOpenAttr = true;
494
+ if (!this.hasAttribute("open")) this.setAttribute("open", "");
495
+ this._syncingOpenAttr = false;
3861
496
  this.dispatchEvent(new CustomEvent("contour:open", { bubbles: true, composed: true }));
3862
497
  // Focus the close button or first focusable element
3863
498
  const focusable = dlg.querySelector("button, [href], input, select, textarea, [tabindex]:not([tabindex='-1'])");
3864
499
  if (focusable) try { focusable.focus(); } catch (e) {}
3865
500
  } else if (e.newState === "closed") {
501
+ this._syncingOpenAttr = true;
502
+ if (this.hasAttribute("open")) this.removeAttribute("open");
503
+ this._syncingOpenAttr = false;
3866
504
  this.dispatchEvent(new CustomEvent("contour:close", { bubbles: true, composed: true }));
3867
505
  // Restore focus
3868
506
  if (lastFocus && typeof lastFocus.focus === "function") {
@@ -3870,28 +508,68 @@ shadow("contour-shadow-filter-pill", `<span class="c-filter-pill" part="filter-p
3870
508
  }
3871
509
  }
3872
510
  });
3873
- // Focus trap: keep Tab within the dialog
511
+ // Focus trap: keep Tab within the dialog. R31-04: the focusables are not
512
+ // only in the shadow tree — slotted light-DOM controls (the dialog body
513
+ // is a <slot>) are real tab stops too, and `document.activeElement` is
514
+ // the shadow host, not the control. Collect both, and read the
515
+ // shadow-aware active element.
516
+ const collectFocusable = () => {
517
+ const sel = "button, [href], input, select, textarea, [tabindex]:not([tabindex='-1'])";
518
+ const out = Array.from(dlg.querySelectorAll(sel));
519
+ for (const slot of dlg.querySelectorAll("slot")) {
520
+ for (const n of slot.assignedElements({ flatten: true })) {
521
+ if (n.matches(sel)) out.push(n);
522
+ for (const sub of n.querySelectorAll(sel)) out.push(sub);
523
+ }
524
+ }
525
+ return out;
526
+ };
527
+ const activeEl = () => (this.shadowRoot && this.shadowRoot.activeElement) || document.activeElement;
3874
528
  dlg.addEventListener("keydown", (e) => {
3875
529
  if (e.key !== "Tab") return;
3876
- const focusables = Array.from(dlg.querySelectorAll("button, [href], input, select, textarea, [tabindex]:not([tabindex='-1'])"));
530
+ const focusables = collectFocusable();
3877
531
  if (!focusables.length) return;
3878
532
  const first = focusables[0];
3879
533
  const last = focusables[focusables.length - 1];
3880
- if (e.shiftKey && document.activeElement === first) {
534
+ if (e.shiftKey && activeEl() === first) {
3881
535
  e.preventDefault();
3882
536
  last.focus();
3883
- } else if (!e.shiftKey && document.activeElement === last) {
537
+ } else if (!e.shiftKey && activeEl() === last) {
3884
538
  e.preventDefault();
3885
539
  first.focus();
3886
540
  }
3887
541
  });
3888
542
  }
3889
543
  }
3890
- show() { this.shadowRoot?.querySelector("dialog")?.showModal(); }
3891
- close() { this.shadowRoot?.querySelector("dialog")?.close(); }
544
+ static get observedAttributes() { return [...super.observedAttributes, "open"]; }
545
+ attributeChangedCallback(name, oldValue, newValue) {
546
+ super.attributeChangedCallback(name, oldValue, newValue);
547
+ // The host's `open` attribute drives the inner native dialog, matching
548
+ // the light family; without this the attribute was inert (R25-12).
549
+ if (name === "open" && this.shadowRoot && !this._syncingOpenAttr) {
550
+ const dlg = this.shadowRoot.querySelector("dialog");
551
+ if (dlg) {
552
+ if (newValue !== null && !dlg.open) this.show();
553
+ else if (newValue === null && dlg.open) this.close();
554
+ }
555
+ }
556
+ }
557
+ connectedCallback() {
558
+ super.connectedCallback();
559
+ // R31-33: an `open` attribute set before the element was connected (or a
560
+ // show() called while disconnected) must engage the dialog once it lands
561
+ // in the document; showModal() on a disconnected dialog throws.
562
+ if (this.hasAttribute("open")) this.show();
563
+ }
564
+ show() {
565
+ // R31-33: showModal() throws on a disconnected element. If not yet
566
+ // connected, leave the `open` attribute set; connectedCallback applies it.
567
+ if (!this.isConnected) { if (!this.hasAttribute("open")) this.setAttribute("open", ""); return; }
568
+ const d = this.shadowRoot?.querySelector("dialog");
569
+ if (d && !d.open) d.showModal();
570
+ }
571
+ close() { const d = this.shadowRoot?.querySelector("dialog"); if (d && d.open) d.close(); }
3892
572
  // 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
573
  showModal() { this.show(); }
3896
574
  get open() { return !!this.shadowRoot?.querySelector("dialog")?.open; }
3897
575
  set open(v) { if (v) this.show(); else this.close(); }
@@ -3912,22 +590,15 @@ shadow("contour-shadow-filter-pill", `<span class="c-filter-pill" part="filter-p
3912
590
  };
3913
591
 
3914
592
  // 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
593
  const FROZEN_SHADOW_MARKUP = Object.freeze({ ...SHADOW_MARKUP });
3919
594
  if (typeof globalThis !== "undefined") {
3920
595
  globalThis.ContourShadowTemplates = FROZEN_SHADOW_MARKUP;
3921
596
  }
597
+ // Only the SHADOW vocabulary publishes here (R25-06). ContourElements and
3922
598
  if (typeof window !== "undefined") {
3923
- window.ContourElements = Object.freeze(REGISTERED.slice());
3924
599
  window.ContourShadowParts = Object.freeze(Object.fromEntries(
3925
600
  Object.entries(SHADOW_PARTS_PUBLIC).map(([name, parts]) => [name, Object.freeze([...new Set(parts)])]),
3926
601
  ));
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
602
  if (!window.Contour) window.Contour = {};
3932
603
  try { window.Contour.shadowTemplates = FROZEN_SHADOW_MARKUP; } catch {}
3933
604
  }
@@ -3937,48 +608,61 @@ shadow("contour-shadow-filter-pill", `<span class="c-filter-pill" part="filter-p
3937
608
 
3938
609
 
3939
610
 
3940
- /* Line numbers for a code block (CDS-075).
3941
-
3942
- The numbers are real elements rather than a CSS counter on `::before`, for two
3943
- reasons: a counter cannot be left out of a selection, and a number that is not
3944
- in the DOM cannot be excluded from the copied text. `.c-code__line-number`
3945
- carries `user-select: none` so a drag does not take it, and `wireCopy` drops it
3946
- before writing to the clipboard, so the copied text is the code and nothing
3947
- else.
3948
-
3949
- Splitting walks the top level only. A text node is split on its newlines; an
3950
- element that contains a newline of its own (a multi-line highlighted token) is
3951
- kept whole on the line it starts on, because taking it apart would break the
3952
- markup the highlighter produced. */
611
+ /* Line numbers are real elements, not a CSS counter: a counter cannot be left
612
+ out of a selection or the copied text. wireCopy drops them before copying.
613
+ A highlight token can span several lines (a multi-line string or comment is
614
+ one <span> whose text holds "\n"). Such a span cannot live inside one grid
615
+ row, so the splitter walks the subtree, breaks at every newline and rebuilds
616
+ each line with its own shallow clone of the spans it touches — the markup is
617
+ preserved per line and no span crosses a row boundary (R24-149). */
3953
618
  const splitCodeLines = (code) => {
3954
- const lines = [];
3955
- let line = null;
3956
- const add = (n) => {
3957
- if (!line) {
3958
- line = document.createElement("span");
3959
- line.className = "c-code__line";
3960
- lines.push(line);
619
+ // Flatten to per-line runs: { chain: [ancestor elements], text } split at "\n".
620
+ const lines = [[]];
621
+ let cur = lines[0];
622
+ const walk = (node, chain) => {
623
+ if (node.nodeType === 3) {
624
+ String(node.textContent || "").split("\n").forEach((p, i) => {
625
+ if (i) { cur = []; lines.push(cur); }
626
+ if (p) cur.push({ chain, text: p });
627
+ });
628
+ return;
3961
629
  }
3962
- line.appendChild(n);
630
+ if (node.nodeType !== 1) return;
631
+ const next = chain.concat(node);
632
+ Array.from(node.childNodes).forEach((c) => walk(c, next));
3963
633
  };
3964
- Array.from(code.childNodes).forEach((n) => {
3965
- if (n.nodeType !== 3) { add(n); return; }
3966
- String(n.textContent || "").split("\n").forEach((p, i) => {
3967
- if (i) line = null;
3968
- if (p) add(document.createTextNode(p));
3969
- });
3970
- });
3971
- const last = lines[lines.length - 1];
3972
- if (last && !last.textContent && lines.length > 1) lines.pop();
634
+ Array.from(code.childNodes).forEach((n) => walk(n, []));
635
+ const lastLine = lines[lines.length - 1];
636
+ if (!lastLine.length && lines.length > 1) lines.pop();
3973
637
  if (!lines.length) return;
638
+
3974
639
  const frag = document.createDocumentFragment();
3975
- lines.forEach((l, i) => {
640
+ lines.forEach((runs, i) => {
641
+ const lineEl = document.createElement("span");
642
+ lineEl.className = "c-code__line";
643
+ lineEl.setAttribute("data-contour-generated", "line");
644
+ // Reuse a clone while consecutive runs share the same ancestor at a depth.
645
+ const clones = [];
646
+ for (const run of runs) {
647
+ for (let d = 0; d < run.chain.length; d++) {
648
+ if (!clones[d] || clones[d]._contourSrc !== run.chain[d]) {
649
+ const clone = run.chain[d].cloneNode(false); // shallow: attrs/class only
650
+ clone._contourSrc = run.chain[d];
651
+ if (d === 0) lineEl.appendChild(clone);
652
+ else clones[d - 1].appendChild(clone);
653
+ clones[d] = clone;
654
+ clones.length = d + 1; // drop deeper clones from a different parent
655
+ }
656
+ }
657
+ const parent = run.chain.length ? clones[run.chain.length - 1] : lineEl;
658
+ parent.appendChild(document.createTextNode(run.text));
659
+ }
3976
660
  const num = document.createElement("span");
3977
661
  num.className = "c-code__line-number";
3978
662
  num.setAttribute("aria-hidden", "true");
3979
663
  num.textContent = String(i + 1);
3980
- l.prepend(num);
3981
- frag.appendChild(l);
664
+ lineEl.prepend(num);
665
+ frag.appendChild(lineEl);
3982
666
  });
3983
667
  code.textContent = "";
3984
668
  code.appendChild(frag);
@@ -4022,8 +706,7 @@ class ContourFeature extends ContourBase {
4022
706
  static get properties() { return { index: { attribute: "index" }, title: { attribute: "title" }, body: { attribute: "body" } }; }
4023
707
  render() {
4024
708
  this.classList.add("c-feature");
4025
- // `.c-feature` defines three parts: `__index`, `__title`, `__body`. It has
4026
- // no icon slot, so the index line is the label this block actually carries.
709
+ // `.c-feature` has no icon slot; the index line is its label.
4027
710
  const index = this.getAttribute("index");
4028
711
  const title = this.getAttribute("title");
4029
712
  const body = this.getAttribute("body");
@@ -4052,20 +735,25 @@ class ContourFeature extends ContourBase {
4052
735
  }
4053
736
  define("contour-feature", ContourFeature);
4054
737
  class ContourSteps extends ContourBase {
4055
- static get observed() { return ["steps", "current", "empty", "loading", "error", "retry", "src", "lazy", "refresh", "timeout", "skeleton", "heading"]; }
738
+ static get observed() { return ["steps", "current", "empty", "loading", "error", "retry", "src", "lazy", "refresh", "timeout", "skeleton", "heading", "cache-key", "no-cache"]; }
4056
739
  static get properties() { return { steps: { attribute: "steps" }, current: { attribute: "current", type: Number }, src: { attribute: "src" } }; }
4057
740
  render() {
4058
741
  this.classList.add("c-steps");
4059
- // Native list semantics: an <ol> carries the numbering and the <li> items
4060
- // are list items, rather than a role="list" on a <div> with role="listitem"
4061
- // children recreating what the platform already provides.
742
+ // Native list semantics: an <ol> numbers itself and <li> are list items.
4062
743
  let list = this.querySelector(".c-steps__list");
4063
- if (!list) { list = document.createElement("ol"); list.className = "c-steps__list"; list.setAttribute("aria-label", this.getAttribute("aria-label") || "Steps"); this.appendChild(list); }
744
+ if (!list) {
745
+ list = document.createElement("ol");
746
+ list.className = "c-steps__list";
747
+ list.setAttribute("aria-label", this.getAttribute("aria-label") || "Steps");
748
+ this.appendChild(list);
749
+ }
4064
750
  wireStates(this);
4065
751
  loadRemote(this, "steps");
4066
752
  if (renderStates(this, "steps")) return;
4067
753
  const steps = remoteData(this, "steps");
4068
754
  const authored = Array.from(this.children).filter((n) => n.classList && n.classList.contains("c-steps__item"));
755
+ // Adopt authored items into the ol so they share its semantics.
756
+ authored.forEach((it) => { if (it.parentNode !== list) list.appendChild(it); });
4069
757
  if (steps && !authored.length) {
4070
758
  // Drop previously generated items so a re-render cannot stack a second set.
4071
759
  Array.from(list.querySelectorAll(".c-steps__item")).forEach((n) => n.remove());
@@ -4095,8 +783,7 @@ class ContourSteps extends ContourBase {
4095
783
  } else if (!steps && !authored.length) {
4096
784
  renderEmpty(this, "steps");
4097
785
  }
4098
- // Reflect the current step onto the items (aria-current) without clobbering
4099
- // a re-render's generated nodes.
786
+ // Reflect the current step onto the items without clobbering generated nodes.
4100
787
  const attrCurrent = this.getAttribute("current");
4101
788
  const current = (this._current != null) ? this._current : (attrCurrent != null ? parseInt(attrCurrent, 10) : NaN);
4102
789
  const items = Array.from(this.querySelectorAll(".c-steps__item"));
@@ -4115,7 +802,7 @@ class ContourSteps extends ContourBase {
4115
802
  this.addEventListener("keydown", (e) => {
4116
803
  const items = Array.from(this.querySelectorAll(".c-steps__item"));
4117
804
  if (!items.length) return;
4118
- navKey(e, items, { wrap: false, homeEnd: true, rtl: isRtl(this), onNavigate: (i) => { this._current = i; items.forEach((it, j) => { it.setAttribute("aria-current", j === i ? "step" : ""); it.tabIndex = j === i ? 0 : -1; }); const title = items[i].querySelector(".c-steps__title")?.textContent || ""; this.dispatchEvent(new CustomEvent("contour:step-change", { bubbles: true, composed: true, detail: { index: i, title } })); }, onKey: () => { if (e.key === "Enter" || e.key === " ") { const idx = items.indexOf(document.activeElement); const title = document.activeElement.querySelector(".c-steps__title")?.textContent || ""; this.dispatchEvent(new CustomEvent("contour:step-activate", { bubbles: true, composed: true, detail: { index: idx, title } })); } } });
805
+ navKey(e, items, { wrap: false, homeEnd: true, rtl: isRtl(this), onNavigate: (i) => { this._current = i; items.forEach((it, j) => { if (j === i) it.setAttribute("aria-current", "step"); else it.removeAttribute("aria-current"); it.tabIndex = j === i ? 0 : -1; }); const title = items[i].querySelector(".c-steps__title")?.textContent || ""; this.dispatchEvent(new CustomEvent("contour:step-change", { bubbles: true, composed: true, detail: { index: i, title } })); }, onKey: () => { if (e.key === "Enter" || e.key === " ") { const idx = items.indexOf(document.activeElement); const title = document.activeElement.querySelector(".c-steps__title")?.textContent || ""; this.dispatchEvent(new CustomEvent("contour:step-activate", { bubbles: true, composed: true, detail: { index: idx, title } })); } } });
4119
806
  });
4120
807
  this.addEventListener("click", (e) => {
4121
808
  const item = e.target && e.target.closest ? e.target.closest(".c-steps__item") : null;
@@ -4143,11 +830,11 @@ class ContourLink extends ContourBase {
4143
830
  this.classList.add("c-link");
4144
831
  const href = this.getAttribute("href");
4145
832
  const label = this.getAttribute("label");
4146
- // Clear previously generated link so a re-render cannot stack a second one.
4147
- const prevLink = this.querySelector("a");
4148
- if (prevLink) prevLink.remove();
833
+ // Remove only generated anchors; an authored-only link renders nothing.
834
+ Array.from(this.querySelectorAll("a[data-contour-generated]")).forEach((n) => n.remove());
4149
835
  if (href && label) {
4150
836
  const a = document.createElement("a");
837
+ a.dataset.contourGenerated = "";
4151
838
  a.href = safeHref(href);
4152
839
  a.textContent = label;
4153
840
  const ariaLabel = this.getAttribute("aria-label");
@@ -4231,29 +918,42 @@ class ContourDiff extends ContourBase {
4231
918
  render() {
4232
919
  this.classList.add("c-diff");
4233
920
  this.setAttribute("role", "group");
4234
- this.setAttribute("aria-label", "Diff");
4235
- // The block is a list of lines, not two panes: `.c-diff__line` carries the
4236
- // +/- sign, the line number, and the text, and `--add`/`--del` are the only
4237
- // two states it defines. A removed line and an added line are what a
4238
- // before/after pair actually becomes in a diff.
921
+ this.setAttribute("aria-label", labelText(this, "diff", "Diff"));
922
+ // The block is a list of lines, not two panes: each `.c-diff__line` carries
923
+ // a sign, number and text, with `--add`/`--del` as its only states.
4239
924
  Array.from(this.querySelectorAll(".c-diff__line")).forEach((n) => n.remove());
4240
- const line = (kind, sign, text) => {
925
+ const line = (kind, sign, text, num) => {
4241
926
  const el = document.createElement("div");
4242
927
  el.className = kind ? `c-diff__line c-diff__line--${kind}` : "c-diff__line";
4243
928
  el.setAttribute("role", "listitem");
4244
929
  el.setAttribute("tabindex", "0");
930
+ // Emit sign+number+text (3 children matching the grid).
4245
931
  const s = document.createElement("span");
4246
932
  s.className = "c-diff__sign";
4247
933
  s.textContent = sign;
934
+ const n = document.createElement("span");
935
+ n.className = "c-diff__num";
936
+ n.setAttribute("aria-hidden", "true");
937
+ n.textContent = String(num || "");
4248
938
  const code = document.createElement("span");
4249
939
  code.textContent = text;
4250
- el.append(s, code);
940
+ el.append(s, n, code);
4251
941
  return el;
4252
942
  };
4253
943
  const before = this.getAttribute("before");
4254
944
  const after = this.getAttribute("after");
4255
- if (before) this.appendChild(line("del", "−", before));
4256
- if (after) this.appendChild(line("add", "+", after));
945
+ // Split before/after on newlines so multi-line values render as separate lines.
946
+ let lineNum = 1;
947
+ if (before) {
948
+ String(before).split("\n").forEach((l) => {
949
+ this.appendChild(line("del", "−", l, lineNum++));
950
+ });
951
+ }
952
+ if (after) {
953
+ String(after).split("\n").forEach((l) => {
954
+ this.appendChild(line("add", "+", l, lineNum++));
955
+ });
956
+ }
4257
957
  }
4258
958
  enhance() {
4259
959
  if (this._wiredDiff) return;
@@ -4283,15 +983,17 @@ class ContourDoDont extends ContourBase {
4283
983
  render() {
4284
984
  this.classList.add("c-do-dont");
4285
985
  this.setAttribute("role", "group");
4286
- this.setAttribute("aria-label", "Do and don't");
4287
- // An item is one element with one state modifier — `__item--do`,
4288
- // `__item--dont` — and the word on top of it is `__label`. There is no
4289
- // `__do` or `__dont` element in the system.
986
+ this.setAttribute("aria-label", labelText(this, "do-and-dont", "Do and don't"));
987
+ // An item is one element with a state modifier (`__item--do`/`--dont`) and
988
+ // a `__label`; there is no `__do`/`__dont` element.
4290
989
  Array.from(this.querySelectorAll(".c-do-dont__item")).forEach((n) => n.remove());
990
+ // role + tabindex are set in render so they survive re-render (enhance() runs
991
+ // once); items are keyboard-activated, so they are buttons, not listitems.
4291
992
  const item = (kind, word, text) => {
4292
993
  const el = document.createElement("div");
4293
994
  el.className = `c-do-dont__item c-do-dont__item--${kind}`;
4294
- el.setAttribute("role", "listitem");
995
+ el.setAttribute("role", "button");
996
+ el.setAttribute("tabindex", "0");
4295
997
  const label = document.createElement("p");
4296
998
  label.className = "c-do-dont__label";
4297
999
  label.textContent = word;
@@ -4343,7 +1045,10 @@ class ContourFlag extends ContourBase {
4343
1045
  if (variant) this.classList.add("c-flag--" + variant);
4344
1046
  const label = this.getAttribute("label");
4345
1047
  if (label) {
4346
- this.textContent = label;
1048
+ // Update the text node, not textContent, so authored children survive.
1049
+ let text = Array.from(this.childNodes).find((n) => n.nodeType === 3);
1050
+ if (!text) { text = document.createTextNode(""); this.appendChild(text); }
1051
+ text.nodeValue = label;
4347
1052
  }
4348
1053
  }
4349
1054
  }
@@ -4376,9 +1081,7 @@ class ContourInstallFull extends ContourBase {
4376
1081
  }
4377
1082
  }
4378
1083
  enhance() {
4379
- // Interaction lives in behaviours.mjs, which the shadow wrappers call too.
4380
- // One implementation, so the two layers cannot drift apart again: the shadow
4381
- // copy queried its root for slotted nodes, found none, and wired nothing.
1084
+ // Interaction lives in behaviours.mjs so the shadow wrappers share it.
4382
1085
  wireCopy(this);
4383
1086
  }
4384
1087
  }
@@ -4419,7 +1122,7 @@ class ContourTestimonialFull extends ContourBase {
4419
1122
  }
4420
1123
  define("contour-testimonial", ContourTestimonialFull);
4421
1124
  class ContourShowcaseFull extends ContourBase {
4422
- static get observed() { return ["title", "text", "media", "reverse", "items", "empty", "loading", "error", "retry", "src", "lazy", "refresh", "timeout", "skeleton", "heading"]; }
1125
+ static get observed() { return ["title", "text", "media", "reverse", "items", "empty", "loading", "error", "retry", "src", "lazy", "refresh", "timeout", "skeleton", "heading", "cache-key", "no-cache"]; }
4423
1126
  static get properties() { return { title: { attribute: "title" }, text: { attribute: "text" }, media: { attribute: "media" }, reverse: { attribute: "reverse" }, items: { attribute: "items" }, src: { attribute: "src" } }; }
4424
1127
  render() {
4425
1128
  this.classList.add("c-showcase");
@@ -4436,8 +1139,7 @@ class ContourShowcaseFull extends ContourBase {
4436
1139
  const text = this.getAttribute("text");
4437
1140
  const media = this.getAttribute("media");
4438
1141
  if (media) {
4439
- // A figure with a figcaption is the native shape for an illustration
4440
- // with a caption; the old div[role=img] hid the caption from the reader.
1142
+ // A figure with a figcaption is the native shape for an image + caption.
4441
1143
  const m = this.ensure(".c-showcase__media", () => { const el = document.createElement("figure"); el.className = "c-showcase__media"; return el; });
4442
1144
  if (/^https?:\/\/|^\/|^\.\/|\.(png|jpg|jpeg|svg|webp|gif|avif)$/i.test(media.trim())) {
4443
1145
  let img = m.querySelector("img");
@@ -4445,7 +1147,7 @@ class ContourShowcaseFull extends ContourBase {
4445
1147
  img.src = media.trim();
4446
1148
  img.alt = title || "";
4447
1149
  } else {
4448
- m.innerHTML = sanitizeHtml(media);
1150
+ setHTML(m, sanitizeHtml(media));
4449
1151
  }
4450
1152
  if (title) {
4451
1153
  let cap = m.querySelector(".c-showcase__caption");
@@ -4500,6 +1202,9 @@ class ContourShowcaseFull extends ContourBase {
4500
1202
  }
4501
1203
  });
4502
1204
  this.addEventListener("keydown", (e) => {
1205
+ // Authored interactive children own Enter/Space; only act on other targets.
1206
+ const target = e.target && e.target.closest ? e.target.closest("button, a, input, select, textarea, [role='button'], [role='link'], [role='checkbox'], [role='menuitem'], [role='option'], [role='tab']") : null;
1207
+ if (target && this.contains(target)) return;
4503
1208
  if (e.key === "Enter" || e.key === " ") {
4504
1209
  const media = this.querySelector(".c-showcase__media");
4505
1210
  if (media) {
@@ -4515,9 +1220,7 @@ define("contour-showcase", ContourShowcaseFull);
4515
1220
  class ContourPricingFull extends ContourBase {
4516
1221
  static get observed() { return []; }
4517
1222
  render() {
4518
- // `.c-pricing` is the grid; every part the guide shows lives on `.c-price`.
4519
- // A pricing element that scaffolded its own label invented a name no rule
4520
- // defines, so the grid holds its children and stays a container.
1223
+ // `.c-pricing` is the grid; its parts live on `.c-price`. It stays a container.
4521
1224
  this.classList.add("c-pricing");
4522
1225
  }
4523
1226
  }
@@ -4605,7 +1308,7 @@ class ContourRecipeFull extends ContourBase {
4605
1308
  img.src = canvas.trim();
4606
1309
  img.alt = "";
4607
1310
  } else {
4608
- c.innerHTML = sanitizeHtml(canvas);
1311
+ setHTML(c, sanitizeHtml(canvas));
4609
1312
  }
4610
1313
  } else {
4611
1314
  const c = this.querySelector(".c-recipe__canvas");
@@ -4616,21 +1319,14 @@ class ContourRecipeFull extends ContourBase {
4616
1319
  define("contour-recipe", ContourRecipeFull);
4617
1320
  class ContourLogosFull extends ContourBase {
4618
1321
  static get observed() { return []; }
4619
- render() {
4620
- this.classList.add("c-logos");
4621
- if (!this.querySelector(".c-logos__item")) {
4622
- for (const name of ["Cartolab", "Nordwand"]) {
4623
- const span = document.createElement("span");
4624
- span.className = "c-logos__item";
4625
- span.textContent = name;
4626
- this.appendChild(span);
4627
- }
4628
- }
4629
- }
1322
+ render() {
1323
+ this.classList.add("c-logos");
1324
+ // No invented brands — an empty logo wall renders nothing.
1325
+ }
4630
1326
  }
4631
1327
  define("contour-logos", ContourLogosFull);
4632
1328
  class ContourLandingFeaturesFull extends ContourBase {
4633
- static get observed() { return ["items", "empty", "loading", "error", "retry", "src", "lazy", "refresh", "timeout", "skeleton"]; }
1329
+ static get observed() { return ["items", "empty", "loading", "error", "retry", "src", "lazy", "refresh", "timeout", "skeleton", "cache-key", "no-cache"]; }
4634
1330
  static get properties() { return { items: { attribute: "items" }, src: { attribute: "src" } }; }
4635
1331
  render() {
4636
1332
  this.classList.add("c-landing-features");
@@ -4709,7 +1405,7 @@ class ContourLandingHeroFull extends ContourBase {
4709
1405
  img.alt = "";
4710
1406
  body.appendChild(img);
4711
1407
  } else {
4712
- body.innerHTML = sanitizeHtml(preview);
1408
+ setHTML(body, sanitizeHtml(preview));
4713
1409
  }
4714
1410
  }
4715
1411
  } else if (pv) {
@@ -4743,10 +1439,10 @@ class ContourLandingHeroFull extends ContourBase {
4743
1439
  el.appendChild(btn);
4744
1440
  });
4745
1441
  } else {
4746
- el.innerHTML = sanitizeHtml(actions);
1442
+ setHTML(el, sanitizeHtml(actions));
4747
1443
  }
4748
1444
  } catch (_) {
4749
- el.innerHTML = sanitizeHtml(actions);
1445
+ setHTML(el, sanitizeHtml(actions));
4750
1446
  }
4751
1447
  } else if (!actions && a && !authored.length) {
4752
1448
  a.remove();
@@ -4765,7 +1461,18 @@ class ContourPriceFull extends ContourBase {
4765
1461
  render() {
4766
1462
  this.classList.add("c-price");
4767
1463
  const value = this.getAttribute("value");
4768
- if (value) this.textContent = formatValue(value, this.getAttribute("format"), this.getAttribute("locale"));
1464
+ // Format into a generated .c-price__amount span, preserving authored parts.
1465
+ let amount = this.querySelector(".c-price__amount");
1466
+ if (value) {
1467
+ if (!amount) {
1468
+ amount = document.createElement("span");
1469
+ amount.className = "c-price__amount";
1470
+ this.appendChild(amount);
1471
+ }
1472
+ amount.textContent = formatValue(value, this.getAttribute("format"), this.getAttribute("locale"));
1473
+ } else if (amount) {
1474
+ amount.remove();
1475
+ }
4769
1476
  }
4770
1477
  }
4771
1478
  define("contour-price", ContourPriceFull);
@@ -4815,18 +1522,19 @@ class ContourPanel extends ContourBase {
4815
1522
  btn = document.createElement("button");
4816
1523
  btn.type = "button";
4817
1524
  btn.className = "c-panel__collapse c-btn c-btn--ghost c-btn--sm";
4818
- btn.setAttribute("aria-label", "Toggle panel");
4819
- btn.textContent = "▾";
1525
+ btn.setAttribute("aria-label", labelText(this, "collapse", "Toggle panel"));
1526
+ // R24-134: SVG glyph instead of text arrows.
1527
+ setHTML(btn, '<svg aria-hidden="true" viewBox="0 0 24 24" width="16" height="16"><use href="#i-chevron-down" /></svg>');
4820
1528
  this.appendChild(btn);
4821
1529
  }
4822
1530
  if (this.hasAttribute("collapsed")) {
4823
1531
  this.classList.add("c-panel--collapsed");
4824
1532
  btn.setAttribute("aria-expanded", "false");
4825
- btn.textContent = "▸";
1533
+ setHTML(btn, '<svg aria-hidden="true" viewBox="0 0 24 24" width="16" height="16"><use href="#i-chevron-right" /></svg>');
4826
1534
  } else {
4827
1535
  this.classList.remove("c-panel--collapsed");
4828
1536
  btn.setAttribute("aria-expanded", "true");
4829
- btn.textContent = "▾";
1537
+ setHTML(btn, '<svg aria-hidden="true" viewBox="0 0 24 24" width="16" height="16"><use href="#i-chevron-down" /></svg>');
4830
1538
  }
4831
1539
  } else {
4832
1540
  const btn = this.querySelector(".c-panel__collapse");
@@ -4837,9 +1545,12 @@ class ContourPanel extends ContourBase {
4837
1545
  const body = this.ensure(".c-panel__body", () => { const el = document.createElement("div"); el.className = "c-panel__body"; return el; });
4838
1546
  body.classList.toggle("c-panel__body--flush", this.hasAttribute("flush"));
4839
1547
  const head = this.querySelector(".c-panel__head");
1548
+ // Exclude the collapse toggle from the body wrap so it stays visible when collapsed.
1549
+ const collapseBtn = this.querySelector(".c-panel__collapse");
4840
1550
  Array.from(this.childNodes).forEach((n) => {
4841
1551
  if (n === body || n === head) return;
4842
1552
  if (n.nodeType === 1 && (n.classList.contains("c-panel__title") || n.classList.contains("c-panel__subtitle") || n.classList.contains("c-panel__status"))) return;
1553
+ if (n === collapseBtn) return;
4843
1554
  body.appendChild(n);
4844
1555
  });
4845
1556
  if (!body.parentNode) this.appendChild(body);
@@ -4883,7 +1594,7 @@ class ContourCta extends ContourBase {
4883
1594
  if (p) p.remove();
4884
1595
  }
4885
1596
  const actions = this.getAttribute("actions");
4886
- // Clear previously generated actions wrap so a re-render cannot stack.
1597
+ // Remove only the generated actions wrap, not authored actions.
4887
1598
  const prevWrap = this.querySelector(".c-cta__actions");
4888
1599
  if (prevWrap) prevWrap.remove();
4889
1600
  if (actions) {
@@ -4891,11 +1602,20 @@ class ContourCta extends ContourBase {
4891
1602
  const parsed = JSON.parse(actions);
4892
1603
  const wrap = document.createElement("div");
4893
1604
  wrap.className = "c-cta__actions";
1605
+ // Support {label, href, primary} like landing-hero.
1606
+ let hasPrimary = false;
4894
1607
  parsed.forEach((a) => {
4895
- const btn = document.createElement("button");
4896
- btn.className = "c-btn c-btn--primary";
4897
- btn.type = "button";
4898
- btn.textContent = typeof a === "string" ? a : (a.label || a);
1608
+ const label = typeof a === "string" ? a : (a.label || a);
1609
+ const href = typeof a === "object" && a ? a.href : null;
1610
+ const primary = typeof a === "object" && a ? a.primary : false;
1611
+ // Single-primary signal: first primary wins, rest are secondary.
1612
+ const isPrimary = primary && !hasPrimary;
1613
+ if (isPrimary) hasPrimary = true;
1614
+ const btn = document.createElement(href ? "a" : "button");
1615
+ btn.className = isPrimary ? "c-btn c-btn--primary" : "c-btn c-btn--ghost";
1616
+ if (href) { btn.href = safeHref(href); btn.setAttribute("role", "button"); }
1617
+ else btn.type = "button";
1618
+ btn.textContent = label;
4899
1619
  wrap.appendChild(btn);
4900
1620
  });
4901
1621
  this.appendChild(wrap);
@@ -4922,11 +1642,15 @@ class ContourCode extends ContourBase {
4922
1642
  if (t) t.remove();
4923
1643
  }
4924
1644
  if (this.hasAttribute("copyable")) {
1645
+ const head = this.ensure(".c-code__head", () => { const el = document.createElement("div"); el.className = "c-code__head"; return el; });
1646
+ // Copy button into head with c-btn classes + icon + labelText.
4925
1647
  this.ensure(".c-code__copy", () => {
4926
1648
  const btn = document.createElement("button");
4927
- btn.className = "c-code__copy";
1649
+ btn.className = "c-btn c-btn--ghost c-btn--sm c-code__copy";
4928
1650
  btn.type = "button";
4929
- btn.textContent = labelText(this, "copy", "Copy");
1651
+ setHTML(btn, '<svg aria-hidden="true" viewBox="0 0 24 24" width="14" height="14"><use href="#i-copy" /></svg>');
1652
+ btn.setAttribute("aria-label", labelText(this, "copy", "Copy"));
1653
+ head.appendChild(btn);
4930
1654
  return btn;
4931
1655
  });
4932
1656
  } else {
@@ -4950,9 +1674,8 @@ class ContourCode extends ContourBase {
4950
1674
  if (head && head.parentNode === this && pre.parentNode === this && head.compareDocumentPosition(pre) & Node.DOCUMENT_POSITION_PRECEDING) {
4951
1675
  this.insertBefore(pre, head.nextSibling);
4952
1676
  }
4953
- // Line numbers are applied after the code is wrapped, and are idempotent:
4954
- // the split is guarded by a flag on the <code>, so a re-render cannot
4955
- // number the same source twice.
1677
+ // Line numbers are applied after wrapping and are idempotent: a flag on the
1678
+ // <code> prevents numbering the same source twice.
4956
1679
  const numbered = this.hasAttribute("numbered");
4957
1680
  this.classList.toggle("c-code--numbered", numbered);
4958
1681
  const codeEl = pre.querySelector("code");
@@ -4968,9 +1691,7 @@ class ContourCode extends ContourBase {
4968
1691
  }
4969
1692
  }
4970
1693
  enhance() {
4971
- // Interaction lives in behaviours.mjs, which the shadow wrappers call too.
4972
- // One implementation, so the two layers cannot drift apart again: the shadow
4973
- // copy queried its root for slotted nodes, found none, and wired nothing.
1694
+ // Interaction lives in behaviours.mjs so the shadow wrappers share it.
4974
1695
  wireCopy(this);
4975
1696
  }
4976
1697
  }
@@ -4986,9 +1707,7 @@ class ContourPullquote extends ContourBase {
4986
1707
  render() {
4987
1708
  this.classList.add("c-pullquote");
4988
1709
  const quote = this.getAttribute("quote");
4989
- // `.c-pullquote` defines no `__quote` or `__byline`: the guide's specimen is
4990
- // the paragraph itself, and the one element the sheet styles inside it is
4991
- // `cite`, which is what an attribution is.
1710
+ // `.c-pullquote` styles the paragraph and `cite`; there is no `__quote`/`__byline`.
4992
1711
  if (quote) {
4993
1712
  // Preserve a generated <cite> (attribution) while updating the quote text.
4994
1713
  Array.from(this.childNodes).forEach((n) => { if (n.nodeType === 3) n.remove(); });
@@ -5013,11 +1732,11 @@ class ContourAnchor extends ContourBase {
5013
1732
  this.classList.add("c-anchor");
5014
1733
  const href = this.getAttribute("href");
5015
1734
  const label = this.getAttribute("label");
5016
- // Clear previously generated link so a re-render cannot stack a second one.
5017
- const prevAnchor = this.querySelector("a");
5018
- if (prevAnchor) prevAnchor.remove();
1735
+ // Remove only generated anchors; an authored-only link renders nothing.
1736
+ Array.from(this.querySelectorAll("a[data-contour-generated]")).forEach((n) => n.remove());
5019
1737
  if (href && label) {
5020
1738
  const a = document.createElement("a");
1739
+ a.dataset.contourGenerated = "";
5021
1740
  a.href = safeHref(href);
5022
1741
  a.textContent = label;
5023
1742
  const ariaLabel = this.getAttribute("aria-label");
@@ -5037,20 +1756,24 @@ class ContourAnchor extends ContourBase {
5037
1756
  * `retry`, `src`, `lazy`, `refresh`, `timeout`, `skeleton`.
5038
1757
  */
5039
1758
  class ContourGeocoder extends ContourBase {
5040
- static get observed() { return ["placeholder", "value", "results", "empty", "loading", "error", "retry", "src", "lazy", "refresh", "timeout", "skeleton"]; }
1759
+ static get observed() { return ["placeholder", "value", "results", "empty", "loading", "error", "retry", "src", "lazy", "refresh", "timeout", "skeleton", "cache-key", "no-cache"]; }
5041
1760
  static get properties() { return { placeholder: { attribute: "placeholder" }, value: { attribute: "value" }, results: { attribute: "results" }, src: { attribute: "src" } }; }
5042
1761
  render() {
5043
1762
  this.classList.add("c-geocoder");
5044
1763
  wireStates(this);
5045
1764
  loadRemote(this, ["results"]);
5046
1765
  if (renderStates(this, "geocoder")) return;
5047
- // Input
1766
+ // The input carries `c-input` so it inherits the system control contract.
5048
1767
  let inp = this.querySelector(".c-geocoder__input");
5049
1768
  if (!inp) {
5050
1769
  inp = document.createElement("input");
5051
1770
  inp.type = "search";
5052
- inp.className = "c-geocoder__input";
1771
+ inp.className = "c-input c-geocoder__input";
5053
1772
  if (!inp.hasAttribute("aria-label")) inp.setAttribute("aria-label", this.getAttribute("placeholder") || "Search location");
1773
+ // Combobox contract: the input owns the list and announces the active option.
1774
+ inp.setAttribute("role", "combobox");
1775
+ inp.setAttribute("aria-autocomplete", "list");
1776
+ inp.setAttribute("aria-expanded", "false");
5054
1777
  this.appendChild(inp);
5055
1778
  }
5056
1779
  const ph = this.getAttribute("placeholder");
@@ -5059,20 +1782,33 @@ class ContourGeocoder extends ContourBase {
5059
1782
  if (val !== null && inp.value !== val) inp.value = val;
5060
1783
  // Results
5061
1784
  Array.from(this.querySelectorAll(".c-geocoder__result")).forEach((n) => n.remove());
1785
+ Array.from(this.querySelectorAll(".c-geocoder__list")).forEach((n) => n.remove());
5062
1786
  let results = [];
5063
1787
  const rAttr = this.getAttribute("results");
5064
1788
  if (rAttr) { try { results = JSON.parse(rAttr); } catch (e) { results = []; } }
5065
1789
  const remote = remoteData(this, "results");
5066
- if (Array.isArray(remote)) results = remote;
1790
+ // remoteData returns a string; parse it so fetched results render.
1791
+ if (typeof remote === "string") {
1792
+ try { const parsed = JSON.parse(remote); if (Array.isArray(parsed)) results = parsed; } catch (e) {}
1793
+ } else if (Array.isArray(remote)) {
1794
+ results = remote;
1795
+ }
5067
1796
  if (Array.isArray(results) && results.length) {
1797
+ // A rebuilt list has no active option, whatever was active before.
1798
+ this._geocoderIndex = -1;
1799
+ // One list id per host, so aria-controls survives a re-render.
1800
+ if (!this._geocoderListId) this._geocoderListId = contourId("geocoder-list");
5068
1801
  const list = document.createElement("ul");
5069
1802
  list.className = "c-geocoder__list";
1803
+ list.id = this._geocoderListId;
5070
1804
  list.setAttribute("role", "listbox");
5071
1805
  results.forEach((r, idx) => {
5072
1806
  const li = document.createElement("li");
5073
1807
  li.className = "c-geocoder__result";
1808
+ li.id = this._geocoderListId + "-" + idx;
5074
1809
  li.setAttribute("role", "option");
5075
- li.setAttribute("tabindex", idx === 0 ? "0" : "-1");
1810
+ li.setAttribute("aria-selected", "false");
1811
+ li.setAttribute("tabindex", "-1");
5076
1812
  li.textContent = (typeof r === "object") ? (r.label || r.name || "") : String(r);
5077
1813
  if (typeof r === "object") {
5078
1814
  if (r.lat != null) li.dataset.lat = String(r.lat);
@@ -5081,45 +1817,123 @@ class ContourGeocoder extends ContourBase {
5081
1817
  list.appendChild(li);
5082
1818
  });
5083
1819
  this.appendChild(list);
5084
- } else if (!this.hasAttribute("loading") && !this.hasAttribute("error")) {
5085
- renderEmpty(this, "geocoder");
1820
+ inp.setAttribute("aria-controls", this._geocoderListId);
1821
+ inp.setAttribute("aria-expanded", "true");
1822
+ } else {
1823
+ inp.removeAttribute("aria-controls");
1824
+ inp.setAttribute("aria-expanded", "false");
1825
+ inp.removeAttribute("aria-activedescendant");
1826
+ this._geocoderIndex = -1;
1827
+ if (!this.hasAttribute("loading") && !this.hasAttribute("error")) {
1828
+ // Suppress the empty state before the user has typed anything.
1829
+ const inp = this.querySelector(".c-geocoder__input");
1830
+ if (inp && inp.value) renderEmpty(this, "geocoder");
1831
+ }
5086
1832
  }
5087
1833
  }
5088
1834
  enhance() {
5089
1835
  if (this._wiredGeocoder) return;
5090
1836
  this._wiredGeocoder = true;
5091
1837
  const inp = this.querySelector(".c-geocoder__input");
1838
+ // Active option index, re-derived from the DOM per event (rule 12). Must be
1839
+ // a number starting at -1: `undefined + 1` is NaN and selects nothing.
1840
+ if (typeof this._geocoderIndex !== "number") this._geocoderIndex = -1;
1841
+ const options = () => Array.from(this.querySelectorAll(".c-geocoder__result"));
1842
+ const active = () => {
1843
+ const opts = options();
1844
+ const i = this._geocoderIndex;
1845
+ return i >= 0 && i < opts.length ? opts[i] : null;
1846
+ };
1847
+ const setActive = (i) => {
1848
+ const opts = options();
1849
+ if (!opts.length) return;
1850
+ const next = Math.max(0, Math.min(opts.length - 1, Number.isFinite(i) ? i : 0));
1851
+ opts.forEach((o, n) => o.setAttribute("aria-selected", n === next ? "true" : "false"));
1852
+ this._geocoderIndex = next;
1853
+ if (inp) {
1854
+ if (next >= 0) inp.setAttribute("aria-activedescendant", opts[next].id);
1855
+ else inp.removeAttribute("aria-activedescendant");
1856
+ }
1857
+ };
1858
+ const clearActive = () => {
1859
+ this._geocoderIndex = -1;
1860
+ options().forEach((o) => o.setAttribute("aria-selected", "false"));
1861
+ if (inp) inp.removeAttribute("aria-activedescendant");
1862
+ };
1863
+ const select = (li) => {
1864
+ if (!li) return;
1865
+ // R24-132: emit numeric lat/lon, not strings.
1866
+ const result = { label: li.textContent.trim(), lat: li.dataset.lat ? Number(li.dataset.lat) : undefined, lon: li.dataset.lon ? Number(li.dataset.lon) : undefined };
1867
+ this.dispatchEvent(new CustomEvent("contour:select", { bubbles: true, composed: true, detail: { result } }));
1868
+ };
5092
1869
  if (inp) {
5093
- let timer = null;
5094
- inp.addEventListener("input", () => {
5095
- if (timer) clearTimeout(timer);
5096
- timer = setTimeout(() => {
1870
+ // Delegate input/keydown on host (rule 12): input is rebuilt every render, so listeners on it are lost.
1871
+ this.addEventListener("input", (e) => {
1872
+ if (e.target !== inp) return;
1873
+ clearActive();
1874
+ if (this._geocoderTimer) clearTimeout(this._geocoderTimer);
1875
+ this._geocoderTimer = setTimeout(() => {
1876
+ this._geocoderTimer = null;
1877
+ if (!this.isConnected) return;
5097
1878
  this.dispatchEvent(new CustomEvent("contour:search", { bubbles: true, composed: true, detail: { query: inp.value } }));
5098
1879
  }, 200);
5099
1880
  });
5100
- inp.addEventListener("keydown", (e) => {
1881
+ this.addEventListener("keydown", (e) => {
1882
+ if (e.target !== inp) return;
1883
+ const opts = options();
1884
+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {
1885
+ if (!opts.length) return;
1886
+ e.preventDefault();
1887
+ const cur = this._geocoderIndex < 0 ? (e.key === "ArrowDown" ? -1 : opts.length) : this._geocoderIndex;
1888
+ setActive(cur + (e.key === "ArrowDown" ? 1 : -1));
1889
+ return;
1890
+ }
5101
1891
  if (e.key === "Enter") {
5102
1892
  e.preventDefault();
5103
- this.dispatchEvent(new CustomEvent("contour:search", { bubbles: true, composed: true, detail: { query: inp.value } }));
1893
+ // R24-132: Enter commits the label + closes the list.
1894
+ const li = active();
1895
+ if (li) {
1896
+ select(li);
1897
+ inp.setAttribute("aria-expanded", "false");
1898
+ inp.removeAttribute("aria-controls");
1899
+ clearActive();
1900
+ } else {
1901
+ this.dispatchEvent(new CustomEvent("contour:search", { bubbles: true, composed: true, detail: { query: inp.value } }));
1902
+ }
1903
+ return;
1904
+ }
1905
+ if (e.key === "Escape") {
1906
+ // R24-132: Escape hides the list (not ARIA-only).
1907
+ if (opts.length && inp.getAttribute("aria-expanded") === "true") {
1908
+ e.preventDefault();
1909
+ clearActive();
1910
+ inp.setAttribute("aria-expanded", "false");
1911
+ inp.removeAttribute("aria-controls");
1912
+ // Actually hide the list from the DOM.
1913
+ const list = this.querySelector(".c-geocoder__list");
1914
+ if (list) list.remove();
1915
+ }
5104
1916
  }
5105
1917
  });
5106
1918
  }
5107
1919
  this.addEventListener("click", (e) => {
5108
1920
  const li = e.target && e.target.closest ? e.target.closest(".c-geocoder__result") : null;
5109
1921
  if (!li || !this.contains(li)) return;
5110
- const result = { label: li.textContent.trim(), lat: li.dataset.lat, lon: li.dataset.lon };
5111
- this.dispatchEvent(new CustomEvent("contour:select", { bubbles: true, composed: true, detail: { result } }));
1922
+ select(li);
5112
1923
  });
5113
1924
  this.addEventListener("keydown", (e) => {
5114
1925
  const li = e.target && e.target.closest ? e.target.closest(".c-geocoder__result") : null;
5115
1926
  if (!li || !this.contains(li)) return;
5116
1927
  if (e.key === "Enter" || e.key === " ") {
5117
1928
  e.preventDefault();
5118
- const result = { label: li.textContent.trim(), lat: li.dataset.lat, lon: li.dataset.lon };
5119
- this.dispatchEvent(new CustomEvent("contour:select", { bubbles: true, composed: true, detail: { result } }));
1929
+ select(li);
5120
1930
  }
5121
1931
  });
5122
1932
  }
1933
+ disconnectedCallback() {
1934
+ // A pending debounce must not outlive its host (F-RO10).
1935
+ if (this._geocoderTimer) { clearTimeout(this._geocoderTimer); this._geocoderTimer = null; }
1936
+ super.disconnectedCallback();
1937
+ }
5123
1938
  }
5124
1939
  define("contour-geocoder", ContourGeocoder);
5125
-