contour-ds 1.7.2 → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/README.md +80 -11
  2. package/dist/agent-rules.json +16 -0
  3. package/dist/build-manifest.json +181 -104
  4. package/dist/contour-wc-content.esm.js +5125 -0
  5. package/dist/contour-wc-content.esm.min.js +1 -0
  6. package/dist/contour-wc-dashboard.esm.js +8654 -0
  7. package/dist/contour-wc-dashboard.esm.min.js +1 -0
  8. package/dist/contour-wc-data.esm.js +8260 -0
  9. package/dist/contour-wc-data.esm.min.js +1 -0
  10. package/dist/contour-wc-docs.esm.js +4305 -0
  11. package/dist/contour-wc-docs.esm.min.js +1 -0
  12. package/dist/contour-wc-feedback.esm.js +4917 -0
  13. package/dist/contour-wc-feedback.esm.min.js +1 -0
  14. package/dist/contour-wc-forms.esm.js +5688 -0
  15. package/dist/contour-wc-forms.esm.min.js +1 -0
  16. package/dist/contour-wc-interaction.esm.js +4580 -0
  17. package/dist/contour-wc-interaction.esm.min.js +1 -0
  18. package/dist/contour-wc-layout.esm.js +4174 -0
  19. package/dist/contour-wc-layout.esm.min.js +1 -0
  20. package/dist/contour-wc-map.esm.js +5205 -0
  21. package/dist/contour-wc-map.esm.min.js +1 -0
  22. package/dist/contour-wc-misc.esm.js +4264 -0
  23. package/dist/contour-wc-misc.esm.min.js +1 -0
  24. package/dist/contour-wc-navigation.esm.js +5844 -0
  25. package/dist/contour-wc-navigation.esm.min.js +1 -0
  26. package/dist/contour-wc-ui.esm.js +9009 -0
  27. package/dist/contour-wc-ui.esm.min.js +1 -0
  28. package/dist/contour-wc.esm.js +6109 -1641
  29. package/dist/contour-wc.esm.min.js +1 -1
  30. package/dist/contour-wc.js +6108 -1641
  31. package/dist/contour-wc.min.js +1 -1
  32. package/dist/contour.code-snippets +4512 -0
  33. package/dist/contour.components.json +2597 -799
  34. package/dist/contour.css +5275 -4050
  35. package/dist/contour.d.ts +560 -1085
  36. package/dist/contour.esm.js +7 -0
  37. package/dist/contour.esm.min.js +1 -1
  38. package/dist/contour.html-data.json +10311 -0
  39. package/dist/contour.js +7 -0
  40. package/dist/contour.min.css +1 -1
  41. package/dist/contour.min.js +1 -1
  42. package/dist/contour.react.d.ts +420 -0
  43. package/dist/contour.single.html +17 -0
  44. package/dist/contour.single.min.css +1 -0
  45. package/dist/contour.tokens.json +940 -902
  46. package/dist/contour.vue.d.ts +418 -0
  47. package/dist/contour.web-types.json +10703 -0
  48. package/dist/custom-elements.json +30708 -0
  49. package/dist/docs/actions.md +3 -2
  50. package/dist/docs/affordances.md +23 -9
  51. package/dist/docs/apireference.md +1 -1
  52. package/dist/docs/colour.md +1 -1
  53. package/dist/docs/componentindex.md +6 -2
  54. package/dist/docs/data.md +7 -2
  55. package/dist/docs/docs.md +9 -2
  56. package/dist/docs/feedback.md +1 -1
  57. package/dist/docs/field.md +1 -1
  58. package/dist/docs/forms.md +1 -1
  59. package/dist/docs/index.json +22 -20
  60. package/dist/docs/install.md +1 -1
  61. package/dist/docs/landing.md +1 -1
  62. package/dist/docs/mapengine.md +19 -2
  63. package/dist/docs/motion.md +1 -1
  64. package/dist/docs/navigation.md +1 -1
  65. package/dist/docs/overlays.md +1 -1
  66. package/dist/docs/overview.md +1 -1
  67. package/dist/docs/patterns.md +2 -2
  68. package/dist/docs/playground.md +22 -2
  69. package/dist/docs/principles.md +1 -1
  70. package/dist/docs/recipes.md +13 -8
  71. package/dist/docs/space.md +1 -1
  72. package/dist/docs/status.md +14 -2
  73. package/dist/docs/surfaces.md +1 -1
  74. package/dist/docs/theming.md +1 -1
  75. package/dist/docs/type.md +1 -1
  76. package/dist/docs/webcomponents.md +17 -3
  77. package/dist/registry/items/contour-core.json +2 -2
  78. package/dist/registry/items/contour-data.json +2 -2
  79. package/dist/registry/items/contour-docs.json +2 -2
  80. package/dist/registry/items/contour-landing.json +2 -2
  81. package/dist/registry/registry.json +8 -8
  82. package/dist/surfaces/contour-core.min.css +1 -1
  83. package/dist/surfaces/contour-data.min.css +1 -1
  84. package/dist/surfaces/contour-docs.min.css +1 -1
  85. package/dist/surfaces/contour-landing.min.css +1 -1
  86. package/dist/wc/behaviours.mjs +45 -57
  87. package/dist/wc/content.mjs +263 -63
  88. package/dist/wc/core.mjs +390 -71
  89. package/dist/wc/dashboard.mjs +220 -13
  90. package/dist/wc/data.mjs +1075 -460
  91. package/dist/wc/docs.mjs +105 -12
  92. package/dist/wc/feedback.mjs +63 -14
  93. package/dist/wc/forms.mjs +733 -104
  94. package/dist/wc/index.mjs +9 -2
  95. package/dist/wc/interaction.mjs +182 -28
  96. package/dist/wc/layout.mjs +95 -25
  97. package/dist/wc/map.mjs +185 -118
  98. package/dist/wc/misc.mjs +124 -24
  99. package/dist/wc/navigation.mjs +384 -115
  100. package/dist/wc/shadow.mjs +94 -18
  101. package/dist/wc/states.mjs +21 -3
  102. package/dist/wc/svg.mjs +104 -0
  103. package/dist/wc/ui.mjs +1988 -476
  104. package/integrations/README.md +2 -0
  105. package/integrations/ai/CLAUDE.md +3 -3
  106. package/integrations/frameworks/README.md +235 -0
  107. package/integrations/native/style-dictionary.config.json +1 -1
  108. package/integrations/tailwind/contour-theme.css +5 -6
  109. package/package.json +53 -24
package/dist/wc/ui.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { ContourBase, define, contourId, onDispose } from './core.mjs';
2
- import { wireRemovable } from './behaviours.mjs';
1
+ import { ContourBase, define, contourId, onDispose, navKey, safeColor, safeHref, cssLength , warnBadJson, labelText } from './core.mjs';
2
+ import { wireRemovable, modalContain } from './behaviours.mjs';
3
3
  /**
4
4
  * Avatar: a circular avatar with initials (from `name`) or an image (`src`),
5
5
  * optional size/variant modifiers and a status dot. Attributes: `name`, `size`,
@@ -95,11 +95,16 @@ class ContourBadgeFull extends ContourBase {
95
95
  * Attributes: `variant`, `key`, `value`.
96
96
  */
