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
@@ -43,24 +43,40 @@
43
43
  abort belongs to the last host out, not the first — see `leaveRequest`.
44
44
  ========================================================================= */
45
45
 
46
- import { onDispose } from './core.mjs';
46
+ import { setHTML, onDispose } from './core.mjs';
47
47
 
48
48
  // Copy. A component overrides any of these through its own attribute, because a
49
- // legend and a table should not both say "No data" — but a default must exist,
50
- // because a state with no text is a state the reader cannot see.
51
49
  /** Fallback state copy used when remote data is unavailable. */
52
50
  export const STATE_FALLBACK = {
53
51
  empty: "No data",
52
+ chart: "No data",
53
+ contour: "No field",
54
+ dropdown: "No options",
54
55
  loading: "Loading…",
55
56
  error: "Could not load.",
56
57
  };
57
58
 
59
+ /**
60
+ * Resolve a state label for a host (R18-63). A consumer supplies a `labels`
61
+ * JSON attribute (e.g. `labels='{"loading":"Chargement…"}'`); it is merged over
62
+ * the English default, so a partial object localises only the keys it names.
63
+ * A malformed attribute is ignored rather than thrown — a bad label must not
64
+ * take the widget down. Returns the default when no override is present.
65
+ */
66
+ export function stateLabel(host, key) {
67
+ const fallback = STATE_FALLBACK[key] || key;
68
+ const raw = host && host.getAttribute ? host.getAttribute("labels") : null;
69
+ if (!raw) return fallback;
70
+ try {
71
+ const parsed = JSON.parse(raw);
72
+ if (parsed && typeof parsed === "object" && typeof parsed[key] === "string" && parsed[key]) return parsed[key];
73
+ } catch (e) { /* a malformed labels attribute is ignored, not fatal */ }
74
+ return fallback;
75
+ }
76
+
58
77
  // One in-flight request per URL, shared by every host that asked for it.
59
78
  const remoteInflight = new Map();
60
79
  // The last result per URL, so a re-mounted host paints instead of re-asking. A
61
- // refused URL is never cached: one blip must not black out a widget until reload.
62
- // Bounded, because a page that routes through a hundred tile URLs is not going to
63
- // re-ask the first ten, and an unbounded Map is a leak with a cache's vocabulary.
64
80
  const REMOTE_CACHE_MAX = 64;
65
81
  const remoteCache = new Map();
66
82
 
@@ -73,15 +89,9 @@ function setStatus(host, status) {
73
89
  host._remoteStatus = status;
74
90
  if (status !== "error") host._remoteError = null;
75
91
  // `aria-busy` is the platform's own word for "this region is mid-update", it is
76
- // not in OBSERVED, so writing it cannot re-enter this render, and it is cleared
77
- // the moment a request is not open.
78
92
  if (status === "loading") host.setAttribute("aria-busy", "true");
79
93
  else host.removeAttribute("aria-busy");
80
94
  // The same status drives the `:state(data-loading)` custom state (BY-32): a
81
- // consumer's CSS can select a mid-request host without an attribute round
82
- // trip. Loader hosts are not formAssociated, so the base mirrors internals
83
- // lazily (probed legal in the gate's Chromium); a host without internals or
84
- // without CustomStateSet simply keeps the attribute path.
85
95
  if (typeof host._setCustomState === "function") host._setCustomState("data-loading", status === "loading");
86
96
  }
87
97
 
@@ -137,21 +147,11 @@ export function loadRemote(host, fields) {
137
147
  return;
138
148
  }
139
149
  // A host below the fold must not compete with the forty above it for the same
140
- // connection. It reports `loading` while it waits, because that is what it is —
141
- // painting "No data" here would claim an empty dataset for data that has not
142
- // been asked for yet.
143
150
  if (!remoteVisible(host)) {
144
151
  setStatus(host, "loading");
145
152
  return;
146
153
  }
147
154
  // The shared cache is keyed by `cache-key` when the author names one,
