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
@@ -0,0 +1,1333 @@
1
+ import { setHTML, ContourBase, define, onDispose, formatValue, contourId, navKey, isRtl, cssLength , safeColor, warnBadJson, labelText } from './core.mjs';
2
+ import { loadRemote, remoteData, renderStates, renderEmpty, wireStates, remoteInvalidate, watchViewport, parseArrayAttr, stateLabel } from './states.mjs';
3
+ import { donutSlices, barRects, smoothPath, polylinePoints, contourPaths, niceTicks, isMissing } from './svg.mjs';
4
+ import { paintDonutGlyph, paintSparklineGlyph, paintPurityRing } from './glyph.mjs';
5
+
6
+ const STREAM_BUFFER_MAX = 600;
7
+ const capBuffer = (arr, max = STREAM_BUFFER_MAX) => {
8
+ if (!Array.isArray(arr) || arr.length <= max) return arr;
9
+ const step = Math.ceil(arr.length / max);
10
+ const out = [];
11
+ for (let i = 0; i < arr.length; i += step) out.push(arr[i]);
12
+ const last = arr[arr.length - 1];
13
+ if (out[out.length - 1] !== last) out.push(last);
14
+ return out;
15
+ };
16
+
17
+ /* R24-88: keyed mark diffing. Reuses DOM nodes by position+tag instead of wiping with innerHTML, preserving focus and avoiding subtree re-allocation on minor edits. */
18
+ const patchChildren = (parent, src) => {
19
+ const newNodes = Array.from(src.childNodes);
20
+ const oldNodes = Array.from(parent.childNodes);
21
+ const n = Math.max(newNodes.length, oldNodes.length);
22
+ for (let i = 0; i < n; i++) {
23
+ const oldN = oldNodes[i];
24
+ const newN = newNodes[i];
25
+ if (!oldN) { if (newN) parent.appendChild(newN); continue; }
26
+ if (!newN) { parent.removeChild(oldN); continue; }
27
+ if (oldN.nodeType === 1 && newN.nodeType === 1 && oldN.tagName === newN.tagName) {
28
+ for (const a of Array.from(oldN.attributes)) {
29
+ if (!newN.hasAttribute(a.name)) oldN.removeAttribute(a.name);
30
+ }
31
+ for (const a of Array.from(newN.attributes)) {
32
+ const v = newN.getAttribute(a.name);
33
+ if (oldN.getAttribute(a.name) !== v) oldN.setAttribute(a.name, v);
34
+ }
35
+ patchChildren(oldN, newN);
36
+ } else if (oldN.nodeType === 3 && newN.nodeType === 3) {
37
+ if (oldN.textContent !== newN.textContent) oldN.textContent = newN.textContent;
38
+ } else {
39
+ parent.replaceChild(newN, oldN);
40
+ }
41
+ }
42
+ };
43
+ /**
44
+ * Coerce a histogram bin into the published shape.
45
+ *
46
+ * A bin may arrive from the author (`series[].bins`) or be pushed by a binder
47
+ * (`chart.bins = …`). Both go through here so `bins` reads back the same way
48
+ * whichever door it came through, and a malformed entry is dropped rather than
49
+ * rendered as NaN geometry.
50
+ */
51
+ const normalizeChartBin = (bin) => {
52
+ if (!bin || typeof bin !== "object") return null;
53
+ const x0 = Number(bin.x0);
54
+ const x1 = Number(bin.x1);
55
+ const count = Number(bin.count);
56
+ if (!Number.isFinite(x0) || !Number.isFinite(x1) || !Number.isFinite(count)) return null;
57
+ const out = { x0, x1, count };
58
+ const normalized = Number(bin.normalized);
59
+ if (Number.isFinite(normalized)) out.normalized = normalized;
60
+ return out;
61
+ };
62
+
63
+ /**
64
+ * Chart: web component wrapper.
65
+ * Attributes: `series`, `axis`, `color`, `label`, `legend`, `brownout`, `brownout-level`, `empty`, `loading`, `error`, `retry`, `skeleton`, `zoomable`, `data-table`, `brush`, `brush-min`, `brush-max`, `brush-start`, `brush-end`.
66
+ *
67
+ * Colour precedence (R25-02): `series[].color` (safeColor-validated) >
68
+ * chart-wide `color` attribute > the `--chart-N` categorical ramp.
69
+ * Naming (R25-13): `label` > the axis JSON's label (top-level `label`/
70
+ * `title`/`name`, or `x.label`) > author `aria-label` is never overwritten.
71
+ * Legend (R25-14): auto-renders from `series[].label`; `legend="off"`
72
+ * (also "false"/"none"/"0") suppresses it for consumers with their own chrome.
73
+ * Brownout (R25-03): level ≥2 sheds legend, tooltip and the decorative
74
+ * gridlines; level ≥3 is marks-only (axis, note and brush shed too). The
75
+ * visually-hidden data table is NOT shed — it is the accessible alternative,
76
+ * not chrome.
77
+ */
78
+ class ContourChart extends ContourBase {
79
+ static get updateMode() { return "keyed"; }
80
+ static get observed() { return ["series", "axis", "color", "label", "legend", "brownout", "brownout-level", "empty", "loading", "error", "retry", "skeleton", "zoomable", "data-table", "brush", "brush-min", "brush-max", "brush-start", "brush-end", "note", "bucket-count", "limit-values", "title", "cache-key", "dir", "src"]; }
81
+ static get properties() { return { series: { attribute: "series" }, axis: { attribute: "axis" }, color: { attribute: "color" }, label: { attribute: "label" }, legend: { attribute: "legend" }, zoomable: { attribute: "zoomable", type: Boolean }, brush: { attribute: "brush", type: Boolean }, note: { attribute: "note" }, "bucket-count": { attribute: "bucket-count" }, "limit-values": { attribute: "limit-values" } }; }
82
+ // Bindable histogram contract (R18-68): consumer drives via bins/backgroundData/range (JS props, not attrs); push re-renders, read returns drawn bins.
83
+ get bins() {
84
+ const pushed = this._pushedBins;
85
+ return (pushed && pushed.length ? pushed : this._renderedBins || []).map((b) => ({ ...b }));
86
+ }
87
+ set bins(value) {
88
+ this._pushedBins = capBuffer(Array.isArray(value) ? value.map(normalizeChartBin).filter(Boolean) : []);
89
+ this.requestRender();
90
+ }
91
+ get backgroundData() {
92
+ const pushed = this._pushedBackground;
93
+ return (pushed && pushed.length ? pushed : this._renderedBackground || []).map((b) => ({ ...b }));
94
+ }
95
+ set backgroundData(value) {
96
+ this._pushedBackground = Array.isArray(value) ? value.map(normalizeChartBin).filter(Boolean) : [];
97
+ this.requestRender();
98
+ }
99
+ // `range` is JS property, not attr write: chart observes brush/start/end; setter calling setAttribute would re-enter render (wc-contract). Override consumed by render, never reflected back.
100
+ _showsBrush() {
101
+ return this.hasAttribute("brush") || this._rangeOverride !== undefined;
102
+ }
103
+ get range() {
104
+ const override = this._rangeOverride;
105
+ if (override !== undefined) return override ? override.slice() : null;
106
+ if (!this.hasAttribute("brush")) return null;
107
+ const start = parseFloat(this.getAttribute("brush-start"));
108
+ const end = parseFloat(this.getAttribute("brush-end"));
109
+ return Number.isFinite(start) && Number.isFinite(end) ? [start, end] : null;
110
+ }
111
+ set range(value) {
112
+ if (value == null) {
113
+ this._rangeOverride = null;
114
+ this.requestRender();
115
+ return;
116
+ }
117
+ const pair = Array.isArray(value) ? value : [value, value];
118
+ const start = Number(pair[0]);
119
+ const end = Number(pair[1]);
120
+ if (!Number.isFinite(start) || !Number.isFinite(end)) return;
121
+ this._rangeOverride = [start, end];
122
+ this.requestRender();
123
+ }
124
+ _axisLabel() {
125
+ const raw = this.getAttribute("axis");
126
+ if (!raw) return "";
127
+ try {
128
+ const parsed = JSON.parse(raw);
129
+ if (parsed && typeof parsed === "object") {
130
+ // R25-13: top-level label/title/name names chart; x.label = category axis title (next fallback); y.label = value axis title (rendered by _renderValueAxis).
131
+ const x = parsed.x;
132
+ return parsed.label || parsed.title || parsed.name
133
+ || (x && typeof x === "object" && (x.label || x.title || x.name)) || "";
134
+ }
135
+ return String(parsed);
136
+ } catch (e) { return raw; }
137
+ }
138
+ // R25-02: one colour decision for marks AND legend swatches (never disagree). Precedence: series.color > chart color attr > categorical ramp (wrapped at 8). safeColor guards injection.
139
+ _seriesColor(s, i) {
140
+ const own = safeColor(s && typeof s === "object" ? s.color : "");
141
+ if (own) return own;
142
+ const wide = safeColor(this.getAttribute("color"));
143
+ if (wide) return wide;
144
+ return "var(--chart-" + ((i % 12) + 1) + ")";
145
+ }
146
+ // R25-14: legend opt-out. Presence-with-value flags follow the sparkline
147
+ // convention (F-FC11): "off"/"false"/"none"/"0" all mean off.
148
+ _legendOff() {
149
+ const v = (this.getAttribute("legend") || "").trim().toLowerCase();
150
+ return v === "off" || v === "false" || v === "none" || v === "0";
151
+ }
152
+ // Chart brownout shed: chrome (gridlines) at level ≥2; marks-only at ≥3 (axis, note, brush). Legend/tooltip shed at build sites.
153
+ _applyBrownout() {
154
+ const chrome = this.shed("chrome", 2);
155
+ const marksOnly = this.shed("marks", 3);
156
+ const plot = this.querySelector(".c-chart__plot");
157
+ if (plot) plot.style.backgroundImage = chrome ? "none" : "";
158
+ const axis = this.querySelector(".c-chart__axis");
159
+ if (axis) axis.style.display = marksOnly ? "none" : "";
160
+ const note = this.querySelector(".c-chart__note");
161
+ if (note) note.style.display = marksOnly ? "none" : "";
162
+ const brush = this.querySelector("contour-brush");
163
+ if (brush) brush.style.display = marksOnly ? "none" : "";
164
+ }
165
+ _axisConfig() {
166
+ const raw = this.getAttribute("axis");
167
+ if (!raw) return null;
168
+ try {
169
+ const parsed = JSON.parse(raw);
170
+ return (parsed && typeof parsed === "object") ? parsed : null;
171
+ } catch (e) { return null; }
172
+ }
173
+ _valueDomain() {
174
+ const series = this.getAttribute("series");
175
+ if (!series) return null;
176
+ try {
177
+ const parsed = JSON.parse(series);
178
+ let min = Infinity, max = -Infinity;
179
+ let zeroBaseline = false;
180
+ (Array.isArray(parsed) ? parsed : []).forEach((s) => {
181
+ if (s && (s.type === "bar" || s.type === "histogram" || s.type === "stacked")) zeroBaseline = true;
182
+ if (s && Array.isArray(s.values)) s.values.forEach((v) => {
183
+ const n = Number(v);
184
+ if (Number.isFinite(n)) { if (n < min) min = n; if (n > max) max = n; }
185
+ });
186
+ });
187
+ if (zeroBaseline && Number.isFinite(min) && Number.isFinite(max)) {
188
+ min = Math.min(0, min);
189
+ max = Math.max(0, max);
190
+ }
191
+ return Number.isFinite(min) && Number.isFinite(max) ? [min, max] : null;
192
+ } catch (e) { return null; }
193
+ }
194
+ _renderValueAxis() {
195
+ const ax = this.querySelector(".c-chart__axis");
196
+ if (!ax) return;
197
+ const cfg = this._axisConfig();
198
+ const y = cfg && cfg.y;
199
+ const domain = (y && y.domain) || this._valueDomain();
200
+ const oldX = this.querySelector(".c-chart__axis-x");
201
+ if (!domain) {
202
+ this.classList.remove("c-chart--value-axis");
203
+ ax.className = "c-chart__axis";
204
+ ax.textContent = this._axisLabel();
205
+ if (oldX) oldX.remove();
206
+ return;
207
+ }
208
+ this.classList.add("c-chart--value-axis");
209
+ ax.className = "c-chart__axis c-chart__axis--y";
210
+ const ticks = (y && y.ticks) || niceTicks(domain[0], domain[1], 5);
211
+ const format = (y && y.format) || ((v) => String(v));
212
+ ax.textContent = "";
213
+ // Per-axis titles: y.label titles value axis; category label (top-level
214
+ // or x.label) rides its own row under the plot.
215
+ const title = (text, which) => {
216
+ const span = document.createElement("span");
217
+ span.className = "c-chart__tick";
218
+ span.dataset.axisTitle = which;
219
+ span.textContent = text;
220
+ return span;
221
+ };
222
+ // Ascending ticks + column-reverse: 0 sits on the baseline, max at the top.
223
+ ticks.forEach((t) => {
224
+ const span = document.createElement("span");
225
+ span.className = "c-chart__tick";
226
+ span.textContent = typeof format === "function" ? format(t) : String(t);
227
+ ax.appendChild(span);
228
+ });
229
+ if (y && typeof y === "object" && (y.label || y.title || y.name)) ax.appendChild(title(y.label || y.title || y.name, "y"));
230
+ const catLabel = this._axisLabel();
231
+ let xax = oldX;
232
+ if (catLabel) {
233
+ if (!xax) { xax = document.createElement("div"); xax.className = "c-chart__axis-x"; this.appendChild(xax); }
234
+ xax.textContent = catLabel;
235
+ } else if (xax) {
236
+ xax.remove();
237
+ }
238
+ this.style.setProperty("--chart-ticks", String(ticks.length));
239
+ }
240
+ _renderLegend() {
241
+ const series = this.getAttribute("series");
242
+ let legend = this.querySelector(".c-chart__legend");
243
+ // R25-14 opt-out and R25-03 shed both remove the legend outright, so a level change or attribute write re-renders it back in.
244
+ if (!series || this._legendOff() || this.shed("legend", 2)) { if (legend) legend.remove(); return; }
245
+ try {
246
+ const parsed = JSON.parse(series);
247
+ // Keep the ORIGINAL series index: the swatch must wear the same ramp stop as the mark; filtering used to shift every legend item's colour after an unlabelled series.
248
+ const labelled = (Array.isArray(parsed) ? parsed : []).map((s, i) => ({ s, i })).filter((p) => p.s && p.s.label);
249
+ if (!labelled.length) { if (legend) legend.remove(); return; }
250
+ if (!legend) { legend = document.createElement("div"); legend.className = "c-chart__legend"; this.appendChild(legend); }
251
+ legend.textContent = "";
252
+ labelled.forEach(({ s, i }) => {
253
+ const item = document.createElement("span");
254
+ item.className = "c-chart__legend-item";
255
+ const swatch = document.createElement("span");
256
+ swatch.className = "c-chart__legend-swatch";
257
+ swatch.style.setProperty("--c", this._seriesColor(s, i));
258
+ // R31-53: carry the series index and style so the swatch draws the
259
+ // same dash the line carries (a solid square beside a dashed line is
260
+ // a mismatch). CSS renders a dashed sample for data-style="line".
261
+ swatch.dataset.series = String((i % 12) + 1);
262
+ swatch.dataset.style = s.style || "line";
263
+ item.appendChild(swatch);
264
+ item.appendChild(document.createTextNode(s.label));
265
+ legend.appendChild(item);
266
+ });
267
+ } catch (e) { /* ignore */ }
268
+ }
269
+ render() {
270
+ this.classList.add("c-chart");
271
+ // A chart with brush handles has focusable descendants, which role="img" forbids (an img is a leaf). A named group exposes the marks and keeps the controls reachable; the data table remains the alternative.
272
+ if (!this.hasAttribute("role")) this.setAttribute("role", "group");
273
+ if (!this.hasAttribute("aria-roledescription")) this.setAttribute("aria-roledescription", "chart");
274
+ // R25-13: `label` names the chart, with the axis label as the fallback. An author's own aria-label is never overwritten; an aria-label WE wrote is refreshed when the name changes (tracked by its last value, so a later author edit is detected and left alone). An empty name writes nothing — the old code set aria-label="" for an axis JSON with only per-axis labels.
275
+ const name = this.getAttribute("label") || this._axisLabel();
276
+ const currentAria = this.getAttribute("aria-label");
277
+ if (name && (currentAria === null || currentAria === this._lastAutoAria)) {
278
+ this.setAttribute("aria-label", name);
279
+ this._lastAutoAria = name;
280
+ }
281
+ if (this.hasAttribute("loading")) {
282
+ this.setAttribute("aria-busy", "true");
283
+ const plot = this.ensure(".c-chart__plot", () => { const el = document.createElement("div"); el.className = "c-chart__plot"; return el; });
284
+ plot.innerHTML = "";
285
+ const loading = document.createElement("div");
286
+ loading.className = "c-chart__loading";
287
+ loading.textContent = this.getAttribute("loading") || "Loading…";
288
+ loading.style.display = "grid";
289
+ loading.style.placeItems = "center";
290
+ loading.style.height = "100%";
291
+ loading.style.color = "var(--color-text-muted)";
292
+ plot.appendChild(loading);
293
+ const axis = this.getAttribute("axis");
294
+ if (axis) {
295
+ const ax = this.ensure(".c-chart__axis", () => { const el = document.createElement("div"); el.className = "c-chart__axis"; return el; });
296
+ ax.textContent = this._axisLabel();
297
+ }
298
+ return;
299
+ } else {
300
+ this.removeAttribute("aria-busy");
301
+ }
302
+ if (this.hasAttribute("error")) {
303
+ const plot = this.ensure(".c-chart__plot", () => { const el = document.createElement("div"); el.className = "c-chart__plot"; return el; });
304
+ plot.innerHTML = "";
305
+ const err = document.createElement("div");
306
+ err.className = "c-chart__error";
307
+ err.textContent = this.getAttribute("error") || "Error";
308
+ err.style.display = "grid";
309
+ err.style.placeItems = "center";
310
+ err.style.height = "100%";
311
+ err.style.color = "var(--color-danger, var(--color-text))";
312
+ if (this.hasAttribute("retry")) {
313
+ const btn = document.createElement("button");
314
+ btn.className = "c-btn c-btn--ghost c-btn--sm";
315
+ btn.type = "button";
316
+ btn.textContent = this.getAttribute("retry") || "Retry";
317
+ btn.dataset.action = "retry";
318
+ btn.classList.add("u-mbs-sm");
319
+ err.appendChild(btn);
320
+ }
321
+ plot.appendChild(err);
322
+ const axis = this.getAttribute("axis");
323
+ if (axis) {
324
+ const ax = this.ensure(".c-chart__axis", () => { const el = document.createElement("div"); el.className = "c-chart__axis"; return el; });
325
+ ax.textContent = this._axisLabel();
326
+ }
327
+ return;
328
+ }
329
+ if (this.hasAttribute("skeleton")) {
330
+ const plot = this.ensure(".c-chart__plot", () => { const el = document.createElement("div"); el.className = "c-chart__plot"; return el; });
331
+ plot.innerHTML = "";
332
+ const count = Math.min(5, Math.max(1, parseInt(this.getAttribute("skeleton") || "3", 10) || 3));
333
+ for (let i = 0; i < count; i++) {
334
+ const sk = document.createElement("div");
335
+ sk.className = "c-skeleton";
336
+ sk.style.display = "block";
337
+ sk.style.inlineSize = "100%";
338
+ sk.style.blockSize = "0.6rem";
339
+ sk.classList.add("u-mbe-2xs");
340
+ plot.appendChild(sk);
341
+ }
342
+ const axis = this.getAttribute("axis");
343
+ if (axis) {
344
+ const ax = this.ensure(".c-chart__axis", () => { const el = document.createElement("div"); el.className = "c-chart__axis"; return el; });
345
+ ax.textContent = this._axisLabel();
346
+ }
347
+ return;
348
+ }
349
+ const axis = this.getAttribute("axis");
350
+ if (axis) {
351
+ const ax = this.ensure(".c-chart__axis", () => { const el = document.createElement("div"); el.className = "c-chart__axis"; return el; });
352
+ ax.textContent = this._axisLabel();
353
+ } else {
354
+ const ax = this.querySelector(".c-chart__axis");
355
+ if (ax) ax.remove();
356
+ }
357
+ // Value axis: when `axis` is {y:{domain,ticks,format}} (or the series carries values), print the ticks and publish --chart-ticks.
358
+ this._renderValueAxis();
359
+ // Legend from series[].label, so a chart with named series is readable without the consumer hand-building a legend.
360
+ this._renderLegend();
361
+ // A bindable histogram may be driven by `bins` alone: a binder pushes the engine's distribution rather than serialising a `series` attribute, so with no series declared the pushed bins become the series this render reads.
362
+ let series = this.getAttribute("series");
363
+ if (!series && this._pushedBins && this._pushedBins.length) {
364
+ series = JSON.stringify([{ type: "histogram", bins: this._pushedBins }]);
365
+ }
366
+ if (series) {
367
+ const parsed = parseArrayAttr(this, "series", warnBadJson);
368
+ if (parsed.length === 0) { renderEmpty(this, "chart"); return; }
369
+ const plot = this.ensure(".c-chart__plot", () => { const el = document.createElement("div"); el.className = "c-chart__plot"; return el; });
370
+ // R24-88: keep the plot alive across renders so patchChildren can reuse its marks instead of the base dropping and rebuilding them.
371
+ this.keepNode(plot);
372
+ const frag = document.createDocumentFragment();
373
+ // Structured series: an item may carry `values` plus a `type` ("donut" | "histogram" | "line") instead of a pre-computed `d` path, or carry pre-binned `bins` instead of raw `values`. The helpers in svg.mjs turn those into geometry so a consumer does not have to hand-compute arc or bar math.
374
+ const hasStructured = parsed.some((s) => s && (Array.isArray(s.values) || Array.isArray(s.bins)));
375
+ if (hasStructured) {
376
+ // Each structured render rebuilds the published bins from the series it draws; without this a chart switched from a histogram to a line keeps reporting the old distribution.
377
+ this._renderedBins = [];
378
+ this._renderedBackground = [];
379
+ parsed.forEach((s, i) => {
380
+ // R25-02: series[].color > chart `color` > --chart-N ramp.
381
+ const color = this._seriesColor(s, i);
382
+ if (s.type === "donut") {
383
+ const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
384
+ svg.setAttribute("viewBox", "0 0 200 200");
385
+ svg.style.cssText = "position: absolute; inset: 0; width: 100%; height: 100%";
386
+ // Donut slices are focusable marks (roving tabindex + arrows), so ring must not be aria-hidden (nested-interactive violation); ring is a group permitting focusable slices.
387
+ svg.setAttribute("role", "group");
388
+ svg.setAttribute("aria-label", s.label || "Donut chart");
389
+ donutSlices(s.values).forEach((sl, si) => {
390
+ const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
391
+ // R28-11 (CD-02): a donut slice is a FILLED annular sector, not a stroked line. The old c-chart__line class gave fill:none and one colour per slice (monochrome outlines). c-donut__slice carries fill:var(--c); each slice takes its own ramp colour, like contour-donut.
392
+ path.setAttribute("class", "c-donut__slice");
393
+ path.setAttribute("data-series", String(i + 1));
394
+ path.dataset.index = String(si);
395
+ path.style.setProperty("--c", safeColor("var(--chart-" + ((si % 12) + 1) + ")") || "var(--chart-1)");
396
+ path.setAttribute("d", sl.path);
397
+ path.setAttribute("data-title", String(s.values[si]));
398
+ path.setAttribute("aria-label", labelText(this, "series", "Series") + " " + (i + 1) + ": " + String(s.values[si]));
399
+ // R28-36: a clickable, focusable mark is a button, and the ring is ONE tab stop — the same contract the bar and point marks carry (and contour-donut after R28-35).
400
+ path.setAttribute("role", "button");
401
+ path.setAttribute("tabindex", si === 0 ? "0" : "-1");
402
+ svg.appendChild(path);
403
+ });
404
+ frag.appendChild(svg);
405
+ } else if (s.type === "bar") {
406
+ // A bar series is the histogram's geometry without bucketing: one rect per value in value order. The histogram branch bins into equal-width buckets and plots counts (a different question), so `bar` cannot be folded into it. `barRects()` already normalises values against the plot box; the only difference is that `plotVals` is the series itself.
407
+ const vals = Array.isArray(s.values) ? s.values : [];
408
+ const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
409
+ svg.setAttribute("viewBox", "0 0 300 120");
410
+ svg.setAttribute("preserveAspectRatio", "none");
411
+ svg.style.cssText = "position: absolute; inset: 0; width: 100%; height: 100%";
412
+ barRects(vals).forEach((r, ri) => {
413
+ // R31-50: a missing value is not a zero bar — skip it.
414
+ if (r.missing) return;
415
+ const rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
416
+ rect.setAttribute("class", "c-chart__bar");
417
+ rect.setAttribute("data-series", String(i + 1));
418
+ rect.style.setProperty("--c", color);
419
+ rect.setAttribute("x", r.x);
420
+ rect.setAttribute("y", r.y);
421
+ rect.setAttribute("width", r.width);
422
+ rect.setAttribute("height", r.height);
423
+ rect.setAttribute("data-title", String(vals[ri]));
424
+ rect.setAttribute("aria-label", labelText(this, "series", "Series") + " " + (i + 1) + ": " + String(vals[ri]));
425
+ rect.setAttribute("tabindex", "0");
426
+ rect.setAttribute("role", "button");
427
+ rect.dataset.index = String(ri);
428
+ svg.appendChild(rect);
429
+ });
430
+ frag.appendChild(svg);
431
+ } else if (s.type === "histogram") {
432
+ // R16-23: bucket-count / limit-values controls. `limit-values` truncates the input array; `bucket-count` bins values into equal-width buckets and renders per-bucket counts as bars. R18-68: a series may arrive pre-binned (`bins`) or be pushed whole by a binder; either way boundaries are published as `chart.bins` so a consumer can read them back.
433
+ let vals = Array.isArray(s.values) ? s.values.slice() : [];
434
+ const limitValues = parseInt(this.getAttribute("limit-values") || "0", 10);
435
+ if (limitValues > 0) vals = vals.slice(0, limitValues);
436
+ const bucketCount = parseInt(this.getAttribute("bucket-count") || "0", 10);
437
+ const pushedBins = this._pushedBins && this._pushedBins.length ? this._pushedBins : null;
438
+ const declaredBins = Array.isArray(s.bins) ? s.bins.map(normalizeChartBin).filter(Boolean) : null;
439
+ let bins = pushedBins || (declaredBins && declaredBins.length ? declaredBins : null);
440
+ let plotVals = vals;
441
+ if (!bins && bucketCount > 0 && vals.length) {
442
+ const nums = vals.map((v) => Number(v) || 0);
443
+ const min = Math.min.apply(null, nums);
444
+ const max = Math.max.apply(null, nums);
445
+ const range = max - min || 1;
446
+ const width = range / bucketCount;
447
+ const buckets = new Array(bucketCount).fill(0);
448
+ nums.forEach((v) => {
449
+ const bi = Math.min(bucketCount - 1, Math.floor((v - min) / width));
450
+ buckets[bi] += 1;
451
+ });
452
+ plotVals = buckets;
453
+ bins = buckets.map((count, bi) => ({ x0: min + bi * width, x1: min + (bi + 1) * width, count }));
454
+ }
455
+ if (bins) plotVals = bins.map((b) => b.count);
456
+ // Raw values with no bucket count have no boundaries to publish: those bars are counts at index positions, not a distribution over a domain, so `bins` stays empty and the consumer is told there is nothing to map a range onto.
457
+ this._renderedBins = bins ? bins.slice() : [];
458
+ const pushedBackground = this._pushedBackground && this._pushedBackground.length ? this._pushedBackground : null;
459
+ const declaredBackground = Array.isArray(s.background) ? s.background.map(normalizeChartBin).filter(Boolean) : null;
460
+ const background = pushedBackground || (declaredBackground && declaredBackground.length ? declaredBackground : []);
461
+ this._renderedBackground = background.slice();
462
+ const backgroundVals = background.map((b) => Number(b.count) || 0);
463
+ let sharedMax = 1;
464
+ if (backgroundVals.length) {
465
+ plotVals.concat(backgroundVals).forEach((v) => { const n = Number(v) || 0; if (n > sharedMax) sharedMax = n; });
466
+ }
467
+ const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
468
+ svg.setAttribute("viewBox", "0 0 300 120");
469
+ svg.setAttribute("preserveAspectRatio", "none");
470
+ svg.style.cssText = "position: absolute; inset: 0; width: 100%; height: 100%";
471
+ if (backgroundVals.length) {
472
+ // Context bars: unfiltered distribution backdrop, not focusable/announced — avoids doubling tab sequence.
473
+ barRects(backgroundVals, { max: sharedMax }).forEach((r) => {
474
+ const rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
475
+ rect.setAttribute("class", "c-chart__bar");
476
+ rect.setAttribute("data-context", "");
477
+ rect.setAttribute("aria-hidden", "true");
478
+ rect.style.setProperty("--c", color);
479
+ rect.setAttribute("x", r.x);
480
+ rect.setAttribute("y", r.y);
481
+ rect.setAttribute("width", r.width);
482
+ rect.setAttribute("height", r.height);
483
+ svg.appendChild(rect);
484
+ });
485
+ }
486
+ barRects(plotVals, backgroundVals.length ? { max: sharedMax } : undefined).forEach((r, ri) => {
487
+ if (r.missing) return; // R31-50: missing is not a zero bar
488
+ const rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
489
+ rect.setAttribute("class", "c-chart__bar");
490
+ rect.setAttribute("data-series", String(i + 1));
491
+ rect.style.setProperty("--c", color);
492
+ rect.setAttribute("x", r.x);
493
+ rect.setAttribute("y", r.y);
494
+ rect.setAttribute("width", r.width);
495
+ rect.setAttribute("height", r.height);
496
+ const markValue = bins ? bins[ri].count : (Array.isArray(s.values) ? s.values[ri] : ri);
497
+ rect.setAttribute("data-title", String(markValue));
498
+ rect.setAttribute("aria-label", labelText(this, "series", "Series") + " " + (i + 1) + ": " + String(markValue));
499
+ rect.setAttribute("tabindex", "0");
500
+ rect.setAttribute("role", "button");
501
+ rect.dataset.index = String(ri);
502
+ svg.appendChild(rect);
503
+ });
504
+ frag.appendChild(svg);
505
+ } else if (s.type === "scatter") {
506
+ const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
507
+ svg.setAttribute("viewBox", "0 0 300 120");
508
+ svg.setAttribute("preserveAspectRatio", "none");
509
+ svg.style.cssText = "position: absolute; inset: 0; width: 100%; height: 100%";
510
+ // R31-50: a missing point (null/undefined entry) is skipped,
511
+ // not plotted at the origin.
512
+ const pts = (Array.isArray(s.values) ? s.values : []).filter((v) => !isMissing(v)).map((v) => {
513
+ if (Array.isArray(v)) return { x: Number(v[0]) || 0, y: Number(v[1]) || 0 };
514
+ return { x: Number(v && v.x) || 0, y: Number(v && v.y) || 0 };
515
+ });
516
+ const xs = pts.map((p) => p.x);
517
+ const ys = pts.map((p) => p.y);
518
+ const minX = xs.length ? Math.min.apply(null, xs) : 0;
519
+ const maxX = xs.length ? Math.max.apply(null, xs) : 1;
520
+ const minY = ys.length ? Math.min.apply(null, ys) : 0;
521
+ const maxY = ys.length ? Math.max.apply(null, ys) : 1;
522
+ const xRange = (maxX - minX) || 1;
523
+ const yRange = (maxY - minY) || 1;
524
+ // R31-56: a scatter of 10k points minted 10k focusable
525
+ // circles (212 ms). Beyond the cap, decimate evenly and emit
526
+ // contour:cap so a consumer knows the render is sampled.
527
+ const SCATTER_CAP = 2000;
528
+ let drawPts = pts;
529
+ if (pts.length > SCATTER_CAP) {
530
+ const stride = Math.ceil(pts.length / SCATTER_CAP);
531
+ drawPts = pts.filter((_, idx) => idx % stride === 0);
532
+ this.dispatchEvent(new CustomEvent("contour:cap", { bubbles: true, composed: true, detail: { series: i + 1, total: pts.length, shown: drawPts.length } }));
533
+ }
534
+ drawPts.forEach((p, pi) => {
535
+ const circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
536
+ circle.setAttribute("class", "c-chart__point");
537
+ circle.setAttribute("data-series", String(i + 1));
538
+ circle.setAttribute("data-index", String(pi));
539
+ circle.style.setProperty("--c", color);
540
+ const cx = ((p.x - minX) / xRange) * 300;
541
+ const cy = 120 - ((p.y - minY) / yRange) * 120;
542
+ circle.setAttribute("cx", cx.toFixed(2));
543
+ circle.setAttribute("cy", cy.toFixed(2));
544
+ circle.setAttribute("r", "3");
545
+ circle.setAttribute("tabindex", pi === 0 ? "0" : "-1");
546
+ circle.setAttribute("role", "button");
547
+ circle.setAttribute("data-title", p.x + ", " + p.y);
548
+ circle.setAttribute("aria-label", labelText(this, "series", "Series") + " " + (i + 1) + ": " + p.x + ", " + p.y);
549
+ svg.appendChild(circle);
550
+ });
551
+ if (drawPts.length !== pts.length) {
552
+ svg.setAttribute("data-decimated", String(pts.length));
553
+ svg.setAttribute("aria-label", labelText(this, "series", "Series") + " " + (i + 1) + " (" + drawPts.length + " " + labelText(this, "of", "of") + " " + pts.length + ")");
554
+ }
555
+ frag.appendChild(svg);
556
+ } else {
557
+ const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
558
+ svg.setAttribute("viewBox", "0 0 300 120");
559
+ svg.setAttribute("preserveAspectRatio", "none");
560
+ svg.style.cssText = "position: absolute; inset: 0; width: 100%; height: 100%";
561
+ const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
562
+ path.setAttribute("class", "c-chart__line");
563
+ path.setAttribute("data-series", String(i + 1));
564
+ path.style.setProperty("--c", color);
565
+ path.setAttribute("d", smoothPath(s.values));
566
+ svg.appendChild(path);
567
+ // Point markers for keyboard/click access. R31-50: skip
568
+ // missing values and use the same finite domain as the path,
569
+ // so a marker never sits at an implied zero.
570
+ const finiteVals = s.values.filter((v) => !isMissing(v)).map(Number).filter((v) => Number.isFinite(v));
571
+ const mx = finiteVals.reduce((a, b) => (b > a ? b : a), finiteVals.length ? finiteVals[0] : 1);
572
+ const mn = finiteVals.reduce((a, b) => (b < a ? b : a), finiteVals.length ? finiteVals[0] : 0);
573
+ const rng = (mx - mn) || 1;
574
+ const vlen = s.values.length || 1;
575
+ let firstMark = true;
576
+ s.values.forEach((v, pi) => {
577
+ if (isMissing(v)) return;
578
+ const num = Number(v);
579
+ if (!Number.isFinite(num)) return;
580
+ const cx = (pi / Math.max(1, vlen - 1)) * 300;
581
+ const cy = 120 - ((num - mn) / rng) * 120;
582
+ const circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
583
+ circle.setAttribute("class", "c-chart__point");
584
+ circle.setAttribute("data-series", String(i + 1));
585
+ circle.setAttribute("data-index", String(pi));
586
+ circle.style.setProperty("--c", color);
587
+ circle.setAttribute("cx", String(cx));
588
+ circle.setAttribute("cy", String(cy));
589
+ circle.setAttribute("r", "3");
590
+ circle.setAttribute("tabindex", firstMark ? "0" : "-1");
591
+ firstMark = false;
592
+ circle.setAttribute("role", "button");
593
+ circle.setAttribute("data-title", String(v));
594
+ circle.setAttribute("aria-label", labelText(this, "series", "Series") + " " + (i + 1) + ": " + String(v));
595
+ svg.appendChild(circle);
596
+ });
597
+ frag.appendChild(svg);
598
+ }
599
+ });
600
+ } else {
601
+ const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
602
+ svg.setAttribute("viewBox", "0 0 300 120");
603
+ svg.setAttribute("preserveAspectRatio", "none");
604
+ svg.style.cssText = "position: absolute; inset: 0; width: 100%; height: 100%";
605
+ svg.setAttribute("aria-hidden", "true");
606
+ parsed.forEach((s, i) => {
607
+ const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
608
+ path.setAttribute("class", "c-chart__line");
609
+ path.setAttribute("data-series", String(i + 1));
610
+ // R25-02: the legacy precomputed-`d` branch used to ignore colour entirely — even the chart-wide attribute. It now shares the structured branch's precedence.
611
+ path.style.setProperty("--c", this._seriesColor(s, i));
612
+ path.setAttribute("d", (typeof s.d === "string" && s.d.trim()) ? s.d : (Array.isArray(s.values) ? smoothPath(s.values) : ""));
613
+ svg.appendChild(path);
614
+ });
615
+ frag.appendChild(svg);
616
+ }
617
+ patchChildren(plot, frag);
618
+ // Styled tooltip element (positioned via --chart-tip-*). R25-03: shed at level ≥2. The hover/focus handlers re-query the tip per event and no-op when absent, so removing it is safe.
619
+ if (this.shed("tooltip", 2)) {
620
+ const oldTip = this.querySelector(".c-chart__tooltip");
621
+ if (oldTip) oldTip.remove();
622
+ } else {
623
+ const tip = this.ensure(".c-chart__tooltip", () => { const el = document.createElement("div"); el.className = "c-chart__tooltip"; el.setAttribute("role", "tooltip"); el.setAttribute("hidden", ""); el.id = contourId("chart-tip"); return el; });
624
+ tip.setAttribute("hidden", "");
625
+ }
626
+ // Accessible data-table fallback (R12-18, R31-167): rendered BY DEFAULT when
627
+ // the series carries values, so the no-JS/AT path exists without the author
628
+ // opting in. `data-table="none"` (also off/false/0) is the explicit opt-out.
629
+ // The graphic remains the primary presentation; the table is visually hidden.
630
+ const dataTableRaw = (this.getAttribute("data-table") || "").trim().toLowerCase();
631
+ const dataTableOff = dataTableRaw === "none" || dataTableRaw === "off" || dataTableRaw === "false" || dataTableRaw === "0";
632
+ const hasTabularValues = parsed.some((s) => Array.isArray(s && s.values) && s.values.length);
633
+ if (!dataTableOff && hasTabularValues) {
634
+ let table = this.querySelector(".c-chart__data-table");
635
+ if (!table) {
636
+ table = document.createElement("table");
637
+ table.className = "c-chart__data-table visually-hidden";
638
+ this.appendChild(table);
639
+ }
640
+ table.innerHTML = "";
641
+ // A caption names the table: a reader who lands on it hears what it holds before the first cell, not "table, 5 rows, 3 columns".
642
+ const title = this.getAttribute("title") || this.getAttribute("aria-label") || labelText(this, "chart-data", "Chart data");
643
+ const cap = document.createElement("caption");
644
+ cap.textContent = title;
645
+ table.appendChild(cap);
646
+ const thead = document.createElement("thead");
647
+ const hr = document.createElement("tr");
648
+ const h = document.createElement("th");
649
+ h.setAttribute("scope", "col");
650
+ h.textContent = labelText(this, "series", "Series");
651
+ hr.appendChild(h);
652
+ const maxLen = parsed.reduce((m, s) => Math.max(m, Array.isArray(s.values) ? s.values.length : (Array.isArray(s) ? s.length : 0)), 0);
653
+ for (let i = 0; i < maxLen; i++) {
654
+ const th = document.createElement("th");
655
+ th.setAttribute("scope", "col");
656
+ th.textContent = labelText(this, "value", "Value") + " " + (i + 1);
657
+ hr.appendChild(th);
658
+ }
659
+ thead.appendChild(hr);
660
+ table.appendChild(thead);
661
+ const tbody = document.createElement("tbody");
662
+ parsed.forEach((s, si) => {
663
+ const vals = Array.isArray(s.values) ? s.values : (Array.isArray(s) ? s : []);
664
+ const tr = document.createElement("tr");
665
+ const td0 = document.createElement("th");
666
+ td0.setAttribute("scope", "row");
667
+ td0.textContent = s.label || ("Series " + (si + 1));
668
+ tr.appendChild(td0);
669
+ for (let i = 0; i < maxLen; i++) {
670
+ const td = document.createElement("td");
671
+ // R31-50: a missing value is an empty cell, not "0"/"NaN".
672
+ td.textContent = isMissing(vals[i]) ? "" : String(vals[i]);
673
+ tr.appendChild(td);
674
+ }
675
+ tbody.appendChild(tr);
676
+ });
677
+ table.appendChild(tbody);
678
+ } else {
679
+ const old = this.querySelector(".c-chart__data-table");
680
+ if (old) old.remove();
681
+ }
682
+ if (this._showsBrush()) {
683
+ const brush = this.ensure("contour-brush", () => document.createElement("contour-brush"));
684
+ // A binned histogram's brush is in data units, so the track defaults to the bins' own extent; a consumer that supplies brush-min/brush-max still wins. Without this a binder's `range` would be positioned against a 0–100 track it never set.
685
+ const drawnBins = this._renderedBins || [];
686
+ const trackMin = this.getAttribute("brush-min") || (drawnBins.length ? String(drawnBins[0].x0) : "0");
687
+ const trackMax = this.getAttribute("brush-max") || (drawnBins.length ? String(drawnBins[drawnBins.length - 1].x1) : "100");
688
+ const override = Array.isArray(this._rangeOverride) ? this._rangeOverride : null;
689
+ // `range = null` means "no constraint": the brush keeps its affordance and shows the full track, rather than vanishing.
690
+ const cleared = this._rangeOverride === null;
691
+ brush.setAttribute("min", trackMin);
692
+ brush.setAttribute("max", trackMax);
693
+ brush.setAttribute("start", override ? String(override[0]) : cleared ? trackMin : (this.getAttribute("brush-start") || trackMin));
694
+ brush.setAttribute("end", override ? String(override[1]) : cleared ? trackMax : (this.getAttribute("brush-end") || trackMax));
695
+ const plotEl = this.querySelector(".c-chart__plot");
696
+ if (brush.previousElementSibling !== plotEl) this.insertBefore(brush, plotEl ? plotEl.nextSibling : null);
697
+ } else {
698
+ const brush = this.querySelector("contour-brush");
699
+ if (brush) brush.remove();
700
+ }
701
+ const note = this.getAttribute("note");
702
+ let noteEl = this.querySelector(".c-chart__note");
703
+ if (note) {
704
+ if (!noteEl) { noteEl = document.createElement("div"); noteEl.className = "c-chart__note"; this.appendChild(noteEl); }
705
+ noteEl.textContent = note;
706
+ } else if (noteEl) {
707
+ noteEl.remove();
708
+ }
709
+ } else {
710
+ // No series: nothing is drawn, so nothing is published either. A consumer reading `bins` must see the empty state, not the last one.
711
+ this._renderedBins = [];
712
+ this._renderedBackground = [];
713
+ const plot = this.ensure(".c-chart__plot", () => { const el = document.createElement("div"); el.className = "c-chart__plot"; return el; });
714
+ plot.innerHTML = "";
715
+ const empty = document.createElement("div");
716
+ empty.className = "c-chart__empty";
717
+ empty.textContent = this.getAttribute("empty") || "No data";
718
+ empty.style.display = "grid";
719
+ empty.style.placeItems = "center";
720
+ empty.style.height = "100%";
721
+ empty.style.color = "var(--color-text-muted)";
722
+ plot.appendChild(empty);
723
+ const note = this.getAttribute("note");
724
+ let noteEl2 = this.querySelector(".c-chart__note");
725
+ if (note) {
726
+ if (!noteEl2) { noteEl2 = document.createElement("div"); noteEl2.className = "c-chart__note"; this.appendChild(noteEl2); }
727
+ noteEl2.textContent = note;
728
+ } else if (noteEl2) {
729
+ noteEl2.remove();
730
+ }
731
+ }
732
+ // R25-03: gridlines/axis/note/brush shed last, over whatever the branches above built. The loading/error/skeleton returns are state chrome, not data chrome, and deliberately skip the shed table.
733
+ this._applyBrownout();
734
+ }
735
+ enhance() {
736
+ if (this._wiredChart) return;
737
+ this._wiredChart = true;
738
+ // R24-25: wire retry button so clicking it re-fetches.
739
+ wireStates(this);
740
+ // Series toggle responding to legend (F-10): hide/show series when a legend item is toggled. The legend may be a sibling of the chart, so listen on the shared parent (which catches both a child and a sibling legend) and match by key, data-key, or the item's index.
741
+ const legendHost = this.parentElement || document;
742
+ const onLegendToggle = (e) => {
743
+ const key = e && e.detail && (e.detail.key != null ? e.detail.key : e.detail.label);
744
+ const index = e && e.detail && e.detail.index;
745
+ const pressed = e && e.detail && e.detail.pressed;
746
+ if (key == null && index == null) return;
747
+ const nodes = this.querySelectorAll("[data-series]");
748
+ nodes.forEach((n) => {
749
+ const s = n.getAttribute("data-series");
750
+ const match = String(s) === String(key)
751
+ || n.getAttribute("data-key") === String(key)
752
+ || (index != null && String(s) === String(index + 1));
753
+ if (match) n.style.display = pressed === false ? "none" : "";
754
+ });
755
+ };
756
+ legendHost.addEventListener("contour:legend-toggle", onLegendToggle);
757
+ onDispose(this, () => legendHost.removeEventListener("contour:legend-toggle", onLegendToggle));
758
+ this.addEventListener("contour:brush-end", (e) => {
759
+ if (!this._showsBrush() || !e.target || !e.target.matches("contour-brush")) return;
760
+ // The brush moves its own attributes, so a chart already driven through the `range` property records the new pair here; an author-driven chart stays attribute-only and reads the brush itself. `undefined` is the switch: once the property has been written, drags keep it current.
761
+ if (this._rangeOverride !== undefined && e.detail && Array.isArray(e.detail.range)) {
762
+ this._rangeOverride = e.detail.range.slice();
763
+ }
764
+ this.dispatchEvent(new CustomEvent("contour:select", {
765
+ bubbles: true,
766
+ composed: true,
767
+ detail: e.detail,
768
+ }));
769
+ });
770
+ // Zoom/pan (F-10 deferred): wheel to zoom, drag to pan, double-click to reset.
771
+ if (this.hasAttribute("zoomable")) {
772
+ let zoom = 1, panX = 0, panY = 0;
773
+ const plot = this.querySelector(".c-chart__plot");
774
+ const apply = () => {
775
+ if (!plot) return;
776
+ plot.style.transform = `translate(${panX}px, ${panY}px) scale(${zoom})`;
777
+ plot.style.transformOrigin = "center center";
778
+ };
779
+ this.addEventListener("wheel", (e) => {
780
+ e.preventDefault();
781
+ const factor = e.deltaY < 0 ? 1.1 : 0.9;
782
+ zoom = Math.min(5, Math.max(0.5, zoom * factor));
783
+ apply();
784
+ }, { passive: false });
785
+ let dragging = false, startX = 0, startY = 0, startPanX = 0, startPanY = 0;
786
+ this.addEventListener("mousedown", (e) => {
787
+ if (e.button !== 0) return;
788
+ dragging = true; startX = e.clientX; startY = e.clientY; startPanX = panX; startPanY = panY;
789
+ this.style.cursor = "grabbing";
790
+ });
791
+ const onMove = (e) => {
792
+ if (!dragging) return;
793
+ panX = startPanX + (e.clientX - startX);
794
+ panY = startPanY + (e.clientY - startY);
795
+ apply();
796
+ };
797
+ const onUp = () => { if (dragging) { dragging = false; this.style.cursor = ""; } };
798
+ window.addEventListener("mousemove", onMove);
799
+ window.addEventListener("mouseup", onUp);
800
+ onDispose(this, () => { window.removeEventListener("mousemove", onMove); window.removeEventListener("mouseup", onUp); });
801
+ this.addEventListener("dblclick", () => { zoom = 1; panX = 0; panY = 0; apply(); });
802
+ }
803
+ // Tooltip: show on hover of a mark. Cache the plot rect across mousemove events: it only changes on resize/scroll, so re-measuring on every pixel is wasted layout work (B3-22). A ResizeObserver invalidates the cache; scroll invalidates via the same observer-less fallback (recompute).
804
+ let plotRectCache = null;
805
+ let plotRectObserver = null;
806
+ const invalidatePlotRect = () => { plotRectCache = null; };
807
+ const showTip = (e) => {
808
+ const plot = this.querySelector(".c-chart__plot");
809
+ const tip = this.querySelector(".c-chart__tooltip");
810
+ if (!plot || !tip) return;
811
+ const mark = e.target && e.target.closest ? e.target.closest(".c-chart__bar, .c-chart__point, .c-chart__line, .c-donut__slice") : null;
812
+ if (!mark || !plot.contains(mark)) { tip.setAttribute("hidden", ""); return; }
813
+ const title = mark.getAttribute("data-title") || mark.getAttribute("title");
814
+ if (title) tip.textContent = title;
815
+ if (!plotRectCache) {
816
+ plotRectCache = plot.getBoundingClientRect();
817
+ if (!plotRectObserver && typeof ResizeObserver === "function") {
818
+ plotRectObserver = new ResizeObserver(invalidatePlotRect);
819
+ plotRectObserver.observe(plot);
820
+ }
821
+ }
822
+ const rect = plotRectCache;
823
+ const mr = mark.getBoundingClientRect();
824
+ const x = mr.left - rect.left + mr.width / 2;
825
+ const y = mr.top - rect.top;
826
+ plot.style.setProperty("--chart-tip-inline-start", x + "px");
827
+ plot.style.setProperty("--chart-tip-block-start", y + "px");
828
+ tip.removeAttribute("hidden");
829
+ };
830
+ const hideTip = () => {
831
+ const tip = this.querySelector(".c-chart__tooltip");
832
+ if (tip) tip.setAttribute("hidden", "");
833
+ };
834
+ // Host-delegated so the handlers survive re-renders (rule 12).
835
+ this.addEventListener("mousemove", showTip);
836
+ this.addEventListener("mouseleave", hideTip);
837
+ onDispose(this, () => { if (plotRectObserver) { plotRectObserver.disconnect(); plotRectObserver = null; } });
838
+ // Keyboard path (BY-39): the marks already carry roving tabindex, so a focused mark shows the same tooltip as a hovered one.
839
+ this.addEventListener("focusin", (e) => {
840
+ const mark = e.target && e.target.closest ? e.target.closest(".c-chart__bar, .c-chart__point, .c-chart__line, .c-donut__slice") : null;
841
+ if (mark && this.contains(mark)) {
842
+ showTip({ target: mark });
843
+ const tip = this.querySelector(".c-chart__tooltip");
844
+ if (tip && tip.id) mark.setAttribute("aria-describedby", tip.id);
845
+ }
846
+ });
847
+ this.addEventListener("focusout", (e) => {
848
+ const mark = e.target && e.target.closest ? e.target.closest(".c-chart__bar, .c-chart__point, .c-chart__line, .c-donut__slice") : null;
849
+ if (mark && this.contains(mark)) mark.removeAttribute("aria-describedby");
850
+ if (!this.contains(e.relatedTarget)) hideTip();
851
+ });
852
+ // Per-bar keyboard/click handling for histogram bars (host-delegated).
853
+ this.addEventListener("click", (e) => {
854
+ const plot2 = this.querySelector(".c-chart__plot");
855
+ if (!plot2) return;
856
+ const bar = e.target && e.target.closest ? e.target.closest(".c-chart__bar") : null;
857
+ if (bar && plot2.contains(bar)) {
858
+ const series = parseInt(bar.getAttribute("data-series") || "1", 10);
859
+ const index = parseInt(bar.dataset.index || "0", 10);
860
+ this.dispatchEvent(new CustomEvent("contour:select", { bubbles: true, composed: true, detail: { series, index } }));
861
+ return;
862
+ }
863
+ const point = e.target && e.target.closest ? e.target.closest(".c-chart__point") : null;
864
+ if (point && plot2.contains(point)) {
865
+ const series = parseInt(point.getAttribute("data-series") || "1", 10);
866
+ const index = parseInt(point.dataset.index || "0", 10);
867
+ this.dispatchEvent(new CustomEvent("contour:select", { bubbles: true, composed: true, detail: { series, index } }));
868
+ return;
869
+ }
870
+ // R28-36: a structured donut slice is a mark like a bar or a point.
871
+ const slice = e.target && e.target.closest ? e.target.closest(".c-donut__slice") : null;
872
+ if (slice && plot2.contains(slice)) {
873
+ const series = parseInt(slice.getAttribute("data-series") || "1", 10);
874
+ const index = parseInt(slice.dataset.index || "0", 10);
875
+ this.dispatchEvent(new CustomEvent("contour:select", { bubbles: true, composed: true, detail: { series, index, value: slice.getAttribute("data-title") || slice.getAttribute("title") } }));
876
+ }
877
+ });
878
+ this.addEventListener("keydown", (e) => {
879
+ const plot2 = this.querySelector(".c-chart__plot");
880
+ if (!plot2) return;
881
+ const bar = e.target && e.target.closest ? e.target.closest(".c-chart__bar") : null;
882
+ if (bar && plot2.contains(bar)) {
883
+ if (e.key === "Enter" || e.key === " ") {
884
+ e.preventDefault();
885
+ const series = parseInt(bar.getAttribute("data-series") || "1", 10);
886
+ const index = parseInt(bar.dataset.index || "0", 10);
887
+ this.dispatchEvent(new CustomEvent("contour:select", { bubbles: true, composed: true, detail: { series, index } }));
888
+ }
889
+ // R24-87: roving arrow traversal for bars (parity with points/slices).
890
+ const seriesAttr = bar.getAttribute("data-series");
891
+ if (seriesAttr) {
892
+ const series = parseInt(seriesAttr, 10);
893
+ const bars = Array.from(plot2.querySelectorAll('.c-chart__bar[data-series="' + series + '"]'));
894
+ const idx = bars.indexOf(bar);
895
+ if (idx >= 0) {
896
+ navKey(e, bars, {
897
+ wrap: false,
898
+ rtl: isRtl(this),
899
+ onNavigate: (i) => bars.forEach((b, j) => b.setAttribute("tabindex", j === i ? "0" : "-1")),
900
+ onKey: () => {}
901
+ });
902
+ }
903
+ }
904
+ return;
905
+ }
906
+ // R28-36: roving arrow traversal across a donut series' slices,
907
+ // Enter/Space activation — the point-mark contract, slice-shaped.
908
+ const slice = e.target && e.target.closest ? e.target.closest(".c-donut__slice") : null;
909
+ if (slice && plot2.contains(slice)) {
910
+ const series = parseInt(slice.getAttribute("data-series") || "1", 10);
911
+ if (e.key === "Enter" || e.key === " ") {
912
+ e.preventDefault();
913
+ const index = parseInt(slice.dataset.index || "0", 10);
914
+ this.dispatchEvent(new CustomEvent("contour:select", { bubbles: true, composed: true, detail: { series, index, value: slice.getAttribute("data-title") || slice.getAttribute("title") } }));
915
+ return;
916
+ }
917
+ const slices = Array.from(plot2.querySelectorAll('.c-donut__slice[data-series="' + series + '"]'));
918
+ navKey(e, slices, {
919
+ wrap: false,
920
+ rtl: isRtl(this),
921
+ onNavigate: (i) => slices.forEach((p, j) => p.setAttribute("tabindex", j === i ? "0" : "-1")),
922
+ onKey: () => {}
923
+ });
924
+ return;
925
+ }
926
+ const point = e.target && e.target.closest ? e.target.closest(".c-chart__point") : null;
927
+ if (!point || !plot2.contains(point)) return;
928
+ const series = parseInt(point.getAttribute("data-series") || "1", 10);
929
+ const points = Array.from(plot2.querySelectorAll('.c-chart__point[data-series="' + series + '"]'));
930
+ const idx = points.indexOf(point);
931
+ if (e.key === "Enter" || e.key === " ") {
932
+ e.preventDefault();
933
+ const index = parseInt(point.dataset.index || "0", 10);
934
+ this.dispatchEvent(new CustomEvent("contour:select", { bubbles: true, composed: true, detail: { series, index } }));
935
+ return;
936
+ }
937
+ navKey(e, points, {
938
+ wrap: false,
939
+ rtl: isRtl(this),
940
+ onNavigate: (i) => points.forEach((p, j) => p.setAttribute("tabindex", j === i ? "0" : "-1")),
941
+ onKey: () => {}
942
+ });
943
+ });
944
+ this.addEventListener("keydown", (e) => {
945
+ // Only the host itself drives series switching; marks handle their own
946
+ // keys (B3-03). Without this gate one Enter fires contour:select twice.
947
+ if (e.target !== this) return;
948
+ let seriesCount = 0;
949
+ try { seriesCount = JSON.parse(this.getAttribute("series") || "[]").length; } catch (e) { seriesCount = 0; }
950
+ if (seriesCount === 0) return;
951
+ if (this._activeSeries === undefined) this._activeSeries = 0;
952
+ let next = this._activeSeries;
953
+ const rtl = (this.getAttribute("dir") || document.documentElement.getAttribute("dir") || "").toLowerCase() === "rtl";
954
+ if (e.key === "ArrowRight") next = rtl ? Math.max(this._activeSeries - 1, 0) : Math.min(this._activeSeries + 1, seriesCount - 1);
955
+ else if (e.key === "ArrowLeft") next = rtl ? Math.min(this._activeSeries + 1, seriesCount - 1) : Math.max(this._activeSeries - 1, 0);
956
+ else if (e.key === "ArrowDown") next = Math.min(this._activeSeries + 1, seriesCount - 1);
957
+ else if (e.key === "ArrowUp") next = Math.max(this._activeSeries - 1, 0);
958
+ else if (e.key === "Home") next = 0;
959
+ else if (e.key === "End") next = seriesCount - 1;
960
+ else if (e.key === "Enter" || e.key === " ") {
961
+ e.preventDefault();
962
+ this.dispatchEvent(new CustomEvent("contour:select", { bubbles: true, composed: true, detail: { series: this._activeSeries } }));
963
+ return;
964
+ } else return;
965
+ if (next !== this._activeSeries) {
966
+ e.preventDefault();
967
+ this._activeSeries = next;
968
+ this.dispatchEvent(new CustomEvent("contour:select", { bubbles: true, composed: true, detail: { series: next } }));
969
+ }
970
+ });
971
+ // Cross-filter contract (R16-16): clear-all resets chart brush state.
972
+ this.addEventListener("contour:clear-all", () => {
973
+ if (this.hasAttribute("brush")) {
974
+ this.removeAttribute("brush");
975
+ this.dispatchEvent(new CustomEvent("contour:filter-change", { bubbles: true, composed: true, detail: { source: "chart", filter: { brush: null } } }));
976
+ this.requestRender();
977
+ }
978
+ });
979
+ }
980
+ }
981
+ define("contour-chart", ContourChart);
982
+ /**
983
+ * Comparison: web component wrapper.
984
+ * Attributes: `divider`, `value`, `before`, `after`.
985
+ */
986
+ class ContourComparison extends ContourBase {
987
+ static get observed() { return ["divider", "value", "before", "after", "before-src", "after-src"]; }
988
+ static get properties() { return { divider: { attribute: "divider" }, value: { attribute: "value" }, before: { attribute: "before" }, after: { attribute: "after" }, beforeSrc: { attribute: "before-src" }, afterSrc: { attribute: "after-src" } }; }
989
+ render() {
990
+ this.classList.add("c-comparison");
991
+ this.setAttribute("role", "group");
992
+ // R24-36: avoid clobbering author-provided aria-label; track auto-set value
993
+ const name = "Comparison";
994
+ const currentAria = this.getAttribute("aria-label");
995
+ if (currentAria === null || currentAria === this._lastAutoAria) {
996
+ this.setAttribute("aria-label", name);
997
+ this._lastAutoAria = name;
998
+ }
999
+ if (!this.style.blockSize) this.style.blockSize = "12rem";
1000
+ // R24-34: sync the divider's aria-valuenow from the value attribute at creation. The old code hardcoded "50", so a `value="70"` host rendered a divider that announced 50 — the aria value was frozen at the markup and only `setPos` (drag/keyboard) ever moved it.
1001
+ const v0 = this.getAttribute("value");
1002
+ this.style.setProperty("--comparison-pos", (v0 ?? "50") + "%");
1003
+ // Ensure two panes exist.
1004
+ const beforeLabel = this.getAttribute("before") ?? "Before";
1005
+ const afterLabel = this.getAttribute("after") ?? "After";
1006
+ if (!this.querySelector(".c-comparison__pane--before")) {
1007
+ const p = document.createElement("div");
1008
+ p.className = "c-comparison__pane c-comparison__pane--before";
1009
+ this.appendChild(p);
1010
+ }
1011
+ if (!this.querySelector(".c-comparison__pane:not(.c-comparison__pane--before)")) {
1012
+ const p = document.createElement("div");
1013
+ p.className = "c-comparison__pane";
1014
+ this.appendChild(p);
1015
+ }
1016
+ // R31-09: labels are overlays, never the pane's text content. An authored
1017
+ // image or map surface must survive every render.
1018
+ const media = (pane, src, side) => {
1019
+ if (!pane) return;
1020
+ let img = pane.querySelector(".c-comparison__media--" + side);
1021
+ if (src) {
1022
+ if (!img) { img = document.createElement("img"); img.className = "c-comparison__media c-comparison__media--" + side; img.alt = ""; pane.prepend(img); }
1023
+ if (img.getAttribute("src") !== src) img.setAttribute("src", src);
1024
+ } else if (img) {
1025
+ img.remove();
1026
+ }
1027
+ };
1028
+ media(this.querySelector(".c-comparison__pane--before"), this.getAttribute("before-src"), "before");
1029
+ media(this.querySelector(".c-comparison__pane:not(.c-comparison__pane--before)"), this.getAttribute("after-src"), "after");
1030
+ // Labels (CARTO-inspired): overlay the before/after text on each pane.
1031
+ const beforePane = this.querySelector(".c-comparison__pane--before");
1032
+ if (beforePane) {
1033
+ let lbl = beforePane.querySelector(".c-comparison__label--before");
1034
+ if (!lbl) { lbl = document.createElement("span"); lbl.className = "c-comparison__label c-comparison__label--before"; beforePane.appendChild(lbl); }
1035
+ lbl.textContent = beforeLabel;
1036
+ }
1037
+ const afterPane = this.querySelector(".c-comparison__pane:not(.c-comparison__pane--before)");
1038
+ if (afterPane) {
1039
+ let lbl = afterPane.querySelector(".c-comparison__label--after");
1040
+ if (!lbl) { lbl = document.createElement("span"); lbl.className = "c-comparison__label c-comparison__label--after"; afterPane.appendChild(lbl); }
1041
+ lbl.textContent = afterLabel;
1042
+ }
1043
+ const divider = this.getAttribute("divider");
1044
+ if (divider !== null) {
1045
+ const d = this.ensure(".c-comparison__divider", () => { const el = document.createElement("div"); el.className = "c-comparison__divider"; el.setAttribute("role", "slider"); el.setAttribute("aria-orientation", "vertical"); el.setAttribute("aria-valuemin", "0"); el.setAttribute("aria-valuemax", "100"); el.setAttribute("aria-valuenow", String(Math.round(parseFloat(v0 ?? "50")))); el.setAttribute("aria-label", labelText(this, "comparison-divider", "Comparison divider")); el.setAttribute("tabindex", "0"); return el; });
1046
+ if (divider) d.textContent = divider;
1047
+ } else {
1048
+ const d = this.querySelector(".c-comparison__divider");
1049
+ if (d) d.remove();
1050
+ }
1051
+ }
1052
+ enhance() {
1053
+ if (this._wiredComparison) return;
1054
+ this._wiredComparison = true;
1055
+ const divider = () => this.querySelector(".c-comparison__divider");
1056
+ const setPos = (pct) => {
1057
+ const clamped = Math.max(0, Math.min(100, pct));
1058
+ this.style.setProperty("--comparison-pos", clamped + "%");
1059
+ this.setAttribute("value", String(Math.round(clamped)));
1060
+ const divider = this.querySelector(".c-comparison__divider");
1061
+ if (divider) divider.setAttribute("aria-valuenow", String(Math.round(clamped)));
1062
+ this.dispatchEvent(new CustomEvent("contour:drag", { bubbles: true, composed: true, detail: { value: clamped } }));
1063
+ };
1064
+ let dragging = false;
1065
+ const onMove = (e) => {
1066
+ if (!dragging) return;
1067
+ const rect = this.getBoundingClientRect();
1068
+ const pct = ((e.clientX - rect.left) / rect.width) * 100;
1069
+ setPos(pct);
1070
+ };
1071
+ const onUp = () => { dragging = false; window.removeEventListener("mousemove", onMove); window.removeEventListener("mouseup", onUp); };
1072
+ onDispose(this, () => { dragging = false; window.removeEventListener("mousemove", onMove); window.removeEventListener("mouseup", onUp); });
1073
+ // R24-34: touch support. The old `mousedown`+`mousemove` on `window` never fires on touch — the sheet's `touch-action: none` cancelled scroll and the divider was dead on touch. Pointer events cover mouse and touch in one API, and `setPointerCapture` keeps move/up following the finger when it leaves the divider (same pattern the brush uses).
1074
+ this.addEventListener("pointerdown", (e) => {
1075
+ const d = divider();
1076
+ if (!d || !d.contains(e.target)) return;
1077
+ dragging = true;
1078
+ try { this.setPointerCapture(e.pointerId); } catch (err) {}
1079
+ const rect = this.getBoundingClientRect();
1080
+ const pct = ((e.clientX - rect.left) / rect.width) * 100;
1081
+ setPos(pct);
1082
+ e.preventDefault();
1083
+ });
1084
+ this.addEventListener("pointermove", (e) => {
1085
+ if (!dragging) return;
1086
+ const rect = this.getBoundingClientRect();
1087
+ const pct = ((e.clientX - rect.left) / rect.width) * 100;
1088
+ setPos(pct);
1089
+ });
1090
+ const onPointerUp = () => { dragging = false; try { this.releasePointerCapture && this.releasePointerCapture(this._comparisonPointer); } catch (err) {} this._comparisonPointer = null; };
1091
+ this.addEventListener("pointerup", onPointerUp);
1092
+ this.addEventListener("pointercancel", onPointerUp);
1093
+ onDispose(this, () => { this.removeEventListener("pointerup", onPointerUp); this.removeEventListener("pointercancel", onPointerUp); });
1094
+ this.addEventListener("keydown", (e) => {
1095
+ const d = divider();
1096
+ if (!d || document.activeElement !== d) return;
1097
+ const cur = parseFloat(this.style.getPropertyValue("--comparison-pos")) || 50;
1098
+ // R24-34: Home/End were absent — a slider without them is an incomplete
1099
+ // keyboard contract. ArrowLeft/Right step, Home jumps to 0, End to 100.
1100
+ if (e.key === "ArrowLeft") { e.preventDefault(); setPos(cur - 5); }
1101
+ else if (e.key === "ArrowRight") { e.preventDefault(); setPos(cur + 5); }
1102
+ else if (e.key === "Home") { e.preventDefault(); setPos(0); }
1103
+ else if (e.key === "End") { e.preventDefault(); setPos(100); }
1104
+ });
1105
+ }
1106
+ }
1107
+ define("contour-comparison", ContourComparison);
1108
+ /**
1109
+ * Streaming Chart: web component wrapper.
1110
+ * Attributes: `line`, `dot`, `values`, `interval`, `pause`, `empty`, `loading`, `error`, `retry`, `src`, `lazy`, `refresh`, `timeout`, `skeleton`.
1111
+ *
1112
+ * Two data doors (R25-09, decision D7):
1113
+ * `line` — the low-level door: a precomputed SVG path `d` in the
1114
+ * element's own viewBox `0 0 300 192` (x 0–300 left→right,
1115
+ * y 0–192 top→bottom). `dot` is "x,y" in the same space.
1116
+ * `values` — a JSON numeric array (attribute, `src` payload field, or the
1117
+ * `values` JS property) the element turns into its own path via
1118
+ * svg.mjs `smoothPath`/`polylinePoints` with {width:300,
1119
+ * height:192}: x spread across the box, y normalised to the
1120
+ * series' own min/max. The live dot defaults to the last point.
1121
+ * Precedence: `line` (authored or remote) wins when both are set; within the
1122
+ * values door, a pushed property > authored attribute > remote payload. An
1123
+ * explicit `dot` always wins over the computed last point. Pause/a11y is
1124
+ * R24-31; buffer/decimation is R24-88 — neither is touched here.
1125
+ */
1126
+ class ContourStreamingChart extends ContourBase {
1127
+ static get updateMode() { return "keyed"; }
1128
+ static get observed() { return ["line", "dot", "values", "interval", "pause", "brownout", "brownout-level", "empty", "loading", "error", "retry", "src", "lazy", "refresh", "timeout", "skeleton", "cache-key", "no-cache"]; }
1129
+ static get properties() { return { line: { attribute: "line" }, dot: { attribute: "dot" }, interval: { attribute: "interval", type: Number }, pause: { attribute: "pause", type: Boolean }, src: { attribute: "src" } }; }
1130
+ // R25-09: the property door. A push re-renders; a read returns the numbers
1131
+ // actually drawn (empty when the `line` door is winning).
1132
+ get values() { return (this._valuesNums || []).slice(); }
1133
+ set values(v) {
1134
+ this._pushedValues = capBuffer(Array.isArray(v) ? v.map(Number).filter(Number.isFinite) : []);
1135
+ this.requestRender();
1136
+ }
1137
+ render() {
1138
+ this.classList.add("c-streaming-chart");
1139
+ // R24-31: role=group (not img) since the chart has an interactive
1140
+ // pause/play button.
1141
+ if (!this.hasAttribute("role")) this.setAttribute("role", "group");
1142
+ if (!this.hasAttribute("aria-label")) this.setAttribute("aria-label", labelText(this, "streaming-chart", "Streaming chart"));
1143
+ if (!this.hasAttribute("tabindex")) this.setAttribute("tabindex", "0");
1144
+ // R24-31: visible pause/play button with aria-pressed. The button is a generated node rebuilt every render, so re-apply the paused state from the host on every render instead of baking it into creation.
1145
+ let btn = this.querySelector(".c-streaming-chart__pause");
1146
+ if (!btn) {
1147
+ btn = document.createElement("button");
1148
+ btn.className = "c-btn c-btn--icon c-btn--ghost c-btn--sm c-streaming-chart__pause";
1149
+ btn.type = "button";
1150
+ this.appendChild(btn);
1151
+ }
1152
+ const paused = !!this._streamPausedByUser;
1153
+ btn.setAttribute("aria-pressed", String(paused));
1154
+ btn.setAttribute("aria-label", paused ? labelText(this, "play-stream", "Play stream") : labelText(this, "pause-stream", "Pause stream"));
1155
+ setHTML(btn, paused
1156
+ ? '<svg aria-hidden="true" viewBox="0 0 24 24"><use href="#i-play" /></svg>'
1157
+ : '<svg aria-hidden="true" viewBox="0 0 24 24"><use href="#i-pause" /></svg>');
1158
+ wireStates(this);
1159
+ loadRemote(this, ["line", "values"]);
1160
+ if (renderStates(this, "streaming-chart")) return;
1161
+ let line = remoteData(this, "line");
1162
+ let dot = remoteData(this, "dot");
1163
+ // R25-09: values door — `line` wins; pushed property > attribute/remote; geometry via svg.mjs helpers in 300×192 viewBox.
1164
+ let nums = this._pushedValues;
1165
+ if (nums === undefined) {
1166
+ nums = null;
1167
+ const raw = remoteData(this, "values");
1168
+ if (raw) {
1169
+ try {
1170
+ const p = JSON.parse(raw);
1171
+ if (Array.isArray(p)) nums = p;
1172
+ else warnBadJson(this, "values", new Error("not an array"));
1173
+ } catch (e) { warnBadJson(this, "values", e); }
1174
+ }
1175
+ }
1176
+ nums = capBuffer((nums || []).map(Number).filter(Number.isFinite));
1177
+ this._valuesNums = [];
1178
+ if (!line && nums.length > 1) {
1179
+ line = smoothPath(nums, { width: 300, height: 192 });
1180
+ this._valuesNums = nums;
1181
+ if (!dot) {
1182
+ const pts = polylinePoints(nums, { width: 300, height: 192 }).split(" ");
1183
+ dot = pts[pts.length - 1];
1184
+ }
1185
+ }
1186
+ if (!line) {
1187
+ // R31-43: remove only the chart's own plot SVG, never the pause button's
1188
+ // icon (`this.querySelector("svg")` matched the button's 24×24 glyph).
1189
+ const svg = this.querySelector(":scope > .c-streaming-chart__plot");
1190
+ if (svg) svg.remove();
1191
+ renderEmpty(this, "streaming-chart");
1192
+ return;
1193
+ }
1194
+ if (line) {
1195
+ // R31-43: the plot is its own direct-child SVG. The pause button carries
1196
+ // its own icon SVG; painting the line into that (the old `querySelector
1197
+ // ("svg")`) drew the series inside the 24×24 control.
1198
+ let svg = this.querySelector(":scope > .c-streaming-chart__plot");
1199
+ if (!svg) {
1200
+ svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
1201
+ svg.setAttribute("class", "c-streaming-chart__plot");
1202
+ svg.setAttribute("viewBox", "0 0 300 192");
1203
+ svg.setAttribute("aria-hidden", "true");
1204
+ this.appendChild(svg);
1205
+ }
1206
+ let path = svg.querySelector(".c-streaming-chart__line");
1207
+ if (!path) {
1208
+ path = document.createElementNS("http://www.w3.org/2000/svg", "path");
1209
+ path.setAttribute("class", "c-streaming-chart__line");
1210
+ svg.appendChild(path);
1211
+ }
1212
+ path.setAttribute("d", line);
1213
+ // Live dot is decorative motion (shed ≥2); line is mark (survives all levels); pause control never shed (WCAG 2.2.2).
1214
+ if (dot && !this.shed("dot", 2)) {
1215
+ let circle = svg.querySelector(".c-streaming-chart__live-dot");
1216
+ if (!circle) {
1217
+ circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
1218
+ circle.setAttribute("class", "c-streaming-chart__live-dot");
1219
+ circle.setAttribute("r", "4");
1220
+ svg.appendChild(circle);
1221
+ }
1222
+ const parts = dot.split(/[ ,]+/);
1223
+ if (parts.length >= 2) {
1224
+ circle.setAttribute("cx", parts[0]);
1225
+ circle.setAttribute("cy", parts[1]);
1226
+ }
1227
+ } else {
1228
+ const circle = svg.querySelector(".c-streaming-chart__live-dot");
1229
+ if (circle) circle.remove();
1230
+ }
1231
+ }
1232
+ }
1233
+ enhance() {
1234
+ // Stream cadence (BY-40). The layer had no timer at all — the literal gap the row names — so the chart gets its own `interval` loop rather than a second clock inside the loader. Each tick emits contour:tick and, when a src is present, re-validates through the loader's own cache path (remoteInvalidate + requestRender — the two steps the loader's refresh tick performs), so the shared cache and abort semantics stay the loader's. The loader's `refresh` attribute is NOT written here: an attribute a component writes to itself must never be observed, or the write re-enters render (measured by the gate). `pause` stops the loop; `interval` growth is clamped to the loader's own 1 s floor so the two cannot disagree.
1235
+ const sync = () => {
1236
+ const seconds = parseFloat(this.getAttribute("interval") || "");
1237
+ const want = Number.isFinite(seconds) && seconds > 0 && !this.hasAttribute("pause") && !this._streamPausedByUser && this._viewVisible !== false;
1238
+ if (want === this._streamRunning) return;
1239
+ this._streamRunning = want;
1240
+ if (this._streamTimer !== undefined) { clearInterval(this._streamTimer); this._streamTimer = undefined; }
1241
+ this.dispatchEvent(new CustomEvent("contour:stream-state", { detail: { running: want }, bubbles: true, composed: true }));
1242
+ if (!want) return;
1243
+ this._streamTimer = setInterval(() => {
1244
+ if (!this.isConnected || this.hasAttribute("pause")) return;
1245
+ this._streamFrame += 1;
1246
+ this.dispatchEvent(new CustomEvent("contour:tick", { detail: { frame: this._streamFrame }, bubbles: true, composed: true }));
1247
+ const src = this.getAttribute("src");
1248
+ if (src) { remoteInvalidate(src); this.requestRender(); }
1249
+ }, Math.max(1000, seconds * 1000));
1250
+ };
1251
+ sync();
1252
+ // Pause the stream while the chart is off-screen (B3-22): watchViewport is the loader's own visibility seam, so the stream reuses it instead of a second observer. A user-set `pause` still wins; this only adds an off-screen pause on top.
1253
+ if (!this._wiredStreamView) {
1254
+ this._wiredStreamView = true;
1255
+ this._viewVisible = true;
1256
+ watchViewport(this);
1257
+ this.addEventListener("contour:view-enter", () => { this._viewVisible = true; sync(); });
1258
+ this.addEventListener("contour:view-leave", () => { this._viewVisible = false; sync(); });
1259
+ }
1260
+ // The base re-runs enhance after every render, so interval/pause changes
1261
+ // are picked up by sync() above; the timer itself is owned exactly once.
1262
+ if (this._wiredStream) return;
1263
+ this._wiredStream = true;
1264
+ this._streamFrame = 0;
1265
+ onDispose(this, () => { if (this._streamTimer !== undefined) { clearInterval(this._streamTimer); this._streamTimer = undefined; } });
1266
+ // Keyboard: Space/Enter toggles pause (BY-08); internal flag prevents re-render re-entry.
1267
+ this._streamPausedByUser = false;
1268
+ // Delegate pause/play click on host: generated button dies on re-render; host listener survives (rule 12).
1269
+ this.addEventListener("click", (e) => {
1270
+ const target = e.target;
1271
+ const b = this.querySelector(".c-streaming-chart__pause");
1272
+ if (!b || (target !== b && !b.contains(target))) return;
1273
+ e.preventDefault();
1274
+ this._streamPausedByUser = !this._streamPausedByUser;
1275
+ b.setAttribute("aria-pressed", String(this._streamPausedByUser));
1276
+ b.setAttribute("aria-label", this._streamPausedByUser ? "Play stream" : "Pause stream");
1277
+ setHTML(b, this._streamPausedByUser
1278
+ ? '<svg aria-hidden="true" viewBox="0 0 24 24"><use href="#i-play" /></svg>'
1279
+ : '<svg aria-hidden="true" viewBox="0 0 24 24"><use href="#i-pause" /></svg>');
1280
+ if (this._streamPausedByUser) {
1281
+ this.setAttribute("data-user-paused", "");
1282
+ this.setAttribute("data-motion", "paused");
1283
+ } else {
1284
+ this.removeAttribute("data-user-paused");
1285
+ this.removeAttribute("data-motion");
1286
+ }
1287
+ sync();
1288
+ });
1289
+ this.addEventListener("keydown", (e) => {
1290
+ if (e.key === " " || e.key === "Enter") {
1291
+ e.preventDefault();
1292
+ this._streamPausedByUser = !this._streamPausedByUser;
1293
+ if (this._streamPausedByUser) {
1294
+ this.setAttribute("data-user-paused", "");
1295
+ this.setAttribute("data-motion", "paused");
1296
+ } else {
1297
+ this.removeAttribute("data-user-paused");
1298
+ this.removeAttribute("data-motion");
1299
+ }
1300
+ const btn = this.querySelector(".c-streaming-chart__pause");
1301
+ if (btn) {
1302
+ btn.setAttribute("aria-pressed", String(this._streamPausedByUser));
1303
+ btn.setAttribute("aria-label", this._streamPausedByUser ? "Play stream" : "Pause stream");
1304
+ }
1305
+ sync();
1306
+ }
1307
+ });
1308
+ }
1309
+ }
1310
+ define("contour-streaming-chart", ContourStreamingChart);
1311
+ // R31-129: a static reference rule (line or band) with a label, overlaid on a
1312
+ // chart. The consumer positions it (absolute) and sets value/direction/label;
1313
+ // the rule draws the mark and the label, never the data.
1314
+ class ContourReferenceRule extends ContourBase {
1315
+ static get observed() { return ["value", "direction", "label", "band"]; }
1316
+ static get properties() { return { value: { attribute: "value" }, direction: { attribute: "direction" }, label: { attribute: "label" }, band: { attribute: "band" } }; }
1317
+ render() {
1318
+ this.classList.add("c-reference-rule");
1319
+ const dir = this.getAttribute("direction") || "horizontal";
1320
+ this.setAttribute("data-direction", dir);
1321
+ let line = this.querySelector(".c-reference-rule__line");
1322
+ if (!line) { line = document.createElement("div"); line.className = "c-reference-rule__line"; this.appendChild(line); }
1323
+ const band = this.getAttribute("band");
1324
+ if (band) this.setAttribute("data-band", band); else this.removeAttribute("data-band");
1325
+ const label = this.getAttribute("label");
1326
+ let lab = this.querySelector(".c-reference-rule__label");
1327
+ if (label) {
1328
+ if (!lab) { lab = document.createElement("span"); lab.className = "c-reference-rule__label"; this.appendChild(lab); }
1329
+ lab.textContent = label;
1330
+ } else if (lab) lab.remove();
1331
+ }
1332
+ }
1333
+ define("contour-reference-rule", ContourReferenceRule);