contour-ds 1.7.2 → 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 (150) hide show
  1. package/README.md +244 -326
  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/agent-rules.json +16 -0
  6. package/dist/build-manifest.json +344 -126
  7. package/dist/contour-wc-content.esm.js +1939 -0
  8. package/dist/contour-wc-content.esm.min.js +1 -0
  9. package/dist/contour-wc-core.esm.js +3724 -0
  10. package/dist/contour-wc-core.esm.min.js +1 -0
  11. package/dist/contour-wc-dashboard.esm.js +6986 -0
  12. package/dist/contour-wc-dashboard.esm.min.js +1 -0
  13. package/dist/contour-wc-data.esm.js +6572 -0
  14. package/dist/contour-wc-data.esm.min.js +1 -0
  15. package/dist/contour-wc-docs.esm.js +976 -0
  16. package/dist/contour-wc-docs.esm.min.js +1 -0
  17. package/dist/contour-wc-feedback.esm.js +1742 -0
  18. package/dist/contour-wc-feedback.esm.min.js +1 -0
  19. package/dist/contour-wc-forms.esm.js +2437 -0
  20. package/dist/contour-wc-forms.esm.min.js +1 -0
  21. package/dist/contour-wc-interaction.esm.js +1343 -0
  22. package/dist/contour-wc-interaction.esm.min.js +1 -0
  23. package/dist/contour-wc-layout.esm.js +845 -0
  24. package/dist/contour-wc-layout.esm.min.js +1 -0
  25. package/dist/contour-wc-map.esm.js +2411 -0
  26. package/dist/contour-wc-map.esm.min.js +1 -0
  27. package/dist/contour-wc-misc.esm.js +945 -0
  28. package/dist/contour-wc-misc.esm.min.js +1 -0
  29. package/dist/contour-wc-navigation.esm.js +2842 -0
  30. package/dist/contour-wc-navigation.esm.min.js +1 -0
  31. package/dist/contour-wc-ui.esm.js +6519 -0
  32. package/dist/contour-wc-ui.esm.min.js +1 -0
  33. package/dist/contour-wc.esm.js +14435 -5723
  34. package/dist/contour-wc.esm.min.js +1 -1
  35. package/dist/contour-wc.js +14436 -5725
  36. package/dist/contour-wc.min.js +1 -1
  37. package/dist/contour.a11y.json +402 -0
  38. package/dist/contour.code-snippets +4534 -0
  39. package/dist/contour.components.json +4870 -1222
  40. package/dist/contour.css +6672 -4711
  41. package/dist/contour.d.ts +753 -1085
  42. package/dist/contour.esm.js +440 -18
  43. package/dist/contour.esm.min.js +1 -1
  44. package/dist/contour.html-data.json +11343 -0
  45. package/dist/contour.js +440 -18
  46. package/dist/contour.min.css +1 -1
  47. package/dist/contour.min.js +1 -1
  48. package/dist/contour.react.d.ts +422 -0
  49. package/dist/contour.single.html +17 -0
  50. package/dist/contour.single.min.css +1 -0
  51. package/dist/contour.themes.json +56 -12
  52. package/dist/contour.tokens.json +1318 -1053
  53. package/dist/contour.vue.d.ts +420 -0
  54. package/dist/contour.web-types.json +11703 -0
  55. package/dist/custom-elements.json +36120 -0
  56. package/dist/docs/actions.md +16 -6
  57. package/dist/docs/affordances.md +21 -85
  58. package/dist/docs/apireference.md +9 -5
  59. package/dist/docs/colour.md +10 -4
  60. package/dist/docs/componentindex.md +9 -22
  61. package/dist/docs/data.md +39 -58
  62. package/dist/docs/docs.md +12 -7
  63. package/dist/docs/feedback.md +30 -12
  64. package/dist/docs/field.md +28 -13
  65. package/dist/docs/forms.md +35 -19
  66. package/dist/docs/index.json +70 -61
  67. package/dist/docs/install.md +12 -7
  68. package/dist/docs/landing.md +7 -4
  69. package/dist/docs/mapengine.md +30 -8
  70. package/dist/docs/motion.md +12 -6
  71. package/dist/docs/navigation.md +31 -7
  72. package/dist/docs/overlays.md +32 -25
  73. package/dist/docs/overview.md +3 -2
  74. package/dist/docs/patterns.md +20 -10
  75. package/dist/docs/playground.md +11 -4
  76. package/dist/docs/principles.md +8 -6
  77. package/dist/docs/recipes.md +117 -13
  78. package/dist/docs/space.md +10 -6
  79. package/dist/docs/status.md +13 -14
  80. package/dist/docs/surfaces.md +17 -22
  81. package/dist/docs/theming.md +18 -32
  82. package/dist/docs/type.md +12 -5
  83. package/dist/docs/webcomponents.md +75 -33
  84. package/dist/hljs.css +1 -20
  85. package/dist/map-chrome.mapbox.css +68 -92
  86. package/dist/map-chrome.maplibre.css +68 -92
  87. package/dist/registry/items/contour-core.json +2 -2
  88. package/dist/registry/items/contour-data.json +2 -2
  89. package/dist/registry/items/contour-docs.json +2 -2
  90. package/dist/registry/items/contour-landing.json +2 -2
  91. package/dist/registry/registry.json +8 -8
  92. package/dist/surfaces/contour-core.min.css +1 -1
  93. package/dist/surfaces/contour-data.min.css +1 -1
  94. package/dist/surfaces/contour-docs.min.css +1 -1
  95. package/dist/surfaces/contour-landing.min.css +1 -1
  96. package/dist/svg/icons.svg +367 -0
  97. package/dist/wc/behaviours.mjs +222 -192
  98. package/dist/wc/content.mjs +486 -142
  99. package/dist/wc/core.mjs +917 -395
  100. package/dist/wc/dashboard.mjs +252 -25
  101. package/dist/wc/data-chart.mjs +1333 -0
  102. package/dist/wc/data-export.mjs +391 -0
  103. package/dist/wc/data-gauge.mjs +779 -0
  104. package/dist/wc/data-geo.mjs +696 -0
  105. package/dist/wc/data-glyphs.mjs +133 -0
  106. package/dist/wc/data-legend.mjs +431 -0
  107. package/dist/wc/data-readout.mjs +227 -0
  108. package/dist/wc/data-series.mjs +1004 -0
  109. package/dist/wc/data-table.mjs +751 -0
  110. package/dist/wc/data.mjs +15 -3707
  111. package/dist/wc/docs.mjs +113 -19
  112. package/dist/wc/feedback.mjs +320 -116
  113. package/dist/wc/forms-controls.mjs +635 -0
  114. package/dist/wc/forms-field.mjs +547 -0
  115. package/dist/wc/forms-groups.mjs +347 -0
  116. package/dist/wc/forms-input.mjs +292 -0
  117. package/dist/wc/forms.mjs +10 -1122
  118. package/dist/wc/glyph.mjs +204 -0
  119. package/dist/wc/index.mjs +16 -7
  120. package/dist/wc/interaction.mjs +322 -75
  121. package/dist/wc/layout.mjs +100 -29
  122. package/dist/wc/map.mjs +888 -285
  123. package/dist/wc/misc.mjs +137 -26
  124. package/dist/wc/navigation-menu.mjs +735 -0
  125. package/dist/wc/navigation-shell.mjs +495 -0
  126. package/dist/wc/navigation-tree.mjs +995 -0
  127. package/dist/wc/navigation.mjs +9 -1636
  128. package/dist/wc/registration.mjs +1 -8
  129. package/dist/wc/shadow.mjs +285 -113
  130. package/dist/wc/states.mjs +75 -78
  131. package/dist/wc/svg.mjs +209 -34
  132. package/dist/wc/ui-atoms.mjs +608 -0
  133. package/dist/wc/ui-data.mjs +1404 -0
  134. package/dist/wc/ui-feedback.mjs +419 -0
  135. package/dist/wc/ui-inputs.mjs +1570 -0
  136. package/dist/wc/ui-menus.mjs +307 -0
  137. package/dist/wc/ui-overlays.mjs +1605 -0
  138. package/integrations/README.md +25 -5
  139. package/integrations/ai/CLAUDE.md +6 -3
  140. package/integrations/ai/COPILOT.md +14 -0
  141. package/integrations/ai/GEMINI.md +14 -0
  142. package/integrations/ai/WINDSURF.md +14 -0
  143. package/integrations/ai/v0-prompt.md +13 -1
  144. package/integrations/frameworks/README.md +235 -0
  145. package/integrations/native/README.md +0 -3
  146. package/integrations/native/style-dictionary.config.json +1 -1
  147. package/integrations/tailwind/contour-theme.css +71 -13
  148. package/integrations/validate-markup.mjs +172 -0
  149. package/package.json +103 -39
  150. package/dist/wc/ui.mjs +0 -3560
package/dist/wc/core.mjs CHANGED
@@ -1,44 +1,25 @@
1
- /* ============================================================================
2
- CONTOUR — Web Components (progressive enhancement)
3
- ----------------------------------------------------------------------------
4
- Two layers over the same blocks. The light-DOM wrappers add the CSS classes
5
- the block already has and, where a block needs scaffolding, generate it from
6
- attributes; styles come straight from ds.css. The contour-shadow-* wrappers
7
- are an opt-in alternative for consumers who want an isolated root with named
8
- parts to style through ::part(); they hold a template and slots and share the
9
- document's sheets. Neither layer replaces a native element, and nothing here
10
- is required for a page to work.
11
-
12
- What this file registers is published as the frozen array
13
- `window.ContourElements`, because `customElements` cannot be enumerated and a
14
- reader should not have to infer the registry by scraping quoted strings out of
15
- the source. A scrape counts whatever shape the prose happens to be in: it is
16
- how a gate came to certify a fraction of this file's elements as the whole of
17
- them, and call the difference a pass. No number is written down here for that
18
- reason — the array is the count, and the contract gate reads it.
19
- ========================================================================= */
1
+ /* CONTOUR Web Components — two light-DOM layers over ds.css blocks; publishes the frozen `window.ContourElements` registry. */
20
2
  "use strict";
21
3
 
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
4
  /** Names registered by this module, in registration order. */
26
5
  export const REGISTERED = [];
27
6
 
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.
7
+ /**
8
+ * R31-38: a real scroller is an element whose computed overflow is
9
+ * auto/scroll AND that actually overflows. The re-render layout pass used to
10
+ * read scrollHeight/clientHeight on EVERY element (4,018 layout reads per
11
+ * 500-row density change); the overflow pre-check is a style query (no
12
+ * layout) and short-circuits, so the layout reads happen only on scrollers.
13
+ */
14
+ const isScroller = (el) => {
15
+ if (typeof getComputedStyle !== "function") return false;
16
+ const s = getComputedStyle(el);
17
+ if (s.overflowY !== "auto" && s.overflowY !== "scroll" && s.overflowX !== "auto" && s.overflowX !== "scroll") return false;
18
+ return el.scrollHeight > el.clientHeight || el.scrollWidth > el.clientWidth;
19
+ };
20
+
21
+ // Anything a host starts against the document (fetch, timer, observer) registers
22
+ // cleanup here; `disconnectedCallback` runs the list, one disposal per mount.
42
23
  const DISPOSERS = new WeakMap();
43
24
  /** Register teardown work for the host's current connection. */
44
25
  export const onDispose = (host, fn) => {
@@ -78,52 +59,67 @@
78
59
 
79
60
  /** Define a custom element once, while remaining safe in SSR runtimes. */
80
61
  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.
62
+ // No-op when the Custom Elements registry is unavailable (SSR-safe); the tag
63
+ // stays unknown until a browser defines it.
84
64
  if (typeof customElements === "undefined" || !customElements || typeof customElements.define !== "function") return;
85
65
  if (customElements.get(name)) return;
66
+ // Opt-in lazy hydration (data-hydrate="lazy"): definitions defer until near viewport; REGISTERED names only handed elements.
67
+ if (typeof window !== "undefined" && typeof window.__contourDefineDefer === "function" && window.__contourDefineDefer(name, cls)) return;
86
68
  customElements.define(name, cls);
87
69
  REGISTERED.push(name);
70
+ // Publish on every registration: raw-fragment imports never load shadow.mjs, so each slice is frozen and current.
71
+ if (typeof window !== "undefined") {
72
+ window.ContourElements = Object.freeze(REGISTERED.slice());
73
+ }
88
74
  };
89
75
 
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".
76
+ // One list for both layers — a separate modifier list is how light and shadow
77
+ // drifted apart over "color".
93
78
  /** Attribute names that map to component modifier classes. */
94
79
  export const MODS = ["variant", "size", "color"];
95
80
 
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.
81
+ // The count — the gate compares emitted names against this object, so no
82
+ // number is written anywhere else; payload keys are the union across sites.
83
+ /**
84
+ * Sentinel type for JSON-typed reflected properties (R24-90). A property
85
+ * declared `type: JSON_TYPE` serialises objects/arrays with JSON.stringify and
86
+ * parses JSON-looking attribute values back on read, so a framework that
87
+ * assigns `el.items = [{label:"Alpha"}]` writes a JSON string instead of
88
+ * "[object Object]".
89
+ */
90
+ const JSON_TYPE = Symbol("JSON");
91
+
103
92
  /** Frozen event vocabulary with the public detail keys for each event. */