148
- // otherwise by the URL itself. `no-cache` opts a host OUT of the shared
149
- // read: it always asks the network fresh, and the fresh bytes it received
150
- // are its own for this mount (the guard below re-reads `_remoteData`, so a
151
- // re-render must not fire a second request). The settle still writes the
152
- // fresh result to the shared cache — "don't reuse" and "don't store" are
153
- // different policies, and this is the former; `remoteInvalidate` gives the
154
- // page the latter.
155
155
  const noCache = host.hasAttribute("no-cache");
156
156
  const cacheKey = host.getAttribute("cache-key") || src;
157
157
  if (noCache) {
@@ -167,14 +167,11 @@ export function loadRemote(host, fields) {
167
167
  setStatus(host, "ready");
168
168
  return;
169
169
  }
170
+ if (host._remoteSrc === src && host._remoteStatus === "ready" && host._remoteData !== undefined) {
171
+ return;
172
+ }
170
173
  }
171
174
  // Already asked: a host still waiting, or one whose last ask settled in
172
- // error, must not re-ask on its own. The retry button (wireStates) and the
173
- // refresh timer are the only re-askers, and both clear `_remoteSrc` first —
174
- // without this guard, an errored host re-fetched on every settle's re-render,
175
- // so a permanent 404 looped forever painting `loading`, and a flaky endpoint
176
- // "recovered" to rows without the user ever clicking retry (both measured by
177
- // the state-contract arm in wc-contract, which is the first lane to mount src).
178
175
  if (host._remoteSrc === src && (host._remoteStatus === "loading" || host._remoteStatus === "error")) return; // already asked
179
176
 
180
177
  leaveRequest(host);