97
97
  class ContourChipFull extends ContourBase {
98
- static get observed() { return ["variant", "key", "value"]; }
99
- static get properties() { return { variant: { attribute: "variant" }, key: { attribute: "key" }, value: { attribute: "value" } }; }
98
+ static get observed() { return ["variant", "key", "value", "live"]; }
99
+ static get properties() { return { variant: { attribute: "variant" }, key: { attribute: "key" }, value: { attribute: "value" }, live: { attribute: "live", type: Boolean } }; }
100
100
  render() {
101
101
  this.classList.add("c-chip");
102
- if (!this.hasAttribute("role")) this.setAttribute("role", "status");
102
+ // A static filter chip is a label, not a live region. Only a chip the
103
+ // author marks `live` announces; otherwise a page with 50 chips creates
104
+ // 50 politeness regions that may speak on load.
105
+ if (this.hasAttribute("live") && !this.hasAttribute("role")) this.setAttribute("role", "status");
106
+ else if (!this.hasAttribute("live") && this.getAttribute("role") === "status" && this._autoChipRole) this.removeAttribute("role");
107
+ this._autoChipRole = this.hasAttribute("live");
103
108
  Array.from(this.classList).forEach((c) => { if (c.startsWith("c-chip--")) this.classList.remove(c); });
104
109
  const variant = this.getAttribute("variant");
105
110
  if (variant) this.classList.add("c-chip--" + variant);
@@ -127,11 +132,15 @@ class ContourChipFull extends ContourBase {
127
132
  * `removable`, `variant`.
128
133
  */
129
134
  class ContourTag extends ContourBase {
130
- static get observed() { return ["label", "removable", "variant"]; }
131
- static get properties() { return { label: { attribute: "label" }, removable: { attribute: "removable", type: Boolean }, variant: { attribute: "variant" } }; }
135
+ static get observed() { return ["label", "removable", "variant", "live"]; }
136
+ static get properties() { return { label: { attribute: "label" }, removable: { attribute: "removable", type: Boolean }, variant: { attribute: "variant" }, live: { attribute: "live", type: Boolean } }; }
132
137
  render() {
133
138
  this.classList.add("c-tag");
134
- if (!this.hasAttribute("role")) this.setAttribute("role", "status");
139
+ // A tag is normally a static label. `live` opts it into a polite region,
140
+ // so a wall of tags does not create a wall of announcements.
141
+ if (this.hasAttribute("live") && !this.hasAttribute("role")) this.setAttribute("role", "status");
142
+ else if (!this.hasAttribute("live") && this.getAttribute("role") === "status" && this._autoTagRole) this.removeAttribute("role");
143
+ this._autoTagRole = this.hasAttribute("live");
135
144
  Array.from(this.classList).forEach((c) => { if (c.startsWith("c-tag--")) this.classList.remove(c); });
136
145
  const variant = this.getAttribute("variant");
137
146
  if (variant) this.classList.add("c-tag--" + variant);
@@ -194,7 +203,11 @@ class ContourPill extends ContourBase {
194
203
  static get properties() { return { label: { attribute: "label" }, live: { attribute: "live", type: Boolean }, variant: { attribute: "variant" } }; }
195
204
  render() {
196
205
  this.classList.add("c-pill");
197
- if (!this.hasAttribute("role")) this.setAttribute("role", "status");
206
+ // `live` is the pill's opt-in to a polite region. A static pill is a label:
207
+ // role=status on every instance makes a page of pills announce itself.
208
+ if (this.hasAttribute("live") && !this.hasAttribute("role")) this.setAttribute("role", "status");
209
+ else if (!this.hasAttribute("live") && this.getAttribute("role") === "status" && this._autoPillRole) this.removeAttribute("role");
210
+ this._autoPillRole = this.hasAttribute("live");
198
211
  Array.from(this.classList).forEach((c) => { if (c.startsWith("c-pill--")) this.classList.remove(c); });
199
212
  const variant = this.getAttribute("variant");
200
213
  if (variant) this.classList.add("c-pill--" + variant);
@@ -249,9 +262,10 @@ class ContourSkeleton extends ContourBase {
249
262
  Array.from(this.classList).forEach((c) => { if (c.startsWith("c-skeleton--")) this.classList.remove(c); });
250
263
  const size = this.getAttribute("size");
251
264
  if (size) this.classList.add("c-skeleton--" + size);
252
- if (!this.hasAttribute("role")) this.setAttribute("role", "status");
253
- if (!this.hasAttribute("aria-label")) this.setAttribute("aria-label", "Loading");
254
- if (!this.hasAttribute("aria-busy")) this.setAttribute("aria-busy", "true");
265
+ // A skeleton is a decorative placeholder: it is hidden from assistive
266
+ // technology, and the loading state (contour-loading) is what announces.
267
+ // The old code set role=status AND aria-hidden=true, which is a live
268
+ // region that can never speak.
255
269
  if (!this.hasAttribute("aria-hidden")) this.setAttribute("aria-hidden", "true");
256
270
  const shimmer = this.getAttribute("shimmer");
257
271
  if (shimmer === "false" || shimmer === "off") this.classList.add("c-skeleton--static");
@@ -268,6 +282,7 @@ class ContourTooltip extends ContourBase {
268
282
  static get properties() { return { text: { attribute: "text" }, anchor: { attribute: "anchor" }, delay: { attribute: "delay", type: Number }, trigger: { attribute: "trigger" } }; }
269
283
  render() {
270
284
  this.classList.add("c-tooltip");
285
+ if (!this.hasAttribute("aria-label")) this.setAttribute("aria-label", "Tooltip");
271
286
  if (!this.hasAttribute("popover")) this.setAttribute("popover", "auto");
272
287
  if (!this.hasAttribute("role")) this.setAttribute("role", "tooltip");
273
288
  if (!this.id) this.id = contourId("tip");
@@ -409,29 +424,49 @@ class ContourProgress extends ContourBase {
409
424
  this.ensure(".c-progress__bar", () => { const el = document.createElement("span"); el.className = "c-progress__bar"; return el; });
410
425
  if (!this.hasAttribute("role")) this.setAttribute("role", "progressbar");
411
426
  const label = this.getAttribute("label");
412
- if (label && !this.hasAttribute("aria-label")) this.setAttribute("aria-label", label);
427
+ if (!this.hasAttribute("aria-label")) this.setAttribute("aria-label", label || "Progress");
413
428
  const min = this.getAttribute("min");
414
429
  const max = this.getAttribute("max");
430
+ const minV = min !== null ? Number(min) : 0;
431
+ const maxV = max !== null ? Number(max) : 100;
415
432
  if (min !== null) this.setAttribute("aria-valuemin", min);
416
433
  else if (!this.hasAttribute("aria-valuemin")) this.setAttribute("aria-valuemin", "0");
417
434
  if (max !== null) this.setAttribute("aria-valuemax", max);
418
435
  else if (!this.hasAttribute("aria-valuemax")) this.setAttribute("aria-valuemax", "100");
436
+ // aria-valuenow must sit inside the declared min/max, not always 0-100.
437
+ if (this.hasAttribute("aria-valuenow")) {
438
+ const now = Number(this.getAttribute("aria-valuenow"));
439
+ if (Number.isFinite(now)) this.setAttribute("aria-valuenow", String(Math.max(minV, Math.min(maxV, now))));
440
+ }
419
441
  if (this.hasAttribute("paused")) this.classList.add("c-progress--paused");
420
442
  else Array.from(this.classList).forEach((c) => { if (c === "c-progress--paused") this.classList.remove(c); });
421
443
  if (this.hasAttribute("pausable")) {
422
- this.ensure(".c-progress__pause", () => {
423
- const btn = document.createElement("button");
424
- btn.className = "c-progress__pause";
425
- btn.type = "button";
426
- btn.setAttribute("aria-label", "Pause");
427
- btn.textContent = "⏸";
428
- return btn;
444
+ const paused = this.hasAttribute("paused");
445
+ const btn = this.ensure(".c-progress__pause", () => {
446
+ const el = document.createElement("button");
447
+ el.className = "c-progress__pause";
448
+ el.type = "button";
449
+ return el;
429
450
  });
451
+ btn.setAttribute("aria-label", paused ? "Resume" : "Pause");
452
+ btn.textContent = paused ? "▶" : "⏸";
430
453
  } else {
431
454
  const btn = this.querySelector(".c-progress__pause");
432
455
  if (btn) btn.remove();
433
456
  }
434
457
  }
458
+ enhance() {
459
+ if (this._wiredProgress) return;
460
+ this._wiredProgress = true;
461
+ this.addEventListener("click", (e) => {
462
+ const btn = e.target && e.target.closest ? e.target.closest(".c-progress__pause") : null;
463
+ if (!btn || !this.contains(btn)) return;
464
+ e.preventDefault();
465
+ const paused = !this.hasAttribute("paused");
466
+ this.toggleAttribute("paused", paused);
467
+ this.dispatchEvent(new CustomEvent("contour:change", { bubbles: true, composed: true, detail: { paused } }));
468
+ });
469
+ }
435
470
  }
436
471
  define("contour-progress", ContourProgress);
437
472
  /**
@@ -447,11 +482,20 @@ class ContourMark extends ContourBase {
447
482
  * Loading: a spinner wrapped in a container. No attributes.
448
483
  */
449
484
  class ContourLoading extends ContourBase {
485
+ static get observed() { return ["label"]; }
486
+ static get properties() { return { label: { attribute: "label" } }; }
450
487
  render() {
451
488
  this.classList.add("c-loading");
452
489
  if (!this.hasAttribute("role")) this.setAttribute("role", "status");
453
490
  if (!this.hasAttribute("aria-live")) this.setAttribute("aria-live", "polite");
454
491
  this.ensure(".c-spinner", () => { const el = document.createElement("span"); el.className = "c-spinner"; el.setAttribute("aria-hidden", "true"); return el; });
492
+ // A status region with no text announces nothing: give it a label the
493
+ // reader can hear, visually hidden so the spinner stays the visual.
494
+ const label = this.getAttribute("label") || "Loading";
495
+ let text = this.querySelector("[data-loading-label]");
496
+ if (!text) { text = document.createElement("span"); text.className = "visually-hidden"; text.setAttribute("data-loading-label", ""); this.appendChild(text); }
497
+ text.textContent = label;
498
+ if (!this.hasAttribute("aria-label")) this.setAttribute("aria-label", label);
455
499
  }
456
500
  }
457
501
  define("contour-loading", ContourLoading);
@@ -479,10 +523,14 @@ class ContourVersionBannerFull extends ContourBase {
479
523
  static get properties() { return { message: { attribute: "message" }, link: { attribute: "link" }, href: { attribute: "href" }, dismissible: { attribute: "dismissible", type: Boolean } }; }
480
524
  render() {
481
525
  this.classList.add("c-version-banner");
526
+ if (!this.hasAttribute("role")) this.setAttribute("role", "status");
527
+ if (!this.hasAttribute("aria-label")) this.setAttribute("aria-label", this.getAttribute("message") || "Version banner");
482
528
  Array.from(this.children).forEach((n) => n.remove());
483
529
  const message = this.getAttribute("message");
484
530
  if (message) {
485
- const icon = document.createElement("svg");
531
+ // createElement("svg") builds an HTMLUnknownElement, not an SVG: the
532
+ // <use> inside it never renders. SVG needs the SVG namespace.
533
+ const icon = document.createElementNS("http://www.w3.org/2000/svg", "svg");
486
534
  icon.setAttribute("aria-hidden", "true");
487
535
  icon.innerHTML = '<use href="#i-info" />';
488
536
  this.appendChild(icon);
@@ -495,7 +543,7 @@ class ContourVersionBannerFull extends ContourBase {
495
543
  if (link && href) {
496
544
  const a = document.createElement("a");
497
545
  a.className = "c-version-banner__link";
498
- a.href = href;
546
+ a.href = safeHref(href);
499
547
  a.textContent = link;
500
548
  this.appendChild(a);
501
549
  }
@@ -532,6 +580,7 @@ class ContourBanner extends ContourBase {
532
580
  render() {
533
581
  this.classList.add("c-banner");
534
582
  const variant = this.getAttribute("variant");
583
+ Array.from(this.classList).forEach((c) => { if (c.startsWith("c-banner--")) this.classList.remove(c); });
535
584
  if (variant) this.classList.add("c-banner--" + variant);
536
585
  const message = this.getAttribute("message");
537
586
  if (message) {
@@ -702,6 +751,9 @@ class ContourSkeletonGroup extends ContourBase {
702
751
  for (let i = 0; i < count; i++) {
703
752
  const sk = document.createElement("div");
704
753
  sk.className = "c-skeleton";
754
+ // Same rule as `contour-skeleton`: a placeholder is decorative. An
755
+ // exposed empty div adds noise and says nothing.
756
+ sk.setAttribute("aria-hidden", "true");
705
757
  this.appendChild(sk);
706
758
  }
707
759
  }
@@ -714,7 +766,7 @@ class ContourSkeletonGroup extends ContourBase {
714
766
  * `cluster-count`, `cluster-expanded`.
715
767
  */
716
768
  class ContourMapPopup extends ContourBase {
717
- static get observed() { return ["title", "content", "cluster-count", "cluster-expanded", "cluster-items"]; }
769
+ static get observed() { return ["title", "content", "cluster-count", "cluster-expanded", "cluster-items", "anchor", "position", "collision"]; }
718
770
  static get properties() { return { title: { attribute: "title" }, content: { attribute: "content" }, "cluster-count": { attribute: "cluster-count", type: Number }, "cluster-expanded": { attribute: "cluster-expanded", type: Boolean }, "cluster-items": { attribute: "cluster-items" } }; }
719
771
  render() {
720
772
  this.classList.add("c-map-popup");
@@ -780,6 +832,46 @@ class ContourMapPopup extends ContourBase {
780
832
  this.dispatchEvent(new CustomEvent("contour:cluster-toggle", { bubbles: true, composed: true, detail: { count: Number(this.getAttribute("cluster-count")), expanded } }));
781
833
  }
782
834
  });
835
+ // CDS-072: anchor + collision handling.
836
+ const anchorSel = this.getAttribute("anchor");
837
+ let anchorEl = null;
838
+ if (anchorSel) {
839
+ anchorEl = anchorSel.startsWith("#") ? document.getElementById(anchorSel.slice(1)) : document.querySelector(anchorSel);
840
+ }
841
+ const anchorName = "--map-popup-" + this.id;
842
+ const applyAnchor = () => {
843
+ if (anchorEl) {
844
+ anchorEl.style.setProperty("anchor-name", anchorName);
845
+ this.style.setProperty("position-anchor", anchorName);
846
+ }
847
+ };
848
+ const flipIfNeeded = () => {
849
+ try {
850
+ const r = this.getBoundingClientRect();
851
+ const flipX = r.right > window.innerWidth || r.left < 0;
852
+ const flipY = r.bottom > window.innerHeight || r.top < 0;
853
+ const flipped = flipX || flipY;
854
+ this.classList.toggle("c-map-popup--flip-x", flipX && !flipY);
855
+ this.classList.toggle("c-map-popup--flip-y", flipY && !flipX);
856
+ this.classList.toggle("c-map-popup--flip-both", flipX && flipY);
857
+ if (flipped) {
858
+ this.dispatchEvent(new CustomEvent("contour:map-popup-reposition", {
859
+ bubbles: true, composed: true,
860
+ detail: { anchor: anchorSel || "", flippedX: flipX, flippedY: flipY, left: Math.round(r.left), top: Math.round(r.top) }
861
+ }));
862
+ }
863
+ } catch (e) {}
864
+ };
865
+ applyAnchor();
866
+ this.addEventListener("toggle", (e) => {
867
+ if (e.newState === "open") {
868
+ requestAnimationFrame(() => { applyAnchor(); flipIfNeeded(); });
869
+ }
870
+ });
871
+ // Re-check on resize/scroll so the popup stays in view.
872
+ const onResize = () => flipIfNeeded();
873
+ window.addEventListener("resize", onResize);
874
+ onDispose(this, () => { window.removeEventListener("resize", onResize); if (anchorEl) anchorEl.style.removeProperty("anchor-name"); });
783
875
  }
784
876
  }
785
877
  define("contour-map-popup", ContourMapPopup);
@@ -790,8 +882,8 @@ class ContourMapPopup extends ContourBase {
790
882
  * `caption`, `show-thumb`, `show-thumb-caption`.
791
883
  */
792
884
  class ContourAnimationControls extends ContourBase {
793
- static get observed() { return ["playing", "speed", "progress", "min", "max", "caption", "show-thumb", "show-thumb-caption"]; }
794
- static get properties() { return { playing: { attribute: "playing", type: Boolean }, speed: { attribute: "speed" }, progress: { attribute: "progress" }, min: { attribute: "min" }, max: { attribute: "max" } }; }
885
+ static get observed() { return ["playing", "speed", "progress", "min", "max", "caption", "show-thumb", "show-thumb-caption", "loop", "step", "markers"]; }
886
+ static get properties() { return { playing: { attribute: "playing", type: Boolean }, speed: { attribute: "speed" }, progress: { attribute: "progress" }, min: { attribute: "min" }, max: { attribute: "max" }, loop: { attribute: "loop", type: Boolean }, step: { attribute: "step" }, markers: { attribute: "markers" } }; }
795
887
  render() {
796
888
  this.classList.add("c-animation-controls");
797
889
  this.setAttribute("role", "toolbar");
@@ -802,16 +894,56 @@ class ContourAnimationControls extends ContourBase {
802
894
  const speed = this.getAttribute("speed") || "1x";
803
895
  const speedBtn = this.ensure(".c-animation-controls__speed", () => { const el = document.createElement("button"); el.className = "c-btn c-btn--sm c-animation-controls__speed"; el.type = "button"; return el; });
804
896
  speedBtn.textContent = speed;
897
+ speedBtn.setAttribute("aria-label", "Playback speed " + speed);
898
+ // Loop is a control, not just an aria-label suffix (R20 T-10).
899
+ const loopBtn = this.ensure(".c-animation-controls__loop", () => { const el = document.createElement("button"); el.className = "c-btn c-btn--sm c-animation-controls__loop"; el.type = "button"; el.textContent = "Loop"; return el; });
900
+ loopBtn.setAttribute("aria-pressed", String(this.hasAttribute("loop")));
901
+ // Toolbar: one tab stop, arrows rove (the scrubber keeps native keys).
902
+ playBtn.tabIndex = 0;
903
+ speedBtn.tabIndex = -1;
904
+ loopBtn.tabIndex = -1;
805
905
  // scrubber
806
906
  const scrubber = this.ensure(".c-animation-controls__scrubber", () => { const el = document.createElement("input"); el.className = "c-range c-animation-controls__scrubber"; el.type = "range"; return el; });
807
907
  if (this.getAttribute("show-thumb") === "false") scrubber.classList.remove("c-animation-controls__scrubber--thumb");
808
908
  else scrubber.classList.add("c-animation-controls__scrubber--thumb");
809
909
  scrubber.min = this.getAttribute("min") || "0";
810
910
  scrubber.max = this.getAttribute("max") || "100";
911
+ scrubber.step = this.getAttribute("step") || "1";
811
912
  scrubber.value = this.getAttribute("progress") || "0";
913
+ // Accessible time values: expose current position as aria-valuenow and a
914
+ // human-readable label as aria-valuetext so screen readers announce it.
915
+ const min = Number(scrubber.min) || 0;
916
+ const max = Number(scrubber.max) || 100;
917
+ const v = Number(scrubber.value) || min;
918
+ scrubber.setAttribute("aria-valuenow", String(v));
919
+ scrubber.setAttribute("aria-valuetext", String(Math.round(v)));
920
+ scrubber.setAttribute("aria-valuemin", String(min));
921
+ scrubber.setAttribute("aria-valuemax", String(max));
812
922
  const caption = this.getAttribute("caption");
813
923
  if (caption) scrubber.setAttribute("aria-label", caption);
814
924
  else if (!scrubber.getAttribute("aria-label")) scrubber.setAttribute("aria-label", "Playhead");
925
+ // Markers (R20 T-10): the attribute was observed but never read. The
926
+ // native range draws datalist ticks, so the platform renders them.
927
+ const markersRaw = this.getAttribute("markers");
928
+ let markers = [];
929
+ if (markersRaw) { try { const p = JSON.parse(markersRaw); markers = Array.isArray(p) ? p : []; } catch (e) { warnBadJson(this, "markers", e); } }
930
+ const oldList = this.querySelector("datalist.c-animation-controls__markers");
931
+ if (markers.length) {
932
+ const dl = this.ensure("datalist.c-animation-controls__markers", () => { const el = document.createElement("datalist"); el.className = "c-animation-controls__markers"; return el; });
933
+ if (!dl.id) dl.id = this._animMarkersId || (this._animMarkersId = contourId("anim-markers"));
934
+ dl.innerHTML = "";
935
+ markers.forEach((m) => {
936
+ const opt = document.createElement("option");
937
+ const val = typeof m === "object" && m !== null ? m.value : m;
938
+ opt.value = String(val);
939
+ if (typeof m === "object" && m !== null && m.label) opt.label = String(m.label);
940
+ dl.appendChild(opt);
941
+ });
942
+ scrubber.setAttribute("list", dl.id);
943
+ } else {
944
+ if (oldList) oldList.remove();
945
+ scrubber.removeAttribute("list");
946
+ }
815
947
  // caption display
816
948
  const showCaption = this.hasAttribute("show-thumb-caption") || this.hasAttribute("show-thumb");
817
949
  if (caption && showCaption) {
@@ -821,41 +953,71 @@ class ContourAnimationControls extends ContourBase {
821
953
  const cap = this.querySelector(".c-animation-controls__caption");
822
954
  if (cap) cap.remove();
823
955
  }
956
+ // loop indicator
957
+ if (this.hasAttribute("loop")) {
958
+ this.setAttribute("aria-label", "Animation controls, loop");
959
+ }
824
960
  // showThumb: hide thumb via attribute? keep default
825
961
  }
826
962
  enhance() {
827
963
  if (this._wiredAnimControls) return;
828
964
  this._wiredAnimControls = true;
965
+ const SPEEDS = [0.5, 1, 2, 4];
966
+ // The playhead writes back to `progress` so a consumer reading the
967
+ // attribute sees it — but not mid-drag: the write re-renders, and a
968
+ // rebuilt scrubber would break the gesture (the time-slider's rule).
969
+ const writeProgress = (v) => { if (!this._animScrubbing) this.setAttribute("progress", String(v)); };
970
+ this.addEventListener("pointerdown", (e) => {
971
+ if (e.target && e.target.closest && e.target.closest(".c-animation-controls__scrubber")) this._animScrubbing = true;
972
+ }, { passive: true });
973
+ const endScrub = () => { this._animScrubbing = false; };
974
+ this.addEventListener("pointerup", endScrub, { passive: true });
975
+ this.addEventListener("pointercancel", endScrub, { passive: true });
829
976
  this.addEventListener("click", (e) => {
830
977
  const play = e.target && e.target.closest ? e.target.closest(".c-animation-controls__play") : null;
831
- const speed = e.target && e.target.closest ? e.target.closest(".c-animation-controls__speed") : null;
832
978
  if (play && this.contains(play)) {
833
- this.dispatchEvent(new CustomEvent("contour:toggle", { bubbles: true, composed: true, detail: { playing: !this.hasAttribute("playing") } }));
979
+ // The attribute is the source of truth: the observer below starts
980
+ // and stops the timer from it, and the re-render flips the label.
981
+ const next = !this.hasAttribute("playing");
982
+ this.toggleAttribute("playing", next);
983
+ this.dispatchEvent(new CustomEvent("contour:toggle", { bubbles: true, composed: true, detail: { playing: next } }));
984
+ return;
834
985
  }
986
+ const speed = e.target && e.target.closest ? e.target.closest(".c-animation-controls__speed") : null;
835
987
  if (speed && this.contains(speed)) {
836
- this.dispatchEvent(new CustomEvent("contour:change", { bubbles: true, composed: true, detail: { speed: speed.textContent } }));
988
+ const cur = parseFloat(this.getAttribute("speed") || "1x");
989
+ const idx = SPEEDS.indexOf(Number.isFinite(cur) ? cur : 1);
990
+ const next = SPEEDS[(idx + 1) % SPEEDS.length];
991
+ this.setAttribute("speed", next + "x");
992
+ this.dispatchEvent(new CustomEvent("contour:speed-change", { bubbles: true, composed: true, detail: { speed: next } }));
993
+ return;
994
+ }
995
+ const loop = e.target && e.target.closest ? e.target.closest(".c-animation-controls__loop") : null;
996
+ if (loop && this.contains(loop)) {
997
+ const next = !this.hasAttribute("loop");
998
+ this.toggleAttribute("loop", next);
999
+ this.dispatchEvent(new CustomEvent("contour:loop-change", { bubbles: true, composed: true, detail: { loop: next } }));
837
1000
  }
838
1001
  });
839
1002
  this.addEventListener("input", (e) => {
840
1003
  const scrubber = e.target && e.target.closest ? e.target.closest(".c-animation-controls__scrubber") : null;
841
1004
  if (scrubber && this.contains(scrubber)) {
842
1005
  const v = Number(scrubber.value);
1006
+ writeProgress(v);
843
1007
  this.dispatchEvent(new CustomEvent("contour:seek", { bubbles: true, composed: true, detail: { progress: v, value: v } }));
844
1008
  }
845
1009
  });
1010
+ this.addEventListener("change", (e) => {
1011
+ const scrubber = e.target && e.target.closest ? e.target.closest(".c-animation-controls__scrubber") : null;
1012
+ if (scrubber && this.contains(scrubber)) this.setAttribute("progress", scrubber.value);
1013
+ });
1014
+ // Toolbar keyboard: arrows rove the buttons; the scrubber keeps the
1015
+ // native range keys (arrows, Home/End, PageUp/PageDown) when focused.
846
1016
  this.addEventListener("keydown", (e) => {
847
- if (e.key === " " || e.key === "Enter") {
848
- const play = this.querySelector(".c-animation-controls__play");
849
- if (play && (e.target === play || !e.target || e.target === this)) { e.preventDefault(); play.click(); }
850
- } else if (e.key === "ArrowRight" || e.key === "ArrowLeft") {
851
- const scrubber = this.querySelector(".c-animation-controls__scrubber");
852
- if (scrubber) {
853
- e.preventDefault();
854
- const step = e.key === "ArrowRight" ? 1 : -1;
855
- scrubber.value = String(Number(scrubber.value) + step);
856
- scrubber.dispatchEvent(new Event("input", { bubbles: true }));
857
- }
858
- }
1017
+ if (e.target && e.target.closest && e.target.closest(".c-animation-controls__scrubber")) return;
1018
+ const buttons = Array.from(this.querySelectorAll(".c-animation-controls__play, .c-animation-controls__speed, .c-animation-controls__loop"));
1019
+ if (!buttons.includes(e.target)) return;
1020
+ navKey(e, buttons, { wrap: true, homeEnd: true, onNavigate: (i) => { buttons.forEach((b, j) => { b.tabIndex = j === i ? 0 : -1; }); }, onKey: (k, idx, item) => { if (k === "Enter" || k === " ") item.click(); } });
859
1021
  });
860
1022
  // Playback ownership: when `playing` is set, advance the playhead on a
861
1023
  // timer and emit contour:time-change so a consumer can sync its data.
@@ -871,9 +1033,18 @@ class ContourAnimationControls extends ContourBase {
871
1033
  const min = Number(scrubber.min || 0);
872
1034
  const max = Number(scrubber.max || 100);
873
1035
  let v = Number(scrubber.value || 0) + speedFactor();
874
- if (v > max) v = min;
1036
+ let ended = false;
1037
+ if (v > max) {
1038
+ if (this.hasAttribute("loop")) v = min;
1039
+ else { v = max; stop(); ended = true; }
1040
+ }
875
1041
  scrubber.value = String(v);
1042
+ writeProgress(v);
876
1043
  this.dispatchEvent(new CustomEvent("contour:time-change", { bubbles: true, composed: true, detail: { progress: v, value: v } }));
1044
+ if (ended) {
1045
+ this.removeAttribute("playing");
1046
+ this.dispatchEvent(new CustomEvent("contour:toggle", { bubbles: true, composed: true, detail: { playing: false } }));
1047
+ }
877
1048
  };
878
1049
  const start = () => { if (timer) return; timer = setInterval(tick, 100); };
879
1050
  const stop = () => { if (timer) { clearInterval(timer); timer = null; } };
@@ -894,9 +1065,16 @@ class ContourDropdown extends ContourBase {
894
1065
  static get properties() { return { label: { attribute: "label" }, items: { attribute: "items" } }; }
895
1066
  render() {
896
1067
  this.classList.add("c-dropdown");
1068
+ if (!this.hasAttribute("aria-label")) this.setAttribute("aria-label", "Dropdown");
897
1069
  const btn = this.ensure(".c-dropdown__trigger", () => { const el = document.createElement("button"); el.className = "c-dropdown__trigger c-btn c-btn--sm"; el.type = "button"; return el; });
898
1070
  btn.textContent = this.getAttribute("label") || "Menu";
1071
+ // The trigger advertises the menu it opens before it is opened: a reader
1072
+ // who tabs to it hears "has popup menu, collapsed", not "button".
1073
+ btn.setAttribute("aria-haspopup", "menu");
1074
+ btn.setAttribute("aria-expanded", "false");
899
1075
  const menu = this.ensure(".c-dropdown__menu", () => { const el = document.createElement("div"); el.className = "c-dropdown__menu c-menu"; el.setAttribute("role", "menu"); el.hidden = true; return el; });
1076
+ if (!menu.id) menu.id = (this.id || contourId("dd")) + "-menu";
1077
+ btn.setAttribute("aria-controls", menu.id);
900
1078
  // Slotted content: authored .c-menu__item children take precedence over
901
1079
  // the JSON `items` attribute.
902
1080
  const authoredItems = Array.from(this.querySelectorAll(":scope > .c-menu__item"));
@@ -915,7 +1093,7 @@ class ContourDropdown extends ContourBase {
915
1093
  li.textContent = typeof it === "string" ? it : (it.label || it.title || "");
916
1094
  menu.appendChild(li);
917
1095
  });
918
- } catch (e) { /* keep existing */ }
1096
+ } catch (e) { warnBadJson(this, "attribute", e); }
919
1097
  }
920
1098
  if (menu.parentNode !== this) this.appendChild(menu);
921
1099
  if (btn.parentNode !== this) this.insertBefore(btn, menu);
@@ -957,18 +1135,12 @@ class ContourDropdown extends ContourBase {
957
1135
  };
958
1136
  document.addEventListener("click", docClick);
959
1137
  onDispose(this, () => document.removeEventListener("click", docClick));
960
- const keyHandler = (e) => {
1138
+ const keyHandler = (e) => {
961
1139
  const m = menu(); const b = btn();
962
1140
  if (e.key === "Escape" && m && !m.hidden) { e.preventDefault(); m.hidden = true; if (b) { b.setAttribute("aria-expanded", "false"); try { b.focus(); } catch (err) {} } return; }
963
1141
  if (!m || m.hidden) return;
964
1142
  const items = Array.from(m.querySelectorAll(".c-menu__item"));
965
- const active = document.activeElement;
966
- const idx = items.indexOf(active);
967
- if (e.key === "ArrowDown") { e.preventDefault(); const next = items[Math.min(items.length - 1, idx + 1)] || items[0]; if (next) try { next.focus(); } catch (err) {} }
968
- else if (e.key === "ArrowUp") { e.preventDefault(); const prev = items[Math.max(0, idx - 1)] || items[items.length - 1]; if (prev) try { prev.focus(); } catch (err) {} }
969
- else if (e.key === "Enter" || e.key === " ") {
970
- if (active && items.includes(active)) { e.preventDefault(); active.click(); }
971
- }
1143
+ navKey(e, items, { wrap: true, enter: false, onKey: (k) => { if (k === "Enter" || k === " ") document.activeElement.click(); } });
972
1144
  };
973
1145
  document.addEventListener("keydown", keyHandler);
974
1146
  onDispose(this, () => document.removeEventListener("keydown", keyHandler));
@@ -977,8 +1149,11 @@ class ContourDropdown extends ContourBase {
977
1149
  define("contour-dropdown", ContourDropdown);
978
1150
 
979
1151
  /**
980
- * Annotation: a positioned note with label and x/y coordinates. Attributes:
981
- * `label`, `x`, `y`.
1152
+ * Annotation: a positioned, movable note. Attributes: `label`, `x`, `y`
1153
+ * (percentages of the offset parent, e.g. "40%"). The note is focusable:
1154
+ * dragging it or nudging with the arrow keys (Shift for 10% steps) writes
1155
+ * `x`/`y` back — the attributes ARE the serialization — and emits
1156
+ * `contour:drag` per move and `contour:dragend` on release (R20 T-11).
982
1157
  */
983
1158
  class ContourAnnotation extends ContourBase {
984
1159
  static get observed() { return ["label", "x", "y"]; }
@@ -986,6 +1161,7 @@ class ContourAnnotation extends ContourBase {
986
1161
  render() {
987
1162
  this.classList.add("c-annotation");
988
1163
  this.setAttribute("role", "note");
1164
+ if (!this.hasAttribute("tabindex")) this.setAttribute("tabindex", "0");
989
1165
  const label = this.getAttribute("label");
990
1166
  if (label) this.setAttribute("aria-label", label);
991
1167
  if (label) {
@@ -997,22 +1173,87 @@ class ContourAnnotation extends ContourBase {
997
1173
  if (x !== null) this.style.setProperty("--annotation-x", x);
998
1174
  if (y !== null) this.style.setProperty("--annotation-y", y);
999
1175
  }
1176
+ enhance() {
1177
+ if (this._wiredAnnotation) return;
1178
+ this._wiredAnnotation = true;
1179
+ // Percent of the offset parent, clamped to [0, 100]. The host itself is
1180
+ // the dragged node and survives re-render (only generated children are
1181
+ // rebuilt), so pointer capture on the host holds across writeback.
1182
+ const pct = (v, fallback) => {
1183
+ const n = parseFloat(v);
1184
+ return Number.isFinite(n) ? Math.min(100, Math.max(0, n)) : fallback;
1185
+ };
1186
+ const write = (x, y, key) => {
1187
+ // One render per move, not two: batch coalesces the x and y writes.
1188
+ this.batch(() => {
1189
+ this.setAttribute("x", x + "%");
1190
+ this.setAttribute("y", y + "%");
1191
+ });
1192
+ this.dispatchEvent(new CustomEvent("contour:drag", { bubbles: true, composed: true, detail: { delta: key ? 1 : 0, key: key || "pointer", value: x + "," + y } }));
1193
+ };
1194
+ let drag = null;
1195
+ this.addEventListener("pointerdown", (e) => {
1196
+ if (e.button !== undefined && e.button !== 0) return;
1197
+ const parent = this.offsetParent || this.parentElement;
1198
+ if (!parent) return;
1199
+ const rect = parent.getBoundingClientRect();
1200
+ drag = { px: e.clientX, py: e.clientY, x: pct(this.getAttribute("x"), 50), y: pct(this.getAttribute("y"), 50), w: rect.width || 1, h: rect.height || 1 };
1201
+ try { this.setPointerCapture(e.pointerId); } catch (err) {}
1202
+ try { this.focus(); } catch (err) {}
1203
+ e.preventDefault();
1204
+ });
1205
+ this.addEventListener("pointermove", (e) => {
1206
+ if (!drag) return;
1207
+ const x = Math.round((drag.x + ((e.clientX - drag.px) / drag.w) * 100) * 10) / 10;
1208
+ const y = Math.round((drag.y + ((e.clientY - drag.py) / drag.h) * 100) * 10) / 10;
1209
+ write(Math.min(100, Math.max(0, x)), Math.min(100, Math.max(0, y)));
1210
+ });
1211
+ const endDrag = () => {
1212
+ if (!drag) return;
1213
+ drag = null;
1214
+ this.dispatchEvent(new CustomEvent("contour:dragend", { bubbles: true, composed: true, detail: { value: (this.getAttribute("x") || "") + "," + (this.getAttribute("y") || "") } }));
1215
+ };
1216
+ this.addEventListener("pointerup", endDrag);
1217
+ this.addEventListener("pointercancel", endDrag);
1218
+ this.addEventListener("keydown", (e) => {
1219
+ const step = e.shiftKey ? 10 : 1;
1220
+ let dx = 0, dy = 0;
1221
+ if (e.key === "ArrowLeft") dx = -step;
1222
+ else if (e.key === "ArrowRight") dx = step;
1223
+ else if (e.key === "ArrowUp") dy = -step;
1224
+ else if (e.key === "ArrowDown") dy = step;
1225
+ else return;
1226
+ e.preventDefault();
1227
+ const x = Math.min(100, Math.max(0, pct(this.getAttribute("x"), 50) + dx));
1228
+ const y = Math.min(100, Math.max(0, pct(this.getAttribute("y"), 50) + dy));
1229
+ write(x, y, e.key);
1230
+ this.dispatchEvent(new CustomEvent("contour:dragend", { bubbles: true, composed: true, detail: { value: x + "," + y } }));
1231
+ });
1232
+ }
1000
1233
  }
1001
1234
  define("contour-annotation", ContourAnnotation);
1002
1235
 
1003
1236
  /**
1004
- * Style Switcher: web component wrapper.
1005
- * Attributes: `items`, `value`.
1237
+ * Style Switcher: a toggle-button group over map/styles. Attributes: `items`
1238
+ * (JSON) or authored `.c-style-switcher__option` buttons, and `value`.
1239
+ * Selecting an option writes `value` back — the pressed/active state is the
1240
+ * attribute's projection, not a one-shot render — and emits `contour:change`
1241
+ * (R20 T-12). Arrow keys rove one tab stop; Enter/Space select.
1006
1242
  */
1007
1243
  class ContourStyleSwitcher extends ContourBase {
1008
1244
  static get observed() { return ["items", "value"]; }
1009
1245
  static get properties() { return { items: { attribute: "items" }, value: { attribute: "value" } }; }
1010
1246
  render() {
1011
1247
  this.classList.add("c-style-switcher");
1248
+ if (!this.hasAttribute("role")) this.setAttribute("role", "group");
1249
+ if (!this.hasAttribute("aria-label")) this.setAttribute("aria-label", "Style switcher");
1012
1250
  const items = this.getAttribute("items");
1013
1251
  const value = this.getAttribute("value");
1014
- Array.from(this.querySelectorAll(".c-style-switcher__option")).forEach((n) => n.remove());
1015
- if (items) {
1252
+ // Authored options win over the JSON attribute (the dropdown contract);
1253
+ // they used to be destroyed on every render.
1254
+ const authored = Array.from(this.children).filter((n) => n.classList && n.classList.contains("c-style-switcher__option"));
1255
+ if (items && !authored.length) {
1256
+ Array.from(this.querySelectorAll(".c-style-switcher__option")).forEach((n) => n.remove());
1016
1257
  try {
1017
1258
  const parsed = JSON.parse(items);
1018
1259
  parsed.forEach((it) => {
@@ -1021,21 +1262,42 @@ class ContourStyleSwitcher extends ContourBase {
1021
1262
  btn.className = "c-style-switcher__option c-btn c-btn--sm";
1022
1263
  btn.type = "button";
1023
1264
  btn.textContent = name;
1024
- if (name === value) btn.classList.add("c-style-switcher__option--active");
1025
1265
  btn.dataset.value = name;
1026
1266
  this.appendChild(btn);
1027
1267
  });
1028
- } catch (e) { /* keep existing */ }
1268
+ } catch (e) { warnBadJson(this, "attribute", e); }
1029
1269
  }
1270
+ // Project the value onto every option, authored or generated, and keep
1271
+ // one tab stop: the active option (or the first).
1272
+ const opts = Array.from(this.querySelectorAll(".c-style-switcher__option"));
1273
+ let active = null;
1274
+ opts.forEach((btn) => {
1275
+ const v = btn.dataset.value != null ? btn.dataset.value : btn.textContent.trim();
1276
+ const on = v === value;
1277
+ btn.classList.toggle("c-style-switcher__option--active", on);
1278
+ btn.setAttribute("aria-pressed", String(on));
1279
+ btn.tabIndex = -1;
1280
+ if (on && !active) active = btn;
1281
+ });
1282
+ (active || opts[0])?.setAttribute("tabindex", "0");
1030
1283
  }
1031
1284
  enhance() {
1032
1285
  if (this._wiredStyleSwitcher) return;
1033
1286
  this._wiredStyleSwitcher = true;
1287
+ const select = (btn) => {
1288
+ const v = btn.dataset.value != null ? btn.dataset.value : btn.textContent.trim();
1289
+ // The writeback re-renders the pressed state; the event carries the
1290
+ // same value the attribute now holds.
1291
+ this.setAttribute("value", v);
1292
+ this.dispatchEvent(new CustomEvent("contour:change", { bubbles: true, composed: true, detail: { value: v } }));
1293
+ };
1034
1294
  this.addEventListener("click", (e) => {
1035
1295
  const btn = e.target && e.target.closest ? e.target.closest(".c-style-switcher__option") : null;
1036
- if (btn && this.contains(btn)) {
1037
- this.dispatchEvent(new CustomEvent("contour:change", { bubbles: true, composed: true, detail: { value: btn.dataset.value } }));
1038
- }
1296
+ if (btn && this.contains(btn)) select(btn);
1297
+ });
1298
+ this.addEventListener("keydown", (e) => {
1299
+ const opts = Array.from(this.querySelectorAll(".c-style-switcher__option"));
1300
+ navKey(e, opts, { onKey: (k) => { if (k === "Enter" || k === " ") { const btn = document.activeElement; if (btn && btn.classList.contains("c-style-switcher__option")) select(btn); } } });
1039
1301
  });
1040
1302
  }
1041
1303
  }
@@ -1050,6 +1312,12 @@ class ContourStylePanel extends ContourBase {
1050
1312
  static get properties() { return { title: { attribute: "title" }, layers: { attribute: "layers" }, classification: { attribute: "classification" }, palette: { attribute: "palette" }, breaks: { attribute: "breaks" }, opacity: { attribute: "opacity" } }; }
1051
1313
  render() {
1052
1314
  this.classList.add("c-style-panel");
1315
+ // Authored defaults captured once, before any edit or Revert writes:
1316
+ // Revert restores THESE, not the last rendered state (R20 T-12).
1317
+ if (!this._stylePanelDefault) {
1318
+ this._stylePanelDefault = {};
1319
+ for (const a of ["property", "classification", "palette", "breaks", "opacity", "n", "colors"]) this._stylePanelDefault[a] = this.getAttribute(a);
1320
+ }
1053
1321
  this.setAttribute("role", "group");
1054
1322
  this.setAttribute("aria-label", "Style panel");
1055
1323
  const title = this.getAttribute("title");
@@ -1061,29 +1329,36 @@ class ContourStylePanel extends ContourBase {
1061
1329
  if (singleMode) {
1062
1330
  const body = this.ensure(".c-style-panel__body", () => { const el = document.createElement("div"); el.className = "c-style-panel__body"; return el; });
1063
1331
  body.innerHTML = "";
1332
+ // Unique ids: the old code used the global "property"/"policy"/"palette"/"n",
1333
+ // so two panels on a page produced duplicate ids and broken label[for].
1334
+ const uid = contourId("style-panel");
1335
+ const propId = uid + "-property";
1336
+ const policyId = uid + "-policy";
1337
+ const paletteId = uid + "-palette";
1338
+ const nId = uid + "-n";
1064
1339
  // property field
1065
- const propLabel = document.createElement("label"); propLabel.textContent = "Colour field"; propLabel.setAttribute("for", "property"); body.appendChild(propLabel);
1066
- const propIn = document.createElement("input"); propIn.type = "text"; propIn.id = "property"; propIn.className = "c-style-panel__property c-input"; propIn.setAttribute("aria-label", "Colour field");
1340
+ const propLabel = document.createElement("label"); propLabel.textContent = labelText(this, "colour-field", "Colour field"); propLabel.setAttribute("for", propId); body.appendChild(propLabel);
1341
+ const propIn = document.createElement("input"); propIn.type = "text"; propIn.id = propId; propIn.className = "c-style-panel__property c-input"; propIn.setAttribute("aria-label", labelText(this, "colour-field", "Colour field"));
1067
1342
  const pv = this.getAttribute("property"); if (pv) propIn.value = pv;
1068
1343
  body.appendChild(propIn);
1069
1344
  // classification method selector (policy)
1070
- const clsLabel = document.createElement("label"); clsLabel.textContent = "Classification"; clsLabel.setAttribute("for", "policy"); body.appendChild(clsLabel);
1071
- const clsSel = document.createElement("select"); clsSel.id = "policy"; clsSel.className = "c-style-panel__classification c-input"; clsSel.setAttribute("aria-label", "Classification method");
1345
+ const clsLabel = document.createElement("label"); clsLabel.textContent = labelText(this, "classification", "Classification"); clsLabel.setAttribute("for", policyId); body.appendChild(clsLabel);
1346
+ const clsSel = document.createElement("select"); clsSel.id = policyId; clsSel.className = "c-style-panel__classification c-input"; clsSel.setAttribute("aria-label", labelText(this, "classification-method", "Classification method"));
1072
1347
  ["equal","quantile","jenks","manual"].forEach((m) => { const o = document.createElement("option"); o.value = m; o.textContent = m; clsSel.appendChild(o); });
1073
1348
  const cls = this.getAttribute("classification"); if (cls) clsSel.value = cls;
1074
1349
  body.appendChild(clsSel);
1075
1350
  // palette picker
1076
- const palLabel = document.createElement("label"); palLabel.textContent = "Palette"; palLabel.setAttribute("for", "palette"); body.appendChild(palLabel);
1077
- const pal = document.createElement("input"); pal.type = "text"; pal.id = "palette"; pal.className = "c-style-panel__palette c-input"; pal.placeholder = "palette"; pal.setAttribute("aria-label", "Palette");
1351
+ const palLabel = document.createElement("label"); palLabel.textContent = labelText(this, "palette", "Palette"); palLabel.setAttribute("for", paletteId); body.appendChild(palLabel);
1352
+ const pal = document.createElement("input"); pal.type = "text"; pal.id = paletteId; pal.className = "c-style-panel__palette c-input"; pal.placeholder = labelText(this, "palette", "Palette"); pal.setAttribute("aria-label", labelText(this, "palette", "Palette"));
1078
1353
  const palv = this.getAttribute("palette"); if (palv) pal.value = palv;
1079
1354
  body.appendChild(pal);
1080
1355
  // n (class count)
1081
- const nLabel = document.createElement("label"); nLabel.textContent = "Classes"; nLabel.setAttribute("for", "n"); body.appendChild(nLabel);
1082
- const nIn = document.createElement("input"); nIn.type = "number"; nIn.id = "n"; nIn.className = "c-style-panel__n c-input"; nIn.min = "2"; nIn.max = "12"; nIn.setAttribute("aria-label", "Class count");
1356
+ const nLabel = document.createElement("label"); nLabel.textContent = labelText(this, "classes", "Classes"); nLabel.setAttribute("for", nId); body.appendChild(nLabel);
1357
+ const nIn = document.createElement("input"); nIn.type = "number"; nIn.id = nId; nIn.className = "c-style-panel__n c-input"; nIn.min = "2"; nIn.max = "12"; nIn.setAttribute("aria-label", labelText(this, "class-count", "Class count"));
1083
1358
  const nv = this.getAttribute("n"); if (nv) nIn.value = nv; else nIn.value = "5";
1084
1359
  body.appendChild(nIn);
1085
1360
  // opacity slider
1086
- const op = document.createElement("input"); op.type = "range"; op.className = "c-style-panel__opacity"; op.setAttribute("aria-label", "Opacity"); op.min = "0"; op.max = "100";
1361
+ const op = document.createElement("input"); op.type = "range"; op.className = "c-style-panel__opacity"; op.setAttribute("aria-label", labelText(this, "opacity", "Opacity")); op.min = "0"; op.max = "100";
1087
1362
  const ov = this.getAttribute("opacity"); op.value = ov != null ? ov : "100";
1088
1363
  body.appendChild(op);
1089
1364
  // breaks as .break elements per class
@@ -1095,7 +1370,7 @@ class ContourStylePanel extends ContourBase {
1095
1370
  breaksArr.forEach((b, i) => {
1096
1371
  const br = document.createElement("div"); br.className = "break";
1097
1372
  const span = document.createElement("span"); span.textContent = String(b); br.appendChild(span);
1098
- const inp = document.createElement("input"); inp.type = "number"; inp.className = "c-style-panel__breaks c-input"; inp.setAttribute("aria-label", "Class lower bound"); inp.value = String(b);
1373
+ const inp = document.createElement("input"); inp.type = "number"; inp.className = "c-style-panel__breaks c-input"; inp.setAttribute("aria-label", labelText(this, "class-lower-bound", "Class lower bound")); inp.value = String(b);
1099
1374
  br.appendChild(inp);
1100
1375
  breaksWrap.appendChild(br);
1101
1376
  });
@@ -1108,17 +1383,18 @@ class ContourStylePanel extends ContourBase {
1108
1383
  if (Array.isArray(colors)) {
1109
1384
  const list = document.createElement("div"); list.className = "c-style-panel__colors";
1110
1385
  colors.forEach((c, i) => {
1111
- const sw = document.createElement("input"); sw.type = "color"; sw.className = "c-style-panel__color c-input"; sw.setAttribute("aria-label", "Colour for class " + (i + 1));
1386
+ const sw = document.createElement("input"); sw.type = "color"; sw.className = "c-style-panel__color c-input"; sw.setAttribute("aria-label", labelText(this, "colour-for-class", "Colour for class") + " " + (i + 1));
1112
1387
  sw.value = c;
1113
- sw.addEventListener("input", () => { sw.setAttribute("data-edited", "true"); });
1388
+ // data-edited is marked by the delegated input handler in
1389
+ // enhance() — a per-node listener here died with the render.
1114
1390
  list.appendChild(sw);
1115
1391
  });
1116
1392
  body.appendChild(list);
1117
1393
  }
1118
1394
  // Apply/Revert buttons
1119
1395
  const actions = document.createElement("div"); actions.className = "c-style-panel__actions c-btn-group";
1120
- const applyBtn = document.createElement("button"); applyBtn.type = "button"; applyBtn.className = "c-btn c-btn--primary"; applyBtn.textContent = "Apply";
1121
- const revertBtn = document.createElement("button"); revertBtn.type = "button"; revertBtn.className = "c-btn"; revertBtn.textContent = "Revert";
1396
+ const applyBtn = document.createElement("button"); applyBtn.type = "button"; applyBtn.className = "c-btn c-btn--primary"; applyBtn.textContent = labelText(this, "apply", "Apply"); applyBtn.dataset.action = "apply";
1397
+ const revertBtn = document.createElement("button"); revertBtn.type = "button"; revertBtn.className = "c-btn"; revertBtn.textContent = labelText(this, "revert", "Revert"); revertBtn.dataset.action = "revert";
1122
1398
  actions.appendChild(applyBtn); actions.appendChild(revertBtn);
1123
1399
  body.appendChild(actions);
1124
1400
  return;
@@ -1162,7 +1438,7 @@ class ContourStylePanel extends ContourBase {
1162
1438
  // classification method selector
1163
1439
  const clsSel = document.createElement("select");
1164
1440
  clsSel.className = "c-style-panel__classification";
1165
- clsSel.setAttribute("aria-label", "Classification method");
1441
+ clsSel.setAttribute("aria-label", labelText(this, "classification-method", "Classification method"));
1166
1442
  ["equal","quantile","jenks","manual"].forEach((m) => { const o = document.createElement("option"); o.value = m; o.textContent = m; clsSel.appendChild(o); });
1167
1443
  if (typeof l === "object" && l.classification) clsSel.value = l.classification;
1168
1444
  row.appendChild(clsSel);
@@ -1179,13 +1455,14 @@ class ContourStylePanel extends ContourBase {
1179
1455
  breaks.type = "text";
1180
1456
  breaks.className = "c-style-panel__breaks";
1181
1457
  breaks.placeholder = "breaks";
1458
+ breaks.setAttribute("aria-label", "Class breaks");
1182
1459
  if (typeof l === "object" && l.breaks) breaks.value = (Array.isArray(l.breaks) ? l.breaks.join(",") : l.breaks);
1183
1460
  row.appendChild(breaks);
1184
1461
  // opacity control
1185
1462
  const op = document.createElement("input");
1186
1463
  op.type = "range";
1187
1464
  op.className = "c-style-panel__opacity";
1188
- op.setAttribute("aria-label", "Opacity");
1465
+ op.setAttribute("aria-label", labelText(this, "opacity", "Opacity"));
1189
1466
  op.min = "0"; op.max = "100";
1190
1467
  op.value = (typeof l === "object" && l.opacity != null) ? l.opacity : "100";
1191
1468
  row.appendChild(op);
@@ -1216,6 +1493,7 @@ class ContourStylePanel extends ContourBase {
1216
1493
  this.addEventListener("input", (e) => {
1217
1494
  const t = e.target;
1218
1495
  if (!t || !this.contains(t)) return;
1496
+ if (t.classList.contains("c-style-panel__color")) t.setAttribute("data-edited", "true");
1219
1497
  if (t.classList.contains("c-style-panel__palette") || t.classList.contains("c-style-panel__breaks")) {
1220
1498
  const row = t.closest(".c-style-panel__row");
1221
1499
  const name = row ? (row.querySelector(".c-style-panel__name")?.textContent || "") : "";
@@ -1225,9 +1503,47 @@ class ContourStylePanel extends ContourBase {
1225
1503
  this.addEventListener("click", (e) => {
1226
1504
  const t = e.target && e.target.closest ? e.target.closest("button") : null;
1227
1505
  if (!t || !this.contains(t)) return;
1228
- if (t.textContent.trim() === "Apply") {
1229
- this.dispatchEvent(new CustomEvent("contour:style-resolved", { detail: { applied: true }, bubbles: true, composed: true }));
1230
- } else if (t.textContent.trim() === "Revert") {
1506
+ // Match the action, not the English label: a localized panel used to
1507
+ // go inert because the handler compared textContent to "Apply".
1508
+ if (t.dataset.action === "apply") {
1509
+ // Carry the current control values, not just { applied: true }: a
1510
+ // consumer listening for the apply needs to know what was applied.
1511
+ const body = this.querySelector(".c-style-panel__body");
1512
+ const payload = { applied: true };
1513
+ if (body) {
1514
+ const prop = body.querySelector(".c-style-panel__property");
1515
+ const cls = body.querySelector(".c-style-panel__classification");
1516
+ const pal = body.querySelector(".c-style-panel__palette");
1517
+ const n = body.querySelector(".c-style-panel__n");
1518
+ const colors = Array.from(body.querySelectorAll(".c-style-panel__color")).map((c) => c.value);
1519
+ if (prop) payload.property = prop.value;
1520
+ if (cls) payload.classification = cls.value;
1521
+ if (pal) payload.palette = pal.value;
1522
+ if (n) payload.n = Number(n.value);
1523
+ if (colors.length) payload.colors = colors;
1524
+ }
1525
+ this.dispatchEvent(new CustomEvent("contour:style-resolved", { detail: payload, bubbles: true, composed: true }));
1526
+ } else if (t.dataset.action === "revert") {
1527
+ // Revert restores the authored defaults captured at first render —
1528
+ // it used to emit { applied: false } and restore nothing. The
1529
+ // controls are the live state, so the rebuild must skip the base
1530
+ // class's value-restore (_contourResetting); otherwise an edited
1531
+ // control is written straight back over the default it was meant
1532
+ // to lose. The explicit __rerender__ fires even when no attribute
1533
+ // actually changed — a user who edited only the live controls
1534
+ // leaves every attribute at its authored value, so batch() alone
1535
+ // would coalesce to nothing and the panel would keep the edit.
1536
+ const def = this._stylePanelDefault || {};
1537
+ this._contourResetting = true;
1538
+ try {
1539
+ for (const a of ["property", "classification", "palette", "breaks", "opacity", "n", "colors"]) {
1540
+ if (def[a] === null || def[a] === undefined) this.removeAttribute(a);
1541
+ else this.setAttribute(a, def[a]);
1542
+ }
1543
+ this.attributeChangedCallback("__rerender__", null, "");
1544
+ } finally {
1545
+ this._contourResetting = false;
1546
+ }
1231
1547
  this.dispatchEvent(new CustomEvent("contour:style-resolved", { detail: { applied: false }, bubbles: true, composed: true }));
1232
1548
  }
1233
1549
  });
@@ -1280,7 +1596,7 @@ class ContourAvatarGroup extends ContourBase {
1280
1596
  overflow.textContent = "+" + (parsed.length - max);
1281
1597
  this.appendChild(overflow);
1282
1598
  }
1283
- } catch (e) { /* keep existing */ }
1599
+ } catch (e) { warnBadJson(this, "attribute", e); }
1284
1600
  }
1285
1601
  }
1286
1602
  }
@@ -1317,7 +1633,12 @@ class ContourStatusLight extends ContourBase {
1317
1633
  this.classList.add("c-status-light");
1318
1634
  const status = this.getAttribute("status") || "neutral";
1319
1635
  this.classList.add("c-status-light--" + status);
1636
+ // A status light is a labelled graphic: give it a role and a name so the
1637
+ // colour is not the only carrier of the state.
1638
+ if (!this.hasAttribute("role")) this.setAttribute("role", "img");
1320
1639
  const label = this.getAttribute("label");
1640
+ if (label && !this.hasAttribute("aria-label")) this.setAttribute("aria-label", label);
1641
+ else if (!label && !this.hasAttribute("aria-label")) this.setAttribute("aria-label", status);
1321
1642
  if (label) {
1322
1643
  const l = this.ensure(".c-status-light__label", () => { const el = document.createElement("span"); el.className = "c-status-light__label"; return el; });
1323
1644
  l.textContent = label;
@@ -1339,6 +1660,12 @@ class ContourSplitButton extends ContourBase {
1339
1660
  main.textContent = this.getAttribute("label") || "Action";
1340
1661
  const toggle = this.ensure(".c-split-button__toggle", () => { const el = document.createElement("button"); el.className = "c-btn c-btn--icon c-split-button__toggle"; el.type = "button"; el.setAttribute("aria-label", "More options"); el.textContent = "▾"; return el; });
1341
1662
  const menu = this.ensure(".c-split-button__menu", () => { const el = document.createElement("div"); el.className = "c-menu c-split-button__menu"; el.setAttribute("role", "menu"); el.hidden = true; return el; });
1663
+ // The toggle opens a menu: it says so, it owns the state, and it names the
1664
+ // node it opens. Without all three a reader hears an unlabelled "▾".
1665
+ if (!menu.id) menu.id = (this.id || contourId("split")) + "-menu";
1666
+ toggle.setAttribute("aria-haspopup", "menu");
1667
+ toggle.setAttribute("aria-controls", menu.id);
1668
+ toggle.setAttribute("aria-expanded", String(!menu.hidden));
1342
1669
  const items = this.getAttribute("menu");
1343
1670
  if (items) {
1344
1671
  try {
@@ -1351,7 +1678,7 @@ class ContourSplitButton extends ContourBase {
1351
1678
  li.textContent = typeof it === "string" ? it : (it.label || it.title || "");
1352
1679
  menu.appendChild(li);
1353
1680
  });
1354
- } catch (e) { /* keep existing */ }
1681
+ } catch (e) { warnBadJson(this, "attribute", e); }
1355
1682
  }
1356
1683
  if (main.parentNode !== this) this.appendChild(main);
1357
1684
  if (toggle.parentNode !== this) this.appendChild(toggle);
@@ -1362,34 +1689,67 @@ class ContourSplitButton extends ContourBase {
1362
1689
  this._wiredSplitButton = true;
1363
1690
  const toggle = () => this.querySelector(".c-split-button__toggle");
1364
1691
  const menu = () => this.querySelector(".c-split-button__menu");
1692
+ const items = () => Array.from(menu()?.querySelectorAll(".c-menu__item") || []);
1693
+ // One open/close path for click, keyboard and outside-click, so the
1694
+ // toggle event and aria-expanded fire exactly once per transition on
1695
+ // every path (the keyboard path used to skip the event).
1696
+ const setOpen = (open, focusFirst) => {
1697
+ const m = menu(); const t = toggle();
1698
+ if (!m) return;
1699
+ const was = !m.hidden;
1700
+ m.hidden = !open;
1701
+ if (t) t.setAttribute("aria-expanded", String(open));
1702
+ if (open && focusFirst) { const first = items()[0]; if (first) try { first.focus(); } catch (e) {} }
1703
+ if (was !== open) this.dispatchEvent(new CustomEvent("contour:toggle", { bubbles: true, composed: true, detail: { open } }));
1704
+ };
1365
1705
  this.addEventListener("click", (e) => {
1706
+ const main = e.target && e.target.closest ? e.target.closest(".c-split-button__main") : null;
1707
+ if (main && this.contains(main)) {
1708
+ // The primary action is half the widget; it used to do nothing.
1709
+ this.dispatchEvent(new CustomEvent("contour:activate", { bubbles: true, composed: true, detail: { label: main.textContent } }));
1710
+ return;
1711
+ }
1366
1712
  const t = toggle();
1367
1713
  if (e.target === t || (t && t.contains(e.target))) {
1368
1714
  const m = menu();
1369
- if (m) { m.hidden = !m.hidden; t.setAttribute("aria-expanded", String(!m.hidden)); this.dispatchEvent(new CustomEvent("contour:toggle", { bubbles: true, composed: true, detail: { open: !m.hidden } })); }
1715
+ setOpen(m ? m.hidden : false, true);
1716
+ return;
1370
1717
  }
1371
1718
  const item = e.target && e.target.closest ? e.target.closest(".c-menu__item") : null;
1372
1719
  if (item && this.contains(item)) {
1373
- const m = menu();
1374
- if (m) { m.hidden = true; const t = toggle(); if (t) t.setAttribute("aria-expanded", "false"); }
1375
- this.dispatchEvent(new CustomEvent("contour:select", { bubbles: true, composed: true, detail: { label: item.textContent } }));
1720
+ const index = items().indexOf(item);
1721
+ setOpen(false, false);
1722
+ try { toggle()?.focus(); } catch (err) {}
1723
+ this.dispatchEvent(new CustomEvent("contour:select", { bubbles: true, composed: true, detail: { label: item.textContent, index } }));
1376
1724
  }
1377
1725
  });
1378
1726
  this.addEventListener("keydown", (e) => {
1379
1727
  const t = toggle();
1380
- if ((e.target === t || (t && t.contains(e.target))) && (e.key === "Enter" || e.key === " ")) {
1728
+ const m = menu();
1729
+ const list = items();
1730
+ const onToggle = e.target === t || (t && t.contains(e.target));
1731
+ const idx = list.indexOf(e.target);
1732
+ if (onToggle && (e.key === "Enter" || e.key === " " || e.key === "ArrowDown")) {
1381
1733
  e.preventDefault();
1382
- const m = menu();
1383
- if (m) { m.hidden = !m.hidden; t.setAttribute("aria-expanded", String(!m.hidden)); }
1384
- } else if (e.key === "Escape") {
1385
- const m = menu();
1386
- if (m && !m.hidden) { m.hidden = true; if (t) t.setAttribute("aria-expanded", "false"); }
1734
+ setOpen(true, true);
1735
+ } else if (onToggle && e.key === "ArrowUp") {
1736
+ e.preventDefault();
1737
+ setOpen(true, false);
1738
+ const last = list[list.length - 1]; if (last) try { last.focus(); } catch (err) {}
1739
+ } else if (idx >= 0) {
1740
+ if (e.key === "ArrowDown") { e.preventDefault(); list[(idx + 1) % list.length]?.focus(); }
1741
+ else if (e.key === "ArrowUp") { e.preventDefault(); list[(idx - 1 + list.length) % list.length]?.focus(); }
1742
+ else if (e.key === "Home") { e.preventDefault(); list[0]?.focus(); }
1743
+ else if (e.key === "End") { e.preventDefault(); list[list.length - 1]?.focus(); }
1744
+ else if (e.key === "Escape") { e.preventDefault(); setOpen(false, false); try { t?.focus(); } catch (err) {} }
1745
+ // Enter/Space on a menuitem is the native button's own click.
1746
+ } else if (e.key === "Escape" && m && !m.hidden) {
1747
+ setOpen(false, false); try { t?.focus(); } catch (err) {}
1387
1748
  }
1388
1749
  });
1389
1750
  const docClick = (e) => {
1390
1751
  const m = menu();
1391
- const t = toggle();
1392
- if (m && !m.hidden && !this.contains(e.target)) { m.hidden = true; if (t) t.setAttribute("aria-expanded", "false"); }
1752
+ if (m && !m.hidden && !this.contains(e.target)) setOpen(false, false);
1393
1753
  };
1394
1754
  document.addEventListener("click", docClick);
1395
1755
  onDispose(this, () => document.removeEventListener("click", docClick));
@@ -1404,57 +1764,157 @@ class ContourSplitButton extends ContourBase {
1404
1764
  class ContourPaletteEditor extends ContourBase {
1405
1765
  static get observed() { return ["colors"]; }
1406
1766
  static get properties() { return { colors: { attribute: "colors" } }; }
1767
+ _palette() {
1768
+ let parsed = [];
1769
+ try { const c = this.getAttribute("colors"); parsed = c ? JSON.parse(c) : []; } catch (e) { warnBadJson(this, "colors", e); }
1770
+ if (!Array.isArray(parsed)) parsed = [];
1771
+ return parsed.map((c) => typeof c === "string" ? { color: c, name: c } : { color: String(c.color || c.value || "#000000"), name: String(c.name || c.label || c.color || c.value || "color") });
1772
+ }
1773
+ _writePalette(entries) {
1774
+ // The colors attribute IS the serialization (R20 T-15): every edit,
1775
+ // add and remove writes it back, so a re-render keeps the user's work.
1776
+ this.setAttribute("colors", JSON.stringify(entries.map((e) => e.name === e.color ? e.color : { color: e.color, name: e.name })));
1777
+ }
1407
1778
  render() {
1408
1779
  this.classList.add("c-palette-editor");
1409
- const colors = this.getAttribute("colors");
1410
- Array.from(this.querySelectorAll(".c-palette-editor__swatch")).forEach((n) => n.remove());
1411
- if (colors) {
1412
- try {
1413
- const parsed = JSON.parse(colors);
1414
- parsed.forEach((c) => {
1415
- const sw = document.createElement("button");
1416
- sw.className = "c-palette-editor__swatch c-swatch";
1417
- sw.type = "button";
1418
- sw.style.background = typeof c === "string" ? c : (c.color || c.value || "");
1419
- sw.dataset.color = typeof c === "string" ? c : (c.color || c.value || "");
1420
- sw.setAttribute("aria-label", typeof c === "string" ? c : (c.name || c.label || "color"));
1421
- this.appendChild(sw);
1422
- });
1423
- } catch (e) { /* keep existing */ }
1780
+ if (!this.hasAttribute("role")) this.setAttribute("role", "group");
1781
+ if (!this.hasAttribute("aria-label")) this.setAttribute("aria-label", "Palette editor");
1782
+ const entries = this._palette();
1783
+ Array.from(this.querySelectorAll(".c-palette-editor__swatch, .c-palette-editor__edit, .c-palette-editor__remove, .c-palette-editor__add, .c-palette-editor__contrast")).forEach((n) => n.remove());
1784
+ entries.forEach((entry, i) => {
1785
+ const sw = document.createElement("button");
1786
+ sw.className = "c-palette-editor__swatch c-swatch" + (this._paletteSelected === i ? " is-selected" : "");
1787
+ sw.type = "button";
1788
+ sw.style.background = safeColor(entry.color);
1789
+ sw.dataset.color = entry.color;
1790
+ sw.dataset.index = String(i);
1791
+ sw.setAttribute("aria-label", entry.name);
1792
+ sw.setAttribute("aria-pressed", String(this._paletteSelected === i));
1793
+ this.appendChild(sw);
1794
+ // The native color input is the edit surface — the platform's picker,
1795
+ // not a reinvented one.
1796
+ const edit = document.createElement("input");
1797
+ edit.type = "color";
1798
+ edit.className = "c-palette-editor__edit";
1799
+ edit.value = /^#[0-9a-f]{6}$/i.test(entry.color) ? entry.color : "#000000";
1800
+ edit.dataset.index = String(i);
1801
+ edit.setAttribute("aria-label", "Edit " + entry.name);
1802
+ this.appendChild(edit);
1803
+ const rm = document.createElement("button");
1804
+ rm.type = "button";
1805
+ rm.className = "c-palette-editor__remove";
1806
+ rm.dataset.index = String(i);
1807
+ rm.setAttribute("aria-label", "Remove " + entry.name);
1808
+ rm.textContent = "×";
1809
+ this.appendChild(rm);
1810
+ });
1811
+ const add = document.createElement("button");
1812
+ add.type = "button";
1813
+ add.className = "c-palette-editor__add";
1814
+ add.setAttribute("aria-label", labelText(this, "add-color", "Add color"));
1815
+ add.textContent = "+";
1816
+ this.appendChild(add);
1817
+ // Contrast feedback for the selected color: the ratio against white
1818
+ // and black, and whether the better one meets AA for body text.
1819
+ const sel = entries[this._paletteSelected];
1820
+ if (sel) {
1821
+ const lum = (hex) => {
1822
+ const m = /^#([0-9a-f]{6})$/i.exec(hex);
1823
+ if (!m) return null;
1824
+ const n = parseInt(m[1], 16);
1825
+ const ch = [(n >> 16) & 255, (n >> 8) & 255, n & 255].map((v) => { v /= 255; return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); });
1826
+ return 0.2126 * ch[0] + 0.7152 * ch[1] + 0.0722 * ch[2];
1827
+ };
1828
+ const l = lum(sel.color);
1829
+ const out = document.createElement("span");
1830
+ out.className = "c-palette-editor__contrast";
1831
+ if (l === null) {
1832
+ out.textContent = sel.color;
1833
+ } else {
1834
+ const ratio = (a, b) => (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
1835
+ const onWhite = ratio(l, 1), onBlack = ratio(l, 0);
1836
+ const best = Math.max(onWhite, onBlack);
1837
+ out.textContent = sel.name + ": " + onWhite.toFixed(1) + ":1 on white, " + onBlack.toFixed(1) + ":1 on black — " + (best >= 4.5 ? "AA" : "below AA");
1838
+ }
1839
+ this.appendChild(out);
1424
1840
  }
1425
1841
  }
1426
1842
  enhance() {
1427
1843
  if (this._wiredPaletteEditor) return;
1428
1844
  this._wiredPaletteEditor = true;
1429
1845
  this.addEventListener("click", (e) => {
1430
- const sw = e.target && e.target.closest ? e.target.closest(".c-palette-editor__swatch") : null;
1846
+ const t = e.target && e.target.closest ? e.target : null;
1847
+ if (!t) return;
1848
+ const sw = t.closest(".c-palette-editor__swatch");
1431
1849
  if (sw && this.contains(sw)) {
1432
- this.dispatchEvent(new CustomEvent("contour:change", { bubbles: true, composed: true, detail: { color: (sw.dataset && sw.dataset.color) || sw.style.background } }));
1850
+ this._paletteSelected = Number(sw.dataset.index);
1851
+ this.requestRender();
1852
+ this.dispatchEvent(new CustomEvent("contour:change", { bubbles: true, composed: true, detail: { color: sw.dataset.color } }));
1853
+ return;
1854
+ }
1855
+ const rm = t.closest(".c-palette-editor__remove");
1856
+ if (rm && this.contains(rm)) {
1857
+ const entries = this._palette();
1858
+ const i = Number(rm.dataset.index);
1859
+ const [gone] = entries.splice(i, 1);
1860
+ if (this._paletteSelected >= entries.length) this._paletteSelected = entries.length - 1;
1861
+ this._writePalette(entries);
1862
+ this.dispatchEvent(new CustomEvent("contour:remove", { bubbles: true, composed: true, detail: { value: gone ? gone.color : "" } }));
1863
+ return;
1864
+ }
1865
+ if (t.closest(".c-palette-editor__add")) {
1866
+ const entries = this._palette();
1867
+ const next = "#888888";
1868
+ entries.push({ color: next, name: next });
1869
+ this._paletteSelected = entries.length - 1;
1870
+ this._writePalette(entries);
1871
+ this.dispatchEvent(new CustomEvent("contour:add", { bubbles: true, composed: true, detail: { value: next } }));
1433
1872
  }
1434
1873
  });
1874
+ this.addEventListener("change", (e) => {
1875
+ const edit = e.target && e.target.closest ? e.target.closest(".c-palette-editor__edit") : null;
1876
+ if (!edit || !this.contains(edit)) return;
1877
+ const entries = this._palette();
1878
+ const i = Number(edit.dataset.index);
1879
+ if (!entries[i]) return;
1880
+ entries[i].color = edit.value;
1881
+ if (entries[i].name === entries[i].color || /^#[0-9a-f]{6}$/i.test(entries[i].name)) entries[i].name = edit.value;
1882
+ this._writePalette(entries);
1883
+ this.dispatchEvent(new CustomEvent("contour:change", { bubbles: true, composed: true, detail: { color: edit.value, values: entries.map((en) => en.color) } }));
1884
+ });
1435
1885
  this.addEventListener("keydown", (e) => {
1436
1886
  const swatches = Array.from(this.querySelectorAll(".c-palette-editor__swatch"));
1437
- const active = document.activeElement;
1438
- const idx = swatches.indexOf(active);
1439
- if (e.key === "ArrowRight") { e.preventDefault(); const next = swatches[Math.min(swatches.length - 1, idx + 1)] || swatches[0]; if (next) try { next.focus(); } catch (err) {} }
1440
- else if (e.key === "ArrowLeft") { e.preventDefault(); const prev = swatches[Math.max(0, idx - 1)] || swatches[swatches.length - 1]; if (prev) try { prev.focus(); } catch (err) {} }
1441
- else if (e.key === "Enter" || e.key === " ") { e.preventDefault(); if (active && active.classList.contains("c-palette-editor__swatch")) active.click(); }
1887
+ if (!swatches.includes(e.target)) return;
1888
+ navKey(e, swatches, { wrap: true, enter: true, onKey: (k, idx, item) => { if (k === "Enter" || k === " ") item.click(); } });
1442
1889
  });
1443
1890
  }
1444
1891
  }
1445
1892
  define("contour-palette-editor", ContourPaletteEditor);
1446
1893
 
1447
1894
  /**
1448
- * Date Range: web component wrapper.
1449
- * Attributes: `start`, `end`, `label`, `time`, `min`, `max`, `locale`.
1895
+ * Date Range: two native date (or datetime-local with `time`) inputs with a
1896
+ * shared label. Attributes: `start`, `end`, `label`, `time`, `min`, `max`,
1897
+ * `locale`, `name`, `required`, `disabled`. Form associated (R20 T-16): the
1898
+ * host submits the two dates as repeated entries under its name, reports
1899
+ * required/inverted validity, and resets to the authored defaults. The
1900
+ * inputs are distinctly named for assistive tech and cross-constrained
1901
+ * (end.min = start, start.max = end); a committed change writes start/end
1902
+ * back. The native pickers supply the calendar; timezone is the consumer's
1903
+ * (the values are local ISO strings, date-only unless `time`).
1450
1904
  */
1451
1905
  class ContourDateRange extends ContourBase {
1452
- static get observed() { return ["start", "end", "label", "time", "min", "max", "locale"]; }
1453
- static get properties() { return { start: { attribute: "start" }, end: { attribute: "end" }, label: { attribute: "label" }, time: { attribute: "time", type: Boolean }, min: { attribute: "min" }, max: { attribute: "max" }, locale: { attribute: "locale" } }; }
1906
+ static get observed() { return ["start", "end", "label", "time", "min", "max", "locale", "name", "required", "disabled"]; }
1907
+ static get properties() { return { start: { attribute: "start" }, end: { attribute: "end" }, label: { attribute: "label" }, time: { attribute: "time", type: Boolean }, min: { attribute: "min" }, max: { attribute: "max" }, locale: { attribute: "locale" }, name: { attribute: "name" }, required: { attribute: "required", type: Boolean }, disabled: { attribute: "disabled", type: Boolean } }; }
1908
+ static get formAssociated() { return true; }
1454
1909
  render() {
1455
1910
  this.classList.add("c-date-range");
1911
+ // Authored defaults captured before any commit reflects into them.
1912
+ if (this._dateRangeDefaultStart === undefined) {
1913
+ this._dateRangeDefaultStart = this.getAttribute("start");
1914
+ this._dateRangeDefaultEnd = this.getAttribute("end");
1915
+ }
1456
1916
  this.setAttribute("role", "group");
1457
- this.setAttribute("aria-label", "Date range");
1917
+ this.setAttribute("aria-label", this.getAttribute("label") || "Date range");
1458
1918
  const label = this.getAttribute("label");
1459
1919
  if (label) {
1460
1920
  const l = this.ensure(".c-date-range__label", () => { const el = document.createElement("span"); el.className = "c-date-range__label"; return el; });
@@ -1463,16 +1923,26 @@ class ContourDateRange extends ContourBase {
1463
1923
  const start = this.ensure(".c-date-range__start", () => { const el = document.createElement("input"); el.className = "c-input c-date-range__start"; return el; });
1464
1924
  start.type = this.hasAttribute("time") ? "datetime-local" : "date";
1465
1925
  start.value = this.getAttribute("start") || "";
1926
+ // Distinct names: both inputs used to carry the identical aria-label,
1927
+ // so a screen reader could not tell start from end.
1928
+ start.setAttribute("aria-label", label ? label + " — start" : "Start date");
1466
1929
  const end = this.ensure(".c-date-range__end", () => { const el = document.createElement("input"); el.className = "c-input c-date-range__end"; return el; });
1467
1930
  end.type = start.type;
1468
1931
  end.value = this.getAttribute("end") || "";
1932
+ end.setAttribute("aria-label", label ? label + " — end" : "End date");
1469
1933
  const min = this.getAttribute("min");
1470
1934
  const max = this.getAttribute("max");
1471
1935
  [start, end].forEach((input) => {
1472
1936
  if (min) input.min = min; else input.removeAttribute("min");
1473
1937
  if (max) input.max = max; else input.removeAttribute("max");
1474
1938
  if (this.getAttribute("locale")) input.lang = this.getAttribute("locale");
1939
+ if (this.hasAttribute("disabled")) input.setAttribute("disabled", ""); else input.removeAttribute("disabled");
1475
1940
  });
1941
+ // Cross-constraint: the picker cannot offer an inverted range.
1942
+ if (start.value) end.min = min && min > start.value ? min : start.value;
1943
+ if (end.value) start.max = max && max < end.value ? max : end.value;
1944
+ if (this.hasAttribute("required")) this.setAttribute("aria-required", "true"); else this.removeAttribute("aria-required");
1945
+ if (this._internals) this._syncFormValue();
1476
1946
  }
1477
1947
  enhance() {
1478
1948
  if (this._wiredDateRange) return;
@@ -1480,10 +1950,62 @@ class ContourDateRange extends ContourBase {
1480
1950
  this.addEventListener("change", (e) => {
1481
1951
  const t = e.target;
1482
1952
  if (t && (t.classList.contains("c-date-range__start") || t.classList.contains("c-date-range__end"))) {
1483
- this.dispatchEvent(new CustomEvent("contour:change", { bubbles: true, composed: true, detail: { start: this.querySelector(".c-date-range__start")?.value, end: this.querySelector(".c-date-range__end")?.value } }));
1953
+ const s = this.querySelector(".c-date-range__start");
1954
+ const en = this.querySelector(".c-date-range__end");
1955
+ // Commit writes back; the re-render re-applies the same values and
1956
+ // refreshes the cross-constraint.
1957
+ this.batch(() => {
1958
+ if (s) this.setAttribute("start", s.value);
1959
+ if (en) this.setAttribute("end", en.value);
1960
+ });
1961
+ this._syncFormValue();
1962
+ this.dispatchEvent(new CustomEvent("contour:change", { bubbles: true, composed: true, detail: { start: s?.value, end: en?.value } }));
1484
1963
  }
1485
1964
  });
1486
1965
  }
1966
+ _syncFormValue() {
1967
+ if (!this._internals) return;
1968
+ const start = this.querySelector(".c-date-range__start")?.value || "";
1969
+ const end = this.querySelector(".c-date-range__end")?.value || "";
1970
+ const name = this.getAttribute("name");
1971
+ if (name && (start || end)) {
1972
+ const fd = new FormData();
1973
+ if (start) fd.append(name, start);
1974
+ if (end) fd.append(name, end);
1975
+ this._internals.setFormValue(fd);
1976
+ } else {
1977
+ this._internals.setFormValue(null);
1978
+ }
1979
+ const missing = this.hasAttribute("required") && (!start || !end);
1980
+ const inverted = !!(start && end && start > end);
1981
+ if (missing) this._internals.setValidity({ valueMissing: true }, "Both dates are required.");
1982
+ else if (inverted) this._internals.setValidity({ customError: true }, "Start must be on or before end.");
1983
+ else this._internals.setValidity({});
1984
+ this._setCustomState("data-invalid", missing || inverted);
1985
+ for (const input of this.querySelectorAll("input")) input.setAttribute("aria-invalid", String(missing || inverted));
1986
+ }
1987
+ formResetCallback() {
1988
+ this._contourResetting = true;
1989
+ try {
1990
+ if (this._dateRangeDefaultStart === null) this.removeAttribute("start"); else this.setAttribute("start", this._dateRangeDefaultStart);
1991
+ if (this._dateRangeDefaultEnd === null) this.removeAttribute("end"); else this.setAttribute("end", this._dateRangeDefaultEnd);
1992
+ this._syncFormValue();
1993
+ } finally {
1994
+ this._contourResetting = false;
1995
+ }
1996
+ }
1997
+ formStateRestoreCallback(state) {
1998
+ if (!this._internals || state == null) return;
1999
+ const values = state instanceof FormData ? Array.from(state.getAll(this.getAttribute("name"))).map(String) : String(state).split(",");
2000
+ this._contourResetting = true;
2001
+ try {
2002
+ this.setAttribute("start", values[0] || "");
2003
+ this.setAttribute("end", values[1] || "");
2004
+ this._syncFormValue();
2005
+ } finally {
2006
+ this._contourResetting = false;
2007
+ }
2008
+ }
1487
2009
  }
1488
2010
  define("contour-date-range", ContourDateRange);
1489
2011
 
@@ -1496,6 +2018,8 @@ class ContourShortcut extends ContourBase {
1496
2018
  static get properties() { return { key: { attribute: "key" }, label: { attribute: "label" } }; }
1497
2019
  render() {
1498
2020
  this.classList.add("c-shortcut");
2021
+ if (!this.hasAttribute("role")) this.setAttribute("role", "group");
2022
+ if (!this.hasAttribute("aria-label")) this.setAttribute("aria-label", this.getAttribute("label") || "Keyboard shortcut");
1499
2023
  const key = this.getAttribute("key") || "";
1500
2024
  const label = this.getAttribute("label") || "";
1501
2025
  if (key) {
@@ -1593,6 +2117,7 @@ class ContourPopover extends ContourBase {
1593
2117
  * Attributes: `value`, `range`, `range-start`, `range-end`, `label`, `disabled`, `error`, `help`, `time`, `min`, `max`, `locale`.
1594
2118
  */
1595
2119
  class ContourDatePicker extends ContourBase {
2120
+ static get formAssociated() { return true; }
1596
2121
  static get observed() { return ["value", "range", "range-start", "range-end", "label", "disabled", "error", "help", "time", "min", "max", "locale"]; }
1597
2122
  static get properties() { return { value: { attribute: "value" }, range: { attribute: "range", type: Boolean }, rangeStart: { attribute: "range-start" }, rangeEnd: { attribute: "range-end" }, label: { attribute: "label" }, disabled: { attribute: "disabled", type: Boolean }, error: { attribute: "error" }, help: { attribute: "help" }, time: { attribute: "time", type: Boolean }, min: { attribute: "min" }, max: { attribute: "max" }, locale: { attribute: "locale" } }; }
1598
2123
  render() {
@@ -1609,7 +2134,12 @@ class ContourDatePicker extends ContourBase {
1609
2134
  const type = this.hasAttribute("time") ? "datetime-local" : "date";
1610
2135
  const configure = (control, value, name) => {
1611
2136
  control.type = type;
1612
- control.value = value || "";
2137
+ // Don't clobber a value the user is typing: only write when the control
2138
+ // is not focused and the incoming value differs. The old code set
2139
+ // control.value on every render, so a typed date reverted on any
2140
+ // attribute change.
2141
+ const next = value || "";
2142
+ if (document.activeElement !== control && control.value !== next) control.value = next;
1613
2143
  control.setAttribute("aria-label", name);
1614
2144
  if (this.hasAttribute("min")) control.min = this.getAttribute("min"); else control.removeAttribute("min");
1615
2145
  if (this.hasAttribute("max")) control.max = this.getAttribute("max"); else control.removeAttribute("max");
@@ -1662,32 +2192,86 @@ class ContourDatePicker extends ContourBase {
1662
2192
  const grid = document.createElement("div");
1663
2193
  grid.className = "c-date-picker__calendar-grid";
1664
2194
  grid.setAttribute("role", "grid");
2195
+ // A grid is rows of cells. The rows use `display: contents`, so the visual
2196
+ // seven-column layout is untouched while the accessibility tree gets a
2197
+ // real row/gridcell structure instead of thirty loose buttons.
2198
+ grid.setAttribute("aria-label", title.textContent);
2199
+ const rowEl = () => {
2200
+ const row = document.createElement("div");
2201
+ row.className = "c-date-picker__calendar-row";
2202
+ row.setAttribute("role", "row");
2203
+ grid.appendChild(row);
2204
+ return row;
2205
+ };
2206
+ let row = rowEl();
2207
+ let cells = 0;
2208
+ const push = (cell) => {
2209
+ if (cells === 7) { row = rowEl(); cells = 0; }
2210
+ row.appendChild(cell);
2211
+ cells++;
2212
+ };
1665
2213
  const weekdays = ["Su","Mo","Tu","We","Th","Fr","Sa"];
1666
- weekdays.forEach((w) => { const h = document.createElement("div"); h.className = "c-date-picker__calendar-weekday"; h.textContent = w; grid.appendChild(h); });
1667
- for (let i = 0; i < startDay; i++) { const empty = document.createElement("div"); empty.className = "c-date-picker__calendar-day c-date-picker__calendar-day--empty"; grid.appendChild(empty); }
2214
+ const weekdayNames = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
2215
+ weekdays.forEach((w, i) => {
2216
+ const h = document.createElement("div");
2217
+ h.className = "c-date-picker__calendar-weekday";
2218
+ h.setAttribute("role", "columnheader");
2219
+ h.setAttribute("aria-label", weekdayNames[i]);
2220
+ h.textContent = w;
2221
+ push(h);
2222
+ });
2223
+ for (let i = 0; i < startDay; i++) {
2224
+ const empty = document.createElement("div");
2225
+ empty.className = "c-date-picker__calendar-day c-date-picker__calendar-day--empty";
2226
+ empty.setAttribute("role", "gridcell");
2227
+ empty.setAttribute("aria-hidden", "true");
2228
+ push(empty);
2229
+ }
1668
2230
  const selected = input ? input.value : "";
2231
+ const inMonth = selected && selected.slice(0, 7) === `${y}-${String(m + 1).padStart(2, "0")}`;
2232
+ const stopDay = inMonth ? parseInt(selected.slice(8, 10), 10) || 1 : 1;
1669
2233
  for (let d = 1; d <= daysInMonth; d++) {
1670
2234
  const btn = document.createElement("button");
1671
2235
  btn.type = "button";
1672
2236
  btn.className = "c-date-picker__calendar-day";
1673
2237
  btn.textContent = String(d);
2238
+ btn.setAttribute("role", "gridcell");
2239
+ // One tab stop for the month; arrows move within the grid.
2240
+ btn.setAttribute("tabindex", d === stopDay ? "0" : "-1");
2241
+ // "12" is a number, not a date. The cell's name says the whole date.
2242
+ btn.setAttribute("aria-label", new Date(y, m, d).toLocaleDateString(this.getAttribute("locale") || undefined, { weekday: "long", day: "numeric", month: "long", year: "numeric" }));
1674
2243
  const iso = `${y}-${String(m + 1).padStart(2, "0")}-${String(d).padStart(2, "0")}`;
1675
- if (selected && selected.startsWith(iso)) btn.classList.add("is-selected");
2244
+ if (selected && selected.startsWith(iso)) { btn.classList.add("is-selected"); btn.setAttribute("aria-selected", "true"); }
1676
2245
  btn.addEventListener("click", () => {
1677
2246
  if (input) { input.value = iso; input.dispatchEvent(new Event("change", { bubbles: true })); }
1678
2247
  cal.setAttribute("hidden", "");
1679
2248
  const tgl = this.querySelector(".c-date-picker__calendar-toggle");
1680
2249
  if (tgl) tgl.setAttribute("aria-expanded", "false");
1681
2250
  });
1682
- grid.appendChild(btn);
2251
+ push(btn);
1683
2252
  }
1684
2253
  cal.appendChild(grid);
1685
2254
  prev.addEventListener("click", () => { this._calMonth = new Date(y, m - 1, 1); this._renderCalendar(); });
1686
2255
  next.addEventListener("click", () => { this._calMonth = new Date(y, m + 1, 1); this._renderCalendar(); });
2256
+ if (this._internals) this._syncFormValue();
2257
+ }
2258
+ _syncFormValue() {
2259
+ if (!this._internals) return;
2260
+ const start = this.querySelector(".c-date-picker__input");
2261
+ const end = this.querySelector(".c-date-picker__end");
2262
+ // A range picker submits both ends; a single picker submits its value.
2263
+ if (this.hasAttribute("range") && end) {
2264
+ this._internals.setFormValue((start ? start.value : "") + "," + end.value);
2265
+ } else {
2266
+ this._internals.setFormValue(start && start.value ? start.value : null);
2267
+ }
2268
+ this._syncValidity(this.hasAttribute("required") && !(start && start.value));
1687
2269
  }
1688
2270
  enhance() {
1689
2271
  if (this._wiredDatePicker) return;
1690
2272
  this._wiredDatePicker = true;
2273
+ this._syncFormValue();
2274
+ this.addEventListener("change", () => { this._syncFormValue(); });
1691
2275
  this.addEventListener("change", (e) => {
1692
2276
  const t = e.target;
1693
2277
  if (t && t.classList.contains("c-date-picker__input")) {
@@ -1708,6 +2292,34 @@ class ContourDatePicker extends ContourBase {
1708
2292
  const btn = e.target && e.target.closest ? e.target.closest(".c-date-picker__calendar-toggle") : null;
1709
2293
  if (btn && this.contains(btn)) { e.preventDefault(); toggle(); }
1710
2294
  });
2295
+ // Grid keyboard: one tab stop enters the month, arrows move between days,
2296
+ // Home/End reach the ends of the month and PageUp/PageDown change month.
2297
+ // Delegated on the host because `_renderCalendar()` rebuilds the cells.
2298
+ this.addEventListener("keydown", (e) => {
2299
+ const cal = this.querySelector(".c-date-picker__calendar");
2300
+ if (!cal || cal.hasAttribute("hidden")) return;
2301
+ const cells = Array.from(cal.querySelectorAll('[role="gridcell"]:not([aria-hidden="true"])'));
2302
+ const i = cells.indexOf(document.activeElement);
2303
+ if (i < 0) return;
2304
+ if (e.key === "PageUp" || e.key === "PageDown") {
2305
+ e.preventDefault();
2306
+ const btn = this.querySelector(e.key === "PageUp" ? ".c-date-picker__calendar-header button:first-child" : ".c-date-picker__calendar-header button:last-child");
2307
+ if (btn) btn.click();
2308
+ return;
2309
+ }
2310
+ let next = -1;
2311
+ if (e.key === "ArrowRight") next = i + 1;
2312
+ else if (e.key === "ArrowLeft") next = i - 1;
2313
+ else if (e.key === "ArrowDown") next = i + 7;
2314
+ else if (e.key === "ArrowUp") next = i - 7;
2315
+ else if (e.key === "Home") next = 0;
2316
+ else if (e.key === "End") next = cells.length - 1;
2317
+ else return;
2318
+ e.preventDefault();
2319
+ if (next < 0 || next >= cells.length) return;
2320
+ cells.forEach((cell, j) => cell.setAttribute("tabindex", j === next ? "0" : "-1"));
2321
+ cells[next].focus();
2322
+ });
1711
2323
  }
1712
2324
  }
1713
2325
  define("contour-date-picker", ContourDatePicker);
@@ -1721,19 +2333,32 @@ class ContourRating extends ContourBase {
1721
2333
  static get properties() { return { value: { attribute: "value", type: Number }, max: { attribute: "max", type: Number }, color: { attribute: "color" } }; }
1722
2334
  render() {
1723
2335
  this.classList.add("c-rating");
1724
- this.setAttribute("role", "radiogroup");
1725
- this.setAttribute("aria-label", "Rating");
2336
+ if (!this.hasAttribute("role")) this.setAttribute("role", "radiogroup");
2337
+ // The group's name is the author's choice; "Rating" is only the fallback.
2338
+ if (!this.hasAttribute("aria-label")) this.setAttribute("aria-label", "Rating");
1726
2339
  const max = parseInt(this.getAttribute("max") || "5", 10) || 5;
1727
2340
  const value = parseInt(this.getAttribute("value") || "0", 10) || 0;
1728
2341
  const color = this.getAttribute("color");
1729
2342
  Array.from(this.querySelectorAll(".c-rating__star")).forEach((n) => n.remove());
2343
+ // A radiogroup is one tab stop, arrow keys move within it. The checked
2344
+ // star (or the first when nothing is rated) is the one Tab reaches.
2345
+ const stop = value >= 1 && value <= max ? value : 1;
1730
2346
  for (let i = 1; i <= max; i++) {
1731
2347
  const star = document.createElement("button");
1732
2348
  star.className = "c-rating__star" + (i <= value ? " c-rating__star--filled" : "");
1733
2349
  star.type = "button";
1734
2350
  star.setAttribute("role", "radio");
1735
2351
  star.setAttribute("aria-checked", String(i === value));
1736
- star.innerHTML = '<span class="c-rating__swatch' + (i <= value ? ' c-rating__swatch--filled' : '') + '" aria-hidden="true"' + (color && i <= value ? ' style="background:' + color + ';border-color:' + color + '"' : '') + '></span>';
2352
+ star.setAttribute("tabindex", String(i === stop ? 0 : -1));
2353
+ star.innerHTML = '<span class="c-rating__swatch' + (i <= value ? ' c-rating__swatch--filled' : '') + '" aria-hidden="true"></span>';
2354
+ if (color && i <= value) {
2355
+ const sw = star.firstChild;
2356
+ const safe = safeColor(color);
2357
+ if (sw && safe) {
2358
+ sw.style.backgroundColor = safe;
2359
+ sw.style.borderColor = safe;
2360
+ }
2361
+ }
1737
2362
  star.dataset.value = String(i);
1738
2363
  star.setAttribute("aria-label", i + " star" + (i > 1 ? "s" : ""));
1739
2364
  this.appendChild(star);
@@ -1742,32 +2367,34 @@ class ContourRating extends ContourBase {
1742
2367
  enhance() {
1743
2368
  if (this._wiredRating) return;
1744
2369
  this._wiredRating = true;
2370
+ const stars = () => Array.from(this.querySelectorAll(".c-rating__star"));
2371
+ // Selection is one state change: aria-checked, the roving tab stop and the
2372
+ // event move together. The old arrow handler moved focus and announced a
2373
+ // value without ever updating aria-checked, so AT kept reading star 2.
2374
+ const select = (v) => {
2375
+ stars().forEach((st) => {
2376
+ const on = parseInt(st.dataset.value, 10) === v;
2377
+ st.setAttribute("aria-checked", String(on));
2378
+ st.setAttribute("tabindex", on ? "0" : "-1");
2379
+ st.classList.toggle("c-rating__star--filled", parseInt(st.dataset.value, 10) <= v);
2380
+ const sw = st.querySelector(".c-rating__swatch");
2381
+ if (sw) sw.classList.toggle("c-rating__swatch--filled", parseInt(st.dataset.value, 10) <= v);
2382
+ });
2383
+ this.dispatchEvent(new CustomEvent("contour:change", { bubbles: true, composed: true, detail: { value: v } }));
2384
+ };
1745
2385
  this.addEventListener("click", (e) => {
1746
2386
  const star = e.target && e.target.closest ? e.target.closest(".c-rating__star") : null;
1747
- if (star && this.contains(star)) {
1748
- const v = parseInt(star.dataset.value, 10);
1749
- Array.from(this.querySelectorAll(".c-rating__star")).forEach((st) => st.setAttribute("aria-checked", String(parseInt(st.dataset.value, 10) === v)));
1750
- this.dispatchEvent(new CustomEvent("contour:change", { bubbles: true, composed: true, detail: { value: v } }));
1751
- }
2387
+ if (star && this.contains(star)) select(parseInt(star.dataset.value, 10));
1752
2388
  });
1753
2389
  this.addEventListener("keydown", (e) => {
1754
- const stars = Array.from(this.querySelectorAll(".c-rating__star"));
1755
- const active = document.activeElement;
1756
- const idx = stars.indexOf(active);
1757
- if (e.key === "ArrowRight" || e.key === "ArrowUp") {
1758
- e.preventDefault();
1759
- const next = stars[Math.min(stars.length - 1, idx + 1)] || stars[0];
1760
- if (next) { try { next.focus(); } catch (err) {} }
1761
- } else if (e.key === "ArrowLeft" || e.key === "ArrowDown") {
1762
- e.preventDefault();
1763
- const prev = stars[Math.max(0, idx - 1)] || stars[stars.length - 1];
1764
- if (prev) { try { prev.focus(); } catch (err) {} }
1765
- } else if (e.key === "Enter" || e.key === " ") {
1766
- e.preventDefault();
1767
- if (active && active.classList.contains("c-rating__star")) {
1768
- this.dispatchEvent(new CustomEvent("contour:change", { bubbles: true, composed: true, detail: { value: parseInt(active.dataset.value, 10) } }));
1769
- }
1770
- }
2390
+ const all = stars();
2391
+ if (!all.length) return;
2392
+ navKey(e, all, {
2393
+ wrap: false,
2394
+ homeEnd: true,
2395
+ onNavigate: (i) => { select(parseInt(all[i].dataset.value, 10)); },
2396
+ onKey: (key, i) => { if (key === "Enter" || key === " ") select(parseInt(all[i].dataset.value, 10)); },
2397
+ });
1771
2398
  });
1772
2399
  }
1773
2400
  }
@@ -1778,6 +2405,7 @@ class ContourRating extends ContourBase {
1778
2405
  * Attributes: `value`, `label`, `disabled`, `error`, `help`.
1779
2406
  */
1780
2407
  class ContourTimePicker extends ContourBase {
2408
+ static get formAssociated() { return true; }
1781
2409
  static get observed() { return ["value", "label", "disabled", "error", "help"]; }
1782
2410
  static get properties() { return { value: { attribute: "value" }, label: { attribute: "label" }, disabled: { attribute: "disabled", type: Boolean }, error: { attribute: "error" }, help: { attribute: "help" } }; }
1783
2411
  render() {
@@ -1789,7 +2417,7 @@ class ContourTimePicker extends ContourBase {
1789
2417
  const l = this.ensure(".c-time-picker__label", () => { const el = document.createElement("label"); el.className = "c-time-picker__label"; return el; });
1790
2418
  l.textContent = label;
1791
2419
  }
1792
- const input = this.ensure(".c-time-picker__input", () => { const el = document.createElement("input"); el.className = "c-input c-time-picker__input"; el.type = "time"; return el; });
2420
+ const input = this.ensure(".c-time-picker__input", () => { const el = document.createElement("input"); el.className = "c-input c-time-picker__input"; el.type = "time"; el.setAttribute("aria-label", this.getAttribute("label") || "Time picker"); return el; });
1793
2421
  input.value = this.getAttribute("value") || "";
1794
2422
  if (this.hasAttribute("disabled")) { input.setAttribute("disabled", ""); this.classList.add("is-disabled"); }
1795
2423
  else { input.removeAttribute("disabled"); this.classList.remove("is-disabled"); }
@@ -1806,10 +2434,13 @@ class ContourTimePicker extends ContourBase {
1806
2434
  const toggle = this.ensure(".c-date-picker__calendar-toggle", () => { const el = document.createElement("button"); el.className = "c-btn c-btn--sm c-date-picker__calendar-toggle"; el.type = "button"; el.textContent = "📅"; el.setAttribute("aria-label", "Open calendar"); el.setAttribute("aria-expanded", "false"); return el; });
1807
2435
  let cal = this.querySelector(".c-date-picker__calendar");
1808
2436
  if (!cal) { cal = document.createElement("div"); cal.className = "c-date-picker__calendar"; cal.setAttribute("hidden", ""); cal.setAttribute("role", "dialog"); cal.setAttribute("aria-label", "Calendar"); this.appendChild(cal); }
2437
+ if (this._internals) this._syncFormValue();
1809
2438
  }
1810
2439
  enhance() {
1811
2440
  if (this._wiredTimePicker) return;
1812
2441
  this._wiredTimePicker = true;
2442
+ this._syncFormValue();
2443
+ this.addEventListener("change", () => { this._syncFormValue(); });
1813
2444
  this.addEventListener("change", (e) => {
1814
2445
  const t = e.target;
1815
2446
  if (t && t.classList.contains("c-time-picker__input")) {
@@ -1825,6 +2456,7 @@ class ContourTimePicker extends ContourBase {
1825
2456
  * Attributes: `value`, `label`, `disabled`, `error`, `help`, `alpha`, `presets`.
1826
2457
  */
1827
2458
  class ContourColorPicker extends ContourBase {
2459
+ static get formAssociated() { return true; }
1828
2460
  static get observed() { return ["value", "label", "disabled", "error", "help", "alpha", "presets"]; }
1829
2461
  static get properties() { return { value: { attribute: "value" }, label: { attribute: "label" }, disabled: { attribute: "disabled", type: Boolean }, error: { attribute: "error" }, help: { attribute: "help" }, alpha: { attribute: "alpha", type: Boolean }, presets: { attribute: "presets" } }; }
1830
2462
  render() {
@@ -1838,6 +2470,7 @@ class ContourColorPicker extends ContourBase {
1838
2470
  }
1839
2471
  const input = this.ensure(".c-color-picker__input", () => { const el = document.createElement("input"); el.className = "c-color-picker__input"; el.type = "color"; return el; });
1840
2472
  input.value = (this.getAttribute("value") || "#000000").slice(0, 7);
2473
+ if (!input.hasAttribute("aria-label")) input.setAttribute("aria-label", label || "Color");
1841
2474
  if (this.hasAttribute("disabled")) { input.setAttribute("disabled", ""); this.classList.add("is-disabled"); }
1842
2475
  else { input.removeAttribute("disabled"); this.classList.remove("is-disabled"); }
1843
2476
  // Alpha channel (optional).
@@ -1866,14 +2499,14 @@ class ContourColorPicker extends ContourBase {
1866
2499
  btn.className = "c-color-picker__preset";
1867
2500
  btn.style.background = c;
1868
2501
  btn.dataset.color = c;
1869
- btn.setAttribute("aria-label", "Preset " + c);
2502
+ btn.setAttribute("aria-label", labelText(this, "preset", "Preset") + " " + c);
1870
2503
  wrap.appendChild(btn);
1871
2504
  });
1872
2505
  this.appendChild(wrap);
1873
2506
  }
1874
2507
  // Eyedropper (if supported).
1875
2508
  if (typeof window !== "undefined" && "EyeDropper" in window) {
1876
- const ed = this.ensure(".c-color-picker__eyedropper", () => { const el = document.createElement("button"); el.className = "c-color-picker__eyedropper"; el.type = "button"; el.textContent = "Pick"; el.setAttribute("aria-label", "Pick color from screen"); return el; });
2509
+ const ed = this.ensure(".c-color-picker__eyedropper", () => { const el = document.createElement("button"); el.className = "c-color-picker__eyedropper"; el.type = "button"; el.textContent = labelText(this, "pick", "Pick"); el.setAttribute("aria-label", labelText(this, "pick-color", "Pick color from screen")); return el; });
1877
2510
  if (this.hasAttribute("disabled")) ed.setAttribute("disabled", "");
1878
2511
  else ed.removeAttribute("disabled");
1879
2512
  } else {
@@ -1893,10 +2526,14 @@ class ContourColorPicker extends ContourBase {
1893
2526
  const toggle = this.ensure(".c-date-picker__calendar-toggle", () => { const el = document.createElement("button"); el.className = "c-btn c-btn--sm c-date-picker__calendar-toggle"; el.type = "button"; el.textContent = "📅"; el.setAttribute("aria-label", "Open calendar"); el.setAttribute("aria-expanded", "false"); return el; });
1894
2527
  let cal = this.querySelector(".c-date-picker__calendar");
1895
2528
  if (!cal) { cal = document.createElement("div"); cal.className = "c-date-picker__calendar"; cal.setAttribute("hidden", ""); cal.setAttribute("role", "dialog"); cal.setAttribute("aria-label", "Calendar"); this.appendChild(cal); }
2529
+ if (this._internals) this._syncFormValue();
1896
2530
  }
1897
2531
  enhance() {
1898
2532
  if (this._wiredColorPicker) return;
1899
2533
  this._wiredColorPicker = true;
2534
+ this._syncFormValue();
2535
+ this.addEventListener("change", () => { this._syncFormValue(); });
2536
+ this.addEventListener("contour:change", () => { this._syncFormValue(); });
1900
2537
  this.addEventListener("change", (e) => {
1901
2538
  const t = e.target;
1902
2539
  if (t && t.classList.contains("c-color-picker__input")) {
@@ -1944,6 +2581,7 @@ class ContourColorPicker extends ContourBase {
1944
2581
  * Attributes: `value`, `min`, `max`, `step`, `label`, `disabled`, `error`, `help`.
1945
2582
  */
1946
2583
  class ContourNumberField extends ContourBase {
2584
+ static get formAssociated() { return true; }
1947
2585
  static get observed() { return ["value", "min", "max", "step", "label", "disabled", "error", "help"]; }
1948
2586
  static get properties() { return { value: { attribute: "value" }, min: { attribute: "min" }, max: { attribute: "max" }, step: { attribute: "step" }, label: { attribute: "label" }, disabled: { attribute: "disabled", type: Boolean }, error: { attribute: "error" }, help: { attribute: "help" } }; }
1949
2587
  render() {
@@ -1962,6 +2600,7 @@ class ContourNumberField extends ContourBase {
1962
2600
  input.setAttribute("aria-valuenow", v === "" ? "" : v);
1963
2601
  if (input.min !== "") input.setAttribute("aria-valuemin", input.min);
1964
2602
  if (input.max !== "") input.setAttribute("aria-valuemax", input.max);
2603
+ if (!input.hasAttribute("aria-label")) input.setAttribute("aria-label", label || "Number");
1965
2604
  if (this.hasAttribute("disabled")) { input.setAttribute("disabled", ""); this.classList.add("is-disabled"); }
1966
2605
  else { input.removeAttribute("disabled"); this.classList.remove("is-disabled"); }
1967
2606
  const err = this.getAttribute("error");
@@ -1977,10 +2616,13 @@ class ContourNumberField extends ContourBase {
1977
2616
  const toggle = this.ensure(".c-date-picker__calendar-toggle", () => { const el = document.createElement("button"); el.className = "c-btn c-btn--sm c-date-picker__calendar-toggle"; el.type = "button"; el.textContent = "📅"; el.setAttribute("aria-label", "Open calendar"); el.setAttribute("aria-expanded", "false"); return el; });
1978
2617
  let cal = this.querySelector(".c-date-picker__calendar");
1979
2618
  if (!cal) { cal = document.createElement("div"); cal.className = "c-date-picker__calendar"; cal.setAttribute("hidden", ""); cal.setAttribute("role", "dialog"); cal.setAttribute("aria-label", "Calendar"); this.appendChild(cal); }
2619
+ if (this._internals) this._syncFormValue();
1980
2620
  }
1981
2621
  enhance() {
1982
2622
  if (this._wiredNumberField) return;
1983
2623
  this._wiredNumberField = true;
2624
+ this._syncFormValue();
2625
+ this.addEventListener("change", () => { this._syncFormValue(); });
1984
2626
  this.addEventListener("change", (e) => {
1985
2627
  const t = e.target;
1986
2628
  if (t && t.classList.contains("c-number-field__input")) {
@@ -2046,11 +2688,23 @@ class ContourHoverCard extends ContourBase {
2046
2688
  const hasPopover = typeof this.showPopover === "function";
2047
2689
  const show = () => { if (hasPopover) { try { this.showPopover(); } catch (e) {} } else this.classList.add("is-open"); this.dispatchEvent(new CustomEvent("contour:open", { bubbles: true, composed: true })); };
2048
2690
  const hide = () => { if (showTimer) clearTimeout(showTimer); if (hasPopover) { try { this.hidePopover(); } catch (e) {} } else this.classList.remove("is-open"); this.dispatchEvent(new CustomEvent("contour:close", { bubbles: true, composed: true })); };
2049
- trigger.addEventListener("mouseenter", () => { showTimer = setTimeout(show, 300); });
2050
- trigger.addEventListener("mouseleave", () => { hide(); });
2051
- trigger.addEventListener("focus", show);
2052
- trigger.addEventListener("blur", () => { setTimeout(hide, 100); });
2053
- onDispose(this, () => { if (showTimer) { clearTimeout(showTimer); showTimer = null; } });
2691
+ const onEnter = () => { showTimer = setTimeout(show, 300); };
2692
+ const onLeave = () => { hide(); };
2693
+ const onFocus = () => show();
2694
+ const onBlur = () => { setTimeout(hide, 100); };
2695
+ trigger.addEventListener("mouseenter", onEnter);
2696
+ trigger.addEventListener("mouseleave", onLeave);
2697
+ trigger.addEventListener("focus", onFocus);
2698
+ trigger.addEventListener("blur", onBlur);
2699
+ // Remove the trigger listeners too: the old cleanup only cleared the
2700
+ // timer, so a removed trigger kept four live handlers.
2701
+ onDispose(this, () => {
2702
+ if (showTimer) { clearTimeout(showTimer); showTimer = null; }
2703
+ trigger.removeEventListener("mouseenter", onEnter);
2704
+ trigger.removeEventListener("mouseleave", onLeave);
2705
+ trigger.removeEventListener("focus", onFocus);
2706
+ trigger.removeEventListener("blur", onBlur);
2707
+ });
2054
2708
  }
2055
2709
  }
2056
2710
  const keyHandler = (e) => { if (e.key === "Escape" && (this.classList.contains("is-open") || this.matches(":popover-open"))) { e.preventDefault(); if (typeof this.hidePopover === "function") { try { this.hidePopover(); } catch (err) {} } this.classList.remove("is-open"); this.dispatchEvent(new CustomEvent("contour:close", { bubbles: true, composed: true })); } };
@@ -2065,11 +2719,12 @@ class ContourHoverCard extends ContourBase {
2065
2719
  * Attributes: `items`.
2066
2720
  */
2067
2721
  class ContourContextMenu extends ContourBase {
2068
- static get observed() { return ["items"]; }
2069
- static get properties() { return { items: { attribute: "items" } }; }
2722
+ static get observed() { return ["items", "trigger"]; }
2723
+ static get properties() { return { items: { attribute: "items" }, trigger: { attribute: "trigger" } }; }
2070
2724
  render() {
2071
2725
  this.classList.add("c-context-menu");
2072
2726
  if (!this.hasAttribute("role")) this.setAttribute("role", "menu");
2727
+ if (!this.hasAttribute("aria-label")) this.setAttribute("aria-label", "Context menu");
2073
2728
  if (!this.hasAttribute("popover")) this.setAttribute("popover", "auto");
2074
2729
  if (!this.id) this.id = contourId("context-menu");
2075
2730
  const items = this.getAttribute("items");
@@ -2084,16 +2739,36 @@ class ContourContextMenu extends ContourBase {
2084
2739
  btn.textContent = typeof it === "string" ? it : (it.label || it.title || "");
2085
2740
  this.appendChild(btn);
2086
2741
  });
2087
- } catch (e) { /* keep existing */ }
2742
+ } catch (e) { warnBadJson(this, "attribute", e); }
2088
2743
  }
2089
2744
  }
2090
2745
  enhance() {
2091
2746
  if (this._wiredContextMenu) return;
2092
2747
  this._wiredContextMenu = true;
2748
+ const openAt = (x, y) => {
2749
+ if (typeof this.showPopover === "function") { try { this.showPopover(); } catch (err) {} }
2750
+ else this.classList.add("is-open");
2751
+ if (Number.isFinite(x) && Number.isFinite(y)) {
2752
+ this.style.position = "fixed";
2753
+ this.style.left = x + "px";
2754
+ this.style.top = y + "px";
2755
+ }
2756
+ };
2757
+ // A context menu is opened by its trigger, not by a right-click on the
2758
+ // menu itself (which is empty until opened). `trigger` names the element.
2759
+ const triggerSel = this.getAttribute("trigger");
2760
+ if (triggerSel) {
2761
+ const trigger = document.querySelector(triggerSel);
2762
+ if (trigger) {
2763
+ if (!trigger.hasAttribute("aria-haspopup")) trigger.setAttribute("aria-haspopup", "menu");
2764
+ const onCtx = (e) => { e.preventDefault(); openAt(e.clientX, e.clientY); };
2765
+ trigger.addEventListener("contextmenu", onCtx);
2766
+ onDispose(this, () => trigger.removeEventListener("contextmenu", onCtx));
2767
+ }
2768
+ }
2093
2769
  this.addEventListener("contextmenu", (e) => {
2094
2770
  e.preventDefault();
2095
- if (typeof this.showPopover === "function") { try { this.showPopover(); } catch (err) {} }
2096
- else this.classList.toggle("is-open");
2771
+ openAt(e.clientX, e.clientY);
2097
2772
  });
2098
2773
  this.addEventListener("click", (e) => {
2099
2774
  const item = e.target && e.target.closest ? e.target.closest(".c-menu__item") : null;
@@ -2105,12 +2780,8 @@ class ContourContextMenu extends ContourBase {
2105
2780
  });
2106
2781
  this.addEventListener("keydown", (e) => {
2107
2782
  const items = Array.from(this.querySelectorAll(".c-menu__item"));
2108
- const active = document.activeElement;
2109
- const idx = items.indexOf(active);
2110
- if (e.key === "ArrowDown") { e.preventDefault(); const next = items[Math.min(items.length - 1, idx + 1)] || items[0]; if (next) try { next.focus(); } catch (err) {} }
2111
- else if (e.key === "ArrowUp") { e.preventDefault(); const prev = items[Math.max(0, idx - 1)] || items[items.length - 1]; if (prev) try { prev.focus(); } catch (err) {} }
2112
- else if (e.key === "Enter" || e.key === " ") { e.preventDefault(); if (active && active.classList.contains("c-menu__item")) active.click(); }
2113
- else if (e.key === "Escape") { e.preventDefault(); if (typeof this.hidePopover === "function") { try { this.hidePopover(); } catch (err) {} } this.classList.remove("is-open"); }
2783
+ navKey(e, items, { wrap: true, onKey: () => { if (e.key === "Enter" || e.key === " ") document.activeElement.click(); } });
2784
+ if (e.key === "Escape") { e.preventDefault(); if (typeof this.hidePopover === "function") { try { this.hidePopover(); } catch (err) {} } this.classList.remove("is-open"); }
2114
2785
  });
2115
2786
  }
2116
2787
  }
@@ -2130,7 +2801,16 @@ class ContourFab extends ContourBase {
2130
2801
  const label = this.getAttribute("label");
2131
2802
  if (label) this.setAttribute("aria-label", label);
2132
2803
  const icon = this.getAttribute("icon");
2133
- if (icon && !this.hasChildNodes()) this.textContent = icon;
2804
+ if (icon && !this.querySelector("svg")) {
2805
+ // Render the icon through the sprite, not as text: an <svg><use> paints
2806
+ // the glyph; the old code wrote the icon name into the button.
2807
+ const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
2808
+ svg.setAttribute("aria-hidden", "true");
2809
+ const use = document.createElementNS("http://www.w3.org/2000/svg", "use");
2810
+ use.setAttribute("href", icon.startsWith("#") ? icon : "#" + icon);
2811
+ svg.appendChild(use);
2812
+ this.appendChild(svg);
2813
+ }
2134
2814
  }
2135
2815
  enhance() {
2136
2816
  if (this._wiredFab) return;
@@ -2150,10 +2830,12 @@ class ContourFab extends ContourBase {
2150
2830
  * Attributes: `label`, `accept`, `multiple`, `progress`.
2151
2831
  */
2152
2832
  class ContourFileUpload extends ContourBase {
2153
- static get observed() { return ["label", "accept", "multiple", "progress"]; }
2154
- static get properties() { return { label: { attribute: "label" }, accept: { attribute: "accept" }, multiple: { attribute: "multiple", type: Boolean }, progress: { attribute: "progress" } }; }
2833
+ static get formAssociated() { return true; }
2834
+ static get observed() { return ["label", "accept", "multiple", "progress", "name"]; }
2835
+ static get properties() { return { label: { attribute: "label" }, accept: { attribute: "accept" }, multiple: { attribute: "multiple", type: Boolean }, progress: { attribute: "progress" }, name: { attribute: "name" } }; }
2155
2836
  render() {
2156
2837
  this.classList.add("c-file-upload");
2838
+ if (!this.hasAttribute("aria-label")) this.setAttribute("aria-label", this.getAttribute("label") || "File upload");
2157
2839
  const label = this.getAttribute("label") || "Drop files here or click to browse";
2158
2840
  const dz = this.ensure(".c-file-upload__dropzone", () => { const el = document.createElement("div"); el.className = "c-file-upload__dropzone"; el.setAttribute("role", "button"); el.tabIndex = 0; return el; });
2159
2841
  dz.textContent = label;
@@ -2171,10 +2853,13 @@ class ContourFileUpload extends ContourBase {
2171
2853
  }
2172
2854
  const preview = this.ensure(".c-file-upload__preview", () => { const el = document.createElement("div"); el.className = "c-file-upload__preview"; return el; });
2173
2855
  if (!preview) {}
2856
+ if (this._internals) this._syncFormValue();
2174
2857
  }
2175
2858
  enhance() {
2176
2859
  if (this._wiredFileUpload) return;
2177
2860
  this._wiredFileUpload = true;
2861
+ this._syncFormValue();
2862
+ this.addEventListener("change", () => { this._syncFormValue(); });
2178
2863
  const dz = () => this.querySelector(".c-file-upload__dropzone");
2179
2864
  const input = () => this.querySelector(".c-file-upload__input");
2180
2865
  const activate = () => { const i = input(); if (i) i.click(); };
@@ -2183,6 +2868,9 @@ class ContourFileUpload extends ContourBase {
2183
2868
  const renderPreview = (files) => {
2184
2869
  const preview = this.querySelector(".c-file-upload__preview");
2185
2870
  if (!preview) return;
2871
+ // Revoke the previous object URLs before dropping the <img> nodes, or
2872
+ // every re-render leaks a blob.
2873
+ this._revokeObjectUrls();
2186
2874
  preview.innerHTML = "";
2187
2875
  Array.from(files || []).forEach((f) => {
2188
2876
  const item = document.createElement("div");
@@ -2193,7 +2881,7 @@ class ContourFileUpload extends ContourBase {
2193
2881
  img.alt = f.name;
2194
2882
  img.loading = "lazy";
2195
2883
  img.decoding = "async";
2196
- try { img.src = URL.createObjectURL(f); } catch (e) {}
2884
+ try { const u = URL.createObjectURL(f); img.src = u; (this._objectUrls || (this._objectUrls = [])).push(u); } catch (e) {}
2197
2885
  item.appendChild(img);
2198
2886
  } else {
2199
2887
  const name = document.createElement("span");
@@ -2208,7 +2896,32 @@ class ContourFileUpload extends ContourBase {
2208
2896
  // drag-drop already dispatches contour:change; also render preview there
2209
2897
  this.addEventListener("dragover", (e) => { e.preventDefault(); this.classList.add("is-dragover"); });
2210
2898
  this.addEventListener("dragleave", () => this.classList.remove("is-dragover"));
2211
- this.addEventListener("drop", (e) => { e.preventDefault(); this.classList.remove("is-dragover"); const i = input(); if (i && e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files.length) { try { i.files = e.dataTransfer.files; } catch (err) { /* some browsers disallow */ } const preview = this.querySelector(".c-file-upload__preview"); if (preview) { preview.innerHTML = ""; Array.from(e.dataTransfer.files).forEach((f) => { const item = document.createElement("div"); item.className = "c-file-upload__preview-item"; if (f.type && f.type.startsWith("image/")) { const img = document.createElement("img"); img.className = "c-file-upload__preview-thumb"; img.alt = f.name; try { img.src = URL.createObjectURL(f); } catch (err2) {} item.appendChild(img); } else { const name = document.createElement("span"); name.className = "c-file-upload__preview-name"; name.textContent = f.name; item.appendChild(name); } preview.appendChild(item); }); } this.dispatchEvent(new CustomEvent("contour:change", { bubbles: true, composed: true, detail: { files: e.dataTransfer.files } })); } });
2899
+ this.addEventListener("drop", (e) => { e.preventDefault(); this.classList.remove("is-dragover"); const i = input(); if (i && e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files.length) { try { i.files = e.dataTransfer.files; } catch (err) { /* some browsers disallow */ } renderPreview(e.dataTransfer.files); this.dispatchEvent(new CustomEvent("contour:change", { bubbles: true, composed: true, detail: { files: e.dataTransfer.files } })); } });
2900
+ }
2901
+ disconnectedCallback() {
2902
+ super.disconnectedCallback();
2903
+ this._revokeObjectUrls();
2904
+ }
2905
+ _revokeObjectUrls() {
2906
+ if (!this._objectUrls) return;
2907
+ this._objectUrls.forEach((u) => { try { URL.revokeObjectURL(u); } catch (e) {} });
2908
+ this._objectUrls = [];
2909
+ }
2910
+ // Form-value sync override (R16-06): submit the selected File(s) via
2911
+ // FormData rather than the input's (useless) path string.
2912
+ _syncFormValue() {
2913
+ if (!this._internals) return;
2914
+ const inp = this.querySelector(".c-file-upload__input");
2915
+ if (inp && inp.files && inp.files.length) {
2916
+ const fd = new FormData();
2917
+ // Use the host's name so the entry matches the control the author
2918
+ // declared, not a hard-coded "file" key.
2919
+ const key = this.getAttribute("name") || "file";
2920
+ Array.from(inp.files).forEach((f) => fd.append(key, f));
2921
+ this._internals.setFormValue(fd);
2922
+ } else {
2923
+ this._internals.setFormValue(null);
2924
+ }
2212
2925
  }
2213
2926
  }
2214
2927
  define("contour-file-upload", ContourFileUpload);
@@ -2222,74 +2935,186 @@ class ContourNotificationCenter extends ContourBase {
2222
2935
  static get properties() { return { count: { attribute: "count" }, items: { attribute: "items" }, color: { attribute: "color" } }; }
2223
2936
  render() {
2224
2937
  this.classList.add("c-notification-center");
2225
- this.setAttribute("role", "list");
2226
- const btn = this.ensure(".c-notification-center__trigger", () => { const el = document.createElement("button"); el.className = "c-btn c-btn--sm c-notification-center__trigger"; el.type = "button"; el.innerHTML = '<span class="c-notification-center__bullet" aria-hidden="true"></span>'; el.setAttribute("aria-haspopup", "dialog"); el.setAttribute("aria-expanded", "false"); return el; });
2938
+ this.setAttribute("role", "group");
2939
+ const btn = this.ensure(".c-notification-center__trigger", () => { const el = document.createElement("button"); el.className = "c-btn c-btn--sm c-notification-center__trigger"; el.type = "button"; el.innerHTML = '<span class="c-notification-center__bullet" aria-hidden="true"></span>'; el.setAttribute("aria-haspopup", "dialog"); el.setAttribute("aria-expanded", "false"); el.setAttribute("aria-label", "Notifications"); return el; });
2227
2940
  const color = this.getAttribute("color");
2228
2941
  const bullet = btn.querySelector(".c-notification-center__bullet");
2229
- if (bullet && color) { bullet.style.background = color; bullet.dataset.color = color; }
2230
- const count = this.getAttribute("count");
2231
- let badge = btn.querySelector(".c-notification-center__badge");
2232
- if (count && Number(count) > 0) {
2233
- if (!badge) { badge = document.createElement("span"); badge.className = "c-notification-center__badge c-badge c-badge--dot"; btn.appendChild(badge); }
2234
- badge.textContent = count;
2235
- } else if (badge) { badge.remove(); }
2942
+ if (bullet && color) { bullet.style.background = safeColor(color); bullet.dataset.color = color; }
2236
2943
  const panel = this.ensure(".c-notification-center__panel", () => { const el = document.createElement("div"); el.className = "c-notification-center__panel"; el.hidden = true; el.setAttribute("role", "dialog"); el.setAttribute("aria-label", "Notifications"); return el; });
2944
+ // The panel is a generated node: a re-render (show more, items change)
2945
+ // rebuilds it, so the open state lives on the host, not on the node.
2946
+ panel.hidden = !this._notifOpen;
2947
+ btn.setAttribute("aria-expanded", String(!!this._notifOpen));
2237
2948
  // Slotted content: authored .c-notification-center__item children take
2238
2949
  // precedence over the JSON `items` attribute.
2239
2950
  const authoredItems = Array.from(this.querySelectorAll(":scope > .c-notification-center__item"));
2240
2951
  const items = this.getAttribute("items");
2241
2952
  if (authoredItems.length) {
2242
2953
  panel.innerHTML = "";
2243
- authoredItems.forEach((it) => { panel.appendChild(it); });
2954
+ const lb = document.createElement("div");
2955
+ lb.setAttribute("role", "listbox");
2956
+ lb.setAttribute("aria-label", "Notifications");
2957
+ authoredItems.forEach((it) => { lb.appendChild(it); });
2958
+ panel.appendChild(lb);
2244
2959
  } else if (items) {
2245
- try {
2246
- const parsed = JSON.parse(items);
2247
- panel.innerHTML = "";
2248
- parsed.forEach((it) => {
2960
+ let parsed = null;
2961
+ try { parsed = JSON.parse(items); } catch (e) { warnBadJson(this, "items", e); }
2962
+ panel.innerHTML = "";
2963
+ if (!Array.isArray(parsed)) {
2964
+ // A malformed payload is an error state, not a silent empty panel.
2965
+ const err = document.createElement("div");
2966
+ err.className = "c-notification-center__error";
2967
+ err.setAttribute("role", "alert");
2968
+ err.textContent = labelText(this, "error", "Could not load notifications");
2969
+ panel.appendChild(err);
2970
+ } else {
2971
+ const lb = document.createElement("div");
2972
+ lb.setAttribute("role", "listbox");
2973
+ lb.setAttribute("aria-label", "Notifications");
2974
+ // Incremental rendering keeps a long list's DOM bounded: the first
2975
+ // window renders, and a control asks for the next (R20 T-17).
2976
+ const shown = this._notifShown || 50;
2977
+ parsed.slice(0, shown).forEach((it) => {
2249
2978
  const row = document.createElement("div");
2250
- row.className = "c-notification-center__item";
2251
- row.setAttribute("tabindex", "0");
2979
+ row.className = "c-notification-center__item" + (it && it.read ? " is-read" : "");
2980
+ row.setAttribute("tabindex", "-1");
2252
2981
  row.setAttribute("role", "option");
2253
- row.textContent = typeof it === "string" ? it : (it.text || it.title || "");
2254
- panel.appendChild(row);
2982
+ row.setAttribute("aria-selected", "false");
2983
+ row.dataset.read = it && it.read ? "true" : "false";
2984
+ const label = document.createElement("span");
2985
+ label.className = "c-notification-center__item-label";
2986
+ label.textContent = typeof it === "string" ? it : (it.text || it.title || "");
2987
+ row.appendChild(label);
2988
+ // Archive keeps the notification out of the list without the
2989
+ // dismiss semantics; both are reachable by keyboard.
2990
+ const archive = document.createElement("button");
2991
+ archive.type = "button";
2992
+ archive.className = "c-notification-center__archive";
2993
+ archive.setAttribute("aria-label", labelText(this, "archive", "Archive notification"));
2994
+ archive.textContent = "⤓";
2995
+ row.appendChild(archive);
2996
+ const dismiss = document.createElement("button");
2997
+ dismiss.type = "button";
2998
+ dismiss.className = "c-notification-center__dismiss";
2999
+ dismiss.setAttribute("aria-label", labelText(this, "dismiss", "Dismiss notification"));
3000
+ dismiss.textContent = "×";
3001
+ row.appendChild(dismiss);
3002
+ lb.appendChild(row);
2255
3003
  });
2256
- } catch (e) { /* keep */ }
3004
+ // Roving tab stop: the first row is reachable, arrows rove.
3005
+ const firstRow = lb.querySelector(".c-notification-center__item");
3006
+ if (firstRow) firstRow.tabIndex = 0;
3007
+ panel.appendChild(lb);
3008
+ if (!parsed.length) {
3009
+ const empty = document.createElement("div");
3010
+ empty.className = "c-notification-center__empty";
3011
+ empty.textContent = labelText(this, "empty", "No notifications");
3012
+ panel.appendChild(empty);
3013
+ } else if (parsed.length > shown) {
3014
+ const more = document.createElement("button");
3015
+ more.type = "button";
3016
+ more.className = "c-btn c-btn--sm c-notification-center__more";
3017
+ more.textContent = labelText(this, "more", "Show more") + " (" + (parsed.length - shown) + ")";
3018
+ panel.appendChild(more);
3019
+ }
3020
+ }
2257
3021
  }
3022
+ this._syncNotifBadge();
3023
+ }
3024
+ // The badge follows the LIVE unread count after read/dismiss/archive;
3025
+ // the authored `count` seeds it until the first interaction (R20 T-17).
3026
+ _syncNotifBadge() {
3027
+ const btn = this.querySelector(".c-notification-center__trigger");
3028
+ if (!btn) return;
3029
+ const rows = Array.from(this.querySelectorAll(".c-notification-center__item"));
3030
+ let unread;
3031
+ if (this._notifInteracted || !this.hasAttribute("count")) unread = rows.filter((r) => r.dataset.read !== "true").length;
3032
+ else unread = Number(this.getAttribute("count")) || 0;
3033
+ let badge = btn.querySelector(".c-notification-center__badge");
3034
+ if (unread > 0) {
3035
+ if (!badge) { badge = document.createElement("span"); badge.className = "c-notification-center__badge c-badge c-badge--dot"; btn.appendChild(badge); }
3036
+ badge.textContent = String(unread);
3037
+ } else if (badge) { badge.remove(); }
2258
3038
  }
2259
3039
  enhance() {
2260
3040
  if (this._wiredNotifCenter) return;
2261
3041
  this._wiredNotifCenter = true;
3042
+ const activate = (item) => {
3043
+ if (item.dataset.read !== "true") {
3044
+ item.dataset.read = "true";
3045
+ item.classList.add("is-read");
3046
+ this._notifInteracted = true;
3047
+ this._syncNotifBadge();
3048
+ this.dispatchEvent(new CustomEvent("contour:read", { bubbles: true, composed: true, detail: { label: item.querySelector(".c-notification-center__item-label")?.textContent || item.textContent } }));
3049
+ }
3050
+ for (const r of this.querySelectorAll(".c-notification-center__item")) r.setAttribute("aria-selected", String(r === item));
3051
+ this.dispatchEvent(new CustomEvent("contour:select", { bubbles: true, composed: true, detail: { label: item.querySelector(".c-notification-center__item-label")?.textContent || item.textContent } }));
3052
+ };
3053
+ const removeRow = (item, kind) => {
3054
+ const label = item.querySelector(".c-notification-center__item-label")?.textContent || item.textContent;
3055
+ item.remove();
3056
+ this._notifInteracted = true;
3057
+ this._syncNotifBadge();
3058
+ this.dispatchEvent(new CustomEvent(kind === "archive" ? "contour:remove" : "contour:dismiss", { bubbles: true, composed: true, detail: { label } }));
3059
+ };
2262
3060
  this.addEventListener("click", (e) => {
2263
3061
  const btn = this.querySelector(".c-notification-center__trigger");
2264
3062
  const panel = this.querySelector(".c-notification-center__panel");
2265
3063
  if (btn && (e.target === btn || btn.contains(e.target))) {
2266
- if (panel) { panel.hidden = !panel.hidden; btn.setAttribute("aria-expanded", String(!panel.hidden)); this.dispatchEvent(new CustomEvent(panel.hidden ? "contour:close" : "contour:open", { bubbles: true, composed: true })); }
3064
+ if (panel) { panel.hidden = !panel.hidden; this._notifOpen = !panel.hidden; btn.setAttribute("aria-expanded", String(!panel.hidden)); this.dispatchEvent(new CustomEvent(panel.hidden ? "contour:close" : "contour:open", { bubbles: true, composed: true })); }
3065
+ return;
2267
3066
  }
2268
- });
2269
- this.addEventListener("click", (e) => {
2270
- const item = e.target && e.target.closest ? e.target.closest(".c-notification-center__item") : null;
2271
- if (item && this.contains(item)) {
2272
- this.dispatchEvent(new CustomEvent("contour:select", { bubbles: true, composed: true, detail: { label: item.textContent } }));
3067
+ const more = e.target && e.target.closest ? e.target.closest(".c-notification-center__more") : null;
3068
+ if (more && this.contains(more)) {
3069
+ this._notifShown = (this._notifShown || 50) + 50;
3070
+ this.requestRender();
3071
+ return;
3072
+ }
3073
+ const archive = e.target && e.target.closest ? e.target.closest(".c-notification-center__archive") : null;
3074
+ if (archive && this.contains(archive)) {
3075
+ const item = archive.closest(".c-notification-center__item");
3076
+ if (item) removeRow(item, "archive");
3077
+ return;
3078
+ }
3079
+ const dismiss = e.target && e.target.closest ? e.target.closest(".c-notification-center__dismiss") : null;
3080
+ if (dismiss && this.contains(dismiss)) {
3081
+ const item = dismiss.closest(".c-notification-center__item");
3082
+ if (item) removeRow(item, "dismiss");
3083
+ return;
2273
3084
  }
3085
+ const item = e.target && e.target.closest ? e.target.closest(".c-notification-center__item") : null;
3086
+ if (item && this.contains(item)) activate(item);
2274
3087
  });
2275
3088
  const docClick = (e) => {
2276
3089
  const panel = this.querySelector(".c-notification-center__panel");
2277
3090
  const btn = this.querySelector(".c-notification-center__trigger");
2278
- if (panel && !panel.hidden && !this.contains(e.target)) { panel.hidden = true; if (btn) btn.setAttribute("aria-expanded", "false"); }
3091
+ if (panel && !panel.hidden && !this.contains(e.target)) { panel.hidden = true; this._notifOpen = false; if (btn) btn.setAttribute("aria-expanded", "false"); }
2279
3092
  };
2280
3093
  document.addEventListener("click", docClick);
2281
3094
  onDispose(this, () => document.removeEventListener("click", docClick));
2282
3095
  const keyHandler = (e) => {
2283
3096
  const panel = this.querySelector(".c-notification-center__panel");
2284
3097
  const btn = this.querySelector(".c-notification-center__trigger");
2285
- if (e.key === "Escape" && panel && !panel.hidden) { panel.hidden = true; if (btn) { btn.setAttribute("aria-expanded", "false"); try { btn.focus(); } catch (err) {} } return; }
3098
+ if (e.key === "Escape" && panel && !panel.hidden) { panel.hidden = true; this._notifOpen = false; if (btn) { btn.setAttribute("aria-expanded", "false"); try { btn.focus(); } catch (err) {} } return; }
2286
3099
  if (!panel || panel.hidden) return;
2287
3100
  const items = Array.from(panel.querySelectorAll(".c-notification-center__item"));
2288
3101
  if (!items.length) return;
2289
- const active = document.activeElement;
2290
- const idx = items.indexOf(active);
2291
- if (e.key === "ArrowDown") { e.preventDefault(); const next = items[Math.min(items.length - 1, idx + 1)] || items[0]; if (next) try { next.focus(); } catch (err) {} }
2292
- else if (e.key === "ArrowUp") { e.preventDefault(); const prev = items[Math.max(0, idx - 1)] || items[items.length - 1]; if (prev) try { prev.focus(); } catch (err) {} }
3102
+ // Enter/Space activate the focused row (a div synthesizes no click);
3103
+ // Delete dismisses it. navKey roves the tab stop with the focus.
3104
+ if ((e.key === "Enter" || e.key === " ") && items.includes(e.target)) {
3105
+ e.preventDefault();
3106
+ activate(e.target);
3107
+ return;
3108
+ }
3109
+ if ((e.key === "Delete" || e.key === "Backspace") && items.includes(e.target)) {
3110
+ e.preventDefault();
3111
+ const idx = items.indexOf(e.target);
3112
+ removeRow(e.target, "dismiss");
3113
+ const next = items[idx + 1] || items[idx - 1];
3114
+ if (next && next.isConnected) { try { next.focus(); } catch (err) {} }
3115
+ return;
3116
+ }
3117
+ navKey(e, items, { wrap: true, onNavigate: (i) => { items.forEach((r, j) => { r.tabIndex = j === i ? 0 : -1; }); } });
2293
3118
  };
2294
3119
  document.addEventListener("keydown", keyHandler);
2295
3120
  onDispose(this, () => document.removeEventListener("keydown", keyHandler));
@@ -2306,6 +3131,8 @@ class ContourStepper extends ContourBase {
2306
3131
  static get properties() { return { steps: { attribute: "steps" }, current: { attribute: "current" } }; }
2307
3132
  render() {
2308
3133
  this.classList.add("c-stepper");
3134
+ if (!this.hasAttribute("role")) this.setAttribute("role", "group");
3135
+ if (!this.hasAttribute("aria-label")) this.setAttribute("aria-label", "Stepper");
2309
3136
  const steps = this.getAttribute("steps");
2310
3137
  const current = Number(this.getAttribute("current") || 0);
2311
3138
  const list = this.ensure(".c-stepper__list", () => { const el = document.createElement("ol"); el.className = "c-stepper__list"; return el; });
@@ -2327,8 +3154,12 @@ class ContourStepper extends ContourBase {
2327
3154
  list.appendChild(li);
2328
3155
  });
2329
3156
  const nav = this.ensure(".c-stepper__nav", () => { const el = document.createElement("div"); el.className = "c-stepper__nav c-btn-group"; return el; });
2330
- const prev = this.ensure(".c-stepper__prev", () => { const el = document.createElement("button"); el.className = "c-btn c-btn--sm c-stepper__prev"; el.type = "button"; el.textContent = "Back"; return el; });
2331
- const next = this.ensure(".c-stepper__next", () => { const el = document.createElement("button"); el.className = "c-btn c-btn--sm c-stepper__next"; el.type = "button"; el.textContent = "Next"; return el; });
3157
+ const prev = this.ensure(".c-stepper__prev", () => { const el = document.createElement("button"); el.className = "c-btn c-btn--sm c-stepper__prev"; el.type = "button"; return el; });
3158
+ // Copy is set on every render, not only at creation: `ensure()` builds the
3159
+ // node once, so a `labels` change would otherwise reach nothing.
3160
+ prev.textContent = labelText(this, "prev", "Back");
3161
+ const next = this.ensure(".c-stepper__next", () => { const el = document.createElement("button"); el.className = "c-btn c-btn--sm c-stepper__next"; el.type = "button"; return el; });
3162
+ next.textContent = labelText(this, "next", "Next");
2332
3163
  if (!nav.contains(prev)) nav.appendChild(prev);
2333
3164
  if (!nav.contains(next)) nav.appendChild(next);
2334
3165
  if (nav.parentNode !== this) this.appendChild(nav);
@@ -2349,8 +3180,18 @@ class ContourStepper extends ContourBase {
2349
3180
  this.addEventListener("click", (e) => {
2350
3181
  const prev = e.target && e.target.closest ? e.target.closest(".c-stepper__prev") : null;
2351
3182
  const next = e.target && e.target.closest ? e.target.closest(".c-stepper__next") : null;
2352
- if (prev && this.contains(prev)) go("prev");
2353
- if (next && this.contains(next)) go("next");
3183
+ if (prev && this.contains(prev)) { go("prev"); return; }
3184
+ if (next && this.contains(next)) { go("next"); return; }
3185
+ // Click a step to jump to it: the step is a control, not just a label.
3186
+ const step = e.target && e.target.closest ? e.target.closest(".c-stepper__step") : null;
3187
+ if (step && this.contains(step)) {
3188
+ const items = Array.from(this.querySelectorAll(".c-stepper__step"));
3189
+ const idx = items.indexOf(step);
3190
+ if (idx >= 0 && idx !== Number(this.getAttribute("current") || 0)) {
3191
+ this.setAttribute("current", String(idx));
3192
+ this.dispatchEvent(new CustomEvent("contour:step-change", { bubbles: true, composed: true, detail: { direction: "jump", index: idx } }));
3193
+ }
3194
+ }
2354
3195
  });
2355
3196
  this.addEventListener("keydown", (e) => {
2356
3197
  if (e.key === "ArrowLeft") { e.preventDefault(); go("prev"); }
@@ -2376,7 +3217,8 @@ class ContourVirtualList extends ContourBase {
2376
3217
  }
2377
3218
  _itemHeight() {
2378
3219
  const h = Number(this.getAttribute("item-height"));
2379
- return Number.isFinite(h) && h > 0 ? h : 28;
3220
+ if (Number.isFinite(h) && h > 0) return h;
3221
+ return cssLength("--virtual-list-item-height", 28);
2380
3222
  }
2381
3223
  _autoHeight() {
2382
3224
  return this.getAttribute("item-height") === "auto";
@@ -2384,6 +3226,7 @@ class ContourVirtualList extends ContourBase {
2384
3226
  render() {
2385
3227
  this.classList.add("c-virtual-list");
2386
3228
  this.setAttribute("role", "list");
3229
+ if (!this.hasAttribute("aria-label")) this.setAttribute("aria-label", "Virtual list");
2387
3230
  const scroller = this.ensure(".c-virtual-list__scroller", () => { const el = document.createElement("div"); el.className = "c-virtual-list__scroller"; return el; });
2388
3231
  scroller.setAttribute("role", "presentation");
2389
3232
  const horizontal = this.getAttribute("orientation") === "horizontal";
@@ -2395,7 +3238,7 @@ class ContourVirtualList extends ContourBase {
2395
3238
  }
2396
3239
  _measureHeights(inner, horizontal) {
2397
3240
  const rows = Array.from(inner.querySelectorAll(".c-virtual-list__item"));
2398
- return rows.map((r) => horizontal ? (r.getBoundingClientRect().width || 28) : (r.getBoundingClientRect().height || 28));
3241
+ return rows.map((r) => horizontal ? (r.getBoundingClientRect().width || this._itemHeight()) : (r.getBoundingClientRect().height || this._itemHeight()));
2399
3242
  }
2400
3243
  _renderWindow(scroller, inner, scrollTop) {
2401
3244
  const items = this._items();
@@ -2410,9 +3253,9 @@ class ContourVirtualList extends ContourBase {
2410
3253
  let cumulative = null;
2411
3254
  if (autoHeight && heights && heights.length === total) {
2412
3255
  cumulative = [0];
2413
- for (let i = 0; i < total; i++) cumulative.push(cumulative[i] + (heights[i] || 28));
3256
+ for (let i = 0; i < total; i++) cumulative.push(cumulative[i] + (heights[i] || this._itemHeight()));
2414
3257
  }
2415
- const visibleCount = autoHeight && !cumulative ? total : (autoHeight ? Math.ceil(viewportSize / 28) + 6 : Math.ceil(viewportSize / ih) + 4);
3258
+ const visibleCount = autoHeight && !cumulative ? total : (autoHeight ? Math.ceil(viewportSize / this._itemHeight()) + 6 : Math.ceil(viewportSize / ih) + 4);
2416
3259
  let start = 0;
2417
3260
  if (autoHeight && cumulative) {
2418
3261
  // binary search for start
@@ -2444,7 +3287,10 @@ class ContourVirtualList extends ContourBase {
2444
3287
  const row = document.createElement("div");
2445
3288
  row.className = "c-virtual-list__item";
2446
3289
  row.setAttribute("role", "listitem");
2447
- // aria-rowindex omitted: not allowed on role="listitem" (axe aria-allowed-attr)
3290
+ // A windowed list must publish its position in the whole set, or a
3291
+ // screen reader cannot tell "item 3 of 1,000" from "item 3 of 12".
3292
+ row.setAttribute("aria-setsize", String(total));
3293
+ row.setAttribute("aria-posinset", String(i + 1));
2448
3294
  row.setAttribute("tabindex", i === 0 ? "0" : "-1");
2449
3295
  row.textContent = typeof items[i] === "string" ? items[i] : (items[i].label || items[i].text || JSON.stringify(items[i]));
2450
3296
  if (this.hasAttribute("sticky") && items[i] && items[i].sticky) {
@@ -2496,23 +3342,30 @@ class ContourVirtualList extends ContourBase {
2496
3342
  this.addEventListener("keydown", (e) => {
2497
3343
  const rows = Array.from(this.querySelectorAll(".c-virtual-list__item"));
2498
3344
  if (!rows.length) return;
2499
- const active = this.querySelector(".c-virtual-list__item:focus") || rows[0];
2500
- const idx = rows.indexOf(active);
2501
- let next = -1;
2502
- if (e.key === "ArrowDown") next = Math.min(idx + 1, rows.length - 1);
2503
- else if (e.key === "ArrowUp") next = Math.max(idx - 1, 0);
2504
- else if (e.key === "Home") next = 0;
2505
- else if (e.key === "End") next = rows.length - 1;
2506
- else if (e.key === "Enter" || e.key === " ") {
3345
+ const horizontal = this.getAttribute("orientation") === "horizontal";
3346
+ const fwd = horizontal ? "ArrowRight" : "ArrowDown";
3347
+ const back = horizontal ? "ArrowLeft" : "ArrowUp";
3348
+ const active = document.activeElement;
3349
+ const at = rows.indexOf(active);
3350
+ const scroller = this.querySelector(".c-virtual-list__scroller");
3351
+ const inner = this.querySelector(".c-virtual-list__inner");
3352
+ // At the window edge the next item is not rendered: scroll one row and
3353
+ // re-render, then move focus, instead of stopping at the last node.
3354
+ if ((e.key === fwd && at === rows.length - 1) || (e.key === back && at === 0 && Number(active && active.dataset.index) > 0)) {
2507
3355
  e.preventDefault();
2508
- const i = Number(active.dataset.index);
2509
- this.dispatchEvent(new CustomEvent("contour:select", { bubbles: true, composed: true, detail: { index: i, value: active.textContent } }));
3356
+ if (scroller && inner) {
3357
+ const delta = (e.key === fwd ? 1 : -1) * this._itemHeight();
3358
+ if (horizontal) scroller.scrollLeft += delta; else scroller.scrollTop += delta;
3359
+ this._renderWindow(scroller, inner, horizontal ? scroller.scrollLeft : scroller.scrollTop);
3360
+ const targetIndex = Number(active && active.dataset.index) + (e.key === fwd ? 1 : -1);
3361
+ requestAnimationFrame(() => {
3362
+ const next = this.querySelector(`.c-virtual-list__item[data-index="${targetIndex}"]`);
3363
+ if (next) { rows.forEach((r) => r.setAttribute("tabindex", "-1")); next.setAttribute("tabindex", "0"); try { next.focus(); } catch (err) {} }
3364
+ });
3365
+ }
2510
3366
  return;
2511
3367
  }
2512
- if (next < 0 || next === idx) return;
2513
- e.preventDefault();
2514
- rows.forEach((r, i) => r.setAttribute("tabindex", i === next ? "0" : "-1"));
2515
- try { rows[next].focus(); } catch (err) {}
3368
+ navKey(e, rows, { wrap: false, homeEnd: true, onNavigate: (i) => rows.forEach((r, j) => r.setAttribute("tabindex", j === i ? "0" : "-1")), onKey: () => { if (e.key === "Enter" || e.key === " ") { const i = Number(document.activeElement.dataset.index); this.dispatchEvent(new CustomEvent("contour:select", { bubbles: true, composed: true, detail: { index: i, value: document.activeElement.textContent } })); } } });
2516
3369
  });
2517
3370
  this.addEventListener("click", (e) => {
2518
3371
  const row = e.target && e.target.closest ? e.target.closest(".c-virtual-list__item") : null;
@@ -2531,44 +3384,126 @@ class ContourVirtualList extends ContourBase {
2531
3384
  class ContourCommandPalette extends ContourBase {
2532
3385
  static get observed() { return ["open", "items"]; }
2533
3386
  static get properties() { return { open: { attribute: "open", type: Boolean }, items: { attribute: "items" } }; }
3387
+ attributeChangedCallback(name, oldValue, newValue) {
3388
+ super.attributeChangedCallback(name, oldValue, newValue);
3389
+ // The open attribute is a first-class input (R20 T-18): setting it opens
3390
+ // the palette, removing it closes. It used to be observed but ignored.
3391
+ if (name === "open" && this.isConnected && oldValue !== newValue) {
3392
+ if (newValue !== null) this.show(); else this.hide();
3393
+ }
3394
+ }
3395
+ _recentsKey() { return "contour-command-palette:" + (this.id || "default") + ":recents"; }
3396
+ _recents() {
3397
+ try { const r = JSON.parse(localStorage.getItem(this._recentsKey()) || "[]"); return Array.isArray(r) ? r : []; } catch (e) { return []; }
3398
+ }
3399
+ _remember(label) {
3400
+ try {
3401
+ const r = this._recents().filter((l) => l !== label);
3402
+ r.unshift(label);
3403
+ localStorage.setItem(this._recentsKey(), JSON.stringify(r.slice(0, 5)));
3404
+ } catch (e) { /* storage is best-effort */ }
3405
+ }
3406
+ _cmdRow(label, index, recent) {
3407
+ const row = document.createElement("div");
3408
+ row.className = "c-command-palette__item";
3409
+ row.setAttribute("role", "option");
3410
+ row.id = this.id + "-opt-" + (recent ? "r" : "") + index;
3411
+ row.textContent = label;
3412
+ row.dataset.index = String(index);
3413
+ row.dataset.label = label;
3414
+ if (recent) row.dataset.recent = "true";
3415
+ return row;
3416
+ }
2534
3417
  render() {
2535
3418
  this.classList.add("c-command-palette");
2536
3419
  if (!this.hasAttribute("role")) this.setAttribute("role", "dialog");
2537
3420
  if (!this.hasAttribute("aria-modal")) this.setAttribute("aria-modal", "true");
2538
3421
  if (!this.hasAttribute("popover")) this.setAttribute("popover", "auto");
2539
- const search = this.ensure(".c-command-palette__search", () => { const el = document.createElement("input"); el.className = "c-input c-command-palette__search"; el.type = "search"; el.placeholder = "Search…"; el.setAttribute("aria-label", "Search commands"); return el; });
3422
+ if (!this.id) this.id = contourId("cmd-palette");
3423
+ const search = this.ensure(".c-command-palette__search", () => { const el = document.createElement("input"); el.className = "c-input c-command-palette__search"; el.type = "search"; el.placeholder = "Search…"; el.setAttribute("aria-label", "Search commands"); el.setAttribute("role", "combobox"); el.setAttribute("aria-autocomplete", "list"); el.setAttribute("aria-expanded", "false"); return el; });
2540
3424
  const list = this.ensure(".c-command-palette__list", () => { const el = document.createElement("div"); el.className = "c-command-palette__list"; el.setAttribute("role", "listbox"); return el; });
3425
+ if (!list.id) list.id = this.id + "-list";
3426
+ search.setAttribute("aria-controls", list.id);
3427
+ let parsed = [];
2541
3428
  const items = this.getAttribute("items");
2542
- if (items) {
2543
- try {
2544
- const parsed = JSON.parse(items);
2545
- list.innerHTML = "";
2546
- parsed.forEach((it, i) => {
2547
- const row = document.createElement("div");
2548
- row.className = "c-command-palette__item";
2549
- row.setAttribute("role", "option");
2550
- row.id = this.id + "-opt-" + i;
2551
- row.textContent = typeof it === "string" ? it : (it.label || it.title || "");
2552
- row.dataset.index = String(i);
2553
- row.dataset.label = row.textContent;
2554
- list.appendChild(row);
2555
- });
2556
- } catch (e) { /* keep */ }
3429
+ if (items) { try { parsed = JSON.parse(items); } catch (e) { warnBadJson(this, "items", e); } }
3430
+ if (!Array.isArray(parsed)) parsed = [];
3431
+ const labelOf = (it) => typeof it === "string" ? it : (it.label || it.title || "");
3432
+ list.innerHTML = "";
3433
+ // Recents: the last committed labels, shown while the query is empty.
3434
+ const q = (this._cmdQuery || "").toLowerCase().trim();
3435
+ const recents = q ? [] : this._recents().filter((l) => parsed.some((it) => labelOf(it) === l));
3436
+ if (recents.length) {
3437
+ const g = document.createElement("div");
3438
+ g.className = "c-command-palette__group";
3439
+ g.setAttribute("role", "presentation");
3440
+ g.textContent = labelText(this, "recent", "Recent");
3441
+ list.appendChild(g);
3442
+ recents.forEach((label) => list.appendChild(this._cmdRow(label, parsed.findIndex((it) => labelOf(it) === label), true)));
3443
+ }
3444
+ // Group headers for items that carry {group}; presentation rows, not
3445
+ // options, so the cursor and the filter skip them.
3446
+ let lastGroup = null;
3447
+ parsed.forEach((it, i) => {
3448
+ const g = typeof it === "object" && it !== null ? (it.group || null) : null;
3449
+ if (g && g !== lastGroup) {
3450
+ const h = document.createElement("div");
3451
+ h.className = "c-command-palette__group";
3452
+ h.setAttribute("role", "presentation");
3453
+ h.textContent = g;
3454
+ list.appendChild(h);
3455
+ lastGroup = g;
3456
+ }
3457
+ list.appendChild(this._cmdRow(labelOf(it), i, false));
3458
+ });
3459
+ // The query survives re-render: the search node is rebuilt, the host
3460
+ // remembers what was typed and re-applies the filter.
3461
+ if (this._cmdQuery) search.value = this._cmdQuery;
3462
+ if (this._cmdFilter) this._cmdFilter(this._cmdQuery || "");
3463
+ else if (this._cmdSetActive) this._cmdSetActive(this._cmdCursor || 0);
3464
+ }
3465
+ show() {
3466
+ if (this.classList.contains("is-open") || this.matches(":popover-open")) {
3467
+ if (!this.hasAttribute("open")) this.setAttribute("open", "");
3468
+ return;
2557
3469
  }
3470
+ if (typeof this.showPopover === "function") { try { this.showPopover(); } catch (e) {} }
3471
+ this.classList.add("is-open");
3472
+ modalContain(this, true);
3473
+ const s = this.querySelector(".c-command-palette__search");
3474
+ if (s) { s.setAttribute("aria-expanded", "true"); try { s.focus(); } catch (e) {} }
3475
+ if (!this.hasAttribute("open")) this.setAttribute("open", "");
3476
+ }
3477
+ hide() {
3478
+ const isOpen = this.classList.contains("is-open") || this.matches(":popover-open");
3479
+ if (!isOpen) { if (this.hasAttribute("open")) this.removeAttribute("open"); return; }
3480
+ if (typeof this.hidePopover === "function") { try { this.hidePopover(); } catch (e) {} }
3481
+ this.classList.remove("is-open");
3482
+ modalContain(this, false);
3483
+ const s = this.querySelector(".c-command-palette__search");
3484
+ if (s) s.setAttribute("aria-expanded", "false");
3485
+ if (this.hasAttribute("open")) this.removeAttribute("open");
2558
3486
  }
2559
- show() { if (typeof this.showPopover === "function") { try { this.showPopover(); } catch (e) {} } this.classList.add("is-open"); }
2560
- hide() { if (typeof this.hidePopover === "function") { try { this.hidePopover(); } catch (e) {} } this.classList.remove("is-open"); }
2561
3487
  toggle() { if (this.classList.contains("is-open") || this.matches(":popover-open")) this.hide(); else this.show(); }
2562
3488
  enhance() {
3489
+ // Rows are rebuilt on every render: re-apply the cursor before the
3490
+ // one-shot wiring guard.
3491
+ if (this._cmdSetActive) this._cmdSetActive(this._cmdCursor || 0);
3492
+ if (this._wiredCmdPalette) return;
2563
3493
  this._wiredCmdPalette = true;
2564
3494
  const search = () => this.querySelector(".c-command-palette__search");
2565
3495
  const list = () => this.querySelector(".c-command-palette__list");
2566
3496
  const items = () => Array.from(this.querySelectorAll(".c-command-palette__item"));
2567
3497
  const visibleItems = () => items().filter((it) => !it.hidden);
3498
+ // A cursor, not the focus position: the items are not focusable (focus
3499
+ // stays in the search field). The cursor is the single source of truth
3500
+ // for the active option, and it lives on the host across re-renders.
2568
3501
  const setActive = (idx) => {
2569
3502
  const vis = visibleItems();
2570
- vis.forEach((it, i) => it.classList.toggle("is-active", i === idx));
2571
- const active = vis[idx];
3503
+ if (!vis.length) { this._cmdCursor = 0; return; }
3504
+ this._cmdCursor = Math.max(0, Math.min(idx, vis.length - 1));
3505
+ vis.forEach((it, i) => it.classList.toggle("is-active", i === this._cmdCursor));
3506
+ const active = vis[this._cmdCursor];
2572
3507
  const s = search();
2573
3508
  if (s && active) s.setAttribute("aria-activedescendant", active.id);
2574
3509
  else if (s) s.removeAttribute("aria-activedescendant");
@@ -2579,35 +3514,59 @@ class ContourCommandPalette extends ContourBase {
2579
3514
  const label = (it.dataset.label || it.textContent || "").toLowerCase();
2580
3515
  it.hidden = needle !== "" && !label.includes(needle);
2581
3516
  });
3517
+ // A group header stays only while it has a visible item before the
3518
+ // next header.
3519
+ Array.from(list().querySelectorAll(".c-command-palette__group")).forEach((g) => {
3520
+ let n = g.nextElementSibling, any = false;
3521
+ while (n && !n.classList.contains("c-command-palette__group")) {
3522
+ if (!n.hidden && n.classList.contains("c-command-palette__item")) any = true;
3523
+ n = n.nextElementSibling;
3524
+ }
3525
+ g.hidden = !any;
3526
+ });
3527
+ // No-results is a state, not an empty box.
3528
+ let empty = list().querySelector(".c-command-palette__empty");
3529
+ const anyVisible = items().some((it) => !it.hidden);
3530
+ if (!anyVisible) {
3531
+ if (!empty) { empty = document.createElement("div"); empty.className = "c-command-palette__empty"; empty.setAttribute("role", "status"); list().appendChild(empty); }
3532
+ empty.textContent = labelText(this, "no-matches", "No matches");
3533
+ empty.hidden = false;
3534
+ } else if (empty) empty.hidden = true;
2582
3535
  setActive(0);
2583
3536
  };
2584
3537
  const select = (it) => {
2585
3538
  if (!it) return;
2586
- this.dispatchEvent(new CustomEvent("contour:select", { bubbles: true, composed: true, detail: { index: Number(it.dataset.index), label: it.dataset.label || it.textContent } }));
2587
- try { this.hidePopover(); } catch (e) {}
2588
- this.classList.remove("is-open");
3539
+ const detail = { index: Number(it.dataset.index), label: it.dataset.label || it.textContent };
3540
+ // The return value: the last committed command, readable without
3541
+ // listening for the event (R20 T-18).
3542
+ this.value = detail;
3543
+ this._remember(detail.label);
3544
+ this.dispatchEvent(new CustomEvent("contour:select", { bubbles: true, composed: true, detail }));
3545
+ this.hide();
2589
3546
  };
2590
- const s = search();
2591
- if (s) {
2592
- s.setAttribute("role", "combobox");
2593
- s.setAttribute("aria-autocomplete", "list");
2594
- s.setAttribute("aria-controls", list() ? list().id || "" : "");
2595
- if (!list().id) list().id = this.id + "-list";
2596
- s.setAttribute("aria-controls", list().id);
2597
- s.addEventListener("input", (e) => filter(e.target.value));
2598
- s.addEventListener("keydown", (e) => {
2599
- const vis = visibleItems();
2600
- const active = this.querySelector(".c-command-palette__item.is-active");
2601
- let idx = active ? vis.indexOf(active) : -1;
2602
- if (e.key === "ArrowDown") { e.preventDefault(); idx = Math.min(vis.length - 1, idx + 1); if (idx < 0) idx = 0; setActive(idx); }
2603
- else if (e.key === "ArrowUp") { e.preventDefault(); idx = Math.max(0, idx - 1); if (vis.length && idx < 0) idx = 0; setActive(idx); }
2604
- else if (e.key === "Home") { e.preventDefault(); setActive(0); }
2605
- else if (e.key === "End") { e.preventDefault(); setActive(vis.length - 1); }
2606
- else if (e.key === "Enter") { e.preventDefault(); if (active) select(active); }
2607
- else if (e.key === "Escape") { e.preventDefault(); try { this.hidePopover(); } catch (e) {} this.classList.remove("is-open"); }
2608
- });
2609
- }
2610
- // click selection
3547
+ this._cmdSetActive = setActive;
3548
+ this._cmdFilter = filter;
3549
+ // Delegated on the host (rule 12): the search node is rebuilt on every
3550
+ // re-render, and node-bound listeners died with it — typing and the
3551
+ // arrow keys stopped after any attribute change.
3552
+ this.addEventListener("input", (e) => {
3553
+ const s = search();
3554
+ if (!s || e.target !== s) return;
3555
+ this._cmdQuery = s.value;
3556
+ filter(s.value);
3557
+ });
3558
+ this.addEventListener("keydown", (e) => {
3559
+ const s = search();
3560
+ if (!s || e.target !== s) return;
3561
+ const vis = visibleItems();
3562
+ if (e.key === "Escape") { e.preventDefault(); this.hide(); return; }
3563
+ if (!vis.length) return;
3564
+ if (e.key === "ArrowDown") { e.preventDefault(); setActive(this._cmdCursor + 1); }
3565
+ else if (e.key === "ArrowUp") { e.preventDefault(); setActive(this._cmdCursor - 1); }
3566
+ else if (e.key === "Home") { e.preventDefault(); setActive(0); }
3567
+ else if (e.key === "End") { e.preventDefault(); setActive(vis.length - 1); }
3568
+ else if (e.key === "Enter") { e.preventDefault(); select(vis[this._cmdCursor]); }
3569
+ });
2611
3570
  this.addEventListener("click", (e) => {
2612
3571
  const it = e.target && e.target.closest ? e.target.closest(".c-command-palette__item") : null;
2613
3572
  if (it && this.contains(it) && !it.hidden) select(it);
@@ -2615,10 +3574,14 @@ class ContourCommandPalette extends ContourBase {
2615
3574
  // focus return on close
2616
3575
  let lastFocus = null;
2617
3576
  this.addEventListener("beforetoggle", (e) => {
2618
- if (e.newState === "open") lastFocus = document.activeElement;
2619
- else if (lastFocus && typeof lastFocus.focus === "function") { try { lastFocus.focus(); } catch (err) {} }
3577
+ if (e.newState === "open") {
3578
+ lastFocus = document.activeElement;
3579
+ this.dispatchEvent(new CustomEvent("contour:open", { bubbles: true, composed: true }));
3580
+ } else if (lastFocus && typeof lastFocus.focus === "function") {
3581
+ this.dispatchEvent(new CustomEvent("contour:close", { bubbles: true, composed: true }));
3582
+ try { lastFocus.focus(); } catch (err) {}
3583
+ }
2620
3584
  });
2621
- // Escape via popover light dismiss is handled by keydown above; also close on outside handled by popover.
2622
3585
  setActive(0);
2623
3586
  }
2624
3587
  }
@@ -2636,7 +3599,10 @@ class ContourBadgeOverflow extends ContourBase {
2636
3599
  const count = Number(this.getAttribute("count") || 0);
2637
3600
  const max = Number(this.getAttribute("max") || 3);
2638
3601
  const extra = Math.max(0, count - max);
2639
- this.textContent = "";
3602
+ // Keep authored children: the component adds the "+N" overflow badge, it
3603
+ // does not replace whatever the author put inside.
3604
+ const existing = this.querySelector(".c-badge-overflow__more");
3605
+ if (existing) existing.remove();
2640
3606
  if (extra > 0) {
2641
3607
  const b = document.createElement("span");
2642
3608
  b.className = "c-badge c-badge-overflow__more";
@@ -2652,15 +3618,36 @@ class ContourBadgeOverflow extends ContourBase {
2652
3618
  * Attributes: `open`, `side`, `title`.
2653
3619
  */
2654
3620
  class ContourSideSheet extends ContourBase {
2655
- static get observed() { return ["open", "side", "title"]; }
2656
- static get properties() { return { open: { attribute: "open", type: Boolean }, side: { attribute: "side" }, title: { attribute: "title" } }; }
3621
+ static get observed() { return ["open", "side", "title", "mode", "size"]; }
3622
+ static get properties() { return { open: { attribute: "open", type: Boolean }, side: { attribute: "side" }, title: { attribute: "title" }, mode: { attribute: "mode" }, size: { attribute: "size" } }; }
3623
+ // Dialog-family parity (R20 T-19/T-32): the open attribute is the state;
3624
+ // these methods route through it so the observer below owns the events,
3625
+ // containment and focus on every path.
3626
+ show() { this.setAttribute("open", ""); }
3627
+ // showModal is an action, not a state write (native dialog semantics):
3628
+ // it forces the modal path for this opening without touching `mode`.
3629
+ showModal() { this._sheetForceModal = true; this.show(); }
3630
+ close() { this.removeAttribute("open"); }
3631
+ get open() { return this.hasAttribute("open"); }
3632
+ set open(v) { if (v) this.show(); else this.close(); }
3633
+ _modal() { return this._sheetForceModal || (this.getAttribute("mode") || "modal") !== "non-modal"; }
2657
3634
  render() {
2658
3635
  this.classList.add("c-side-sheet");
2659
3636
  this.setAttribute("role", "dialog");
2660
- this.setAttribute("aria-modal", "true");
2661
- if (!this.hasAttribute("aria-label")) this.setAttribute("aria-label", "Side sheet");
2662
- const side = this.getAttribute("side") || "end";
3637
+ // Non-modal mode keeps the background live: no aria-modal, no
3638
+ // containment, no focus trap (R20 T-19).
3639
+ if (this._modal()) this.setAttribute("aria-modal", "true");
3640
+ else this.removeAttribute("aria-modal");
3641
+ if (!this.hasAttribute("aria-label")) this.setAttribute("aria-label", this.getAttribute("title") || "Side sheet");
3642
+ // Strip stale modifiers before projecting the current ones: changing
3643
+ // `side` or `size` used to accumulate classes.
3644
+ for (const c of Array.from(this.classList)) {
3645
+ if (/^c-side-sheet--(start|end|sm|md|lg)$/.test(c)) this.classList.remove(c);
3646
+ }
3647
+ const side = this.getAttribute("side") === "start" ? "start" : "end";
2663
3648
  this.classList.add("c-side-sheet--" + side);
3649
+ const size = this.getAttribute("size");
3650
+ if (size === "sm" || size === "md" || size === "lg") this.classList.add("c-side-sheet--" + size);
2664
3651
  if (this.hasAttribute("open")) this.classList.add("is-open"); else this.classList.remove("is-open");
2665
3652
  const title = this.getAttribute("title");
2666
3653
  if (title) {
@@ -2672,10 +3659,10 @@ class ContourSideSheet extends ContourBase {
2672
3659
  if (this._wiredSideSheet) return;
2673
3660
  this._wiredSideSheet = true;
2674
3661
  let lastFocus = null;
2675
- const close = () => this.removeAttribute("open");
2676
3662
  const keyHandler = (e) => {
2677
- if (e.key === "Escape" && this.hasAttribute("open")) { e.preventDefault(); close(); return; }
2678
- if (e.key === "Tab" && this.hasAttribute("open")) {
3663
+ if (e.key === "Escape" && this.hasAttribute("open")) { e.preventDefault(); this.close(); return; }
3664
+ // The focus trap is modal-only; a non-modal sheet shares the page.
3665
+ if (e.key === "Tab" && this.hasAttribute("open") && this._modal()) {
2679
3666
  const focusables = Array.from(this.querySelectorAll("button, [href], input, select, textarea, [tabindex]:not([tabindex='-1'])")).filter((el) => !el.hasAttribute("disabled"));
2680
3667
  if (!focusables.length) { e.preventDefault(); return; }
2681
3668
  const first = focusables[0], last = focusables[focusables.length - 1];
@@ -2686,60 +3673,196 @@ class ContourSideSheet extends ContourBase {
2686
3673
  document.addEventListener("keydown", keyHandler);
2687
3674
  onDispose(this, () => document.removeEventListener("keydown", keyHandler));
2688
3675
  this.addEventListener("click", (e) => {
2689
- if (e.target === this) close();
3676
+ if (e.target === this) this.close();
2690
3677
  });
2691
- // Focus management: capture focus on open, restore on close.
2692
- const obs = new MutationObserver(() => {
2693
- if (this.hasAttribute("open")) {
3678
+ // Focus management: capture focus on open, restore on close. The
3679
+ // transition guard (not lastFocus) decides whether a close happened,
3680
+ // so a sheet mounted open still reports its close.
3681
+ let wasOpen = false;
3682
+ const transition = () => {
3683
+ const isOpen = this.hasAttribute("open");
3684
+ if (isOpen && !wasOpen) {
3685
+ wasOpen = true;
2694
3686
  lastFocus = document.activeElement;
3687
+ if (this._modal()) modalContain(this, true);
2695
3688
  const first = this.querySelector("button, [href], input, select, textarea, [tabindex]:not([tabindex='-1'])");
2696
3689
  if (first) try { first.focus(); } catch (err) {}
2697
- } else if (lastFocus) {
2698
- try { lastFocus.focus(); } catch (err) {}
3690
+ this.dispatchEvent(new CustomEvent("contour:open", { bubbles: true, composed: true }));
3691
+ } else if (!isOpen && wasOpen) {
3692
+ wasOpen = false;
3693
+ if (this._modal()) modalContain(this, false);
3694
+ this._sheetForceModal = false;
3695
+ if (lastFocus && typeof lastFocus.focus === "function") try { lastFocus.focus(); } catch (err) {}
2699
3696
  lastFocus = null;
3697
+ this.dispatchEvent(new CustomEvent("contour:close", { bubbles: true, composed: true }));
2700
3698
  }
2701
- });
3699
+ };
3700
+ const obs = new MutationObserver(transition);
2702
3701
  obs.observe(this, { attributes: true, attributeFilter: ["open"] });
2703
- onDispose(this, () => obs.disconnect());
3702
+ if (this.hasAttribute("open")) transition();
3703
+ onDispose(this, () => { obs.disconnect(); if (this.hasAttribute("open") && this._modal()) modalContain(this, false); });
2704
3704
  }
2705
3705
  }
2706
3706
  define("contour-side-sheet", ContourSideSheet);
2707
3707
 
2708
3708
  /**
2709
- * Tour: web component wrapper.
2710
- * Attributes: `steps`, `current`.
3709
+ * Tour: a coach-mark walkthrough. Attributes: `steps` (JSON of strings or
3710
+ * {text, target}), `current`, `open`, and `persist` (with an `id`) to remember
3711
+ * completion in localStorage. The tour advances `current` itself (R20 T-20) —
3712
+ * clicks used to emit events only, so without a consumer round-trip the tour
3713
+ * never moved. ArrowLeft/Right step, Escape closes (only while open), the tip
3714
+ * positions near its step's target, and a step counter names the place.
3715
+ * Non-modal by design: the page behind stays live.
2711
3716
  */
2712
3717
  class ContourTour extends ContourBase {
2713
- static get observed() { return ["steps", "current"]; }
2714
- static get properties() { return { steps: { attribute: "steps" }, current: { attribute: "current" } }; }
3718
+ static get observed() { return ["steps", "current", "open", "persist", "id"]; }
3719
+ static get properties() { return { steps: { attribute: "steps" }, current: { attribute: "current" }, open: { attribute: "open", type: Boolean }, persist: { attribute: "persist", type: Boolean } }; }
3720
+ _steps() {
3721
+ let parsed = [];
3722
+ try { const s = this.getAttribute("steps"); parsed = s ? JSON.parse(s) : []; } catch (e) { parsed = []; }
3723
+ return Array.isArray(parsed) ? parsed : [];
3724
+ }
3725
+ _current(n) {
3726
+ const c = Number(this.getAttribute("current") || 0);
3727
+ return Number.isFinite(c) ? Math.min(Math.max(0, c), Math.max(0, n - 1)) : 0;
3728
+ }
3729
+ _storageKey() { return this.id ? "contour-tour:" + this.id : null; }
3730
+ _completed() {
3731
+ if (!this.hasAttribute("persist")) return false;
3732
+ const key = this._storageKey();
3733
+ try { return key ? localStorage.getItem(key) === "done" : false; } catch (e) { return false; }
3734
+ }
3735
+ _markCompleted() {
3736
+ if (!this.hasAttribute("persist")) return;
3737
+ const key = this._storageKey();
3738
+ try { if (key) localStorage.setItem(key, "done"); } catch (e) { /* storage is best-effort */ }
3739
+ }
3740
+ show() { this.setAttribute("open", ""); }
3741
+ close() {
3742
+ if (!this.hasAttribute("open")) return;
3743
+ this.removeAttribute("open");
3744
+ this._markCompleted();
3745
+ this.dispatchEvent(new CustomEvent("contour:close", { bubbles: true, composed: true }));
3746
+ }
2715
3747
  render() {
2716
3748
  this.classList.add("c-tour");
2717
3749
  this.setAttribute("role", "dialog");
2718
- this.setAttribute("aria-modal", "true");
2719
- this.setAttribute("aria-label", "Tour");
2720
- const steps = this.getAttribute("steps");
2721
- const current = Number(this.getAttribute("current") || 0);
2722
- let parsed = [];
2723
- try { parsed = steps ? JSON.parse(steps) : []; } catch (e) { parsed = []; }
3750
+ // No aria-modal: a tour is a coach mark, not a modal. It points at a
3751
+ // target in the page (step.target), so the page behind it stays
3752
+ // scrollable, clickable and focusable, and assistive tech must not be
3753
+ // told the rest of the document is inert.
3754
+ this.setAttribute("aria-label", labelText(this, "tour", "Tour"));
3755
+ const parsed = this._steps();
3756
+ // First render normalizes the open state: a tour with steps starts open
3757
+ // unless persistence says it was completed. After that, `open` is the
3758
+ // single source of truth (close removes it; nothing re-normalizes).
3759
+ if (!this._tourInitialized) {
3760
+ this._tourInitialized = true;
3761
+ if (parsed.length && !this.hasAttribute("open") && !this._completed()) this.setAttribute("open", "");
3762
+ }
3763
+ const isOpen = this.hasAttribute("open") && parsed.length > 0;
3764
+ if (isOpen) this.removeAttribute("hidden"); else this.setAttribute("hidden", "");
3765
+ const current = this._current(parsed.length);
2724
3766
  const step = parsed[current] || {};
3767
+ const counter = this.ensure(".c-tour__step", () => { const el = document.createElement("div"); el.className = "c-tour__step"; return el; });
3768
+ counter.textContent = labelText(this, "step", "Step") + " " + (current + 1) + " / " + parsed.length;
2725
3769
  const tip = this.ensure(".c-tour__tip", () => { const el = document.createElement("div"); el.className = "c-tour__tip"; return el; });
2726
3770
  tip.textContent = typeof step === "string" ? step : (step.text || step.title || "");
3771
+ if (counter.nextSibling !== tip) this.insertBefore(counter, tip);
2727
3772
  const nav = this.ensure(".c-tour__nav", () => { const el = document.createElement("div"); el.className = "c-tour__nav c-btn-group"; return el; });
2728
- const next = this.ensure(".c-tour__next", () => { const el = document.createElement("button"); el.className = "c-btn c-btn--sm c-tour__next"; el.type = "button"; el.textContent = "Next"; return el; });
2729
- if (!nav.contains(next)) nav.appendChild(next);
3773
+ const back = this.ensure(".c-tour__back", () => { const el = document.createElement("button"); el.className = "c-btn c-btn--sm c-tour__back"; el.type = "button"; return el; }, nav);
3774
+ back.textContent = labelText(this, "back", "Back");
3775
+ back.disabled = current === 0;
3776
+ const next = this.ensure(".c-tour__next", () => { const el = document.createElement("button"); el.className = "c-btn c-btn--sm c-tour__next"; el.type = "button"; return el; }, nav);
3777
+ next.textContent = current >= parsed.length - 1 ? labelText(this, "done", "Done") : labelText(this, "next", "Next");
3778
+ const close = this.ensure(".c-tour__close", () => { const el = document.createElement("button"); el.className = "c-btn c-btn--sm c-tour__close"; el.type = "button"; return el; }, nav);
3779
+ close.textContent = labelText(this, "close", "Close");
3780
+ // Keep the controls in order regardless of which were just created.
3781
+ if (nav.firstChild !== back) nav.insertBefore(back, nav.firstChild);
3782
+ if (back.nextSibling !== next) nav.insertBefore(next, back.nextSibling);
3783
+ if (next.nextSibling !== close) nav.insertBefore(close, next.nextSibling);
3784
+ // Target highlight: a step may name the element it points at, so the
3785
+ // reader sees what the tip is about instead of a floating box.
3786
+ if (this._tourTarget && this._tourTarget.classList) this._tourTarget.classList.remove("c-tour__target");
3787
+ this._tourTarget = null;
3788
+ const targetSel = isOpen && typeof step === "object" && step ? step.target : null;
3789
+ if (targetSel) {
3790
+ const target = document.querySelector(targetSel);
3791
+ if (target && target.classList) { target.classList.add("c-tour__target"); this._tourTarget = target; }
3792
+ }
3793
+ if (isOpen) this._positionTour();
3794
+ }
3795
+ _positionTour() {
3796
+ // Near the target when there is one (below, or above when there is no
3797
+ // room), clamped to the viewport; otherwise bottom-center. The host is
3798
+ // position:fixed with no inset in the sheet, so without this it sat at
3799
+ // its static position.
3800
+ const vw = window.innerWidth, vh = window.innerHeight;
3801
+ const w = this.offsetWidth || 280, h = this.offsetHeight || 120;
3802
+ const target = this._tourTarget;
3803
+ if (target && target.getBoundingClientRect) {
3804
+ const r = target.getBoundingClientRect();
3805
+ let top = r.bottom + 8;
3806
+ if (top + h > vh - 8) top = Math.max(8, r.top - h - 8);
3807
+ const left = Math.min(Math.max(8, r.left), Math.max(8, vw - w - 8));
3808
+ this.style.insetBlockStart = top + "px";
3809
+ this.style.insetInlineStart = left + "px";
3810
+ this.style.insetBlockEnd = "auto";
3811
+ this.style.transform = "";
3812
+ } else {
3813
+ this.style.insetBlockStart = "auto";
3814
+ this.style.insetBlockEnd = "1rem";
3815
+ this.style.insetInlineStart = "50%";
3816
+ this.style.transform = "translateX(-50%)";
3817
+ }
2730
3818
  }
2731
3819
  enhance() {
2732
3820
  if (this._wiredTour) return;
2733
3821
  this._wiredTour = true;
2734
- const nextBtn = this.querySelector(".c-tour__next");
2735
- if (nextBtn) try { nextBtn.focus(); } catch (err) {}
3822
+ // A tour is a coach mark, not a modal, so it must not take the page with
3823
+ // it: no modalContain, no focus steal (the guide went offline when both
3824
+ // happened on upgrade). Stepping writes `current` back — the event is
3825
+ // for consumers, not the mechanism.
3826
+ const step = (dir) => {
3827
+ const parsed = this._steps();
3828
+ if (!parsed.length || !this.hasAttribute("open")) return;
3829
+ const cur = this._current(parsed.length);
3830
+ if (dir === "next") {
3831
+ if (cur >= parsed.length - 1) { this.close(); return; }
3832
+ this.setAttribute("current", String(cur + 1));
3833
+ this.dispatchEvent(new CustomEvent("contour:step-change", { bubbles: true, composed: true, detail: { direction: "next", index: cur + 1 } }));
3834
+ } else {
3835
+ if (cur === 0) return;
3836
+ this.setAttribute("current", String(cur - 1));
3837
+ this.dispatchEvent(new CustomEvent("contour:step-change", { bubbles: true, composed: true, detail: { direction: "prev", index: cur - 1 } }));
3838
+ }
3839
+ };
3840
+ this._tourStep = step;
2736
3841
  this.addEventListener("click", (e) => {
2737
- const next = e.target && e.target.closest ? e.target.closest(".c-tour__next") : null;
2738
- if (next && this.contains(next)) this.dispatchEvent(new CustomEvent("contour:step-change", { bubbles: true, composed: true, detail: { direction: "next" } }));
3842
+ const t = e.target && e.target.closest ? e.target : null;
3843
+ if (!t) return;
3844
+ if (t.closest(".c-tour__next")) { step("next"); return; }
3845
+ if (t.closest(".c-tour__back")) { step("prev"); return; }
3846
+ if (t.closest(".c-tour__close")) this.close();
2739
3847
  });
2740
- const keyHandler = (e) => { if (e.key === "Escape") this.dispatchEvent(new CustomEvent("contour:close", { bubbles: true, composed: true })); };
3848
+ const keyHandler = (e) => {
3849
+ if (!this.hasAttribute("open")) return;
3850
+ const tag = e.target && e.target.tagName;
3851
+ if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") return;
3852
+ if (e.key === "Escape") { e.preventDefault(); this.close(); }
3853
+ else if (e.key === "ArrowRight") { e.preventDefault(); step("next"); }
3854
+ else if (e.key === "ArrowLeft") { e.preventDefault(); step("prev"); }
3855
+ };
2741
3856
  document.addEventListener("keydown", keyHandler);
2742
- onDispose(this, () => document.removeEventListener("keydown", keyHandler));
3857
+ const reposition = () => { if (this.hasAttribute("open")) this._positionTour(); };
3858
+ window.addEventListener("scroll", reposition, { passive: true, capture: true });
3859
+ window.addEventListener("resize", reposition, { passive: true });
3860
+ onDispose(this, () => {
3861
+ document.removeEventListener("keydown", keyHandler);
3862
+ window.removeEventListener("scroll", reposition, { capture: true });
3863
+ window.removeEventListener("resize", reposition);
3864
+ if (this._tourTarget && this._tourTarget.classList) this._tourTarget.classList.remove("c-tour__target");
3865
+ });
2743
3866
  }
2744
3867
  }
2745
3868
  define("contour-tour", ContourTour);
@@ -2749,10 +3872,13 @@ class ContourTour extends ContourBase {
2749
3872
  * Attributes: `value`, `placeholder`, `disabled`, `error`, `help`.
2750
3873
  */
2751
3874
  class ContourTagsInput extends ContourBase {
2752
- static get observed() { return ["value", "placeholder", "disabled", "error", "help"]; }
2753
- static get properties() { return { value: { attribute: "value" }, placeholder: { attribute: "placeholder" }, disabled: { attribute: "disabled", type: Boolean }, error: { attribute: "error" }, help: { attribute: "help" } }; }
3875
+ static get formAssociated() { return true; }
3876
+ static get observed() { return ["value", "placeholder", "disabled", "error", "help", "required", "max"]; }
3877
+ static get properties() { return { value: { attribute: "value" }, placeholder: { attribute: "placeholder" }, disabled: { attribute: "disabled", type: Boolean }, error: { attribute: "error" }, help: { attribute: "help" }, required: { attribute: "required", type: Boolean }, max: { attribute: "max" } }; }
2754
3878
  render() {
2755
3879
  this.classList.add("c-tags-input");
3880
+ if (!this.hasAttribute("role")) this.setAttribute("role", "group");
3881
+ if (!this.hasAttribute("aria-label")) this.setAttribute("aria-label", "Tags input");
2756
3882
  const input = this.ensure(".c-tags-input__input", () => { const el = document.createElement("input"); el.className = "c-input c-tags-input__input"; el.type = "text"; el.setAttribute("aria-label", "Add tag"); return el; });
2757
3883
  input.placeholder = this.getAttribute("placeholder") || "Add tag…";
2758
3884
  if (this.hasAttribute("disabled")) { input.setAttribute("disabled", ""); this.classList.add("is-disabled"); }
@@ -2782,33 +3908,74 @@ class ContourTagsInput extends ContourBase {
2782
3908
  chip.appendChild(rm);
2783
3909
  this.insertBefore(chip, input);
2784
3910
  });
3911
+ if (this._internals) this._syncFormValue();
2785
3912
  }
2786
3913
  enhance() {
2787
3914
  if (this._wiredTagsInput) return;
2788
3915
  this._wiredTagsInput = true;
2789
- let live = this.querySelector(".c-tags-input__live");
2790
- if (!live) { live = document.createElement("span"); live.className = "c-tags-input__live visually-hidden"; live.setAttribute("aria-live", "polite"); live.setAttribute("aria-atomic", "true"); this.appendChild(live); }
2791
- const announce = (msg) => { if (live) live.textContent = msg; };
3916
+ this._syncFormValue();
3917
+ this.addEventListener("contour:add", () => { this._syncFormValue(); });
3918
+ this.addEventListener("contour:remove", () => { this._syncFormValue(); });
3919
+ // The live region is a generated node: a re-render drops it, so look
3920
+ // it up (and recreate it) per announcement — rule 12.
3921
+ const announce = (msg) => {
3922
+ let live = this.querySelector(".c-tags-input__live");
3923
+ if (!live) {
3924
+ live = document.createElement("span");
3925
+ live.className = "c-tags-input__live visually-hidden";
3926
+ live.setAttribute("aria-live", "polite");
3927
+ live.setAttribute("aria-atomic", "true");
3928
+ this.appendChild(live);
3929
+ }
3930
+ live.textContent = msg;
3931
+ };
3932
+ const readTags = () => {
3933
+ const raw = this.getAttribute("value") || "";
3934
+ let tags = [];
3935
+ try { tags = JSON.parse(raw); } catch (err) { tags = raw.split(",").map((s) => s.trim()).filter(Boolean); }
3936
+ return Array.isArray(tags) ? tags.map(String) : [];
3937
+ };
3938
+ // One add path for Enter, comma and paste (R20 T-21): dedupe and the
3939
+ // `max` limit are announced, not silent.
3940
+ const addMany = (candidates) => {
3941
+ if (this.hasAttribute("disabled")) return;
3942
+ const tags = readTags();
3943
+ const max = Number(this.getAttribute("max"));
3944
+ const added = [], dups = [];
3945
+ let limitHit = false;
3946
+ for (const raw of candidates) {
3947
+ const v = String(raw).trim();
3948
+ if (!v) continue;
3949
+ if (tags.includes(v)) { dups.push(v); continue; }
3950
+ if (Number.isFinite(max) && max > 0 && tags.length >= max) { limitHit = true; break; }
3951
+ tags.push(v);
3952
+ added.push(v);
3953
+ }
3954
+ if (added.length) {
3955
+ this.setAttribute("value", JSON.stringify(tags));
3956
+ for (const v of added) this.dispatchEvent(new CustomEvent("contour:add", { bubbles: true, composed: true, detail: { value: v } }));
3957
+ }
3958
+ // One composed announcement AFTER the writeback re-render, so the
3959
+ // limit/duplicate feedback is not overwritten by the "Added" line.
3960
+ const parts = [];
3961
+ if (added.length) parts.push("Added " + added.join(", "));
3962
+ if (dups.length) parts.push(dups.join(", ") + " already added");
3963
+ if (limitHit) parts.push("Tag limit reached (" + max + ")");
3964
+ if (parts.length) announce(parts.join(". "));
3965
+ };
2792
3966
  this.addEventListener("keydown", (e) => {
2793
3967
  const input = this.querySelector(".c-tags-input__input");
2794
- if (!input) return;
3968
+ if (!input || this.hasAttribute("disabled")) return;
2795
3969
  if (e.key === "Enter" && e.target === input) {
2796
3970
  e.preventDefault();
2797
- const v = input.value.trim();
2798
- if (v) {
2799
- let tags = [];
2800
- try { tags = JSON.parse(this.getAttribute("value") || "[]"); } catch (err) { tags = (this.getAttribute("value") || "").split(",").map((s) => s.trim()).filter(Boolean); }
2801
- if (!Array.isArray(tags)) tags = [];
2802
- if (!tags.includes(v)) tags.push(v);
2803
- this.setAttribute("value", JSON.stringify(tags));
2804
- input.value = "";
2805
- announce("Added " + v);
2806
- this.dispatchEvent(new CustomEvent("contour:add", { bubbles: true, composed: true, detail: { value: v } }));
2807
- }
3971
+ // Clear BEFORE addMany: its attribute write re-renders, and a
3972
+ // clear afterwards would land on the detached node while the base
3973
+ // restore resurrects the committed text in the new one.
3974
+ const v = input.value;
3975
+ input.value = "";
3976
+ addMany([v]);
2808
3977
  } else if (e.key === "Backspace" && e.target === input && input.value === "") {
2809
- let tags = [];
2810
- try { tags = JSON.parse(this.getAttribute("value") || "[]"); } catch (err) { tags = (this.getAttribute("value") || "").split(",").map((s) => s.trim()).filter(Boolean); }
2811
- if (!Array.isArray(tags)) tags = [];
3978
+ const tags = readTags();
2812
3979
  if (tags.length) {
2813
3980
  const removed = tags.pop();
2814
3981
  this.setAttribute("value", JSON.stringify(tags));
@@ -2817,53 +3984,109 @@ class ContourTagsInput extends ContourBase {
2817
3984
  }
2818
3985
  }
2819
3986
  });
3987
+ // A typed comma commits the segment before it, the way tag fields do.
3988
+ this.addEventListener("input", (e) => {
3989
+ const input = this.querySelector(".c-tags-input__input");
3990
+ if (!input || e.target !== input || this.hasAttribute("disabled")) return;
3991
+ if (input.value.includes(",")) {
3992
+ const parts = input.value.split(",");
3993
+ input.value = parts.pop();
3994
+ addMany(parts);
3995
+ }
3996
+ });
3997
+ // Paste splits on commas, semicolons and newlines into separate tags.
3998
+ this.addEventListener("paste", (e) => {
3999
+ const input = this.querySelector(".c-tags-input__input");
4000
+ if (!input || e.target !== input || this.hasAttribute("disabled")) return;
4001
+ const text = e.clipboardData && e.clipboardData.getData("text/plain");
4002
+ if (text && /[,;\n]/.test(text)) {
4003
+ e.preventDefault();
4004
+ addMany(text.split(/[,;\n]+/));
4005
+ }
4006
+ });
2820
4007
  this.addEventListener("click", (e) => {
2821
4008
  const rm = e.target && e.target.closest ? e.target.closest(".c-tags-input__remove") : null;
2822
- if (rm && this.contains(rm)) {
4009
+ // The remove buttons used to work while the host was disabled.
4010
+ if (rm && this.contains(rm) && !this.hasAttribute("disabled")) {
2823
4011
  const val = rm.dataset.value;
2824
- let tags = [];
2825
- try { tags = JSON.parse(this.getAttribute("value") || "[]"); } catch (err) { tags = (this.getAttribute("value") || "").split(",").map((s) => s.trim()).filter(Boolean); }
2826
- if (!Array.isArray(tags)) tags = [];
2827
- const next = tags.filter((t) => t !== val);
4012
+ const next = readTags().filter((t) => t !== val);
2828
4013
  this.setAttribute("value", JSON.stringify(next));
2829
4014
  announce("Removed " + val);
2830
4015
  this.dispatchEvent(new CustomEvent("contour:remove", { bubbles: true, composed: true, detail: { value: val } }));
2831
4016
  }
2832
4017
  });
2833
4018
  }
4019
+ // Form-value sync override (R16-06): tags are stored as a JSON array on the
4020
+ // host, not in the inner input, so the base class's generic sync would read
4021
+ // the empty add-tag input. Submit the host's value instead. Required means
4022
+ // at least one TAG — "[]" is a present attribute but an empty answer.
4023
+ _syncFormValue() {
4024
+ if (!this._internals) return;
4025
+ this._internals.setFormValue(this.getAttribute("value") || "[]");
4026
+ let count = 0;
4027
+ try { const p = JSON.parse(this.getAttribute("value") || "[]"); count = Array.isArray(p) ? p.length : 0; } catch (err) { count = (this.getAttribute("value") || "").split(",").filter((s) => s.trim()).length; }
4028
+ this._syncValidity(this.hasAttribute("required") && count === 0);
4029
+ }
2834
4030
  }
2835
4031
  define("contour-tags-input", ContourTagsInput);
2836
4032
 
2837
4033
  /**
2838
- * Sortable List: web component wrapper.
2839
- * Attributes: `items`.
4034
+ * Sortable List: a reorderable list. Attributes: `items` (JSON, the authored
4035
+ * data) and `order` (JSON array of source indices — the user's permutation,
4036
+ * written back on every move so a re-render never reverts it, R20 T-22).
4037
+ * Drag with the pointer, or focus a handle and use ArrowUp/Down/Home/End;
4038
+ * moves announce position and emit contour:move + contour:reorder.
4039
+ * Update mode is scaffold: the list rebuilds on render (the old "keyed"
4040
+ * claim was false — render cleared innerHTML).
2840
4041
  */
2841
4042
  class ContourSortableList extends ContourBase {
2842
- static get updateMode() { return "keyed"; }
2843
- static get observed() { return ["items"]; }
2844
- static get properties() { return { items: { attribute: "items" } }; }
4043
+ static get observed() { return ["items", "order"]; }
4044
+ static get properties() { return { items: { attribute: "items" }, order: { attribute: "order" } }; }
2845
4045
  render() {
2846
4046
  this.classList.add("c-sortable-list");
2847
4047
  const list = this.ensure(".c-sortable-list__list", () => { const el = document.createElement("ul"); el.className = "c-sortable-list__list"; return el; });
2848
4048
  const items = this.getAttribute("items");
2849
4049
  let parsed = [];
2850
4050
  try { parsed = items ? JSON.parse(items) : []; } catch (e) { parsed = []; }
4051
+ if (!Array.isArray(parsed)) parsed = [];
4052
+ // Apply the user's permutation when it still fits the data; a changed
4053
+ // items payload with a stale order falls back to the authored sequence.
4054
+ let sourceOrder = Array.from({ length: parsed.length }, (_, i) => i);
4055
+ const orderRaw = this.getAttribute("order");
4056
+ if (orderRaw) {
4057
+ try {
4058
+ const order = JSON.parse(orderRaw);
4059
+ if (Array.isArray(order) && order.length === parsed.length && order.every((i) => Number.isInteger(i) && i >= 0 && i < parsed.length)) {
4060
+ sourceOrder = order.slice();
4061
+ parsed = order.map((i) => parsed[i]);
4062
+ }
4063
+ } catch (e) { /* a malformed order is ignored, not fatal */ }
4064
+ }
4065
+ this._sortableSourceOrder = sourceOrder;
4066
+ this._sortableItems = parsed;
2851
4067
  list.innerHTML = "";
2852
4068
  parsed.forEach((it, i) => {
2853
4069
  const li = document.createElement("li");
2854
4070
  li.className = "c-sortable-list__item";
2855
4071
  li.setAttribute("draggable", "true");
2856
4072
  li.dataset.index = String(i);
4073
+ const itemLabel = typeof it === "string" ? it : (it.label || it.text || "");
2857
4074
  const handle = document.createElement("span");
2858
4075
  handle.className = "c-sortable-list__handle";
2859
4076
  handle.textContent = "⋮⋮";
2860
4077
  handle.setAttribute("role", "button");
4078
+ // "⋮⋮" is the glyph, not a name. A screen reader hears the glyph as
4079
+ // punctuation unless the handle says what it moves.
4080
+ handle.setAttribute("aria-label", labelText(this, "reorder", "Reorder") + " " + (itemLabel || String(i + 1)));
4081
+ // The writeback re-render rebuilds the list; the preserve key puts
4082
+ // focus back on the handle that moved, not the one at its old index.
4083
+ handle.setAttribute("data-contour-preserve-key", itemLabel || String(i));
2861
4084
  handle.tabIndex = 0;
2862
4085
  li.appendChild(handle);
2863
- const label = document.createElement("span");
2864
- label.className = "c-sortable-list__label";
2865
- label.textContent = typeof it === "string" ? it : (it.label || it.text || "");
2866
- li.appendChild(label);
4086
+ const labelEl = document.createElement("span");
4087
+ labelEl.className = "c-sortable-list__label";
4088
+ labelEl.textContent = itemLabel;
4089
+ li.appendChild(labelEl);
2867
4090
  list.appendChild(li);
2868
4091
  });
2869
4092
  }
@@ -2871,11 +4094,32 @@ class ContourSortableList extends ContourBase {
2871
4094
  if (this._wiredSortableList) return;
2872
4095
  this._wiredSortableList = true;
2873
4096
  const list = () => this.querySelector(".c-sortable-list__list");
2874
- // Live region for position announcements.
2875
- let live = this.querySelector(".c-sortable-list__live");
2876
- if (!live) { live = document.createElement("span"); live.className = "c-sortable-list__live visually-hidden"; live.setAttribute("aria-live", "polite"); live.setAttribute("aria-atomic", "true"); this.appendChild(live); }
2877
- const announce = (msg) => { if (live) live.textContent = msg; };
4097
+ // Live region for position announcements. Generated node: the writeback
4098
+ // re-render drops it, so look it up (and recreate it) per call — rule 12.
4099
+ const announce = (msg) => {
4100
+ let live = this.querySelector(".c-sortable-list__live");
4101
+ if (!live) {
4102
+ live = document.createElement("span");
4103
+ live.className = "c-sortable-list__live visually-hidden";
4104
+ live.setAttribute("aria-live", "polite");
4105
+ live.setAttribute("aria-atomic", "true");
4106
+ this.appendChild(live);
4107
+ }
4108
+ live.textContent = msg;
4109
+ };
2878
4110
  const index = (li) => Array.from(list().children).indexOf(li);
4111
+ // Persist the permutation (R20 T-22): the DOM move alone was reverted
4112
+ // by the next attribute-triggered re-render. `order` maps display
4113
+ // positions back to source indices; `items` stays the authored data.
4114
+ const writeBack = (from, to) => {
4115
+ const n = (this._sortableItems || []).length;
4116
+ const cur = Array.isArray(this._sortableSourceOrder) && this._sortableSourceOrder.length === n
4117
+ ? this._sortableSourceOrder.slice()
4118
+ : Array.from({ length: n }, (_, i) => i);
4119
+ const [src] = cur.splice(from, 1);
4120
+ cur.splice(to, 0, src);
4121
+ this.setAttribute("order", JSON.stringify(cur));
4122
+ };
2879
4123
  // Pointer drag reorder.
2880
4124
  let dragFrom = null;
2881
4125
  this.addEventListener("dragstart", (e) => {
@@ -2903,7 +4147,9 @@ class ContourSortableList extends ContourBase {
2903
4147
  else l.insertBefore(fromLi, l.children[to]);
2904
4148
  const item = fromLi.querySelector(".c-sortable-list__label");
2905
4149
  announce((item ? item.textContent : "Item") + " moved to position " + (to + 1));
2906
- this.dispatchEvent(new CustomEvent("contour:reorder", { bubbles: true, composed: true, detail: { from: dragFrom, to } }));
4150
+ const from = dragFrom;
4151
+ writeBack(from, to);
4152
+ this.dispatchEvent(new CustomEvent("contour:reorder", { bubbles: true, composed: true, detail: { from, to } }));
2907
4153
  }
2908
4154
  dragFrom = null;
2909
4155
  Array.from(l.children).forEach((n) => n.classList.remove("is-dragging"));
@@ -2921,23 +4167,29 @@ class ContourSortableList extends ContourBase {
2921
4167
  if (!li) return;
2922
4168
  const l = list();
2923
4169
  const from = index(li);
2924
- if (e.key === "ArrowUp" && li.previousElementSibling) {
2925
- e.preventDefault();
2926
- l.insertBefore(li, li.previousElementSibling);
2927
- const to = index(li);
4170
+ const moved = (direction, to) => {
2928
4171
  const label = li.querySelector(".c-sortable-list__label");
2929
4172
  announce((label ? label.textContent : "Item") + " moved to position " + (to + 1));
2930
- this.dispatchEvent(new CustomEvent("contour:move", { bubbles: true, composed: true, detail: { direction: "up", from, to } }));
4173
+ writeBack(from, to);
4174
+ this.dispatchEvent(new CustomEvent("contour:move", { bubbles: true, composed: true, detail: { direction, from, to } }));
2931
4175
  this.dispatchEvent(new CustomEvent("contour:reorder", { bubbles: true, composed: true, detail: { from, to } }));
2932
- }
2933
- if (e.key === "ArrowDown" && li.nextElementSibling) {
4176
+ };
4177
+ if (e.key === "ArrowUp" && li.previousElementSibling) {
4178
+ e.preventDefault();
4179
+ l.insertBefore(li, li.previousElementSibling);
4180
+ moved("up", index(li));
4181
+ } else if (e.key === "ArrowDown" && li.nextElementSibling) {
2934
4182
  e.preventDefault();
2935
4183
  l.insertBefore(li.nextElementSibling, li);
2936
- const to = index(li);
2937
- const label = li.querySelector(".c-sortable-list__label");
2938
- announce((label ? label.textContent : "Item") + " moved to position " + (to + 1));
2939
- this.dispatchEvent(new CustomEvent("contour:move", { bubbles: true, composed: true, detail: { direction: "down", from, to } }));
2940
- this.dispatchEvent(new CustomEvent("contour:reorder", { bubbles: true, composed: true, detail: { from, to } }));
4184
+ moved("down", index(li));
4185
+ } else if (e.key === "Home" && from > 0) {
4186
+ e.preventDefault();
4187
+ l.insertBefore(li, l.firstElementChild);
4188
+ moved("up", 0);
4189
+ } else if (e.key === "End" && from < l.children.length - 1) {
4190
+ e.preventDefault();
4191
+ l.appendChild(li);
4192
+ moved("down", l.children.length - 1);
2941
4193
  }
2942
4194
  });
2943
4195
  }
@@ -2953,6 +4205,11 @@ class ContourSwatch extends ContourBase {
2953
4205
  static get properties() { return { color: { attribute: "color" }, selected: { attribute: "selected", type: Boolean }, label: { attribute: "label" } }; }
2954
4206
  render() {
2955
4207
  this.classList.add("c-swatch");
4208
+ if (!this.hasAttribute("role")) this.setAttribute("role", "button");
4209
+ // role=button on a span is not focusable by itself. Without a tab stop the
4210
+ // swatch is mouse-only; a keyboard user cannot reach the picker at all.
4211
+ if (this.getAttribute("role") === "button" && !this.hasAttribute("tabindex")) this.setAttribute("tabindex", "0");
4212
+ if (!this.hasAttribute("aria-label")) this.setAttribute("aria-label", this.getAttribute("label") || this.getAttribute("color") || "Swatch");
2956
4213
  const color = this.getAttribute("color") || "#000";
2957
4214
  this.style.setProperty("--swatch-color", color);
2958
4215
  if (this.hasAttribute("selected")) this.classList.add("is-selected");
@@ -2962,10 +4219,10 @@ class ContourSwatch extends ContourBase {
2962
4219
  this.setAttribute("aria-label", label);
2963
4220
  }
2964
4221
  if (!this.querySelector("button") && !this.querySelector("span")) {
2965
- const btn = document.createElement("button");
2966
- btn.className = "c-swatch__btn";
2967
- btn.type = "button";
2968
- this.appendChild(btn);
4222
+ const span = document.createElement("span");
4223
+ span.className = "c-swatch__btn";
4224
+ span.setAttribute("aria-hidden", "true");
4225
+ this.appendChild(span);
2969
4226
  }
2970
4227
  }
2971
4228
  enhance() {
@@ -2974,119 +4231,206 @@ class ContourSwatch extends ContourBase {
2974
4231
  this.addEventListener("click", () => {
2975
4232
  this.dispatchEvent(new CustomEvent("contour:select", { bubbles: true, composed: true, detail: { value: this.getAttribute("color") } }));
2976
4233
  });
4234
+ // A role=button must answer Enter and Space as well as the pointer.
4235
+ this.addEventListener("keydown", (e) => {
4236
+ if (e.key !== "Enter" && e.key !== " ") return;
4237
+ e.preventDefault();
4238
+ this.dispatchEvent(new CustomEvent("contour:select", { bubbles: true, composed: true, detail: { value: this.getAttribute("color") } }));
4239
+ });
2977
4240
  }
2978
4241
  }
2979
4242
  define("contour-swatch", ContourSwatch);
2980
4243
 
2981
4244
  /**
2982
- * Calendar: web component wrapper.
2983
- * Attributes: `value`.
4245
+ * Calendar: a month grid with keyboard navigation and optional range
4246
+ * selection (R20 T-23). Attributes: `value` (ISO date), `month` (0-11),
4247
+ * `year`, and `range` with `start`/`end`. Dates are local ISO date strings —
4248
+ * deliberately timezone-free; a consumer who needs instants converts at its
4249
+ * own boundary. One tab stop roves the grid: arrows move by day/week and
4250
+ * cross month boundaries, PageUp/PageDown change month (Shift: year),
4251
+ * Home/End jump to the month's first/last day. Weekday columnheaders name
4252
+ * the columns. In range mode the first click sets start, the second sets
4253
+ * end (ordered), and contour:select carries { value, range: [start, end] }.
2984
4254
  */
2985
4255
  class ContourCalendar extends ContourBase {
2986
- static get observed() { return ["value"]; }
2987
- static get properties() { return { value: { attribute: "value" }, month: { attribute: "month" }, year: { attribute: "year" } }; }
4256
+ static get observed() { return ["value", "month", "year", "range", "start", "end"]; }
4257
+ static get properties() { return { value: { attribute: "value" }, month: { attribute: "month" }, year: { attribute: "year" }, range: { attribute: "range", type: Boolean }, start: { attribute: "start" }, end: { attribute: "end" } }; }
4258
+ // month="0" is January, not "unset": the old `Number(attr) || fallback`
4259
+ // made January unreachable unless the current month happened to be it.
4260
+ _attrNum(name, fallback) {
4261
+ const raw = this.getAttribute(name);
4262
+ const n = Number(raw);
4263
+ return raw !== null && Number.isFinite(n) ? n : fallback;
4264
+ }
4265
+ _ym() {
4266
+ const now = new Date();
4267
+ return { year: this._attrNum("year", now.getFullYear()), month: this._attrNum("month", now.getMonth()) };
4268
+ }
2988
4269
  render() {
2989
4270
  this.classList.add("c-calendar");
2990
4271
  const now = new Date();
2991
- const year = Number(this.getAttribute("year")) || now.getFullYear();
2992
- const month = Number(this.getAttribute("month")) || now.getMonth();
4272
+ const { year, month } = this._ym();
2993
4273
  const header = this.ensure(".c-calendar__header", () => { const el = document.createElement("div"); el.className = "c-calendar__header"; return el; });
2994
4274
  header.innerHTML = "";
2995
- const prev = document.createElement("button");
2996
- prev.type = "button"; prev.className = "c-btn c-btn--sm c-calendar__prev"; prev.textContent = "‹"; prev.setAttribute("aria-label", "Previous month");
4275
+ const navBtn = (cls, glyph, label) => {
4276
+ const b = document.createElement("button");
4277
+ b.type = "button"; b.className = "c-btn c-btn--sm " + cls; b.textContent = glyph; b.setAttribute("aria-label", label);
4278
+ return b;
4279
+ };
4280
+ const prevYear = navBtn("c-calendar__prev-year", "«", "Previous year");
4281
+ const prev = navBtn("c-calendar__prev", "‹", "Previous month");
2997
4282
  const title = document.createElement("span");
2998
4283
  title.className = "c-calendar__title";
2999
4284
  title.textContent = new Date(year, month, 1).toLocaleString(undefined, { month: "long", year: "numeric" });
3000
- const next = document.createElement("button");
3001
- next.type = "button"; next.className = "c-btn c-btn--sm c-calendar__next"; next.textContent = "›"; next.setAttribute("aria-label", "Next month");
3002
- header.appendChild(prev); header.appendChild(title); header.appendChild(next);
4285
+ const next = navBtn("c-calendar__next", "›", "Next month");
4286
+ const nextYear = navBtn("c-calendar__next-year", "»", "Next year");
4287
+ header.append(prevYear, prev, title, next, nextYear);
3003
4288
  const grid = this.ensure(".c-calendar__grid", () => { const el = document.createElement("div"); el.className = "c-calendar__grid"; el.setAttribute("role", "grid"); return el; });
3004
4289
  grid.setAttribute("aria-label", title.textContent);
3005
4290
  grid.innerHTML = "";
3006
4291
  const first = new Date(year, month, 1);
3007
4292
  const startDay = first.getDay();
3008
4293
  const daysInMonth = new Date(year, month + 1, 0).getDate();
4294
+ const isRange = this.hasAttribute("range");
3009
4295
  const selected = this.getAttribute("value");
4296
+ const rStart = this.getAttribute("start");
4297
+ const rEnd = this.getAttribute("end");
4298
+ let row = null;
4299
+ let col = 0;
4300
+ const newRow = () => { row = document.createElement("div"); row.className = "c-calendar__row"; row.setAttribute("role", "row"); grid.appendChild(row); col = 0; };
4301
+ // Weekday columnheaders: the grid's columns had no names.
4302
+ const wdFmt = new Intl.DateTimeFormat(undefined, { weekday: "short" });
4303
+ newRow();
4304
+ for (let i = 0; i < 7; i++) {
4305
+ const wd = document.createElement("div");
4306
+ wd.className = "c-calendar__weekday";
4307
+ wd.setAttribute("role", "columnheader");
4308
+ wd.textContent = wdFmt.format(new Date(2023, 0, 1 + i)); // 2023-01-01 was a Sunday
4309
+ row.appendChild(wd);
4310
+ }
4311
+ newRow();
3010
4312
  for (let i = 0; i < startDay; i++) {
3011
4313
  const empty = document.createElement("div");
3012
4314
  empty.className = "c-calendar__day c-calendar__day--empty";
3013
- grid.appendChild(empty);
4315
+ row.appendChild(empty);
4316
+ col++;
4317
+ if (col === 7) newRow();
3014
4318
  }
4319
+ const todayIso = now.getFullYear() + "-" + String(now.getMonth() + 1).padStart(2, "0") + "-" + String(now.getDate()).padStart(2, "0");
4320
+ // One tab stop: the selected day, else today, else the first of the month.
4321
+ const focusIso = (selected && selected.startsWith(year + "-" + String(month + 1).padStart(2, "0"))) ? selected
4322
+ : (todayIso.startsWith(year + "-" + String(month + 1).padStart(2, "0")) ? todayIso : year + "-" + String(month + 1).padStart(2, "0") + "-01");
3015
4323
  for (let d = 1; d <= daysInMonth; d++) {
3016
4324
  const cell = document.createElement("button");
3017
4325
  cell.className = "c-calendar__day";
3018
4326
  cell.type = "button";
3019
4327
  cell.setAttribute("role", "gridcell");
3020
- cell.setAttribute("tabindex", "0");
3021
4328
  cell.textContent = String(d);
3022
4329
  const iso = year + "-" + String(month + 1).padStart(2, "0") + "-" + String(d).padStart(2, "0");
3023
- if (iso === selected) { cell.classList.add("is-selected"); cell.setAttribute("aria-selected", "true"); }
3024
- else cell.setAttribute("aria-selected", "false");
3025
- const todayIso = now.getFullYear() + "-" + String(now.getMonth() + 1).padStart(2, "0") + "-" + String(now.getDate()).padStart(2, "0");
4330
+ const isSelected = isRange ? (iso === rStart || iso === rEnd) : iso === selected;
4331
+ if (isSelected) cell.classList.add("is-selected");
4332
+ if (isRange && rStart && rEnd && iso > rStart && iso < rEnd) cell.classList.add("is-in-range");
4333
+ cell.setAttribute("aria-selected", String(isSelected));
3026
4334
  if (iso === todayIso) cell.setAttribute("aria-current", "date");
4335
+ cell.setAttribute("tabindex", iso === focusIso ? "0" : "-1");
3027
4336
  cell.dataset.value = iso;
3028
- grid.appendChild(cell);
4337
+ row.appendChild(cell);
4338
+ col++;
4339
+ if (col === 7) newRow();
3029
4340
  }
3030
4341
  if (header.parentNode !== this) this.insertBefore(header, grid);
3031
4342
  }
3032
4343
  enhance() {
3033
4344
  if (this._wiredCalendar) return;
3034
4345
  this._wiredCalendar = true;
3035
- this.addEventListener("click", (e) => {
3036
- const prev = e.target && e.target.closest ? e.target.closest(".c-calendar__prev") : null;
3037
- const next = e.target && e.target.closest ? e.target.closest(".c-calendar__next") : null;
3038
- if (prev && this.contains(prev)) {
3039
- let m = Number(this.getAttribute("month")) || new Date().getMonth();
3040
- let y = Number(this.getAttribute("year")) || new Date().getFullYear();
3041
- m -= 1;
3042
- if (m < 0) { m = 11; y -= 1; }
3043
- this.setAttribute("month", String(m));
3044
- this.setAttribute("year", String(y));
3045
- this.render();
3046
- this.dispatchEvent(new CustomEvent("contour:change", { bubbles: true, composed: true, detail: { month: m, year: y } }));
3047
- return;
3048
- }
3049
- if (next && this.contains(next)) {
3050
- let m = Number(this.getAttribute("month")) || new Date().getMonth();
3051
- let y = Number(this.getAttribute("year")) || new Date().getFullYear();
3052
- m += 1;
3053
- if (m > 11) { m = 0; y += 1; }
4346
+ const navigate = (m, y) => {
4347
+ this.batch(() => {
3054
4348
  this.setAttribute("month", String(m));
3055
4349
  this.setAttribute("year", String(y));
3056
- this.render();
3057
- this.dispatchEvent(new CustomEvent("contour:change", { bubbles: true, composed: true, detail: { month: m, year: y } }));
3058
- return;
3059
- }
3060
- const cell = e.target && e.target.closest ? e.target.closest(".c-calendar__day") : null;
4350
+ });
4351
+ this.dispatchEvent(new CustomEvent("contour:change", { bubbles: true, composed: true, detail: { month: m, year: y } }));
4352
+ };
4353
+ const focusIso = (iso) => {
4354
+ const cell = this.querySelector('.c-calendar__day[data-value="' + iso + '"]');
4355
+ if (cell) { try { cell.focus(); } catch (err) {} }
4356
+ };
4357
+ // Roving tab stop follows focus wherever it lands (click or keyboard).
4358
+ this.addEventListener("focusin", (e) => {
4359
+ const cell = e.target && e.target.closest ? e.target.closest(".c-calendar__day:not(.c-calendar__day--empty)") : null;
4360
+ if (!cell || !this.contains(cell)) return;
4361
+ for (const c of this.querySelectorAll(".c-calendar__day")) c.tabIndex = -1;
4362
+ cell.tabIndex = 0;
4363
+ });
4364
+ this.addEventListener("click", (e) => {
4365
+ const t = e.target && e.target.closest ? e.target : null;
4366
+ if (!t) return;
4367
+ const { year, month } = this._ym();
4368
+ if (t.closest(".c-calendar__prev")) { const d = new Date(year, month - 1, 1); navigate(d.getMonth(), d.getFullYear()); return; }
4369
+ if (t.closest(".c-calendar__next")) { const d = new Date(year, month + 1, 1); navigate(d.getMonth(), d.getFullYear()); return; }
4370
+ if (t.closest(".c-calendar__prev-year")) { navigate(month, year - 1); return; }
4371
+ if (t.closest(".c-calendar__next-year")) { navigate(month, year + 1); return; }
4372
+ const cell = t.closest(".c-calendar__day");
3061
4373
  if (cell && this.contains(cell) && cell.dataset.value) {
3062
- this.setAttribute("value", cell.dataset.value);
3063
- this.dispatchEvent(new CustomEvent("contour:select", { bubbles: true, composed: true, detail: { value: cell.dataset.value } }));
4374
+ const iso = cell.dataset.value;
4375
+ if (this.hasAttribute("range")) {
4376
+ const start = this.getAttribute("start");
4377
+ const end = this.getAttribute("end");
4378
+ let s, en;
4379
+ if (!start || (start && end)) { s = iso; en = null; }
4380
+ else { s = iso < start ? iso : start; en = iso < start ? start : iso; }
4381
+ this.batch(() => {
4382
+ this.setAttribute("start", s);
4383
+ if (en === null) this.removeAttribute("end"); else this.setAttribute("end", en);
4384
+ });
4385
+ this.dispatchEvent(new CustomEvent("contour:select", { bubbles: true, composed: true, detail: { value: iso, range: en ? [s, en] : [s] } }));
4386
+ } else {
4387
+ this.setAttribute("value", iso);
4388
+ this.dispatchEvent(new CustomEvent("contour:select", { bubbles: true, composed: true, detail: { value: iso } }));
4389
+ }
3064
4390
  }
3065
4391
  });
3066
4392
  this.addEventListener("keydown", (e) => {
3067
- const cell = e.target && e.target.closest ? e.target.closest(".c-calendar__day") : null;
3068
- if (!cell || !this.contains(cell)) return;
3069
- const cells = Array.from(this.querySelectorAll(".c-calendar__day:not(.c-calendar__day--empty)"));
3070
- const idx = cells.indexOf(cell);
3071
- let next = null;
3072
- if (e.key === "ArrowRight") next = cells[idx + 1];
3073
- else if (e.key === "ArrowLeft") next = cells[idx - 1];
3074
- else if (e.key === "ArrowDown") next = cells[idx + 7];
3075
- else if (e.key === "ArrowUp") next = cells[idx - 7];
3076
- else if (e.key === "Enter" || e.key === " ") { e.preventDefault(); cell.click(); return; }
3077
- if (next) { e.preventDefault(); try { next.focus(); } catch (err) {} }
4393
+ const cell = e.target && e.target.closest ? e.target.closest(".c-calendar__day:not(.c-calendar__day--empty)") : null;
4394
+ if (!cell || !this.contains(cell) || !cell.dataset.value) return;
4395
+ const [y, m, d] = cell.dataset.value.split("-").map(Number);
4396
+ const cur = new Date(y, m - 1, d);
4397
+ const { year, month } = this._ym();
4398
+ const daysInMonth = new Date(year, month + 1, 0).getDate();
4399
+ const isoOf = (dt) => dt.getFullYear() + "-" + String(dt.getMonth() + 1).padStart(2, "0") + "-" + String(dt.getDate()).padStart(2, "0");
4400
+ let target = null;
4401
+ if (e.key === "ArrowRight") target = new Date(y, m - 1, d + 1);
4402
+ else if (e.key === "ArrowLeft") target = new Date(y, m - 1, d - 1);
4403
+ else if (e.key === "ArrowDown") target = new Date(y, m - 1, d + 7);
4404
+ else if (e.key === "ArrowUp") target = new Date(y, m - 1, d - 7);
4405
+ else if (e.key === "PageUp") target = e.shiftKey ? new Date(y - 1, m - 1, Math.min(d, new Date(y - 1, m, 0).getDate())) : new Date(y, m - 2, Math.min(d, new Date(y, m - 1, 0).getDate()));
4406
+ else if (e.key === "PageDown") target = e.shiftKey ? new Date(y + 1, m - 1, Math.min(d, new Date(y + 1, m, 0).getDate())) : new Date(y, m, Math.min(d, new Date(y, m + 1, 0).getDate()));
4407
+ else if (e.key === "Home") target = new Date(year, month, 1);
4408
+ else if (e.key === "End") target = new Date(year, month, daysInMonth);
4409
+ else return; // Enter/Space are the native button's own click
4410
+ e.preventDefault();
4411
+ const iso = isoOf(target);
4412
+ if (target.getFullYear() === year && target.getMonth() === month) {
4413
+ focusIso(iso);
4414
+ } else {
4415
+ // Cross the month boundary, then land on the target day.
4416
+ navigate(target.getMonth(), target.getFullYear());
4417
+ focusIso(iso);
4418
+ }
3078
4419
  });
3079
4420
  }
3080
4421
  }
3081
4422
  define("contour-calendar", ContourCalendar);
3082
4423
 
3083
4424
  /**
3084
- * Carousel: web component wrapper.
3085
- * Attributes: `items`, `index`.
4425
+ * Carousel: slides with prev/next, dots, swipe and arrow keys. Attributes:
4426
+ * `items`, `index`, `autoplay` (milliseconds per slide) and `paused`.
4427
+ * Autoplay ships with a pause/play control and never starts under
4428
+ * prefers-reduced-motion (WCAG 2.2.2, R20 T-24); the timer reconciles with
4429
+ * the attributes on every render and dies with the host.
3086
4430
  */
3087
4431
  class ContourCarousel extends ContourBase {
3088
- static get observed() { return ["items", "index"]; }
3089
- static get properties() { return { items: { attribute: "items" }, index: { attribute: "index" } }; }
4432
+ static get observed() { return ["items", "index", "autoplay", "paused"]; }
4433
+ static get properties() { return { items: { attribute: "items" }, index: { attribute: "index" }, autoplay: { attribute: "autoplay" }, paused: { attribute: "paused", type: Boolean } }; }
3090
4434
  _items() {
3091
4435
  const items = this.getAttribute("items");
3092
4436
  let parsed = [];
@@ -3122,10 +4466,59 @@ class ContourCarousel extends ContourBase {
3122
4466
  const next = this.ensure(".c-carousel__next", () => { const el = document.createElement("button"); el.className = "c-btn c-btn--sm c-carousel__next"; el.type = "button"; el.textContent = "›"; el.setAttribute("aria-label", "Next slide"); return el; });
3123
4467
  const status = this.ensure(".c-carousel__status", () => { const el = document.createElement("span"); el.className = "c-carousel__status"; el.setAttribute("aria-live", "polite"); return el; });
3124
4468
  status.textContent = (idx + 1) + " of " + items.length;
4469
+ // Indicators: one dot per slide, so a reader can jump directly and see
4470
+ // where they are without reading the status text.
4471
+ const dots = this.ensure(".c-carousel__dots", () => { const el = document.createElement("div"); el.className = "c-carousel__dots"; el.setAttribute("role", "tablist"); el.setAttribute("aria-label", "Slides"); return el; });
4472
+ dots.innerHTML = "";
4473
+ items.forEach((it, i) => {
4474
+ const dot = document.createElement("button");
4475
+ dot.type = "button";
4476
+ dot.className = "c-carousel__dot" + (i === idx ? " is-active" : "");
4477
+ dot.setAttribute("role", "tab");
4478
+ dot.setAttribute("aria-label", "Go to slide " + (i + 1));
4479
+ dot.setAttribute("aria-selected", i === idx ? "true" : "false");
4480
+ dot.dataset.index = String(i);
4481
+ dots.appendChild(dot);
4482
+ });
4483
+ // Autoplay ships with its own pause control (WCAG 2.2.2): moving
4484
+ // content that starts automatically must be pausable by a control on
4485
+ // the page, and this one is on the component itself.
4486
+ const autoplay = Number(this.getAttribute("autoplay"));
4487
+ if (Number.isFinite(autoplay) && autoplay > 0) {
4488
+ const paused = this.hasAttribute("paused") || this._reducedMotion();
4489
+ const pp = this.ensure(".c-carousel__pause", () => { const el = document.createElement("button"); el.className = "c-btn c-btn--sm c-carousel__pause"; el.type = "button"; return el; });
4490
+ pp.textContent = paused ? "▶" : "⏸";
4491
+ pp.setAttribute("aria-label", paused ? "Play slides automatically" : "Pause automatic slides");
4492
+ pp.setAttribute("aria-pressed", String(paused));
4493
+ } else {
4494
+ const pp = this.querySelector(".c-carousel__pause");
4495
+ if (pp) pp.remove();
4496
+ }
4497
+ }
4498
+ _reducedMotion() {
4499
+ try { return typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches; } catch (e) { return false; }
3125
4500
  }
3126
4501
  enhance() {
4502
+ // Autoplay reconciles with the attributes on every render: `paused`,
4503
+ // a removed `autoplay`, or reduced motion stops the timer; the next
4504
+ // render under the right conditions starts it again.
4505
+ const autoplay = Number(this.getAttribute("autoplay"));
4506
+ const want = Number.isFinite(autoplay) && autoplay > 0 && !this.hasAttribute("paused") && !this._reducedMotion() && this._items().length > 1;
4507
+ if (want && !this._carouselTimer) {
4508
+ this._carouselTimer = setInterval(() => {
4509
+ const items = this._items();
4510
+ if (!items.length) return;
4511
+ const idx = (this._index() + 1) % items.length;
4512
+ this.setAttribute("index", String(idx));
4513
+ this.dispatchEvent(new CustomEvent("contour:change", { bubbles: true, composed: true, detail: { index: idx, direction: "next" } }));
4514
+ }, Math.max(500, autoplay));
4515
+ } else if (!want && this._carouselTimer) {
4516
+ clearInterval(this._carouselTimer);
4517
+ this._carouselTimer = null;
4518
+ }
3127
4519
  if (this._wiredCarousel) return;
3128
4520
  this._wiredCarousel = true;
4521
+ onDispose(this, () => { if (this._carouselTimer) { clearInterval(this._carouselTimer); this._carouselTimer = null; } });
3129
4522
  const go = (dir) => {
3130
4523
  const items = this._items();
3131
4524
  if (!items.length) return;
@@ -3136,16 +4529,47 @@ class ContourCarousel extends ContourBase {
3136
4529
  this.dispatchEvent(new CustomEvent("contour:change", { bubbles: true, composed: true, detail: { index: idx, direction: dir } }));
3137
4530
  };
3138
4531
  this.addEventListener("click", (e) => {
4532
+ const pp = e.target && e.target.closest ? e.target.closest(".c-carousel__pause") : null;
4533
+ if (pp && this.contains(pp)) {
4534
+ // Reduced motion keeps the carousel static; the control cannot
4535
+ // start motion the reader asked not to see.
4536
+ if (this._reducedMotion()) return;
4537
+ const nowPaused = !this.hasAttribute("paused");
4538
+ this.toggleAttribute("paused", nowPaused);
4539
+ this.dispatchEvent(new CustomEvent(nowPaused ? "contour:pause" : "contour:play", { bubbles: true, composed: true }));
4540
+ return;
4541
+ }
3139
4542
  const prev = e.target && e.target.closest ? e.target.closest(".c-carousel__prev") : null;
3140
4543
  const next = e.target && e.target.closest ? e.target.closest(".c-carousel__next") : null;
3141
- if (prev && this.contains(prev)) go("prev");
3142
- if (next && this.contains(next)) go("next");
4544
+ if (prev && this.contains(prev)) { go("prev"); return; }
4545
+ if (next && this.contains(next)) { go("next"); return; }
4546
+ const dot = e.target && e.target.closest ? e.target.closest(".c-carousel__dot") : null;
4547
+ if (dot && this.contains(dot)) {
4548
+ const i = Number(dot.dataset.index);
4549
+ if (Number.isFinite(i) && i !== this._index()) {
4550
+ this.setAttribute("index", String(i));
4551
+ this.dispatchEvent(new CustomEvent("contour:change", { bubbles: true, composed: true, detail: { index: i, direction: "jump" } }));
4552
+ }
4553
+ }
4554
+ });
4555
+ // Swipe: a horizontal drag past the threshold advances one slide.
4556
+ let startX = null;
4557
+ this.addEventListener("pointerdown", (e) => { startX = e.clientX; });
4558
+ this.addEventListener("pointerup", (e) => {
4559
+ if (startX === null) return;
4560
+ const dx = e.clientX - startX;
4561
+ startX = null;
4562
+ if (Math.abs(dx) > 40) { if (dx < 0) go("next"); else go("prev"); }
3143
4563
  });
4564
+ this.addEventListener("pointercancel", () => { startX = null; });
3144
4565
  this.addEventListener("keydown", (e) => {
3145
4566
  if (e.key === "ArrowLeft") { e.preventDefault(); go("prev"); }
3146
4567
  else if (e.key === "ArrowRight") { e.preventDefault(); go("next"); }
3147
- else if (e.key === "Home") { e.preventDefault(); this.setAttribute("index", "0"); this.render(); this.dispatchEvent(new CustomEvent("contour:change", { bubbles: true, composed: true, detail: { index: 0, direction: "home" } })); }
3148
- else if (e.key === "End") { e.preventDefault(); const last = this._items().length - 1; if (last >= 0) { this.setAttribute("index", String(last)); this.render(); this.dispatchEvent(new CustomEvent("contour:change", { bubbles: true, composed: true, detail: { index: last, direction: "end" } })); } }
4568
+ // index is observed: the attribute write re-renders through the base
4569
+ // lifecycle (snapshot/restore/focus). The old direct this.render()
4570
+ // bypassed it and dropped focus.
4571
+ else if (e.key === "Home") { e.preventDefault(); this.setAttribute("index", "0"); this.dispatchEvent(new CustomEvent("contour:change", { bubbles: true, composed: true, detail: { index: 0, direction: "home" } })); }
4572
+ else if (e.key === "End") { e.preventDefault(); const last = this._items().length - 1; if (last >= 0) { this.setAttribute("index", String(last)); this.dispatchEvent(new CustomEvent("contour:change", { bubbles: true, composed: true, detail: { index: last, direction: "end" } })); } }
3149
4573
  });
3150
4574
  }
3151
4575
  }
@@ -3157,8 +4581,8 @@ class ContourCarousel extends ContourBase {
3157
4581
  */
3158
4582
  class ContourDataGrid extends ContourBase {
3159
4583
  static get updateMode() { return "keyed"; }
3160
- static get observed() { return ["columns", "rows", "page", "filter", "page-size", "resizable", "virtual", "row-height"]; }
3161
- static get properties() { return { columns: { attribute: "columns" }, rows: { attribute: "rows" }, page: { attribute: "page" }, filter: { attribute: "filter" }, "page-size": { attribute: "page-size" }, resizable: { attribute: "resizable", type: Boolean }, virtual: { attribute: "virtual", type: Boolean }, "row-height": { attribute: "row-height" } }; }
4584
+ static get observed() { return ["columns", "rows", "page", "filter", "page-size", "resizable", "virtual", "row-height", "loading", "error", "empty"]; }
4585
+ static get properties() { return { columns: { attribute: "columns" }, rows: { attribute: "rows" }, page: { attribute: "page" }, filter: { attribute: "filter" }, "page-size": { attribute: "page-size" }, resizable: { attribute: "resizable", type: Boolean }, virtual: { attribute: "virtual", type: Boolean }, "row-height": { attribute: "row-height" }, loading: { attribute: "loading" }, error: { attribute: "error" }, empty: { attribute: "empty" } }; }
3162
4586
  render() {
3163
4587
  this.classList.add("c-data-grid");
3164
4588
  if (this.hasAttribute("loading") || this.hasAttribute("error") || this.hasAttribute("empty")) {
@@ -3178,7 +4602,7 @@ class ContourDataGrid extends ContourBase {
3178
4602
  tbody.appendChild(tr);
3179
4603
  // Wrap in a scroll container for virtualization of large datasets.
3180
4604
  let wrap = this.querySelector(".c-data-grid__wrap");
3181
- if (!wrap) { wrap = document.createElement("div"); wrap.className = "c-data-grid__wrap"; wrap.style.maxHeight = "400px"; wrap.style.overflow = "auto"; }
4605
+ if (!wrap) { wrap = document.createElement("div"); wrap.className = "c-table-wrap c-data-grid__wrap"; }
3182
4606
  if (table.parentNode !== wrap) wrap.appendChild(table);
3183
4607
  if (wrap.parentNode !== this) this.appendChild(wrap);
3184
4608
  return;
@@ -3239,7 +4663,7 @@ class ContourDataGrid extends ContourBase {
3239
4663
  const key = typeof c === "string" ? c : (c.key || c.label || "");
3240
4664
  const td = document.createElement("td");
3241
4665
  td.setAttribute("role", "gridcell");
3242
- td.setAttribute("tabindex", "0");
4666
+ td.setAttribute("tabindex", "-1");
3243
4667
  td.textContent = r && r[key] != null ? r[key] : "";
3244
4668
  if (!String(td.textContent).trim()) td.setAttribute("aria-label", "Empty");
3245
4669
  tr.appendChild(td);
@@ -3249,13 +4673,21 @@ class ContourDataGrid extends ContourBase {
3249
4673
  }
3250
4674
  // Wrap in a scroll container for virtualization of large datasets.
3251
4675
  let wrap = this.querySelector(".c-data-grid__wrap");
3252
- if (!wrap) { wrap = document.createElement("div"); wrap.className = "c-data-grid__wrap"; wrap.style.maxHeight = "400px"; wrap.style.overflow = "auto"; }
4676
+ if (!wrap) { wrap = document.createElement("div"); wrap.className = "c-table-wrap c-data-grid__wrap"; }
3253
4677
  if (table.parentNode !== wrap) wrap.appendChild(table);
3254
4678
  if (wrap.parentNode !== this) this.appendChild(wrap);
4679
+ // One tab stop per grid: cells are -1 and the arrow keys move a roving
4680
+ // tabindex, so a 1,000-row grid is not 1,000 tab stops.
4681
+ if (!table.querySelector('[tabindex="0"]')) {
4682
+ const first = table.querySelector("tbody td, thead th");
4683
+ if (first) first.setAttribute("tabindex", "0");
4684
+ }
3255
4685
  }
3256
4686
  _rowHeight() {
3257
4687
  const h = Number(this.getAttribute("row-height"));
3258
- return Number.isFinite(h) && h > 0 ? h : 32;
4688
+ if (Number.isFinite(h) && h > 0) return h;
4689
+ if (this._measuredRowHeight > 0) return this._measuredRowHeight;
4690
+ return cssLength("--data-grid-row-height", 32);
3259
4691
  }
3260
4692
  _renderDataGridWindow(scrollTop) {
3261
4693
  const table = this.querySelector(".c-data-grid__table");
@@ -3289,7 +4721,7 @@ class ContourDataGrid extends ContourBase {
3289
4721
  const key = typeof c === "string" ? c : (c.key || c.label || "");
3290
4722
  const td = document.createElement("td");
3291
4723
  td.setAttribute("role", "gridcell");
3292
- td.setAttribute("tabindex", "0");
4724
+ td.setAttribute("tabindex", "-1");
3293
4725
  td.textContent = r && r[key] != null ? r[key] : "";
3294
4726
  if (!String(td.textContent).trim()) td.setAttribute("aria-label", "Empty");
3295
4727
  tr.appendChild(td);
@@ -3305,6 +4737,12 @@ class ContourDataGrid extends ContourBase {
3305
4737
  sp.appendChild(td);
3306
4738
  tbody.appendChild(sp);
3307
4739
  }
4740
+ // The window re-renders rows, so the single tab stop has to be re-seeded
4741
+ // here too, or a scroll would leave the grid with no tabbable cell.
4742
+ if (!tbody.querySelector('[tabindex="0"]')) {
4743
+ const first = tbody.querySelector("tr[data-index] td");
4744
+ if (first) first.setAttribute("tabindex", "0");
4745
+ }
3308
4746
  }
3309
4747
  enhance() {
3310
4748
  if (this._wiredDataGrid) return;
@@ -3334,7 +4772,13 @@ class ContourDataGrid extends ContourBase {
3334
4772
  else if (e.key === "ArrowLeft") target = row.children[ci - 1];
3335
4773
  else if (e.key === "ArrowDown") target = rows[ri + 1] && rows[ri + 1].children[ci];
3336
4774
  else if (e.key === "ArrowUp") target = rows[ri - 1] && rows[ri - 1].children[ci];
3337
- if (target) { e.preventDefault(); try { target.focus(); } catch (err) {} }
4775
+ if (target) {
4776
+ e.preventDefault();
4777
+ // Move the single tab stop with the focus.
4778
+ table.querySelectorAll('[tabindex="0"]').forEach((c) => c.setAttribute("tabindex", "-1"));
4779
+ target.setAttribute("tabindex", "0");
4780
+ try { target.focus(); } catch (err) {}
4781
+ }
3338
4782
  });
3339
4783
  this.addEventListener("click", (e) => {
3340
4784
  const tr = e.target && e.target.closest ? e.target.closest("tr") : null;
@@ -3347,28 +4791,43 @@ class ContourDataGrid extends ContourBase {
3347
4791
  const idx = Array.from(th.parentElement.children).indexOf(th);
3348
4792
  if (sortCol === idx) sortDir = sortDir === "asc" ? "desc" : "asc";
3349
4793
  else { sortCol = idx; sortDir = "asc"; }
3350
- // Re-render sorted rows.
4794
+ // Sort the full filtered dataset, not just the rendered page: a page
4795
+ // slice sorted on its own leaves the other pages in the wrong order.
3351
4796
  const table = this.querySelector(".c-data-grid__table");
3352
4797
  const tbody = table && table.querySelector("tbody");
3353
4798
  const thead = table && table.querySelector("thead");
3354
- if (tbody && thead) {
3355
- const cols = Array.from(thead.querySelectorAll("th")).map((h) => h.textContent);
3356
- const rows = Array.from(tbody.querySelectorAll("tr")).map((tr) => Array.from(tr.querySelectorAll("td")).map((td) => td.textContent));
3357
- rows.sort((a, b) => {
3358
- const va = a[idx] || "", vb = b[idx] || "";
3359
- const na = Number(va), nb = Number(vb);
3360
- const cmp = (!isNaN(na) && !isNaN(nb)) ? na - nb : String(va).localeCompare(String(vb));
3361
- return sortDir === "asc" ? cmp : -cmp;
3362
- });
4799
+ const cols = this._dgCols || [];
4800
+ const key = cols[idx] ? (typeof cols[idx] === "string" ? cols[idx] : (cols[idx].key || cols[idx].label || "")) : String(idx);
4801
+ const full = (this._dgFilteredRows || []).slice();
4802
+ full.sort((a, b) => {
4803
+ const va = a && a[key] != null ? a[key] : "";
4804
+ const vb = b && b[key] != null ? b[key] : "";
4805
+ const na = Number(va), nb = Number(vb);
4806
+ const cmp = (!isNaN(na) && !isNaN(nb)) ? na - nb : String(va).localeCompare(String(vb));
4807
+ return sortDir === "asc" ? cmp : -cmp;
4808
+ });
4809
+ this._dgFilteredRows = full;
4810
+ if (tbody) {
4811
+ const page = Number(this.getAttribute("page") || 1);
4812
+ const pageSize = Number(this.getAttribute("page-size") || 0);
4813
+ let pageRows = full;
4814
+ if (pageSize > 0) { const start = (page - 1) * pageSize; pageRows = full.slice(start, start + pageSize); }
3363
4815
  tbody.innerHTML = "";
3364
- rows.forEach((r) => {
4816
+ pageRows.forEach((r) => {
3365
4817
  const tr = document.createElement("tr");
3366
- r.forEach((v) => { const td = document.createElement("td"); td.textContent = v; tr.appendChild(td); });
4818
+ cols.forEach((c) => {
4819
+ const k = typeof c === "string" ? c : (c.key || c.label || "");
4820
+ const td = document.createElement("td");
4821
+ td.setAttribute("role", "gridcell");
4822
+ td.setAttribute("tabindex", "-1");
4823
+ td.textContent = r && r[k] != null ? r[k] : "";
4824
+ tr.appendChild(td);
4825
+ });
3367
4826
  tbody.appendChild(tr);
3368
4827
  });
3369
4828
  }
3370
4829
  // Update aria-sort on headers.
3371
- Array.from(thead.querySelectorAll("th")).forEach((h, i) => {
4830
+ if (thead) Array.from(thead.querySelectorAll("th")).forEach((h, i) => {
3372
4831
  h.setAttribute("aria-sort", i === idx ? (sortDir === "asc" ? "ascending" : "descending") : "none");
3373
4832
  });
3374
4833
  this.dispatchEvent(new CustomEvent("contour:sort", { bubbles: true, composed: true, detail: { column: idx, direction: sortDir } }));
@@ -3402,8 +4861,8 @@ class ContourDataGrid extends ContourBase {
3402
4861
  */
3403
4862
  class ContourTreeGrid extends ContourBase {
3404
4863
  static get updateMode() { return "keyed"; }
3405
- static get observed() { return ["items", "expanded"]; }
3406
- static get properties() { return { items: { attribute: "items" }, expanded: { attribute: "expanded" } }; }
4864
+ static get observed() { return ["items", "expanded", "loading", "error", "empty"]; }
4865
+ static get properties() { return { items: { attribute: "items" }, expanded: { attribute: "expanded" }, loading: { attribute: "loading" }, error: { attribute: "error" }, empty: { attribute: "empty" } }; }
3407
4866
  _expandedSet() {
3408
4867
  const raw = this.getAttribute("expanded");
3409
4868
  if (!raw) return new Set();
@@ -3455,7 +4914,12 @@ class ContourTreeGrid extends ContourBase {
3455
4914
  }
3456
4915
  };
3457
4916
  parsed.forEach((n, i) => renderNode(n, 0, String(i)));
3458
- if (table.parentNode !== this) this.appendChild(table);
4917
+ // Wrap the table in the same scroller the reflow gate requires, so a
4918
+ // tree grid is not a bare .c-table that stretches the page.
4919
+ let wrap = this.querySelector(".c-tree-grid__wrap");
4920
+ if (!wrap) { wrap = document.createElement("div"); wrap.className = "c-table-wrap c-tree-grid__wrap"; }
4921
+ if (table.parentNode !== wrap) wrap.appendChild(table);
4922
+ if (wrap.parentNode !== this) this.appendChild(wrap);
3459
4923
  }
3460
4924
  enhance() {
3461
4925
  if (this._wiredTreeGrid) return;
@@ -3515,46 +4979,94 @@ class ContourPullToRefresh extends ContourBase {
3515
4979
  static get properties() { return { threshold: { attribute: "threshold" } }; }
3516
4980
  render() {
3517
4981
  this.classList.add("c-pull-to-refresh");
4982
+ if (!this.hasAttribute("role")) this.setAttribute("role", "region");
4983
+ if (!this.hasAttribute("aria-label")) this.setAttribute("aria-label", labelText(this, "label", "Pull to refresh"));
3518
4984
  const ind = this.ensure(".c-pull-to-refresh__indicator", () => {
3519
4985
  const e = document.createElement("div");
3520
4986
  e.className = "c-pull-to-refresh__indicator";
3521
- e.textContent = "Pull to refresh";
3522
4987
  return e;
3523
4988
  });
4989
+ ind.innerHTML = "";
4990
+ const label = document.createElement("span");
4991
+ label.className = "c-pull-to-refresh__label";
4992
+ label.setAttribute("aria-live", "polite");
4993
+ label.textContent = this._ptrError
4994
+ ? this._ptrError
4995
+ : (this._ptrRefreshing ? labelText(this, "refreshing", "Refreshing…") : labelText(this, "label", "Pull to refresh"));
4996
+ ind.appendChild(label);
4997
+ // A keyboard-reachable refresh alternative: the gesture is pointer-only,
4998
+ // and a control the reader can press must exist anyway (R20 T-25).
4999
+ const btn = document.createElement("button");
5000
+ btn.type = "button";
5001
+ btn.className = "c-pull-to-refresh__btn";
5002
+ btn.textContent = labelText(this, "refresh", "Refresh");
5003
+ ind.appendChild(btn);
3524
5004
  if (ind.parentNode !== this) this.prepend(ind);
5005
+ this.classList.toggle("is-refreshing", !!this._ptrRefreshing);
5006
+ this.classList.toggle("has-error", !!this._ptrError);
5007
+ this.setAttribute("aria-busy", String(!!this._ptrRefreshing));
5008
+ }
5009
+ // Completion is consumer-driven (R20 T-25): the old fixed 800 ms timeout
5010
+ // faked it. The consumer calls complete() when its fetch settles, or
5011
+ // fail(message) to surface the error; both clear the pull offset.
5012
+ complete() {
5013
+ this._ptrRefreshing = false;
5014
+ this._ptrError = null;
5015
+ this.style.removeProperty("--ptr-offset");
5016
+ this.requestRender();
5017
+ }
5018
+ fail(message) {
5019
+ this._ptrRefreshing = false;
5020
+ this._ptrError = String(message || labelText(this, "error", "Refresh failed"));
5021
+ this.style.removeProperty("--ptr-offset");
5022
+ this.requestRender();
5023
+ this.dispatchEvent(new CustomEvent("contour:error", { bubbles: true, composed: true, detail: { message: this._ptrError } }));
5024
+ }
5025
+ _refresh() {
5026
+ if (this._ptrRefreshing) return;
5027
+ this._ptrRefreshing = true;
5028
+ this._ptrError = null;
5029
+ this.style.removeProperty("--ptr-offset");
5030
+ this.requestRender();
5031
+ this.dispatchEvent(new CustomEvent("contour:refresh", { bubbles: true, composed: true }));
3525
5032
  }
3526
5033
  enhance() {
3527
5034
  if (this._wiredPullToRefresh) return;
3528
5035
  this._wiredPullToRefresh = true;
5036
+ this.addEventListener("click", (e) => {
5037
+ const btn = e.target && e.target.closest ? e.target.closest(".c-pull-to-refresh__btn") : null;
5038
+ if (btn && this.contains(btn)) this._refresh();
5039
+ });
5040
+ // Pointer events cover touch AND mouse; the gesture had been touch-only.
3529
5041
  let startY = 0;
3530
5042
  let pulling = false;
3531
- this.addEventListener("touchstart", (e) => {
3532
- if (this.scrollTop > 0) return;
3533
- const t = e.touches && e.touches[0];
3534
- if (t) { startY = t.clientY; pulling = true; }
3535
- }, { passive: true });
3536
- this.addEventListener("touchmove", (e) => {
5043
+ let offset = 0;
5044
+ this.addEventListener("pointerdown", (e) => {
5045
+ if (this._ptrRefreshing || this.scrollTop > 0) return;
5046
+ if (e.target && e.target.closest && e.target.closest(".c-pull-to-refresh__btn")) return;
5047
+ startY = e.clientY;
5048
+ pulling = true;
5049
+ offset = 0;
5050
+ try { this.setPointerCapture(e.pointerId); } catch (err) {}
5051
+ });
5052
+ this.addEventListener("pointermove", (e) => {
3537
5053
  if (!pulling) return;
3538
- const t = e.touches && e.touches[0];
3539
- if (!t) return;
3540
- const dy = t.clientY - startY;
3541
- if (dy > 0 && dy < 120) {
3542
- this.style.setProperty("--ptr-offset", dy + "px");
5054
+ const dy = e.clientY - startY;
5055
+ if (dy > 0) {
5056
+ offset = Math.min(120, dy * 0.6);
5057
+ this.style.setProperty("--ptr-offset", offset + "px");
3543
5058
  }
3544
- }, { passive: true });
3545
- this.addEventListener("touchend", (e) => {
5059
+ });
5060
+ const end = () => {
3546
5061
  if (!pulling) return;
3547
5062
  pulling = false;
3548
- const t = e.changedTouches && e.changedTouches[0];
3549
- const dy = t ? t.clientY - startY : 0;
3550
5063
  const thr = Number(this.getAttribute("threshold")) || 60;
3551
- if (dy >= thr) {
3552
- this.classList.add("is-refreshing");
3553
- this.dispatchEvent(new CustomEvent("contour:refresh", { bubbles: true, composed: true }));
3554
- setTimeout(() => this.classList.remove("is-refreshing"), 800);
3555
- }
3556
- this.style.removeProperty("--ptr-offset");
3557
- }, { passive: true });
5064
+ if (offset >= thr) this._refresh();
5065
+ else this.style.removeProperty("--ptr-offset");
5066
+ offset = 0;
5067
+ };
5068
+ this.addEventListener("pointerup", end);
5069
+ this.addEventListener("pointercancel", end);
3558
5070
  }
3559
5071
  }
3560
5072
  define("contour-pull-to-refresh", ContourPullToRefresh);