104
93
  export const CONTOUR_EVENTS = Object.freeze({
105
- "contour:activate": { payload: ["row"], composed: true },
94
+ "contour:activate": { payload: ["files", "label", "row", "value"], composed: true },
106
95
  "contour:add": { payload: ["value"], composed: true },
96
+ "contour:activity-clear": { payload: [], composed: true },
97
+ "contour:activity-filter": { payload: ["unread"], composed: true },
107
98
  "contour:activity-select": { payload: ["index", "text"], composed: true },
99
+ "contour:rendered": { payload: ["renderCount"], composed: true },
100
+ "contour:cap": { payload: ["series", "total", "shown"], composed: true },
101
+ "contour:action": { payload: ["label"], composed: true },
108
102
  "contour:break-change": { payload: ["layer", "value"], composed: true },
109
- "contour:style-resolved": { payload: ["applied", "items", "layer", "property", "value"], composed: true },
103
+ "contour:style-resolved": { payload: ["applied", "classification", "colors", "items", "layer", "n", "palette", "property", "value"], composed: true },
110
104
  "contour:advanced-toggle": { payload: ["title"], composed: true },
111
105
  "contour:affordance-activate": { payload: ["name"], composed: true },
112
106
  "contour:aggregate": { payload: ["aggregate"], composed: true },
113
107
  "contour:bearing": { payload: ["direction", "degrees"], composed: true },
114
108
  "contour:btn-group-change": { payload: ["index", "label"], composed: true },
115
- "contour:brush-start": { payload: ["end", "start", "value"], composed: true },
116
- "contour:brush-end": { payload: ["end", "start", "value"], composed: true },
117
- "contour:brush": { payload: ["end", "start", "value"], composed: true },
118
- "contour:change": { payload: ["checked", "color", "direction", "end", "files", "high", "index", "low", "month", "name", "speed", "start", "unit", "value", "year"], composed: true },
109
+ "contour:brush-start": { payload: ["end", "range", "start", "value"], composed: true },
110
+ "contour:brush-end": { payload: ["end", "range", "start", "value"], composed: true },
111
+ "contour:brush": { payload: ["end", "range", "start", "value"], composed: true },
112
+ "contour:change": { payload: ["checked", "color", "direction", "end", "files", "high", "index", "low", "month", "name", "paused", "query", "speed", "start", "unit", "value", "values", "year"], composed: true },
119
113
  "contour:collapse": { payload: ["collapsed"], composed: true },
120
114
  "contour:cluster-toggle": { payload: ["count", "expanded"], composed: true },
121
115
  "contour:clear": { payload: [], composed: true },
122
116
  "contour:clear-all": { payload: [], composed: true },
123
- "contour:close": { payload: ["index", "label"], composed: true },
117
+ "contour:close": { payload: ["count", "index", "label", "message", "open", "value"], composed: true },
124
118
  "contour:copy": { payload: ["text"], composed: true },
119
+ "contour:apply": { payload: ["name"], composed: true },
125
120
  "contour:dash-action": { payload: ["label"], composed: true },
126
121
  "contour:diff-activate": { payload: ["kind", "text"], composed: true },
122
+ "contour:dismiss": { payload: ["label"], composed: true },
127
123
  "contour:draw-start": { payload: ["mode"], composed: true },
128
124
  "contour:drag": { payload: ["delta", "key", "value"], composed: true },
129
125
  "contour:do-dont-activate": { payload: ["kind", "text"], composed: true },
@@ -133,49 +129,62 @@
133
129
  "contour:drop": { payload: ["value", "label"], composed: true },
134
130
  "contour:empty-action": { payload: ["state"], composed: true },
135
131
  "contour:filter": { payload: ["query"], composed: true },
132
+ "contour:filter-change": { payload: ["source", "filter"], composed: true },
136
133
  "contour:error": { payload: ["src", "message", "name", "status"], composed: true },
137
134
  "contour:export": { payload: ["format"], composed: true },
138
135
  "contour:refresh": { payload: [], composed: true },
139
- "contour:hide": { payload: [], composed: true },
136
+ "contour:hide": { payload: [], composed: true, deprecated: "use contour:close instead" },
140
137
  "contour:hover": { payload: ["row"], composed: true },
141
138
  "contour:input": { payload: ["name", "value", "checked"], composed: true },
142
- "contour:layer-opacity": { payload: ["name", "opacity"], composed: true },
143
- "contour:layer-rename": { payload: ["name", "newName"], composed: true },
144
- "contour:layer-duplicate": { payload: ["name"], composed: true },
145
- "contour:layer-zoom": { payload: ["name"], composed: true },
146
- "contour:layer-projection": { payload: ["name", "projection"], composed: true },
147
- "contour:layer-remove": { payload: ["name"], composed: true },
139
+ "contour:invalid": { payload: ["field", "input", "message"], composed: true, cancelable: true },
140
+ "contour:inspect-action": { payload: ["label", "value"], composed: true },
141
+ "contour:layer-opacity": { payload: ["layerId", "name", "opacity"], composed: true },
142
+ "contour:layer-rename": { payload: ["layerId", "name", "newName"], composed: true },
143
+ "contour:layer-duplicate": { payload: ["layerId", "name"], composed: true },
144
+ "contour:layer-zoom": { payload: ["layerId", "name"], composed: true },
145
+ "contour:zoom": { payload: ["data", "index", "row"], composed: true },
146
+ "contour:layer-projection": { payload: ["layerId", "name", "projection"], composed: true },
147
+ "contour:layer-remove": { payload: ["layerId", "name"], composed: true },
148
148
  "contour:layer-reorder": { payload: ["layerIds"], composed: true },
149
- "contour:layer-toggle": { payload: ["name", "visible"], composed: true },
150
- "contour:layer-visibility": { payload: ["name", "visible"], composed: true },
151
- "contour:legend-toggle": { payload: ["key", "label", "pressed"], composed: true },
149
+ "contour:layer-toggle": { payload: ["layerId", "name", "visible"], composed: true },
150
+ "contour:layer-visibility": { payload: ["layerId", "name", "visible"], composed: true },
151
+ "contour:legend-toggle": { payload: ["index", "key", "label", "pressed"], composed: true },
152
152
  "contour:leave": { payload: [], composed: true },
153
153
  "contour:load": { payload: ["src", "count"], composed: true },
154
154
  "contour:map-control": { payload: ["control"], composed: true },
155
+ "contour:map-style": { payload: ["style", "name"], composed: true },
155
156
  "contour:map-attach": { payload: [], composed: true },
157
+ "contour:map-ready": { payload: [], composed: true },
156
158
  "contour:map-detach": { payload: [], composed: true },
159
+ "contour:map-popup-reposition": { payload: ["anchor", "flippedX", "flippedY", "left", "top"], composed: true },
160
+ "contour:map-viewport": { payload: ["crossesAntimeridian", "west", "south", "east", "north", "zoom", "center"], composed: true },
157
161
  "contour:mode-change": { payload: ["mode"], composed: true },
158
- "contour:move": { payload: ["direction", "from", "to"], composed: true },
162
+ "contour:scope-change": { payload: ["scope"], composed: true },
163
+ "contour:move": { payload: ["direction", "from", "to", "dx", "dy"], composed: true },
159
164
  "contour:open": { payload: [], composed: true },
160
165
  "contour:page": { payload: ["page"], composed: true },
161
166
  "contour:ready": { payload: ["version", "count"], composed: true },
162
- "contour:remove": { payload: ["key", "label", "value"], composed: true },
167
+ "contour:read": { payload: ["label"], composed: true },
168
+ "contour:remove": { payload: ["key", "label", "name", "value"], composed: true },
163
169
  "contour:reorder": { payload: ["from", "to"], composed: true },
164
170
  "contour:range-change": { payload: ["value"], composed: true },
165
- "contour:resize": { payload: ["height", "width"], composed: true },
171
+ "contour:resize": { payload: ["column", "delta", "height", "value", "width"], composed: true },
166
172
  "contour:retry": { payload: ["src"], composed: true },
167
173
  "contour:loop-change": { payload: ["loop"], composed: true },
168
174
  "contour:pause": { payload: [], composed: true },
169
175
  "contour:play": { payload: [], composed: true },
170
176
  "contour:seek": { payload: ["progress", "value"], composed: true },
171
- "contour:select": { payload: ["area", "col", "index", "key", "label", "labels", "path", "row", "rows", "series", "value"], composed: true },
177
+ "contour:select": { payload: ["area", "col", "expanded", "href", "index", "key", "label", "labels", "level", "path", "range", "result", "row", "rows", "series", "value"], composed: true },
172
178
  "contour:search": { payload: ["query"], composed: true },
179
+ "contour:spatial-filter": { payload: ["action", "mode", "operator"], composed: true },
180
+ "contour:split-change": { payload: ["value", "width", "height"], composed: true },
173
181
  "contour:speed-change": { payload: ["speed"], composed: true },
174
182
  "contour:showcase-activate": { payload: ["title"], composed: true },
175
183
  "contour:step-activate": { payload: ["index", "title"], composed: true },
176
184
  "contour:step-change": { payload: ["direction", "index", "title"], composed: true },
177
- "contour:show": { payload: [], composed: true },
185
+ "contour:show": { payload: [], composed: true, deprecated: "use contour:open instead" },
178
186
  "contour:sort": { payload: ["column", "direction"], composed: true },
187
+ "contour:column-toggle": { payload: ["column", "visible"], composed: true },
179
188
  "contour:submit": { payload: ["submitting"], composed: true },
180
189
  "contour:stream-state": { payload: ["running"], composed: true },
181
190
  "contour:tab-change": { payload: ["index", "label"], composed: true },
@@ -183,65 +192,192 @@
183
192
  "contour:tick": { payload: ["frame"], composed: true },
184
193
  "contour:time-change": { payload: ["progress", "value"], composed: true },
185
194
  "contour:time-range-change": { payload: ["value"], composed: true },
186
- "contour:toggle": { payload: ["expanded", "label", "open", "path", "playing"], composed: true },
195
+ "contour:toggle": { payload: ["collapsed", "expanded", "label", "open", "path", "playing"], composed: true },
187
196
  "contour:view-enter": { payload: [], composed: true },
188
197
  "contour:view-leave": { payload: [], composed: true },
189
198
  });
190
199
 
191
- // Shared HTML sanitizer (B3-18): allowlist via DOMParser instead of a
192
- // blacklist regex, so single-quoted, unquoted and javascript: payloads
193
- // cannot slip through.
200
+ // DOMParser allowlist (blocklist regexes let `javascript:` variants through); `style` dropped (UI-redress), colour via safeColor.
201
+ const SANITIZE_DROP = new Set(["script", "iframe", "object", "embed", "style", "link", "meta", "base", "form", "input", "button"]);
202
+ const SANITIZE_ANIMATE = new Set(["animate", "animatemotion", "animatetransform", "set", "discard"]);
203
+ const SANITIZE_URL_ATTRS = new Set(["href", "src", "xlink:href", "from", "to", "values", "by", "attributename"]);
204
+ /**
205
+ * Normalise a candidate URL the way the URL parser does before testing its
206
+ * scheme: strip ASCII tab/newline/CR anywhere, strip leading and trailing C0
207
+ * controls and spaces, then percent-decode. `javascript:…` and
208
+ * `java\tscript:…` both collapse to `javascript:` here.
209
+ *
210
+ * @param {string} value raw attribute value
211
+ * @returns {string} the normalised candidate, lowercased
212
+ */
213
+ function normalizeUrlCandidate(value) {
214
+ let v = String(value == null ? "" : value);
215
+ v = v.replace(/[\t\n\r]/g, "");
216
+ // Leading C0 controls and spaces are what `trim()` misses and the URL
217
+ // parser drops; trailing ones are harmless but stripped for symmetry.
218
+ v = v.replace(/^[\u0000-\u0020]+/, "").replace(/[\u0000-\u0020]+$/, "");
219
+ try { v = decodeURIComponent(v); } catch (e) { /* malformed escape: test as-is */ }
220
+ return v.toLowerCase();
221
+ }
222
+ /**
223
+ * Whether a URL attribute value names a scheme the sanitizer refuses.
224
+ *
225
+ * @param {string} value raw attribute value
226
+ * @returns {boolean} true when the value must be removed
227
+ */
228
+ function isUnsafeUrl(value) {
229
+ const v = normalizeUrlCandidate(value);
230
+ // Strip any remaining embedded controls so `java\tscript:` cannot re-form
231
+ // after decoding, then test the scheme prefix.
232
+ const flat = v.replace(/[\u0000-\u001f\u007f]/g, "");
233
+ return flat.startsWith("javascript:") || flat.startsWith("vbscript:") || flat.startsWith("data:text/html") || flat.startsWith("data:image/svg+xml");
234
+ }
194
235
  /** Sanitize consumer-provided HTML using a DOM allowlist. */