@@ -183,24 +180,17 @@ export function loadRemote(host, fields) {
183
180
 
184
181
  let entry = remoteInflight.get(src);
185
182
  if (!entry) {
186
- entry = { hosts: new Set(), controller: new AbortController(), cacheKey };
183
+ entry = { hosts: new Set(), controller: new AbortController(), cacheKey, cacheKeys: new Set() };
187
184
  remoteInflight.set(src, entry);
188
185
  // All three arguments: `host` carries the timeout attribute and owns the
189
- // disposer, `src` is the URL to ask, `entry` holds the shared controller.
190
- // Dropping `host` (as the call did between 8cde6ba and 566b85a) shifts
191
- // `entry` into its slot, so `host.getAttribute` runs against the URL
192
- // string and every fetch throws before it starts — caught by the
193
- // state-contract arm in wc-contract, which is the first lane to mount src.
194
186
  entry.promise = startFetch(host, src, entry).then(
195
187
  (data) => {
196
188
  if (remoteInflight.get(src) === entry) remoteInflight.delete(src);
197
189
  // The entry is keyed by URL, but a host that named a cache-key must be
198
- // able to paint from cache on a re-mount: the fresh result is filed
199
- // under both the URL and its named key, so the key is not a private
200
- // lane that only ever misses.
201
190
  cacheResult(src, data);
202
- const namedKey = entry.cacheKey;
203
- if (namedKey && namedKey !== src) cacheResult(namedKey, data);
191
+ for (const k of entry.cacheKeys) {
192
+ if (k && k !== src) cacheResult(k, data);
193
+ }
204
194
  for (const h of entry.hosts) {
205
195
  h._remoteData = data;
206
196
  h._remoteEntry = null;
@@ -228,11 +218,9 @@ export function loadRemote(host, fields) {
228
218
  });
229
219
  }
230
220
  entry.hosts.add(host);
221
+ if (!noCache && cacheKey) entry.cacheKeys.add(cacheKey);
231
222
  host._remoteEntry = entry;
232
223
  // Leaving the page is not failing the request; the host simply stops caring.
233
- // Registered once per mount, because `loadRemote` runs from `render()` and a
234
- // disposers list that grows with the render count is the leak this file exists
235
- // to stop. The flag is cleared inside the disposer, so a reconnect re-registers.
236
224
  if (!host._remoteDisposeRegistered) {
237
225
  host._remoteDisposeRegistered = true;
238
226
  onDispose(host, () => {
@@ -255,8 +243,6 @@ export function remoteInvalidate(srcOrKey) {
255
243
  }
256
244
 
257
245
  // `AbortSignal.timeout` is the platform's own deadline; where it is missing, the
258
- // same thing is a timer and an abort. Either way an unreachable internal tile
259
- // server cannot leave a widget in `loading` for the life of the page.
260
246
  function startFetch(host, src, entry) {
261
247
  const ms = parseInt(host.getAttribute("timeout") || "", 10);
262
248
  let timer = null;
@@ -272,14 +258,30 @@ function startFetch(host, src, entry) {
272
258
  }
273
259
  // The deadline belongs to the request, so the last host out already aborts it;
274
260
  // the timer is cleared on any settle so a cached answer costs nothing later.
275
- onDispose(host, () => { if (timer) clearTimeout(timer); });
261
+ // One disposer per host, not per request: `refresh` re-issues a request, and
262
+ // the old shape appended a closure to the host's teardown list on every one,
263
+ // retaining a timer id that had already fired until the next disconnect.
264
+ if (timer) {
265
+ host._remoteDeadline = timer;
266
+ if (!host._remoteDeadlineWired) {
267
+ host._remoteDeadlineWired = true;
268
+ onDispose(host, () => {
269
+ host._remoteDeadlineWired = false;
270
+ clearTimeout(host._remoteDeadline);
271
+ host._remoteDeadline = null;
272
+ });
273
+ }
274
+ }
275
+ const clearDeadline = () => {
276
+ if (!timer) return;
277
+ clearTimeout(timer);
278
+ if (host._remoteDeadline === timer) host._remoteDeadline = null;
279
+ };
276
280
 
277
281
  return fetch(src, { signal })
278
282
  .then((res) => {
279
- if (timer) clearTimeout(timer);
283
+ clearDeadline();
280
284
  // The status line is the boundary. `fetch` resolves on 404 and on 500, so
281
- // without this test a failed request became an empty dataset and the
282
- // component told the reader there was nothing to show.
283
285
  if (!res.ok) {
284
286
  const e = new Error(`Could not load (${res.status})`);
285
287
  e.name = "HttpError";
@@ -369,14 +371,6 @@ export function remoteRefresh(host) {
369
371
  }
370
372
 
371
373
  // `loading="lazy"` belongs to the markup, not to the platform: an element below
372
- // the fold must not compete with the forty above it. Where IntersectionObserver
373
- // is missing the host simply asks, which is the honest fallback rather than never
374
- // asking at all.
375
- // One shared IntersectionObserver for every lazy host (B3-22): the previous
376
- // shape opened a fresh observer per host, so a dashboard with N lazy blocks
377
- // paid N observers for a single viewport. The shared observer fans entries out
378
- // to the host that owns each target; a host is unobserved (not the whole
379
- // observer disconnected) once it enters, so siblings keep watching.
380
374
  let _sharedLazyIO = null;
381
375
  const _sharedLazyTargets = new Map();
382
376
  /** Whether remote data is currently visible. */
@@ -447,22 +441,9 @@ export function watchViewport(host) {
447
441
  return () => io.disconnect();
448
442
  }
449
443
 
450
- // ---------------------------------------------------------------------------
451
- // The states themselves
452
444
  // ---------------------------------------------------------------------------
453
445
 
454
446
  // A state node carries the block-scoped element class the sheet already defines
455
- // (`c-readout__loading`, `c-tree__empty`, …) so an author can theme one block's
456
- // state without reaching for the whole system, and never carries a `style`
457
- // attribute — which is the defect that made the matching CSS rule dead.
458
- //
459
- // It also carries `data-contour-state`, the only new hook here. The error state has
460
- // to read as a failure, but the per-block rules group `__error` with `__empty` and
461
- // `__loading` as muted text, so a failure looks exactly like a placeholder that
462
- // simply has not arrived yet. Colouring it by name would mean editing 34 rules in
463
- // the four sheets another writer is landing changes into; one rule on this
464
- // attribute does it, and an attribute is a host-set input rather than a published
465
- // class — no specimen, no inventory entry, nothing to deprecate.
466
447
  function stateNode(block, kind, text) {
467
448
  const node = document.createElement("div");
468
449
  node.className = "c-" + block + "__" + kind;
@@ -473,9 +454,6 @@ function stateNode(block, kind, text) {
473
454
 
474
455
  function skeletonRow(i, total) {
475
456
  // The system's own skeleton block and its own modifiers: `--title` for the first
476
- // line so a placeholder has a shape instead of a uniform stack of bars, `--text`
477
- // for the rest. No per-block name is invented here, which is how the 33
478
- // undefined `c-*__skeleton` classes stop being generated at all.
479
457
  const node = document.createElement("div");
480
458
  node.className = "c-skeleton " + (i === 0 && total > 1 ? "c-skeleton--title" : "c-skeleton--text");
481
459
  node.dataset.contourState = "skeleton";
@@ -495,21 +473,21 @@ export function renderStates(host, block, opts) {
495
473
  const options = opts || {};
496
474
  const loading = host.getAttribute("loading");
497
475
  if (loading !== null || host._remoteStatus === "loading") {
498
- host.appendChild(stateNode(block, "loading", loading || STATE_FALLBACK.loading));
476
+ host.appendChild(stateNode(block, "loading", loading || stateLabel(host, "loading")));
499
477
  return true;
500
478
  }
501
479
  const error = host.getAttribute("error");
502
480
  if (error !== null || host._remoteStatus === "error") {
503
- const message = (error !== null && error !== "") ? error : (host._remoteError || STATE_FALLBACK.error);
481
+ const message = (error !== null && error !== "") ? error : (host._remoteError || stateLabel(host, "error"));
504
482
  const node = stateNode(block, "error", message);
505
483
  // `retry` is the actionable half of an error. It reuses the button the system
506
- // already ships and the `contour:retry` event three components already emit,
507
- // rather than inventing a control for the same job.
508
484
  if (host.hasAttribute("retry")) {
509
485
  const btn = document.createElement("button");
510
486
  btn.type = "button";
511
487
  btn.className = "c-btn c-btn--ghost c-btn--sm";
512
- btn.textContent = host.getAttribute("retry") || "Retry";
488
+ // R31-145: retry is a primary recovery action — icon+text, never icon-only.
489
+ setHTML(btn, '<svg aria-hidden="true" viewBox="0 0 24 24"><use href="#i-refresh" /></svg>');
490
+ btn.appendChild(document.createTextNode(" " + (host.getAttribute("retry") || "Retry")));
513
491
  btn.dataset.action = "retry";
514
492
  node.appendChild(btn);
515
493
  }
@@ -528,7 +506,26 @@ export function renderStates(host, block, opts) {
528
506
  /** Paint the empty state — for a host with no data and no authored content. */
529
507
  /** Render the empty state for a block. */
530
508
  export function renderEmpty(host, block) {
531
- host.appendChild(stateNode(block, "empty", host.getAttribute("empty") || STATE_FALLBACK.empty));
509
+ host.appendChild(stateNode(block, "empty", host.getAttribute("empty") || stateLabel(host, "empty")));
510
+ }
511
+
512
+ /**
513
+ * R24-24: shared JSON array parser. Parses a JSON attribute and returns an
514
+ * array (empty if not an array or malformed). Warns on malformed JSON so
515
+ * the error is visible in the console.
516
+ */
517
+ export function parseArrayAttr(host, attr, warn) {
518
+ const raw = host.getAttribute(attr);
519
+ if (!raw) return [];
520
+ try {
521
+ const parsed = JSON.parse(raw);
522
+ if (Array.isArray(parsed)) return parsed;
523
+ if (warn) warn(host, attr, new Error("not an array"));
524
+ return [];
525
+ } catch (e) {
526
+ if (warn) warn(host, attr, e);
527
+ return [];
528
+ }
532
529
  }
533
530
 
534
531
  // Delegated on the host (AGENTS.md rule 12): the retry button is regenerated on
package/dist/wc/svg.mjs CHANGED
@@ -1,19 +1,26 @@
1
- /* ============================================================================
2
- CONTOUR — SVG geometry helpers (pure functions, zero dependencies)
3
- ----------------------------------------------------------------------------
4
- Lightweight path generators for the spatial chart variants that Contour's
5
- CSS already styles (.c-chart--donut, .c-chart--histogram, .c-sparkline).
6
- They return strings suitable for an SVG `d` attribute or a list of
7
- {x, y, width, height} rectangles, so a consumer never has to hand-compute
8
- arc math or bar widths for a basic cartographic control.
9
-
10
- Every function is pure: no DOM, no state, no side effects. They are
11
- exported so a consumer can import them directly, and the chart component
12
- uses them when its `series` attribute carries structured data rather than
13
- a pre-computed path string.
14
- ========================================================================= */
1
+ /* CONTOUR — SVG geometry helpers: pure path generators, zero dependencies. */
15
2
  "use strict";
16
3
 
4
+ /**
5
+ * R31-50: the one null/NaN policy. A value is "missing" when it is null or
6
+ * undefined, a non-finite number (NaN/Infinity), the `__missing` sentinel, or
7
+ * an empty string. Missing values are NOT zero: a line breaks at them, a bar
8
+ * is not drawn, and the data table leaves the cell empty. Every geometry
9
+ * helper and the chart renderer share this predicate so the three agree.
10
+ *
11
+ * @param {*} v
12
+ * @returns {boolean}
13
+ */
14
+ export function isMissing(v) {
15
+ if (v == null) return true;
16
+ if (typeof v === "number") return !Number.isFinite(v);
17
+ if (typeof v === "string") {
18
+ const t = v.trim();
19
+ return t === "" || t === "__missing";
20
+ }
21
+ return false;
22
+ }
23
+
17
24
  /**
18
25
  * Build an SVG arc path for a single donut slice.
19
26
  *
@@ -27,8 +34,7 @@
27
34
  */
28
35
  /** Build an SVG arc path string. */
29
36
  export function arcPath(cx, cy, r, inner, startAngle, endAngle) {
30
- // Clamp non-finite inputs so a bad value cannot emit NaN/Infinity into the
31
- // path string (B3-22). A degenerate slice collapses to a point.
37
+ // Clamp non-finite inputs so a bad value cannot emit NaN/Infinity into the path.
32
38
  cx = Number.isFinite(cx) ? cx : 0;
33
39
  cy = Number.isFinite(cy) ? cy : 0;
34
40
  r = Number.isFinite(r) && r > 0 ? r : 0;
@@ -70,7 +76,11 @@ export function donutSlices(values, opts) {
70
76
  const r = opts.r != null ? opts.r : 90;
71
77
  const inner = opts.inner != null ? opts.inner : 55;
72
78
  const gap = opts.gap != null ? opts.gap : 0.02;
73
- const total = values.reduce((a, b) => a + (Number(b) || 0), 0) || 1;
79
+ // R31-51: the total is the sum of the POSITIVE slices only. A negative value
80
+ // is not a slice (it is skipped below), so including it in the total made the
81
+ // drawn sweeps overflow 360° (e.g. [10,-5,20] swept 432°). Excluding it keeps
82
+ // the ring a full circle and the centre total honest.
83
+ const total = values.reduce((a, b) => a + (Number(b) > 0 ? Number(b) : 0), 0) || 1;
74
84
  let angle = -Math.PI / 2;
75
85
  const out = [];
76
86
  values.forEach((v, i) => {
@@ -103,17 +113,53 @@ export function barRects(values, opts) {
103
113
  const width = opts.width != null ? opts.width : 300;
104
114
  const height = opts.height != null ? opts.height : 120;
105
115
  const gap = opts.gap != null ? opts.gap : 2;
106
- const max = opts.max != null ? opts.max : (Math.max.apply(null, values.map((v) => Number(v) || 0)) || 1);
107
- if (!Number.isFinite(max) || max <= 0) return values.map(() => ({ x: 0, y: height, width: 0, height: 0 }));
116
+ // R31-50: a missing value is not a zero-height bar. It is flagged so the
117
+ // renderer can skip it, and it does not contribute to the domain.
118
+ const missing = values.map(isMissing);
119
+ const nums = values.map((v, i) => (missing[i] ? 0 : Number(v) || 0));
120
+ // R31-44: the domain includes 0, so a negative value hangs below a zero
121
+ // baseline instead of being clamped to a zero-height bar at the foot. Each
122
+ // rect carries `zeroY` (the baseline) so the axis and the bars agree.
123
+ let lo = Math.min(0, Math.min.apply(null, nums.length ? nums : [0]));
124
+ let hi = Math.max(0, Math.max.apply(null, nums.length ? nums : [0]));
125
+ if (opts.min != null) lo = Math.min(lo, Number(opts.min) || 0);
126
+ if (opts.max != null) hi = Math.max(hi, Number(opts.max) || 0);
127
+ if (!Number.isFinite(lo) || !Number.isFinite(hi)) { lo = 0; hi = 1; }
128
+ if (hi === lo) hi = lo + 1;
129
+ const span = hi - lo;
108
130
  const n = values.length || 1;
109
131
  const slot = width / n;
110
132
  const barW = Math.max(1, slot - gap);
111
- return values.map((v, i) => {
112
- const h = ((Number(v) || 0) / max) * height;
113
- return { x: i * slot + gap / 2, y: height - h, width: barW, height: h };
133
+ const zeroY = height - ((0 - lo) / span) * height;
134
+ return nums.map((v, i) => {
135
+ const yv = height - ((v - lo) / span) * height;
136
+ return { x: i * slot + gap / 2, y: Math.min(yv, zeroY), width: barW, height: missing[i] ? 0 : Math.abs(zeroY - yv), zeroY, missing: missing[i] };
114
137
  });
115
138
  }
116
139
 
140
+ /**
141
+ * Nice value-axis ticks for a chart, independent of `ds.js`. The wc layer used
142
+ * to read `window.Contour.chart.ticks`, which only exists when the optional
143
+ * guide script is loaded; a wc-only consumer got two ticks.
144
+ */
145
+ export function niceTicks(min, max, count) {
146
+ count = count || 5;
147
+ const span = max - min || 1;
148
+ let step = Math.pow(10, Math.floor(Math.log10(span / count)));
149
+ if (!Number.isFinite(step) || step <= 0) return [min, max];
150
+ const err = (count * step) / span;
151
+ if (err <= 0.15) step *= 10;
152
+ else if (err <= 0.35) step *= 5;
153
+ else if (err <= 0.75) step *= 2;
154
+ const lo = Math.floor(min / step) * step;
155
+ const hi = Math.ceil(max / step) * step;
156
+ const ticks = [];
157
+ for (let v = lo; v <= hi + step / 2; v += step) {
158
+ ticks.push(Math.round(v * 1e9) / 1e9);
159
+ }
160
+ return ticks;
161
+ }
162
+
117
163
  /**
118
164
  * Build an SVG polyline `points` attribute from a list of numbers.
119
165
  *
@@ -152,16 +198,40 @@ export function polylinePoints(values, opts) {
152
198
  */
153
199
  /** Compute a smoothed SVG path. */
154
200
  export function smoothPath(values, opts) {
155
- const pts = polylinePoints(values, opts).split(" ").map((p) => p.split(",").map(Number));
156
- if (!pts.length) return "";
157
- let d = `M ${pts[0][0]} ${pts[0][1]}`;
158
- for (let i = 1; i < pts.length; i++) {
159
- const prev = pts[i - 1];
160
- const cur = pts[i];
161
- const cpx = (prev[0] + cur[0]) / 2;
162
- d += ` C ${cpx} ${prev[1]}, ${cpx} ${cur[1]}, ${cur[0]} ${cur[1]}`;
163
- }
164
- return d;
201
+ // R31-50: a missing value breaks the path into a new subpath (a gap), it is
202
+ // not drawn as zero. The domain ignores missing values.
203
+ opts = opts || {};
204
+ const width = opts.width != null ? opts.width : 300;
205
+ const height = opts.height != null ? opts.height : 120;
206
+ const finite = values.filter((v) => !isMissing(v)).map(Number).filter((v) => Number.isFinite(v));
207
+ const max = opts.max != null ? opts.max : (finite.length ? Math.max.apply(null, finite) : 1);
208
+ const min = opts.min != null ? opts.min : (finite.length ? Math.min.apply(null, finite) : 0);
209
+ const range = (Number.isFinite(max - min) && (max - min) !== 0) ? (max - min) : 1;
210
+ const n = values.length || 1;
211
+ const pts = values.map((v, i) => {
212
+ if (isMissing(v)) return null;
213
+ const num = Number(v);
214
+ if (!Number.isFinite(num)) return null;
215
+ const x = (i / Math.max(1, n - 1)) * width;
216
+ const y = height - ((num - min) / range) * height;
217
+ return [x, y];
218
+ });
219
+ let d = "";
220
+ let seg = [];
221
+ const flush = () => {
222
+ if (!seg.length) return;
223
+ d += ` M ${seg[0][0]} ${seg[0][1]}`;
224
+ for (let k = 1; k < seg.length; k++) {
225
+ const prev = seg[k - 1];
226
+ const cur = seg[k];
227
+ const cpx = (prev[0] + cur[0]) / 2;
228
+ d += ` C ${cpx} ${prev[1]}, ${cpx} ${cur[1]}, ${cur[0]} ${cur[1]}`;
229
+ }
230
+ seg = [];
231
+ };
232
+ pts.forEach((p) => { if (p) seg.push(p); else flush(); });
233
+ flush();
234
+ return d.trim();
165
235
  }
166
236
 
167
237
  /**
@@ -178,8 +248,11 @@ export function smoothPath(values, opts) {
178
248
  */
179
249
  /** Compute compass needle geometry. */
180
250
  export function compassNeedle(cx, cy, length, angleDeg, width) {
181
- angleDeg = angleDeg == null ? 0 : angleDeg;
182
- width = width == null ? 3 : width;
251
+ cx = Number.isFinite(Number(cx)) ? Number(cx) : 0;
252
+ cy = Number.isFinite(Number(cy)) ? Number(cy) : 0;
253
+ length = Number.isFinite(Number(length)) ? Number(length) : 0;
254
+ angleDeg = angleDeg == null ? 0 : (Number.isFinite(Number(angleDeg)) ? Number(angleDeg) : 0);
255
+ width = width == null ? 3 : (Number.isFinite(Number(width)) ? Number(width) : 3);
183
256
  const a = (angleDeg - 90) * Math.PI / 180; // 0deg = up
184
257
  const tipX = cx + length * Math.cos(a);
185
258
  const tipY = cy + length * Math.sin(a);
@@ -230,3 +303,105 @@ export function markerStyles(shape) {
230
303
  export function assignMarkers(items) {
231
304
  return (items || []).map((it, i) => ({ ...it, marker: MARKER_SHAPES[i % MARKER_SHAPES.length] }));
232
305
  }
306
+
307
+ /* Contour lines — marching squares over a 2D field; iso-lines of one field cannot cross. */
308
+
309
+ /**
310
+ * Extract the iso-line segments of a scalar field at one level.
311
+ *
312
+ * @param {number[][]} grid row-major field values
313
+ * @param {number} level iso-level to extract
314
+ * @returns {Array<[{x:number,y:number},{x:number,y:number}]>} segments in grid space
315
+ */
316
+ export function marchingSquares(grid, level) {
317
+ const rows = grid.length;
318
+ const cols = rows ? grid[0].length : 0;
319
+ const segments = [];
320
+ if (!rows || !cols) return segments;
321
+
322
+ const lerp = (a, b, va, vb) => (vb === va ? 0.5 : (level - va) / (vb - va));
323
+
324
+ for (let y = 0; y < rows - 1; y++) {
325
+ for (let x = 0; x < cols - 1; x++) {
326
+ const tl = grid[y][x];
327
+ const tr = grid[y][x + 1];
328
+ const bl = grid[y + 1][x];
329
+ const br = grid[y + 1][x + 1];
330
+ const code =
331
+ (tl >= level ? 8 : 0) |
332
+ (tr >= level ? 4 : 0) |
333
+ (br >= level ? 2 : 0) |
334
+ (bl >= level ? 1 : 0);
335
+ if (code === 0 || code === 15) continue;
336
+
337
+ const top = { x: x + lerp(tl, tr, tl, tr), y };
338
+ const right = { x: x + 1, y: y + lerp(tr, br, tr, br) };
339
+ const bottom = { x: x + lerp(bl, br, bl, br), y: y + 1 };
340
+ const left = { x, y: y + lerp(tl, bl, tl, bl) };
341
+
342
+ let connect;
343
+ // R31-47: the asymptotic decider (as tools/contour-gen.py uses), not the
344
+ // plain corner average. The bilinear interpolant's saddle value is
345
+ // (tl*br - tr*bl) / (tl - tr - bl + br); the average misclassifies
346
+ // asymmetric cells and produces the wrong pairing (crossed shelves).
347
+ const saddle = (() => {
348
+ const denom = tl - tr - bl + br;
349
+ return Math.abs(denom) < 1e-12 ? (tl + tr + bl + br) / 4 : (tl * br - tr * bl) / denom;
350
+ })();
351
+ if (code === 5) {
352
+ connect = saddle >= level ? "top-bottom" : "left-right";
353
+ } else if (code === 10) {
354
+ connect = saddle >= level ? "left-right" : "top-bottom";
355
+ }
356
+
357
+ switch (code) {
358
+ case 1: case 14: segments.push([left, bottom]); break;
359
+ case 2: case 13: segments.push([bottom, right]); break;
360
+ case 3: case 12: segments.push([left, right]); break;
361
+ case 4: case 11: segments.push([top, right]); break;
362
+ case 6: case 9: segments.push([top, bottom]); break;
363
+ case 7: case 8: segments.push([left, top]); break;
364
+ case 5:
365
+ if (connect === "top-bottom") {
366
+ segments.push([top, bottom], [left, right]);
367
+ } else {
368
+ segments.push([top, right], [left, bottom]);
369
+ }
370
+ break;
371
+ case 10:
372
+ if (connect === "left-right") {
373
+ segments.push([left, right], [top, bottom]);
374
+ } else {
375
+ segments.push([top, right], [left, bottom]);
376
+ }
377
+ break;
378
+ }
379
+ }
380
+ }
381
+ return segments;
382
+ }
383
+
384
+ /**
385
+ * Build the SVG `d` path for every level of a field.
386
+ *
387
+ * @param {number[][]} grid row-major field values
388
+ * @param {number[]} levels iso-levels, one path per level
389
+ * @param {number} width viewBox width in px
390
+ * @param {number} height viewBox height in px
391
+ * @returns {Array<{level:number, d:string}>} one entry per level
392
+ */
393
+ export function contourPaths(grid, levels, width, height) {
394
+ const rows = grid.length;
395
+ const cols = rows ? grid[0].length : 0;
396
+ if (rows < 2 || cols < 2) return [];
397
+ const sx = width / (cols - 1);
398
+ const sy = height / (rows - 1);
399
+ return (levels || []).map((level) => {
400
+ const segs = marchingSquares(grid, level);
401
+ let d = "";
402
+ for (const [a, b] of segs) {
403
+ d += `M ${(a.x * sx).toFixed(2)} ${(a.y * sy).toFixed(2)} L ${(b.x * sx).toFixed(2)} ${(b.y * sy).toFixed(2)} `;
404
+ }
405
+ return { level, d: d.trim() };
406
+ });
407
+ }