195
236
  export function sanitizeHtml(input) {
196
237
  const str = String(input == null ? "" : input);
197
- // Fail closed when no parser is available (SSR, constrained runtimes):
198
- // never treat "no parser" as "trusted markup". Return the input as inert
199
- // text so no tag is interpreted by an innerHTML assignment.
238
+ // Fail closed when no parser is available (SSR): return input as inert text, never treat "no parser" as trusted markup.
200
239
  if (typeof DOMParser === "undefined") {
201
240
  return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
202
241
  }
203
242
  const doc = new DOMParser().parseFromString(str, "text/html");
204
- const drop = new Set(["script", "iframe", "object", "embed", "style", "link", "meta", "base", "form", "input", "button"]);
205
243
  const walk = (node) => {
244
+ // Snapshot: the loop mutates the child list (removals, template walks).
206
245
  const children = Array.from(node.childNodes);
207
246
  for (const c of children) {
208
- if (c.nodeType === 1) {
209
- const tag = c.tagName.toLowerCase();
210
- if (drop.has(tag)) { c.remove(); continue; }
211
- // Strip every on-* attribute and javascript: URLs.
212
- for (const attr of Array.from(c.attributes)) {
213
- const name = attr.name.toLowerCase();
214
- if (name.startsWith("on")) { c.removeAttribute(attr.name); continue; }
215
- const val = String(attr.value || "").trim().toLowerCase();
216
- if ((name === "href" || name === "src" || name === "xlink:href") && (val.startsWith("javascript:") || val.startsWith("data:text/html"))) {
217
- c.removeAttribute(attr.name);
218
- }
219
- }
220
- walk(c);
247
+ if (c.nodeType !== 1) continue;
248
+ const tag = c.tagName.toLowerCase();
249
+ if (SANITIZE_DROP.has(tag)) { c.remove(); continue; }
250
+ // SMIL animation can rewrite a URL-bearing attribute after the walk,
251
+ // so the element goes before its target attribute is ever read.
252
+ if (SANITIZE_ANIMATE.has(tag)) {
253
+ const attrNames = Array.from(c.attributes).map((a) => a.name.toLowerCase());
254
+ const target = String(c.getAttribute("attributename") || "").toLowerCase();
255
+ const carriesUrl = attrNames.some((n) => SANITIZE_URL_ATTRS.has(n));
256
+ if (carriesUrl || SANITIZE_URL_ATTRS.has(target)) { c.remove(); continue; }
257
+ }
258
+ for (const attr of Array.from(c.attributes)) {
259
+ const name = attr.name.toLowerCase();
260
+ if (name.startsWith("on")) { c.removeAttribute(attr.name); continue; }
261
+ if (name === "style") { c.removeAttribute(attr.name); continue; }
262
+ if (name === "srcdoc") { c.removeAttribute(attr.name); continue; }
263
+ if (SANITIZE_URL_ATTRS.has(name) && isUnsafeUrl(attr.value)) { c.removeAttribute(attr.name); }
221
264
  }
265
+ // `<template>` keeps its markup in a separate document fragment, so
266
+ // the walk has to descend into `.content` explicitly.
267
+ if (tag === "template") { walk(c.content || c); continue; }
268
+ walk(c);
222
269
  }
223
270
  };
224
271
  walk(doc.body);
225
272
  return doc.body.innerHTML;
226
273
  }
227
- // contract: an attribute that is not here cannot ask an element to re-render,
228
- // and an attribute a component WRITES to itself must never be here, because
229
- // that write would fire the callback that performs the render.
230
- //
231
- // Excluded because the render bodies below set them on the host:
232
- // role, open, aria-label, aria-valuenow, aria-valuemin, aria-valuemax, tabindex
233
- // Adding one of those back to this list makes that component recurse.
274
+ /**
275
+ * Validate a CSS colour for use in an inline style.
276
+ *
277
+ * Returns the trimmed value when it is a plain colour (named, hex, or a
278
+ * known colour function) and an empty string otherwise. Anything that could
279
+ * break out of the declaration, load a resource, or run script is rejected,
280
+ * so a consumer-supplied `color` attribute cannot become an injection sink.
281
+ *
282
+ * @param {unknown} value candidate colour
283
+ * @returns {string} the safe colour, or "" when rejected
284
+ */
285
+ export function safeColor(value) {
286
+ const raw = String(value == null ? "" : value).trim();
287
+ if (!raw) return "";
288
+ if (/[;{}<>"'`\\]/.test(raw)) return "";
289
+ if (/url\s*\(/i.test(raw) || /expression\s*\(/i.test(raw)) return "";
290
+ if (/^#[0-9a-f]{3,8}$/i.test(raw)) return raw;
291
+ if (/^(rgb|rgba|hsl|hsla|hwb|lab|lch|oklab|oklch|color)\(/i.test(raw)) return raw;
292
+ // Token-driven colours are the system's own vocabulary: `var(--color-…)`, `light-dark(…)` and `color-mix(…)` are all le...
293
+ if (/^(var|light-dark|color-mix)\(/i.test(raw)) {
294
+ let depth = 0;
295
+ for (let i = 0; i < raw.length; i++) {
296
+ const ch = raw[i];
297
+ if (ch === "(") depth++;
298
+ else if (ch === ")") { depth--; if (depth < 0) return ""; }
299
+ }
300
+ return depth === 0 ? raw : "";
301
+ }
302
+ if (/^[a-z]+$/i.test(raw)) return raw;
303
+ return "";
304
+ }
305
+ /**
306
+ * Resolve an href candidate to a value that is safe to assign to a sink.
307
+ *
308
+ * Fragments, relative paths and the schemes we can vouch for pass through
309
+ * unchanged; `javascript:`, `data:` and any other scheme collapse to "#".
310
+ * This closes the attribute-to-property path that `sanitizeHtml` does not
311
+ * cover, because assigning `a.href = "javascript:…"` executes on click.
312
+ *
313
+ * @param {unknown} value candidate href
314
+ * @returns {string} the safe href, or "#"
315
+ */
316
+ export function safeHref(value) {
317
+ const raw = String(value == null ? "" : value).trim();
318
+ if (!raw) return "#";
319
+ if (raw.startsWith("#") || raw.startsWith("/") || raw.startsWith("./") || raw.startsWith("../") || raw.startsWith("?")) return raw;
320
+ if (typeof document === "undefined" || !document.baseURI) return "#";
321
+ try {
322
+ const url = new URL(raw, document.baseURI);
323
+ return ["http:", "https:", "mailto:", "tel:"].includes(url.protocol) ? raw : "#";
324
+ } catch (e) {
325
+ return "#";
326
+ }
327
+ }
328
+ /**
329
+ * Read a length token from the document root, in pixels.
330
+ *
331
+ * Virtualized components used to hard-code 36/32/28 px row heights, which
332
+ * disagreed with the rendered row and ignored density. The height is now a
333
+ * token (`--data-grid-row-height`, …) and this reads its computed value.
334
+ *
335
+ * @param {string} name custom-property name
336
+ * @param {number} fallback pixels to use when the token is absent or invalid
337
+ * @returns {number} the resolved length in pixels
338
+ */
339
+ export function cssLength(name, fallback) {
340
+ if (typeof getComputedStyle === "undefined" || typeof document === "undefined") return fallback;
341
+ const v = parseFloat(getComputedStyle(document.documentElement).getPropertyValue(name));
342
+ return Number.isFinite(v) && v > 0 ? v : fallback;
343
+ }
344
+ /**
345
+ * Surface a malformed JSON attribute instead of swallowing it.
346
+ *
347
+ * A bare `catch (e) { /* keep existing *\/ }` turns a typo in a component
348
+ * attribute into a silent no-op: the render keeps whatever was there before
349
+ * and the defect is invisible. This warns once, with the component name and
350
+ * the parser message, so the author can find it.
351
+ *
352
+ * @param {Element|null} host the component that owns the attribute
353
+ * @param {string} label the attribute (or a short description)
354
+ * @param {unknown} error the thrown parse error
355
+ */
356
+ export function warnBadJson(host, label, error) {
357
+ if (typeof console === "undefined" || !console.warn) return;
358
+ const name = host && host.tagName ? host.tagName.toLowerCase() : "component";
359
+ const msg = (error && error.message) || String(error);
360
+ console.warn(`[contour] ${name}: malformed ${label || "attribute"} — ${msg}`);
361
+ }
362
+ // contract: an attribute that is not here cannot ask an element to re-render, and an attribute a component WRITES to it...
234
363
  /** Shared attribute vocabulary used by components that opt into defaults. */
235
364
  export const OBSERVED = [
236
- "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", "breakpoint", "breaks", "brush", "brush-end", "brush-max", "brush-min", "brush-start", "cache-key", "canvas", "center", "clearable", "cols", "columns", "color", "command",
237
- "cells", "checked", "chrome", "debounce", "closable", "collapsed", "collapsible", "classification", "colors", "continuous", "content", "controls", "copyable", "count", "data", "data-table", "date", "delta", "description", "glyphs", "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",
238
- "empty", "exclusive", "fallback", "filename", "format", "heading", "help", "hint", "href", "icon", "illustration", "instrument", "interval", "items", "key", "layers", "level", "range-end", "range-start",
239
- "label", "lazy", "lede", "legend", "line", "limit", "link", "links", "live", "loading", "locale", "loop", "max", "media", "message", "method", "menu", "min", "multiple", "name", "needle", "next", "no", "no-cache", "no-data-message", "nodes", "note", "norm", "normalize",
240
- "options", "orientation", "page-size", "pages", "pause", "paused", "pausable", "persist", "placeholder", "playing", "point", "points", "prev", "presets", "progress", "prompt", "question", "recent", "required",
241
- "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", "speed", "status", "step", "submit", "submitting", "timeout", "trigger", "virtual", "sticky", "cluster-count", "cluster-expanded", "time", "resizable",
242
- "state", "steps", "style", "subtitle", "summary", "src", "table", "tabs", "tag", "text", "ticks", "title", "type", "unit", "cluster-items", "row-height",
243
- "variant", "values", "viewport", "yes", "zoomable", "x", "y",
244
- "caption", "current-time", "is-playing", "loop-label", "no-data-color", "property", "show-loop", "show-thumb", "show-thumb-caption", "speeds", "item-height", "pause-label", "play-label", "speed-label", "time-label", "shimmer",
365
+ "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",
366
+ "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",
367
+ "empty", "exclusive", "fallback", "filename", "format", "heading", "help", "hint", "href", "icon", "illustration", "instrument", "interval", "items", "key", "layers", "level", "markers",
368
+ "label", "labels", "latitude", "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",
369
+ "options", "orientation", "page-size", "pages", "pause", "paused", "pausable", "persist", "placeholder", "playing", "point", "points", "prev", "presets", "prompt", "question", "recent", "required",
370
+ "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",
371
+ "state", "steps", "style", "subtitle", "summary", "src", "source", "table", "tabs", "tag", "text", "ticks", "title", "type", "unread-only", "unit", "updated", "row-height",
372
+ "variant", "values", "viewport", "warning", "yes", "zoom", "zoomable",
373
+ "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",
374
+ "search",
375
+ "numbered",
376
+ "bucket-count", "limit-values",
377
+ "autocomplete", "levels", "submit-label",
378
+ "fields", "gap",
379
+ "flush", "head", "preview", "tags", "url",
380
+ "custom-error",
245
381
  ];
246
382
 
247
383
  /** Resolve an authored heading level while keeping the fallback valid. */
@@ -250,6 +386,178 @@
250
386
  return /^h[1-6]$/.test(v || "") ? v : fallback;
251
387
  }
252
388
 
389
+ /**
390
+ * Read a boolean attribute the way an author means it.
391
+ *
392
+ * `hasAttribute()` answers "is it there", not "is it on": a consumer who
393
+ * writes `closable="false"` or `sparkline="0"` from a template still has the
394
+ * attribute, so a presence test renders the close button / the sparkline they
395
+ * explicitly switched off (F-RO19, F-RO20, F-FC11). The HTML boolean
396
+ * convention is presence-only, but these attributes are commonly rendered by
397
+ * frameworks that stringify `false`, so the explicit negative values win.
398
+ *
399
+ * A bare attribute (`closable`) is present with an empty value and is ON —
400
+ * that is the HTML boolean convention, and treating `""` as off broke every
401
+ * plain `closable` in the guide.
402
+ */
403
+ export function flagOn(host, name) {
404
+ if (!host || !host.getAttribute) return false;
405
+ const raw = host.getAttribute(name);
406
+ if (raw === null) return false;
407
+ const v = raw.trim().toLowerCase();
408
+ return v !== "0" && v !== "false" && v !== "no" && v !== "off" && v !== "null" && v !== "undefined";
409
+ }
410
+
411
+ /**
412
+ * R24-91: Resolve a boolean value the way an author means it, for the
413
+ * property-setter path. `el.disabled = "false"` must turn the feature OFF
414
+ * (string negatives route through the same vocabulary as flagOn), while
415
+ * `el.disabled = true` turns it ON. The attribute path keeps HTML presence
416
+ * semantics (`disabled="false"` stays ON) — that's a deliberate judgment call
417
+ * (R24-83), not a bug.
418
+ */
419
+ export function flagOnValue(v) {
420
+ if (v === null || v === undefined || v === false) return false;
421
+ if (typeof v === "string") {
422
+ const s = v.trim().toLowerCase();
423
+ return s !== "0" && s !== "false" && s !== "no" && s !== "off" && s !== "null" && s !== "undefined";
424
+ }
425
+ return Boolean(v);
426
+ }
427
+
428
+ /** R31-148: the default shape for a status variant, so a state never rides
429
+ * on hue alone. `icon="none"` is the explicit opt-out at each call site. */
430
+ export function statusIcon(variant) {
431
+ switch (String(variant || "").toLowerCase()) {
432
+ case "success": return "i-check-circle";
433
+ case "warning": return "i-alert";
434
+ case "danger":
435
+ case "error": return "i-x";
436
+ case "info":
437
+ case "note":
438
+ case "tip":
439
+ case "accent": return "i-info";
440
+ default: return "";
441
+ }
442
+ }
443
+
444
+ /**
445
+ * R24-93: Emit an overlay visibility event. `contour:open`/`contour:close`
446
+ * are the canonical pair; `contour:show`/`contour:hide` are deprecated
447
+ * aliases emitted alongside for one minor release with a console warning
448
+ * (per the repo's deprecation policy). `contour:toggle` is kept for
449
+ * non-visibility transitions (tree expansion, accordion, sidebar collapse)
450
+ * and is not aliased here.
451
+ *
452
+ * Consumers listening to `show`/`hide` will still receive their event during
453
+ * the deprecation window, but each emission logs a warning directing them to
454
+ * migrate to `open`/`close`. The aliases are removed in v2.0.
455
+ */
456
+ export function wcEmitOverlay(host, type, detail) {
457
+ if (!host || !host.dispatchEvent) return;
458
+ const isOpen = type === "contour:open";
459
+ const isClose = type === "contour:close";
460
+ if (!isOpen && !isClose) {
461
+ host.dispatchEvent(new CustomEvent(type, { detail, bubbles: true, composed: true }));
462
+ return;
463
+ }
464
+ // Canonical event first.
465
+ host.dispatchEvent(new CustomEvent(type, { detail, bubbles: true, composed: true }));
466
+ // Deprecated alias with a one-minor deprecation warning.
467
+ const alias = isOpen ? "contour:show" : "contour:hide";
468
+ console.warn(
469
+ `[Contour] ${alias} is deprecated, use ${type} instead. ` +
470
+ `Will be removed in v2.0. (host: ${host.tagName || host.constructor.name})`
471
+ );
472
+ host.dispatchEvent(new CustomEvent(alias, { detail, bubbles: true, composed: true }));
473
+ }
474
+
475
+ /**
476
+ * Resolve a localised label for a host (R18-63). A consumer supplies a
477
+ * `labels` JSON attribute (e.g. `labels='{"clear":"Effacer"}'`); it is merged
478
+ * over the English `fallback`, so a partial object localises only the keys it
479
+ * names. A malformed attribute is ignored rather than thrown — a bad label
480
+ * must not take the widget down. Returns `fallback` when no override exists.
481
+ */
482
+ export function labelText(host, key, fallback) {
483
+ const def = fallback !== undefined ? fallback : key;
484
+ const raw = host && host.getAttribute ? host.getAttribute("labels") : null;
485
+ if (!raw) return def;
486
+ try {
487
+ const parsed = JSON.parse(raw);
488
+ if (parsed && typeof parsed === "object" && typeof parsed[key] === "string" && parsed[key]) return parsed[key];
489
+ } catch (e) { /* a malformed labels attribute is ignored, not fatal */ }
490
+ return def;
491
+ }
492
+
493
+ /**
494
+ * R31-147: the one way to write a sprite icon. Every icon-only control used
495
+ * to inline the same `<svg><use href="#i-…">` string; a helper keeps the
496
+ * shape (and the aria-hidden) in one place, so a new glyph cannot forget it.
497
+ *
498
+ * @param {string} id symbol id, e.g. "i-check"
499
+ * @returns {string} svg markup
500
+ */
501
+ export function iconMarkup(id) {
502
+ return '<svg aria-hidden="true" viewBox="0 0 24 24"><use href="#' + id + '" /></svg>';
503
+ }
504
+
505
+ /**
506
+ * R31-160: write markup through a Trusted Types policy, when the page has one.
507
+ *
508
+ * The system has ~86 `innerHTML` sinks. Under
509
+ * `Content-Security-Policy: require-trusted-types-for 'script'` a raw
510
+ * `el.innerHTML = "..."` throws even for a constant string, because the sink
511
+ * demands a TrustedHTML. This helper is the one place that crosses that
512
+ * boundary: it routes the string through a named policy (`contour-html`) whose
513
+ * `createHTML` is the identity for the strings this system already controls
514
+ * (constants, `sanitizeHtml()` output, `iconMarkup()`), so a page that sets
515
+ * the policy is satisfied and a page that does not is unaffected.
516
+ *
517
+ * The policy is created lazily and only when `window.trustedTypes` exists, so
518
+ * a browser without Trusted Types (or a page without the CSP) takes the plain
519
+ * path. It never installs a global default policy — a consumer that wants to
520
+ * audit every sink names its own policy and this helper uses it if present.
521
+ */
522
+ let _contourHtmlPolicy = null;
523
+ export function setHTML(el, html) {
524
+ if (!el) return;
525
+ const empty = html == null || html === "";
526
+ if (!empty && typeof window !== "undefined" && window.trustedTypes && typeof window.trustedTypes.createPolicy === "function") {
527
+ if (!_contourHtmlPolicy) {
528
+ try { _contourHtmlPolicy = window.trustedTypes.createPolicy("contour-html", { createHTML: (s) => s }); }
529
+ catch (e) { _contourHtmlPolicy = null; /* a consumer already named it */ }
530
+ }
531
+ el.innerHTML = _contourHtmlPolicy ? _contourHtmlPolicy.createHTML(html) : html;
532
+ return;
533
+ }
534
+ el.innerHTML = empty ? "" : html;
535
+ }
536
+
537
+ /**
538
+ * Write localised copy onto a node without stealing an author's words (R18-63).
539
+ *
540
+ * `labelText()` resolves the string; this decides whether the node may take it.
541
+ * A node the component generated on an earlier render carries
542
+ * `data-contour-label`, so a `labels` change reaches it. A node the AUTHOR
543
+ * wrote — a `.c-saved-view__apply` button with its own text, a
544
+ * `.c-spatial-filter__clear-all` — has no such mark and keeps its words,
545
+ * because a default must never overwrite copy a consumer chose.
546
+ *
547
+ * This exists because the rule is not obvious and the failure is silent: an
548
+ * unconditional `node.textContent = labelText(...)` looks like the fix and is a
549
+ * regression for every consumer who supplied their own button.
550
+ */
551
+ export function applyLabel(node, host, key, fallback) {
552
+ if (!node) return;
553
+ if (node.dataset && node.dataset.contourLabel === "true") {
554
+ node.textContent = labelText(host, key, fallback);
555
+ } else if (!node.textContent) {
556
+ node.textContent = labelText(host, key, fallback);
557
+ if (node.dataset) node.dataset.contourLabel = "true";
558
+ }
559
+ }
560
+
253
561
  /**
254
562
  * Base class for all Contour web components.
255
563
  *
@@ -259,26 +567,10 @@
259
567
  *
260
568
  * All components use light DOM so that `ds.css` styles apply directly.
261
569
  */
262
- // Base class: the lifecycle belongs here, the markup belongs to the subclass.
263
- //
264
- // A render body is written to run more than once, and it is idempotent because
265
- // of this snapshot rather than because of its own guards. The first
266
- // connectedCallback records the nodes and the class attribute the AUTHOR
267
- // wrote; every later render drops everything, re-appends exactly those nodes,
268
- // and runs again. So a body may keep the natural
269
- // `if (!this.querySelector(".c-card__title"))` shape: after the reset the
270
- // generated node is gone, the guard passes, and the changed attribute reaches
271
- // the page. Without the reset the guard is permanent and reactivity is a lie.
272
- //
273
- // The snapshot holds node references, not a re-parsed string, so listeners a
274
- // consumer put on authored children survive a re-render. The cost is honest:
275
- // nodes a component generated are rebuilt, so state inside them (a typed
276
- // value, a focus ring) is lost when a host attribute changes.
277
- // SSR-safe base (R12-25): in a non-DOM runtime (Node, type-only tooling)
278
- // HTMLElement is undefined. Fall back to Object so the module can be imported
279
- // for metadata/type inspection without a DOM shim; components cannot be
280
- // instantiated there, which is the correct boundary.
570
+ // Base class: the lifecycle belongs here, the markup belongs to the subclass. A render body is written to run more than...
281
571
  const _ContourBaseParent = (typeof HTMLElement !== "undefined") ? HTMLElement : Object;
572
+ // R31-39: constructors whose property accessors are already installed.
573
+ const INSTALLED_PROPS = new WeakSet();
282
574
  export class ContourBase extends _ContourBaseParent {
283
575
  static formAssociated = false;
284
576
  constructor() {
@@ -287,37 +579,36 @@
287
579
  this._internals = this.attachInternals();
288
580
  }
289
581
  }
290
- // Per-component observed attributes. Subclasses override `static get observed()`
291
- // with only the attributes they read; the default is the full shared list so
292
- // a component that does not opt in keeps working.
582
+ // Per-component observed attributes. Subclasses override `static get observed()` with only the attributes they read; th...
293
583
  static get observed() {
294
584
  return OBSERVED;
295
585
  }
296
- static get observedAttributes() {
297
- return this.observed;
298
- }
586
+ /**
587
+ * The attribute list the platform is told about.
588
+ *
589
+ * `labels` is appended here rather than left to each subclass's `observed`,
590
+ * because the reader is a SHARED helper: `labelText()` below resolves copy for
591
+ * whichever component asks, so a per-class list has to remember it once per
592
+ * class or a `labels` change silently does nothing on every host that forgot.
593
+ * That is exactly how it stood — one component listed it and eleven did not.
594
+ * A component that writes `labels` to itself would recurse, and none does.
595
+ */
596
+ static get observedAttributes() {
597
+ const list = this.observed;
598
+ return list.includes("labels") ? list : [...list, "labels"];
599
+ }
299
600
 
300
- // Subclasses override to declare reflected properties:
301
- // static get properties() { return { value: { attribute: "value", type: String } }; }
302
- // A property with no entry is not reflected. Types: String (default), Number, Boolean.
601
+ // Subclasses override to declare reflected properties: static get properties() { return { value: { attribute: "value", ...
303
602
  static get properties() {
304
603
  return {};
305
604
  }
306
605
 
307
- // Update policy (R12-06): "scaffold" components may rebuild their generated
308
- // DOM on attribute change (the default lifecycle). High-volume components
309
- // (table, grid, tree, virtual-list, chart) should override to "keyed" and
310
- // use ensure()/keyed patching, or expose an imperative update method.
311
- // Documented here so consumers know which components guarantee identity
312
- // stability across renders.
606
+ // Update policy : "scaffold" components may rebuild their generated DOM on attribute change (the default lifecycle). Hi...
313
607
  static get updateMode() {
314
608
  return "scaffold";
315
609
  }
316
610
 
317
- // Brownout helpers (G-16): components read their degraded level from the
318
- // `brownout` / `brownout-level` attribute and shed non-essential chrome
319
- // above a threshold. Centralised here so a new component does not
320
- // re-implement the attribute lookup.
611
+ // Brownout helpers : components read their degraded level from the `brownout` / `brownout-level` attribute and shed non...
321
612
  brownoutLevel() {
322
613
  const raw = this.getAttribute("brownout-level") || this.getAttribute("brownout") || "0";
323
614
  const n = parseInt(raw, 10);
@@ -326,41 +617,126 @@
326
617
  shed(kind, threshold) {
327
618
  return this.brownoutLevel() >= (threshold || 1);
328
619
  }
329
- // Read-only and diagnostic: it exists so a page can show that `batch()` did
330
- // what it claims instead of asking the reader to believe it, and so a test can
331
- // assert a re-render happened without watching for a specific node. A consumer
332
- // that never calls `batch()` never needs it, and nothing here reads it.
620
+ // Read-only and diagnostic: it exists so a page can show that `batch()` did what it claims instead of asking the reader...
333
621
  get renderCount() {
334
622
  return this._contourRenderCount || 0;
335
623
  }
336
624
 
625
+ /**
626
+ * Resolves one microtask after the last render has settled (render →
627
+ * enhance → restore for a re-render, render → enhance for a first paint).
628
+ * Read it when a caller needs the measured result of an attribute change —
629
+ * a box that has been laid out, a control that exists — instead of waiting
630
+ * on a timer. Also announced as `contour:rendered`; a caller may listen for
631
+ * the event when it holds the element before it is connected.
632
+ */
633
+ get updateComplete() {
634
+ return this._renderTicket || Promise.resolve(this);
635
+ }
636
+
637
+ // R31-93: a re-render is synchronous, but its *effects* are not observable
638
+ // from outside, so consumers reached for `setTimeout(50)`. One microtask
639
+ // after the render settles, the promise resolves and the event fires with
640
+ // the render count that produced it.
641
+ _announceRendered() {
642
+ // The count is read now: two renders in one task each announce, and the
643
+ // later one would otherwise relabel the earlier event with its own count.
644
+ const renderCount = this.renderCount;
645
+ this._renderTicket = new Promise((resolve) => {
646
+ queueMicrotask(() => {
647
+ this._renderTicket = null;
648
+ resolve(this);
649
+ if (!this.isConnected) return;
650
+ this.dispatchEvent(new CustomEvent("contour:rendered", {
651
+ bubbles: true,
652
+ composed: true,
653
+ detail: { renderCount },
654
+ }));
655
+ });
656
+ });
657
+ }
658
+
337
659
  _countRender() {
338
660
  this._contourRenderCount = (this._contourRenderCount || 0) + 1;
339
661
  }
340
662
 
341
663
  // Install accessors once per class, so `el.value = 42` writes the attribute
342
664
  // and triggers the normal re-render path instead of being a silent no-op.
343
- static _propsInstalled = false;
665
+ // R31-39: track installed constructors in a module-level WeakSet, not a
666
+ // static flag read through the prototype chain. A subclass that installs
667
+ // after its parent saw the inherited `true` and skipped its own property
668
+ // declarations, so a child-only property was missing on pages that
669
+ // instantiated the parent first.
344
670
  _installProperties() {
345
671
  const ctor = this.constructor;
346
- if (ctor._propsInstalled) return;
347
- ctor._propsInstalled = true;
672
+ if (INSTALLED_PROPS.has(ctor)) return;
673
+ INSTALLED_PROPS.add(ctor);
348
674
  const props = ctor.properties || {};
675
+ const declared = new Set();
676
+ // R24-90: JSON-typed property support. When a framework sets `el.items = [{label:"Alpha"}]`, the setter must write a JS...
677
+ const serialize = (v) => (typeof v === "object" && v !== null) ? JSON.stringify(v) : String(v);
678
+ const deserialize = (raw) => {
679
+ if (raw === null) return null;
680
+ const t = raw.trim();
681
+ if (t.startsWith("[") || t.startsWith("{")) {
682
+ try { return JSON.parse(t); } catch { /* not JSON, return raw */ }
683
+ }
684
+ return raw;
685
+ };
349
686
  for (const [name, spec] of Object.entries(props)) {
350
687
  const attr = (spec && spec.attribute) || name;
688
+ declared.add(attr);
351
689
  const type = (spec && spec.type) || String;
352
690
  Object.defineProperty(ctor.prototype, name, {
353
691
  get() {
354
692
  const raw = this.getAttribute(attr);
355
- if (type === Boolean) return raw !== null;
693
+ // R31-37: a boolean property must agree with what render() draws.
694
+ // The render path reads flags through flagOn()/flagOnValue(), which
695
+ // treat "false"/"0"/"off" as OFF; returning `raw !== null` here made
696
+ // `el.closable` true for `closable="false"` while the close button
697
+ // was absent. Presence with a false-y string is off.
698
+ if (type === Boolean) return flagOnValue(raw);
356
699
  if (raw === null) return spec && spec.default !== undefined ? spec.default : null;
357
700
  if (type === Number) { const n = Number(raw); return Number.isNaN(n) ? null : n; }
701
+ if (type === JSON_TYPE) return deserialize(raw);
358
702
  return raw;
359
703
  },
360
704
  set(v) {
361
705
  if (v === null || v === undefined || v === false) this.removeAttribute(attr);
362
- else if (type === Boolean) { if (v) this.setAttribute(attr, ""); else this.removeAttribute(attr); }
363
- else this.setAttribute(attr, String(v));
706
+ else if (type === Boolean) {
707
+ // R24-91: route string negatives ("false", "0", "no", "off", …) through the flagOn vocabulary so el.disabled = "false" ...
708
+ if (!flagOnValue(v)) this.removeAttribute(attr);
709
+ else this.setAttribute(attr, "");
710
+ }
711
+ else this.setAttribute(attr, serialize(v));
712
+ },
713
+ configurable: true,
714
+ });
715
+ }
716
+ // Default reflection : every observed attribute a component reads but does not declare in properties() still gets an ac...
717
+ const observed = ctor.observedAttributes;
718
+ for (const attr of observed) {
719
+ if (declared.has(attr)) continue;
720
+ const prop = attr.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
721
+ if (!/^[a-zA-Z_$][\w$]*$/.test(prop)) continue;
722
+ if (prop in ctor.prototype) continue; // an inherited accessor already exists
723
+ const isBool = attr === "disabled" || attr === "checked" || attr === "required" || attr === "readonly" || attr === "multiple" || attr === "selected" || attr === "open" || attr === "hidden";
724
+ Object.defineProperty(ctor.prototype, prop, {
725
+ get() {
726
+ const raw = this.getAttribute(attr);
727
+ // R31-37: same as the declared-property getter — a reflected boolean
728
+ // agrees with the rendered state, not with raw presence.
729
+ if (isBool) return flagOnValue(raw);
730
+ return deserialize(raw);
731
+ },
732
+ set(v) {
733
+ if (v === null || v === undefined || v === false) this.removeAttribute(attr);
734
+ else if (isBool) {
735
+ // R24-91: route string negatives through the flagOn vocabulary.
736
+ if (!flagOnValue(v)) this.removeAttribute(attr);
737
+ else this.setAttribute(attr, "");
738
+ }
739
+ else this.setAttribute(attr, serialize(v));
364
740
  },
365
741
  configurable: true,
366
742
  });
@@ -368,25 +744,56 @@
368
744
  }
369
745
 
370
746
  connectedCallback() {
371
- if (this._contourAuthored) { this._wireFormData(); return; } // reconnected, not re-specified
747
+ if (this._contourAuthored) {
748
+ // R24-01 / R28-09: reconnected, not re-specified. Reset _wired* flags and re-run enhance() so disposables (document/win...
749
+ this._wireFormData();
750
+ for (const key of Object.keys(this)) {
751
+ // CI-11: _wiredFormData and _wiredValueTracking are NOT reset here.
752
+ // Their listeners live on the host and survive a disconnect (they are
753
+ // added outside _runEnhance, so _contourHostListeners does not track
754
+ // them and disconnectedCallback does not remove them). Resetting the
755
+ // flag would re-add a duplicate pair on every reconnect. _wireFormData
756
+ // re-wires against a new form owner via its own disposer; value
757
+ // tracking is host-bound and needs no re-wire.
758
+ if (key.startsWith("_wired") && key !== "_wiredFormData" && key !== "_wiredValueTracking") {
759
+ this[key] = false;
760
+ }
761
+ }
762
+ // R24-01 residue (INF-5/6): re-render on reconnect, not just re-enhance. disconnectedCallback cleared _remoteStatus/_re...
763
+ this.attributeChangedCallback("__contour_reconnect__", null, "");
764
+ return;
765
+ }
372
766
  this._installProperties();
373
- this._contourAuthored = {
374
- nodes: Array.from(this.childNodes),
375
- cls: this.getAttribute("class"),
376
- };
767
+ this._contourAuthored = {
768
+ nodes: Array.from(this.childNodes),
769
+ };
770
+ // R31-02: the base owns only the classes IT generates, never the whole
771
+ // `class` attribute. A framework's state class, `hidden`, a Tailwind
772
+ // utility or any app-owned modifier added after mount must survive a
773
+ // re-render; the old code restored a frozen snapshot and deleted them.
774
+ this._contourOwnedClasses = new Set();
775
+ // R24-02: mark authored nodes so the refresh can find them inside generated wrappers. A component that moves authored c...
776
+ for (const n of this._contourAuthored.nodes) {
777
+ if (n.nodeType === 1) n.setAttribute("data-contour-authored", "");
778
+ }
377
779
  const before = Array.from(this.childNodes);
378
780
  this._contourRenderGen = (this._contourRenderGen || 0) + 1;
379
781
  this._ensureCache = new Map();
380
782
  this._ensureCacheGen = this._contourRenderGen;
381
783
  this._countRender();
784
+ const _preRenderClasses = new Set(Array.from(this.classList));
382
785
  try { this.render(); }
383
- catch (e) { console.error("Contour render error:", e); this.textContent = "Component failed to render."; }
786
+ catch (e) { console.error("Contour render error:", e); this.textContent = labelText(this, "render-error", "Component failed to render."); }
384
787
  this._contourGenerated = Array.from(this.childNodes).filter((n) => !before.includes(n));
385
- this._applyParts(this);
788
+ // R31-02: the classes render() just added are the ones this component
789
+ // owns; remember them so the next render removes only those.
790
+ this._contourOwnedClasses = new Set(Array.from(this.classList).filter((c) => !_preRenderClasses.has(c)));
386
791
  this._applyDensity();
387
- this.enhance();
792
+ this._runEnhance();
388
793
  this._detachInnerFormControls();
389
794
  this._wireFormData();
795
+ this._wireValueTracking();
796
+ this._announceRendered();
390
797
  }
391
798
 
392
799
  attributeChangedCallback(name, oldValue, newValue) {
@@ -394,17 +801,12 @@
394
801
  // Fires before connectedCallback during an upgrade: nothing to reset to
395
802
  // yet, and connectedCallback will render with the final attributes.
396
803
  if (!this.isConnected || !this._contourAuthored) return;
397
- // Opt-in batching: when inside batch(), attribute changes are coalesced
398
- // into a single render that fires when the batch ends. This lets a
399
- // dashboard update value + delta + direction without three rebuilds,
400
- // without changing the default synchronous contract the gate enforces.
804
+ // Opt-in batching: when inside batch(), attribute changes are coalesced into a single render that fires when the batch ...
401
805
  if (this._batchDepth > 0) {
402
806
  this._batchDirty = true;
403
807
  return;
404
808
  }
405
- // Re-entrant change (an attribute set while a render is in flight): do
406
- // not drop it, defer a single re-render to the next microtask so the
407
- // in-flight render can finish first. Coalesces several such changes.
809
+ // Re-entrant change (an attribute set while a render is in flight): do not drop it, defer a single re-render to the nex...
408
810
  if (this._contourRendering) {
409
811
  if (!this._pendingRerender) {
410
812
  this._pendingRerender = true;
@@ -421,112 +823,138 @@
421
823
  if (name === "checked") this._checkedAttrChanged = true;
422
824
  this._contourRendering = true;
423
825
  try {
424
- // Preserve form control values across a re-render: generated inputs are
425
- // dropped and rebuilt, so without this a host attribute change wipes
426
- // whatever the user typed.
826
+ // Preserve form control values across a re-render: generated inputs are dropped and rebuilt, so without this a host att...
427
827
  const savedControls = Array.from(this.querySelectorAll("input, textarea, select"));
428
- const savedValues = savedControls.map((el) => ({ key: el.name || el.id || null, value: el.value, checked: el.checked, type: el.type }));
429
- // Preserve focus, scroll position and <details> open state across the
430
- // rebuild, so a host attribute change does not yank focus to <body>
431
- // or collapse an open disclosure.
828
+ const savedValues = savedControls.map((el) => ({
829
+ key: el.name || el.id || null,
830
+ preserveKey: el.getAttribute("data-contour-preserve-key") || null,
831
+ value: el.value,
832
+ checked: el.checked,
833
+ type: el.type,
834
+ // User-dirty tracking (R20 T-02): a control the user edited keeps its value until the host's `value` attribute changes....
835
+ dirty: !!el._contourUserDirty,
836
+ attrAtDirty: el._contourAttrAtDirty,
837
+ selected: el.tagName === "SELECT" && el.multiple ? Array.from(el.selectedOptions).map((o) => o.value) : null,
838
+ }));
839
+ // Preserve focus, scroll position and <details> open state across the rebuild, so a host attribute change does not yank...
432
840
  const hadFocus = this.contains(document.activeElement) ? document.activeElement : null;
433
- // Capture a recovery key for unkeyed active elements: an id is the
434
- // strongest key, then a `name`, then the relative index among all
435
- // focusable controls inside the host. Without these, an attribute
436
- // update that rebuilds an unkeyed input drops focus to <body>.
841
+ // Capture a recovery key for unkeyed active elements: an id is the strongest key, then a `data-contour-preserve-key`, t...
437
842
  const _focusableSelector = "button, [href], input, select, textarea, [tabindex]:not([tabindex='-1'])";
438
843
  const _focusablesBefore = Array.from(this.querySelectorAll(_focusableSelector));
439
844
  const hadFocusIndex = hadFocus ? _focusablesBefore.indexOf(hadFocus) : -1;
845
+ const hadFocusKey = hadFocus ? (hadFocus.id || null) : null;
846
+ const hadFocusPreserveKey = hadFocus ? (hadFocus.getAttribute("data-contour-preserve-key") || null) : null;
440
847
  const hadFocusName = hadFocus ? (hadFocus.getAttribute("name") || null) : null;
441
- const savedScrolls = Array.from(this.querySelectorAll("*")).filter((el) => el.scrollHeight > el.clientHeight || el.scrollWidth > el.clientWidth).map((el) => ({ el, top: el.scrollTop, left: el.scrollLeft }));
442
- const savedDetails = Array.from(this.querySelectorAll("details")).map((d) => ({ id: d.id || null, open: d.open }));
443
- // Unwrap authored content from generated wrappers before dropping them,
444
- // so an attribute re-render cannot destroy authored light-DOM children
445
- // that render() moved into a body/pre wrapper (B3-05).
848
+ const savedScrolls = Array.from(this.querySelectorAll("*")).filter(isScroller).map((el) => ({ el, id: el.id || null, preserveKey: el.getAttribute("data-contour-preserve-key") || null, top: el.scrollTop, left: el.scrollLeft }));
849
+ const savedDetails = Array.from(this.querySelectorAll("details")).map((d) => ({ id: d.id || null, preserveKey: d.getAttribute("data-contour-preserve-key") || null, open: d.open }));
850
+ // Unwrap authored content from generated wrappers before dropping them, so an attribute re-render cannot destroy author...
446
851
  for (const g of (this._contourGenerated || [])) {
447
852
  if (!g || g.parentNode !== this) continue;
448
853
  let wrapper = null;
449
- if (g.classList && (g.classList.contains("c-panel__body") || g.classList.contains("c-dialog__body"))) wrapper = g;
854
+ if (g.classList && (g.classList.contains("c-panel__body") || g.classList.contains("c-dialog__body") || g.classList.contains("c-popover__body") || g.classList.contains("c-map-popup__body") || g.classList.contains("c-hover-card__body") || g.classList.contains("c-drawer__body") || g.classList.contains("c-sheet__body") || g.classList.contains("c-alert__body"))) wrapper = g;
450
855
  else if (g.tagName === "PRE") wrapper = g.querySelector("code") || g;
451
856
  if (wrapper) {
452
857
  while (wrapper.firstChild) this.insertBefore(wrapper.firstChild, g);
453
858
  }
454
859
  }
455
- // Drop generated nodes from the previous render.
456
- for (const g of (this._contourGenerated || [])) {
457
- if (g.parentNode === this) this.removeChild(g);
458
- }
459
- // Refresh the authored snapshot so content added after connect survives.
860
+ // Drop generated nodes from the previous render. Drop generated nodes from the previous render — except the ones the co...
861
+ const persistent = this._contourPersistent;
862
+ const isPersistent = (n) => !!(persistent && persistent.size && persistent.has(n));
863
+ // R24-02: before dropping a generated wrapper, extract any authored children it holds back to the host. A component tha...
864
+ const authoredSet = new Set(this._contourAuthored.nodes || []);
865
+ for (const g of (this._contourGenerated || [])) {
866
+ if (isPersistent(g)) continue;
867
+ // Extract authored children before dropping the wrapper.
868
+ for (const child of Array.from(g.childNodes)) {
869
+ if (authoredSet.has(child)) {
870
+ g.parentNode.insertBefore(child, g);
871
+ }
872
+ }
873
+ if (g.parentNode === this) this.removeChild(g);
874
+ }
875
+ // Refresh the authored snapshot so content added after connect survives. Persistent nodes are generated, not authored: ...
460
876
  const generated = new Set(this._contourGenerated || []);
461
- const authoredNow = Array.from(this.childNodes).filter((n) => !generated.has(n));
877
+ const authoredNow = Array.from(this.childNodes).filter((n) => !generated.has(n) && !isPersistent(n));
878
+ // Find authored nodes inside generated wrappers.
879
+ for (const g of (this._contourGenerated || [])) {
880
+ if (isPersistent(g)) continue;
881
+ const marked = g.querySelectorAll ? g.querySelectorAll("[data-contour-authored]") : [];
882
+ for (const m of marked) {
883
+ if (!authoredNow.includes(m)) authoredNow.push(m);
884
+ }
885
+ }
462
886
  this._contourAuthored.nodes = authoredNow;
463
- // Clear and restore authored nodes.
464
- while (this.firstChild) this.removeChild(this.firstChild);
465
- for (const node of this._contourAuthored.nodes) this.appendChild(node);
466
- if (this._contourAuthored.cls === null) this.removeAttribute("class");
467
- else this.setAttribute("class", this._contourAuthored.cls);
887
+ // Clear and restore authored nodes. Persistent nodes stay connected: they are lifted to the end of the child list and t...
888
+ const kept = Array.from(this.childNodes).filter(isPersistent);
889
+ for (const node of kept) this.appendChild(node); // move to end, no detach
890
+ while (this.firstChild && !isPersistent(this.firstChild)) this.removeChild(this.firstChild);
891
+ for (const node of this._contourAuthored.nodes) this.insertBefore(node, this.firstChild && isPersistent(this.firstChild) ? this.firstChild : null);
892
+ for (const node of kept) this.appendChild(node); // re-assert order after authored inserts
893
+ // R31-02: remove only the classes the previous render generated, then
894
+ // let render() re-add them. Authored and app-added classes are left
895
+ // untouched, so a consumer's own classList edits survive every render.
896
+ for (const c of this._contourOwnedClasses) this.classList.remove(c);
897
+ const _preRenderClasses = new Set(Array.from(this.classList));
468
898
  const before = Array.from(this.childNodes);
469
899
  this._contourRenderGen = (this._contourRenderGen || 0) + 1;
470
900
  this._ensureCache = new Map();
471
901
  this._ensureCacheGen = this._contourRenderGen;
472
902
  this._countRender();
473
903
  try { this.render(); }
474
- catch (e) { console.error("Contour render error:", e); this.textContent = "Component failed to render."; }
904
+ catch (e) { console.error("Contour render error:", e); this.textContent = labelText(this, "render-error", "Component failed to render."); }
475
905
  this._contourGenerated = Array.from(this.childNodes).filter((n) => !before.includes(n));
476
- this._applyParts(this);
906
+ // R31-02: remember the classes this render added, so the next pass
907
+ // removes only those and never a consumer's own class.
908
+ this._contourOwnedClasses = new Set(Array.from(this.classList).filter((c) => !_preRenderClasses.has(c)));
477
909
  this._applyDensity();
478
- // Restore preserved form control values. A re-render that adds or
479
- // removes a control must not wipe the rest: keyed controls (those with
480
- // a `name` or `id`) are matched by key first, so a new field inserted
481
- // between two existing ones leaves both neighbours' values intact.
482
- // Unkeyed controls fall back to index matching up to the shorter of
483
- // the two lists, so a field removed at the end does not shift values
484
- // onto the wrong input.
910
+ // Restore preserved form control values. A re-render that adds or removes a control must not wipe the rest: keyed contr...
485
911
  const newControls = Array.from(this.querySelectorAll("input, textarea, select"));
486
- const keyed = savedValues.filter((sv) => sv.key);
487
- const unkeyed = savedValues.filter((sv) => !sv.key);
912
+ const keyed = savedValues.filter((sv) => sv.key || sv.preserveKey);
913
+ const unkeyed = savedValues.filter((sv) => !sv.key && !sv.preserveKey);
488
914
  const used = new Set();
489
915
  for (const el of newControls) {
490
- const key = el.name || el.id || null;
916
+ const key = el.name || el.id || el.getAttribute("data-contour-preserve-key") || null;
491
917
  if (!key) continue;
492
- const match = keyed.find((sv) => sv.key === key && !used.has(sv));
918
+ const match = keyed.find((sv) => (sv.key === key || sv.preserveKey === key) && !used.has(sv));
493
919
  if (!match) continue;
494
920
  used.add(match);
495
- if (el.value === "" && el.getAttribute("value") === null) {
496
- el.value = match.value;
497
- }
498
- if ((el.type === "checkbox" || el.type === "radio") && typeof match.checked === "boolean" && !this._checkedAttrChanged) {
921
+ if (!this._contourResetting) this._restoreControlValue(el, match);
922
+ if ((el.type === "checkbox" || el.type === "radio") && typeof match.checked === "boolean" && !this._checkedAttrChanged && !this._contourResetting) {
499
923
  el.checked = match.checked;
500
924
  }
501
925
  }
502
- let u = 0;
926
+ // Restore unkeyed controls by type-aware index matching: group saved unkeyed controls by type, then match new unkeyed c...
927
+ const savedByType = new Map();
928
+ for (const sv of unkeyed) {
929
+ const group = savedByType.get(sv.type) || [];
930
+ group.push(sv);
931
+ savedByType.set(sv.type, group);
932
+ }
933
+ const usedByType = new Map();
503
934
  for (const el of newControls) {
504
935
  if (el.name || el.id) continue;
505
- const saved = unkeyed[u];
506
- u += 1;
507
- if (!saved) continue;
508
- if (el.value === "" && el.getAttribute("value") === null) {
509
- el.value = saved.value;
936
+ const type = el.type;
937
+ const group = savedByType.get(type) || [];
938
+ const used = usedByType.get(type) || 0;
939
+ if (used >= group.length) continue;
940
+ const saved = group[used];
941
+ usedByType.set(type, used + 1);
942
+ if (!this._contourResetting) this._restoreControlValue(el, saved);
943
+ if ((el.type === "checkbox" || el.type === "radio") && typeof saved.checked === "boolean" && !this._checkedAttrChanged && !this._contourResetting) {
944
+ el.checked = saved.checked;
510
945
  }
511
- if ((el.type === "checkbox" || el.type === "radio") && typeof saved.checked === "boolean" && !this._checkedAttrChanged) {
512
- el.checked = saved.checked;
513
- }
514
946
  }
515
- // Restore <details> open state. A disclosure carries an `id` when it is
516
- // stable across renders (a faq item, a doc section); match those by id
517
- // so inserting a new disclosure above them does not collapse the ones
518
- // below. Disclosures without an id fall back to index matching up to
519
- // the shorter list, which is the behaviour the length guard existed
520
- // to protect and still protects for the tail of either list.
947
+ // Restore <details> open state. A disclosure carries an `id` when it is stable across renders (a faq item, a doc sectio...
521
948
  const newDetails = Array.from(this.querySelectorAll("details"));
522
- const keyedDetails = savedDetails.filter((sd) => sd.id);
949
+ const keyedDetails = savedDetails.filter((sd) => sd.id || sd.preserveKey);
523
950
  const usedIds = new Set();
524
951
  for (const d of newDetails) {
525
952
  const id = d.id || null;
526
- if (!id) continue;
527
- const match = keyedDetails.find((sd) => sd.id === id && !usedIds.has(sd.id));
953
+ const preserveKey = d.getAttribute("data-contour-preserve-key") || null;
954
+ if (!id && !preserveKey) continue;
955
+ const match = keyedDetails.find((sd) => (sd.id === id || sd.preserveKey === preserveKey) && !usedIds.has(sd.id || sd.preserveKey));
528
956
  if (!match) continue;
529
- usedIds.add(match.id);
957
+ usedIds.add(match.id || match.preserveKey);
530
958
  d.open = match.open;
531
959
  }
532
960
  let di = 0;
@@ -538,24 +966,22 @@
538
966
  if (!sd) break;
539
967
  d.open = sd.open;
540
968
  }
541
- // Restore scroll positions. A scroller that carries an `id` is matched by
542
- // id so inserting another scroller above it does not hand its offset to
543
- // the wrong container; the rest fall back to index matching up to the
544
- // shorter list, which is what the old length guard protected.
545
- const newScrolls = Array.from(this.querySelectorAll("*")).filter((el) => el.scrollHeight > el.clientHeight || el.scrollWidth > el.clientWidth);
546
- const keyedScrolls = savedScrolls.filter((s) => s.el.id);
969
+ // Restore scroll positions. A scroller that carries an `id` is matched by id so inserting another scroller above it doe...
970
+ const newScrolls = Array.from(this.querySelectorAll("*")).filter(isScroller);
971
+ const keyedScrolls = savedScrolls.filter((s) => s.id || s.preserveKey);
547
972
  const usedScrolls = new Set();
548
973
  for (const el of newScrolls) {
549
974
  const id = el.id || null;
550
- if (!id) continue;
551
- const match = keyedScrolls.find((s) => s.el.id === id && !usedScrolls.has(s.el));
975
+ const preserveKey = el.getAttribute("data-contour-preserve-key") || null;
976
+ if (!id && !preserveKey) continue;
977
+ const match = keyedScrolls.find((s) => (s.id === id || s.preserveKey === preserveKey) && !usedScrolls.has(s.el));
552
978
  if (!match) continue;
553
979
  usedScrolls.add(match.el);
554
980
  el.scrollTop = match.top;
555
981
  el.scrollLeft = match.left;
556
982
  }
557
983
  let si = 0;
558
- const plainScrolls = savedScrolls.filter((s) => !s.el.id);
984
+ const plainScrolls = savedScrolls.filter((s) => !s.id && !s.preserveKey);
559
985
  for (const el of newScrolls) {
560
986
  if (el.id) continue;
561
987
  const s = plainScrolls[si];
@@ -564,24 +990,33 @@
564
990
  el.scrollTop = s.top;
565
991
  el.scrollLeft = s.left;
566
992
  }
567
- // Restore focus if it was inside the host. Keyed elements (id) are
568
- // matched first; unkeyed ones fall back to a `name` attribute, then to
569
- // their relative index among focusable controls, so an attribute update
570
- // that rebuilds an unkeyed input no longer drops focus to <body>.
993
+ // A persistent node kept its identity but not necessarily its offset: the rebuild clears its subtree, and the browser c...
994
+ for (const s of savedScrolls) {
995
+ if (!s.el || !s.el.isConnected) continue;
996
+ // _contourPersistent only exists once keepNode() has been called; a host with scrollable descendants but no persistent ...
997
+ if (!persistent || !persistent.has(s.el)) continue;
998
+ if (s.el.scrollTop === s.top && s.el.scrollLeft === s.left) continue;
999
+ s.el.scrollTop = s.top;
1000
+ s.el.scrollLeft = s.left;
1001
+ }
1002
+ // Restore focus if it was inside the host. Keyed elements (id) are matched first; unkeyed ones fall back to a `name` at...
571
1003
  if (hadFocus) {
572
- let target = null;
573
- if (hadFocus.id) {
574
- try { target = this.querySelector("#" + CSS.escape(hadFocus.id)); } catch (e) { target = null; }
575
- }
576
- if (!target && hadFocusName) {
577
- try { target = this.querySelector('[name="' + CSS.escape(hadFocusName) + '"]'); } catch (e) { target = null; }
578
- }
579
- if (!target && hadFocusIndex >= 0) {
580
- const after = Array.from(this.querySelectorAll(_focusableSelector));
581
- if (after.length) {
582
- target = after[Math.min(hadFocusIndex, after.length - 1)];
583
- }
584
- }
1004
+ let target = null;
1005
+ if (hadFocusKey) {
1006
+ try { target = this.querySelector("#" + CSS.escape(hadFocusKey)); } catch (e) { target = null; }
1007
+ }
1008
+ if (!target && hadFocusPreserveKey) {
1009
+ try { target = this.querySelector('[data-contour-preserve-key="' + CSS.escape(hadFocusPreserveKey) + '"]'); } catch (e) { target = null; }
1010
+ }
1011
+ if (!target && hadFocusName) {
1012
+ try { target = this.querySelector('[name="' + CSS.escape(hadFocusName) + '"]'); } catch (e) { target = null; }
1013
+ }
1014
+ if (!target && hadFocusIndex >= 0) {
1015
+ const after = Array.from(this.querySelectorAll(_focusableSelector));
1016
+ if (after.length) {
1017
+ target = after[Math.min(hadFocusIndex, after.length - 1)];
1018
+ }
1019
+ }
585
1020
  if (target && typeof target.focus === "function") {
586
1021
  try { target.focus(); } catch (e) {}
587
1022
  } else if (document.contains(hadFocus)) {
@@ -592,12 +1027,14 @@
592
1027
  else try { this.focus(); } catch (e) {}
593
1028
  }
594
1029
  }
595
- this.enhance();
1030
+ this._runEnhance();
596
1031
  this._detachInnerFormControls();
597
1032
  this._checkedAttrChanged = false;
1033
+ this._contourResetting = false;
598
1034
  } finally {
599
1035
  this._contourRendering = false;
600
1036
  }
1037
+ this._announceRendered();
601
1038
  }
602
1039
 
603
1040
  disconnectedCallback() {
@@ -608,29 +1045,47 @@
608
1045
  // Form listeners were removed by runDisposers below; clear the guard so
609
1046
  // a reconnected host re-attaches them (connectedCallback re-wires).
610
1047
  this._wiredFormData = false;
1048
+ // R24-98: clear remote-load state so a reconnect re-fetches. A host detached mid-fetch has _remoteStatus="loading" and ...
1049
+ this._remoteStatus = null;
1050
+ this._remoteSrc = null;
611
1051
  runDisposers(this);
1052
+ // R28-09 : drop the host listeners enhance() added this mount. They live on the host element and would otherwise surviv...
1053
+ const hostListeners = this._contourHostListeners;
1054
+ if (hostListeners) {
1055
+ for (const { type, listener, options } of hostListeners) {
1056
+ try { this.removeEventListener(type, listener, options); } catch (e) { /* already gone */ }
1057
+ }
1058
+ this._contourHostListeners = null;
1059
+ }
612
1060
  // Override in subclasses that attach event listeners or timers.
613
1061
  }
614
1062
 
615
1063
  adoptedCallback() {
616
1064
  // Re-apply parts and the density mirror when the node is moved to a new
617
1065
  // document.
618
- if (this._contourAuthored) { this._applyParts(this); this._applyDensity(); }
1066
+ if (this._contourAuthored) { this._applyDensity(); }
619
1067
  }
620
1068
 
621
1069
  // Default no-op: subclasses with behaviour override this.
622
1070
  enhance() {}
623
1071
 
624
- // Form lifecycle (form-associated components only). The platform calls
625
- // these on <form>.reset(), on disable by a fieldset/form, and on bfcache
626
- // restore; before this, a reset left the generated control showing its old
627
- // value and a disabled fieldset reached nothing. The implementations are
628
- // generic over the host's inner control(s), so a subclass overrides only
629
- // when its control is not a plain input/textarea/select.
630
- //
631
- // The inner-value contract mirrors what each form class's enhance() sync
632
- // already writes: a boolean control submits its `checked` value (or null),
633
- // a text-like control submits its raw value, and `required` sets validity.
1072
+ // R28-09 : a host listener added by enhance() lives on the host element, which a disconnect does not destroy, so it sur...
1073
+ addEventListener(type, listener, options) {
1074
+ // Behaviour listeners (behaviours.mjs wcTrack) carry _contourBehaviour: their claim persists across a light reconnect, ...
1075
+ if (this._contourHostWiring && listener && !listener._contourBehaviour) {
1076
+ let list = this._contourHostListeners;
1077
+ if (!list) { list = []; this._contourHostListeners = list; }
1078
+ list.push({ type, listener, options });
1079
+ }
1080
+ return super.addEventListener(type, listener, options);
1081
+ }
1082
+ _runEnhance() {
1083
+ this._contourHostWiring = true;
1084
+ try { this.enhance(); }
1085
+ finally { this._contourHostWiring = false; }
1086
+ }
1087
+
1088
+ // Form lifecycle (form-associated components only). The platform calls these on <form>.reset(), on disable by a fieldse...
634
1089
  _syncFormValue() {
635
1090
  if (!this._internals) return;
636
1091
  // A boolean group (a contour-radio-list) submits the *checked* item's
@@ -643,29 +1098,33 @@
643
1098
  this._syncValidity(this.hasAttribute("required") && !value);
644
1099
  }
645
1100
 
646
- // The single validity writer (BY-32). Every form class used to repeat the
647
- // required-check + setValidity pair; the copies in forms.mjs now call here,
648
- // and the call ALSO mirrors the host's `data-invalid` custom state
649
- // (ElementInternals.states → `:state(data-invalid)`), so validity and the
650
- // state a consumer's CSS can select can never drift apart.
1101
+ // The single validity writer . Every form class used to repeat the required-check + setValidity pair; the copies in for...
1102
+ // R31-61: mirror the inner control's NATIVE validity onto the host, not only
1103
+ // `required`. A `contour-input type="email" value="not-an-email"` must make
1104
+ // the host and its form invalid (typeMismatch), and number/pattern/min/max
1105
+ // must do the same. `valueMissing` is the authored-required fallback for
1106
+ // groups that have no single inner control to read.
651
1107
  _syncValidity(valueMissing) {
652
1108
  if (!this._internals) return;
653
- if (valueMissing) this._internals.setValidity({ valueMissing: true }, "This field is required.");
654
- else this._internals.setValidity({});
655
- this._setCustomState("data-invalid", !!valueMissing);
1109
+ const flags = valueMissing ? { valueMissing: true } : {};
1110
+ let msg = valueMissing ? "This field is required." : "";
1111
+ const ctl = this.querySelector("input, textarea, select");
1112
+ const v = ctl && ctl.validity;
1113
+ if (v) {
1114
+ if (v.valueMissing) { flags.valueMissing = true; msg = msg || "This field is required."; }
1115
+ if (v.typeMismatch) { flags.typeMismatch = true; msg = msg || "Please enter a valid value."; }
1116
+ if (v.patternMismatch) { flags.patternMismatch = true; msg = msg || "Please match the requested format."; }
1117
+ if (v.rangeUnderflow) { flags.rangeUnderflow = true; msg = msg || "Value is too low."; }
1118
+ if (v.rangeOverflow) { flags.rangeOverflow = true; msg = msg || "Value is too high."; }
1119
+ if (v.tooLong) { flags.tooLong = true; msg = msg || "Value is too long."; }
1120
+ if (v.tooShort) { flags.tooShort = true; msg = msg || "Value is too short."; }
1121
+ if (v.badInput) { flags.badInput = true; msg = msg || "Invalid input."; }
1122
+ }
1123
+ this._internals.setValidity(flags, msg);
1124
+ this._setCustomState("data-invalid", Object.keys(flags).length > 0);
656
1125
  }
657
1126
 
658
- // Custom-state mirror (BY-32). `ElementInternals.states` exposes a host's
659
- // own boolean to CSS as `:state(name)` — a consumer writes
660
- // `contour-switch:state(data-checked)` without the layer inventing a data-*
661
- // attribute. Loader hosts are NOT formAssociated, so the states-only
662
- // internals are attached lazily into `_stateInternals` — never `_internals`,
663
- // which every form path uses as its "form-associated" guard (`_wireFormData`
664
- // reads .form on it, which throws on a non-form host; probing lazy attach
665
- // into `_internals` broke every src-mounting arm with exactly that error).
666
- // Where CustomStateSet is absent the mirror is a silent no-op and the
667
- // ARIA/attribute path remains the announcement. Not a write to OBSERVED,
668
- // so it can never re-enter render.
1127
+ // Custom-state mirror . `ElementInternals.states` exposes a host's own boolean to CSS as `:state(name)` — a consumer wr...
669
1128
  _setCustomState(name, on) {
670
1129
  let internals = this._internals;
671
1130
  if (!internals) {
@@ -680,12 +1139,7 @@
680
1139
  else if (states.has(name)) states.delete(name);
681
1140
  }
682
1141
 
683
- // The form value events (BY-44). §23 promises interactive components emit
684
- // bubbling contour:* events; the form family had 16 user-interaction
685
- // listeners and emitted none, so a consumer could not observe a change
686
- // without polling. This is the ONE value-shape both `contour:input` and
687
- // `contour:change` carry, derived from the same control state _syncFormValue
688
- // submits, so the event can never disagree with the entry list.
1142
+ // The form value events . §23 promises interactive components emit bubbling contour:* events; the form family had 16 us...
689
1143
  _emitForm(type) {
690
1144
  if (!this._internals) return;
691
1145
  const ctl = this.querySelector("input:checked, textarea, select") || this.querySelector("input, textarea, select");
@@ -702,11 +1156,9 @@
702
1156
  }));
703
1157
  }
704
1158
  formResetCallback() {
705
- // Reset synchronously: re-rendering would restore the base class's
706
- // *preserved* typed value, not the authored default. The authored
707
- // default is the host's own value/checked attributes, so restore the
708
- // inner control from them, then re-sync internals.
1159
+ // Reset synchronously: re-rendering would restore the base class's *preserved* typed value, not the authored default. T...
709
1160
  for (const ctl of this.querySelectorAll("input, textarea, select")) {
1161
+ ctl._contourUserDirty = false;
710
1162
  if (ctl.type === "checkbox" || ctl.type === "radio") {
711
1163
  ctl.checked = this.hasAttribute("checked");
712
1164
  } else if (ctl.tagName === "SELECT") {
@@ -750,14 +1202,7 @@
750
1202
  return this._internals ? this._internals.reportValidity() : true;
751
1203
  }
752
1204
 
753
- // Keep internals in step with the group. Checking radio B fires `change` on
754
- // B only — the deselected host A hears nothing, so its internals keep the
755
- // stale "a" and the entry list collects both ("g=a","g=b"; measured by the
756
- // form-lifecycle probe, 2026-10-28). Re-syncing in the `formdata` handler
757
- // is too late: the entry list has already copied each host's internals
758
- // before that event fires. `change` bubbles through the shared form, so a
759
- // same-name host re-derives its value the moment B is checked — before any
760
- // collection can read it.
1205
+ // Keep internals in step with the group. Checking radio B fires `change` on B only — the deselected host A hears nothin...
761
1206
  _wireFormData() {
762
1207
  if (!this._internals || this._wiredFormData) return;
763
1208
  const form = this._internals.form;
@@ -777,13 +1222,40 @@
777
1222
  });
778
1223
  }
779
1224
 
780
- // The inner native control(s) are scaffolding; the host reports through
781
- // ElementInternals. A same-name native control inside a <form> would submit
782
- // a second entry with the same name — double submission, measured as
783
- // ["g=a","g=a"] in a two-entry FormData (2026-10-27, form-lifecycle probe).
784
- // form="" (no matching form element) detaches it from the form owner while
785
- // keeping native radio-group semantics: same name, same tree, both
786
- // form-ownerless → they still share one checked state.
1225
+ // User-dirty value tracking (R20 T-02). The restore path only fills controls a render left empty, so a host with an aut...
1226
+ _wireValueTracking() {
1227
+ if (!this._internals || this._wiredValueTracking) return;
1228
+ this._wiredValueTracking = true;
1229
+ const mark = (e) => {
1230
+ const t = e.target;
1231
+ if (!t || !t.matches || !t.matches("input, textarea, select")) return;
1232
+ if (this._ownerBetween(t, this)) return;
1233
+ t._contourUserDirty = true;
1234
+ t._contourAttrAtDirty = this.getAttribute("value");
1235
+ };
1236
+ this.addEventListener("input", mark);
1237
+ this.addEventListener("change", mark);
1238
+ }
1239
+
1240
+ // Restore one control's value from its snapshot (R20 T-02/T-06). A user-dirty control keeps its typed value — a multi-s...
1241
+ _restoreControlValue(el, saved) {
1242
+ // R24-116: a file input's `.value` is read-only — assigning it throws an InvalidStateError (the value is a synthetic "C...
1243
+ if (el.type === "file") return;
1244
+ if (saved.dirty && saved.attrAtDirty === this.getAttribute("value")) {
1245
+ if (saved.selected && el.tagName === "SELECT" && el.multiple) {
1246
+ const wanted = new Set(saved.selected);
1247
+ for (const o of el.options) o.selected = wanted.has(o.value);
1248
+ } else {
1249
+ el.value = saved.value;
1250
+ }
1251
+ el._contourUserDirty = true;
1252
+ el._contourAttrAtDirty = saved.attrAtDirty;
1253
+ return;
1254
+ }
1255
+ if (el.value === "" && el.getAttribute("value") === null) el.value = saved.value;
1256
+ }
1257
+
1258
+ // The inner native control(s) are scaffolding; the host reports through ElementInternals. A same-name native control in...
787
1259
  _detachInnerFormControls() {
788
1260
  if (!this._internals) return;
789
1261
  for (const ctl of this.querySelectorAll("input, textarea, select")) {
@@ -791,10 +1263,7 @@
791
1263
  }
792
1264
  }
793
1265
 
794
- // Opt-in batching: coalesce multiple attribute changes into a single
795
- // render. Usage: el.batch(() => { el.value = 42; el.delta = "+3"; });
796
- // The render fires once when the callback returns, reading all final
797
- // attribute values. Nested calls are supported.
1266
+ // Opt-in batching: coalesce multiple attribute changes into a single render. Usage: el.batch(() => { el.value = 42; el....
798
1267
  /** Coalesce synchronous property changes into one render. */
799
1268
  batch(fn) {
800
1269
  if (typeof fn !== "function") return;
@@ -814,19 +1283,7 @@
814
1283
  }
815
1284
  }
816
1285
 
817
- // Ask for a re-render without naming the attribute that changed, for work the
818
- // host started itself — a `src` fetch that resolved, a timer, an observer. A
819
- // render body must never reach for `attributeChangedCallback` directly: on the
820
- // connect path `_contourRendering` is still false, so that call performs a
821
- // synchronous nested re-render and the outer body then carries on painting the
822
- // node the nested pass already painted. Measured in Chromium (tmp/wc9/probe.mjs,
823
- // 2026-10-27): a host with `src` rendered "Loading…Loading…" — two nodes — while
824
- // the identical host with an authored `loading` attribute rendered one.
825
- //
826
- // Deferring to a microtask lets the in-flight render finish before the next one
827
- // starts, and the flag coalesces N asks in one pass into one render. It runs
828
- // through the same reset/restore path as an attribute change, so a consumer's
829
- // authored nodes and focus survive it exactly as they survive a real change.
1286
+ // Request a re-render without naming the changed attribute (for host-driven work: a resolved fetch, a timer, an observer). A render body must never call attributeChangedCallback directly — on the connect path that nests a synchronous render. Deferring to a microtask coalesces N asks into one render through the same reset/restore path.
830
1287
  requestRender() {
831
1288
  if (this._contourRerenderQueued) return;
832
1289
  this._contourRerenderQueued = true;
@@ -837,38 +1294,21 @@
837
1294
  });
838
1295
  }
839
1296
 
840
- // Expose ::part() hooks on every generated node whose class follows the
841
- // `c-<block>__<element>` convention, so a consumer can theme internals
842
- // without shadow DOM. Runs after render() in both connect and re-render.
843
- _applyParts(root) {
844
- const scope = root || this;
845
- const nodes = scope.querySelectorAll ? Array.from(scope.querySelectorAll("[class]")) : [];
846
- for (const node of nodes) {
847
- if (node.hasAttribute("part")) continue;
848
- if (typeof node.className !== "string") continue;
849
- for (const c of node.className.split(/\s+/)) {
850
- const m = c.match(/^c-[a-z0-9-]+__([a-z0-9-]+)$/);
851
- if (m) { node.setAttribute("part", m[1]); break; }
852
- }
853
- }
854
- }
1297
+ // R31-15: the light layer no longer writes `part=` on generated nodes.
1298
+ // `::part()` matches only shadow parts, so the attribute was inert on every
1299
+ // light component while `_applyParts` scanned every `[class]` on every
1300
+ // render (~12% of steady-state re-render on a 500-row table). The light
1301
+ // theming seam is `contour-<block> .c-<block>__<element>`; the shadow layer
1302
+ // keeps its real `::part()` hooks (shadow.mjs).
855
1303
 
856
- // Density modifier (BY-48). The sheet hooks on `[data-density]` — the
857
- // attribute the token layer ships with (`--density`, `--density-compact`
858
- // in tokens.css) — so the wc layer exposes a `density` attribute and
859
- // mirrors it to `data-density` on the host. `data-density` is not in
860
- // OBSERVED, so the write cannot re-enter the render this runs from.
1304
+ // Density modifier: mirror `density` attribute to `data-density` on the host (the sheet hooks on it); not in OBSERVED so the write can't re-enter render.
861
1305
  _applyDensity() {
862
1306
  const density = this.getAttribute("density");
863
1307
  if (density !== null) this.setAttribute("data-density", density);
864
1308
  else if (this.hasAttribute("data-density")) this.removeAttribute("data-density");
865
1309
  }
866
1310
 
867
- // The closest host above `node` on the way up to `root`, or null when the
868
- // path never crosses another host. `ensure()` may only reuse a node its own
869
- // host owns: querySelector reaches straight through a nested host's
870
- // boundary, so two blocks that both carry a `__title` would share one
871
- // element and the outer render would write the inner one's text.
1311
+ // Closest host above `node` up to `root`, or null. ensure() may only reuse a node its own host owns: querySelector reaches through a nested host's boundary, so two blocks with a `__title` would share one element.
872
1312
  _ownerBetween(node, root) {
873
1313
  for (let p = node.parentElement; p && p !== root; p = p.parentElement) {
874
1314
  if (p instanceof ContourBase) return p;
@@ -877,15 +1317,26 @@
877
1317
  }
878
1318
 
879
1319
  // Helper for update-or-create reactivity: returns the first node matching
880
- // `selector`, creating it via `factory()` and appending it if absent. Render
881
- // bodies use this so an attribute change updates the existing node instead
882
- // of being blocked by a `!querySelector` guard.
883
- //
884
- // A per-render cache avoids re-querying the subtree for every ensure() call
885
- // in the same render pass (O(k*n) -> O(n+k)). The cache is keyed by the
886
- // scope it was read from as well as the selector, because a `parent` that is
887
- // not the host survives the next render's node reset while its cached match
888
- // does not — a detached element handed back instead of a fresh one appended.
1320
+ // `selector`, creating it via `factory()` and appending if absent, so an attribute change updates the existing node. A per-render cache (keyed by scope and selector) avoids re-querying the subtree for every ensure() call.
1321
+ /**
1322
+ * Register a generated node as persistent across re-renders.
1323
+ *
1324
+ * The base class drops every generated node on each render and rebuilds it
1325
+ * from `render()`. That is right for markup and wrong for a node whose
1326
+ * identity carries state the markup does not: a scroller's `scrollTop`, a
1327
+ * canvas' drawn pixels, a media element's `currentTime`. Registering the
1328
+ * node here keeps it alive across the rebuild; `render()` re-attaches it.
1329
+ *
1330
+ * @param {Node} node generated node to keep
1331
+ * @returns {Node} the same node, for chaining
1332
+ */
1333
+ keepNode(node) {
1334
+ if (!node) return node;
1335
+ if (!this._contourPersistent) this._contourPersistent = new Set();
1336
+ this._contourPersistent.add(node);
1337
+ return node;
1338
+ }
1339
+
889
1340
  ensure(selector, factory, parent) {
890
1341
  const root = parent || this;
891
1342
  if (!root._ensureCache || root._ensureCacheGen !== this._contourRenderGen) {
@@ -905,13 +1356,8 @@
905
1356
  }
906
1357
  if (!node) {
907
1358
  node = factory();
908
- // Expose a ::part() hook for every generated element, so a consumer
909
- // can theme internals without shadow DOM. The part name is the element
910
- // name after the block's `__` separator (e.g. .c-card__title -> "title").
911
- if (node && node.setAttribute && !node.hasAttribute("part")) {
912
- const m = String(selector).match(/\.c-[a-z0-9-]+__([a-z0-9-]+)/);
913
- if (m) node.setAttribute("part", m[1]);
914
- }
1359
+ // R31-15: no `part=` write here — it is inert on light DOM (see the
1360
+ // removed _applyParts). Shadow wrappers set their own real parts.
915
1361
  root.appendChild(node);
916
1362
  cache.set(key, node);
917
1363
  }
@@ -919,10 +1365,7 @@
919
1365
  }
920
1366
  }
921
1367
 
922
- // Brownout mixin (G-16): opt-in base for components that shed non-essential
923
- // chrome under degraded conditions. Merges `brownout` / `brownout-level`
924
- // into the subclass observed list and exposes the helpers already on
925
- // ContourBase. Usage: `class Foo extends withBrownout(ContourBase) { ... }`.
1368
+ // Brownout mixin : opt-in base for components that shed non-essential chrome under degraded conditions. Merges `brownou...
926
1369
  export function withBrownout(Base) {
927
1370
  return class extends Base {
928
1371
  static get observed() {
@@ -934,6 +1377,11 @@
934
1377
  shed(kind, threshold) { return this.brownoutLevel() >= (threshold || 1); }
935
1378
  };
936
1379
  }
1380
+ /** Pure helper: compute brownout level from an attribute bag (framework-neutral). */
1381
+ export function levelFromAttributes(attrs = {}) {
1382
+ const raw = (attrs && (attrs["brownout-level"] || attrs["brownout"])) || "0";
1383
+ return parseInt(raw, 10) || 0;
1384
+ }
937
1385
 
938
1386
  // Simple component: just adds CSS classes.
939
1387
  /** Create a light-DOM component that only applies block and modifier classes. */
@@ -957,21 +1405,13 @@
957
1405
  };
958
1406
 
959
1407
  // ---- Class-only blocks ----
960
- //
961
- // A block in this list needs nothing but its own class: the element name is
962
- // \`contour-<block>\` and the class is \`c-<block>\`, which is why the table holds
963
- // the block and not two spellings of it. Blocks that need scaffolding are not
964
- // here — they declare a class above, and their presence in this list would be
965
- // a fallback that only runs when the real component is broken, so the
966
- // registration loop skips a name an explicit component already claimed.
1408
+ // A block here needs only its own class: element `contour-<block>`, class `c-<block>`. Blocks needing scaffolding declare a class above; the registration loop skips a name an explicit component already claimed.
967
1409
  /** Blocks whose custom elements need no generated markup. */
968
1410
  export const CLASS_ONLY = [
969
1411
  "box", "cluster", "container", "row", "scrim", "stack"
970
1412
  ];
971
1413
 
972
- // Feature detection for `hidden="until-found"` (BY-51). Browsers that do not
973
- // support it treat the value as the boolean hidden attribute, which would
974
- // hide the content permanently — so we only upgrade where supported.
1414
+ // Feature detection for `hidden="until-found"`: unsupported browsers treat the value as boolean hidden (permanent hide), so only upgrade where supported.
975
1415
  /** Detect support for the non-destructive `hidden="until-found"` value. */
976
1416
  export function supportsUntilFound() {
977
1417
  try {
@@ -981,11 +1421,7 @@
981
1421
  } catch (e) { return false; }
982
1422
  }
983
1423
 
984
- // Value formatting (BY-31/BY-22): opt-in Intl formatting for kpi/stat/readout/coordinate.
985
- // `format` is a preset ("number","currency","percent","compact","date","time",
986
- // "unit","relative") or a JSON string of Intl.NumberFormat/DateTimeFormat/
987
- // RelativeTimeFormat options. `locale` defaults to the runtime locale.
988
- // Returns the raw value when formatting fails.
1424
+ // Value formatting: opt-in Intl formatting for kpi/stat/readout/coordinate. `format` is a preset or JSON of Intl options; `locale` defaults to runtime locale; returns raw value on failure.
989
1425
  /** Format a value with the component's supported Intl presets. */
990
1426
  export function formatValue(value, format, locale, unit) {
991
1427
  if (!format) return value;
@@ -1024,6 +1460,44 @@
1024
1460
  catch (e) { return value; }
1025
1461
  }
1026
1462
 
1463
+ // Shared keyboard navigation for roving-tabindex patterns. Options: { wrap=true, enter=true, homeEnd=false, onKey(key,idx,item)→truthy prevents default, onNavigate(newIdx), rtl (defaults to dir attr) }.
1464
+ /** Navigate a roving-tabindex group with arrow keys, Home/End, Enter/Space. */
1465
+ export function navKey(e, items, { wrap = true, enter = true, homeEnd = false, onKey, onNavigate, rtl } = {}) {
1466
+ const idx = items.indexOf(document.activeElement);
1467
+ if (idx < 0) return;
1468
+ let next = -1;
1469
+ // Determine direction: ArrowRight/Down always advance forward in LTR.
1470
+ // With RTL, ArrowRight goes back and ArrowLeft goes forward.
1471
+ const fwdKey = rtl ? "ArrowLeft" : "ArrowRight";
1472
+ const revKey = rtl ? "ArrowRight" : "ArrowLeft";
1473
+ if (e.key === fwdKey || e.key === "ArrowDown") next = wrap ? (idx + 1) % items.length : Math.min(idx + 1, items.length - 1);
1474
+ else if (e.key === revKey || e.key === "ArrowUp") next = wrap ? (idx - 1 + items.length) % items.length : Math.max(0, idx - 1);
1475
+ else if ((homeEnd || wrap) && e.key === "Home") next = 0;
1476
+ else if ((homeEnd || wrap) && e.key === "End") next = items.length - 1;
1477
+ if (next >= 0 && next !== idx) {
1478
+ e.preventDefault();
1479
+ try { items[next].focus(); } catch (_) {}
1480
+ if (onNavigate) onNavigate(next);
1481
+ if (onKey) onKey(e.key, idx, items[idx]);
1482
+ } else if ((enter || wrap) && (e.key === "Enter" || e.key === " ")) {
1483
+ e.preventDefault();
1484
+ if (onKey) onKey(e.key, idx, items[idx]);
1485
+ }
1486
+ }
1487
+
1488
+ // Resolve RTL direction from element or document. Returns true for RTL layout.
1489
+ /** Check whether the given element uses right-to-left text direction. */
1490
+ export function isRtl(el) {
1491
+ let node = el;
1492
+ while (node && node.nodeType === 1) {
1493
+ const d = node.getAttribute && node.getAttribute("dir");
1494
+ if (d) return d.toLowerCase() === "rtl";
1495
+ node = node.parentElement;
1496
+ }
1497
+ try { return (typeof document !== "undefined" && (document.documentElement.getAttribute("dir") || "").toLowerCase() === "rtl"); }
1498
+ catch (e) { return false; }
1499
+ }
1500
+
1027
1501
  // Spatial maths (BY-23): pure functions on the host's own attributes.
1028
1502
  // Haversine distance in meters between two lat/lon points.
1029
1503
  /** Return the great-circle distance between two latitude/longitude points. */
@@ -1046,7 +1520,55 @@
1046
1520
  return (toDeg(Math.atan2(y, x)) + 360) % 360;
1047
1521
  }
1048
1522
  // Mercator resolution (meters per pixel) at a given latitude and zoom.
1523
+ /** The latitude Web Mercator can represent; beyond it the projection diverges. */
1524
+ export const MERCATOR_MAX_LAT = 85.05112878;
1525
+
1526
+ /** Clamp a latitude into the Mercator domain; NaN when the input is not a number. */
1527
+ export function clampLat(lat) {
1528
+ const v = Number(lat);
1529
+ if (!Number.isFinite(v)) return NaN;
1530
+ return Math.max(-MERCATOR_MAX_LAT, Math.min(MERCATOR_MAX_LAT, v));
1531
+ }
1532
+
1533
+ /** Wrap a longitude into [-180, 180). NaN when the input is not a number. */
1534
+ export function normaliseLng(lng) {
1535
+ const v = Number(lng);
1536
+ if (!Number.isFinite(v)) return NaN;
1537
+ return ((((v + 180) % 360) + 360) % 360) - 180;
1538
+ }
1539
+
1540
+ /**
1541
+ * Normalise a west/south/east/north box. A box that crosses the antimeridian
1542
+ * arrives as `west > east` (MapLibre reports 170 → -170 that way), which makes
1543
+ * `east - west` negative and hides the crossing. The returned box is unwrapped
1544
+ * — `east` continues past 180 — and says so, so a span is always positive and
1545
+ * a consumer that needs the engine's own numbers can subtract 360 from `east`
1546
+ * when `crossesAntimeridian` is true.
1547
+ */
1548
+ export function unwrapBounds(bounds) {
1549
+ const b = bounds || {};
1550
+ const west = normaliseLng(b.west);
1551
+ const eastRaw = normaliseLng(b.east);
1552
+ const crossesAntimeridian = Number.isFinite(west) && Number.isFinite(eastRaw) && west > eastRaw;
1553
+ return {
1554
+ west,
1555
+ south: clampLat(b.south),
1556
+ east: crossesAntimeridian ? eastRaw + 360 : eastRaw,
1557
+ north: clampLat(b.north),
1558
+ crossesAntimeridian,
1559
+ };
1560
+ }
1561
+
1049
1562
  /** Return meters per pixel for Web Mercator at a latitude and zoom level. */
1050
1563
  export function mercatorResolution(lat, zoom) {
1051
- return 156543.03392 * Math.cos(lat * Math.PI / 180) / Math.pow(2, zoom);
1564
+ // Beyond ±85.05112878° the projection is undefined and cos() collapses
1565
+ // toward zero (resolution 6e-17 at the pole instead of a finite number).
1566
+ const phi = clampLat(lat);
1567
+ if (!Number.isFinite(phi)) return NaN;
1568
+ return 156543.03392 * Math.cos(phi * Math.PI / 180) / Math.pow(2, zoom);
1569
+ }
1570
+
1571
+ // Event vocabulary is static, so publish once here (frozen) rather than per-registration; any import path reaching core.mjs exposes it.
1572
+ if (typeof window !== "undefined") {
1573
+ window.ContourEvents = Object.freeze(CONTOUR_EVENTS);
1052
1574
  }