contour-ds 1.7.1 → 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 +184 -107
  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 +6136 -1634
  29. package/dist/contour-wc.esm.min.js +1 -1
  30. package/dist/contour-wc.js +6135 -1634
  31. package/dist/contour-wc.min.js +1 -1
  32. package/dist/contour.code-snippets +4512 -0
  33. package/dist/contour.components.json +3321 -868
  34. package/dist/contour.css +5863 -3999
  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 +25 -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 +264 -63
  88. package/dist/wc/core.mjs +390 -71
  89. package/dist/wc/dashboard.mjs +220 -13
  90. package/dist/wc/data.mjs +1094 -458
  91. package/dist/wc/docs.mjs +105 -12
  92. package/dist/wc/feedback.mjs +63 -14
  93. package/dist/wc/forms.mjs +739 -106
  94. package/dist/wc/index.mjs +9 -2
  95. package/dist/wc/interaction.mjs +184 -28
  96. package/dist/wc/layout.mjs +97 -27
  97. package/dist/wc/map.mjs +185 -118
  98. package/dist/wc/misc.mjs +124 -24
  99. package/dist/wc/navigation.mjs +384 -114
  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 +1995 -478
  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`,
@@ -28,6 +28,8 @@ class ContourAvatar extends ContourBase {
28
28
  img.className = "c-avatar__img";
29
29
  img.src = src;
30
30
  img.alt = name || "";
31
+ img.loading = "lazy";
32
+ img.decoding = "async";
31
33
  this.appendChild(img);
32
34
  } else if (name) {
33
35
  const initials = name.split(" ").map((w) => w[0]).join("").toUpperCase().slice(0, 2);
@@ -93,11 +95,16 @@ class ContourBadgeFull extends ContourBase {
93
95
  * Attributes: `variant`, `key`, `value`.
94
96
  */
95
97
  class ContourChipFull extends ContourBase {
96
- static get observed() { return ["variant", "key", "value"]; }
97
- 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 } }; }
98
100
  render() {
99
101
  this.classList.add("c-chip");
100
- 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");
101
108
  Array.from(this.classList).forEach((c) => { if (c.startsWith("c-chip--")) this.classList.remove(c); });
102
109
  const variant = this.getAttribute("variant");
103
110
  if (variant) this.classList.add("c-chip--" + variant);
@@ -125,11 +132,15 @@ class ContourChipFull extends ContourBase {
125
132
  * `removable`, `variant`.
126
133
  */
127
134
  class ContourTag extends ContourBase {
128
- static get observed() { return ["label", "removable", "variant"]; }
129
- 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 } }; }
130
137
  render() {
131
138
  this.classList.add("c-tag");
132
- 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");
133
144
  Array.from(this.classList).forEach((c) => { if (c.startsWith("c-tag--")) this.classList.remove(c); });
134
145
  const variant = this.getAttribute("variant");
135
146
  if (variant) this.classList.add("c-tag--" + variant);
@@ -192,7 +203,11 @@ class ContourPill extends ContourBase {
192
203
  static get properties() { return { label: { attribute: "label" }, live: { attribute: "live", type: Boolean }, variant: { attribute: "variant" } }; }
193
204
  render() {
194
205
  this.classList.add("c-pill");
195
- 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");
196
211
  Array.from(this.classList).forEach((c) => { if (c.startsWith("c-pill--")) this.classList.remove(c); });
197
212
  const variant = this.getAttribute("variant");
198
213
  if (variant) this.classList.add("c-pill--" + variant);
@@ -247,9 +262,10 @@ class ContourSkeleton extends ContourBase {
247
262
  Array.from(this.classList).forEach((c) => { if (c.startsWith("c-skeleton--")) this.classList.remove(c); });
248
263
  const size = this.getAttribute("size");
249
264
  if (size) this.classList.add("c-skeleton--" + size);
250
- if (!this.hasAttribute("role")) this.setAttribute("role", "status");
251
- if (!this.hasAttribute("aria-label")) this.setAttribute("aria-label", "Loading");
252
- 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.
253
269
  if (!this.hasAttribute("aria-hidden")) this.setAttribute("aria-hidden", "true");
254
270
  const shimmer = this.getAttribute("shimmer");
255
271
  if (shimmer === "false" || shimmer === "off") this.classList.add("c-skeleton--static");
@@ -266,6 +282,7 @@ class ContourTooltip extends ContourBase {
266
282
  static get properties() { return { text: { attribute: "text" }, anchor: { attribute: "anchor" }, delay: { attribute: "delay", type: Number }, trigger: { attribute: "trigger" } }; }
267
283
  render() {
268
284
  this.classList.add("c-tooltip");
285
+ if (!this.hasAttribute("aria-label")) this.setAttribute("aria-label", "Tooltip");
269
286
  if (!this.hasAttribute("popover")) this.setAttribute("popover", "auto");
270
287
  if (!this.hasAttribute("role")) this.setAttribute("role", "tooltip");
271
288
  if (!this.id) this.id = contourId("tip");
@@ -407,29 +424,49 @@ class ContourProgress extends ContourBase {
407
424
  this.ensure(".c-progress__bar", () => { const el = document.createElement("span"); el.className = "c-progress__bar"; return el; });
408
425
  if (!this.hasAttribute("role")) this.setAttribute("role", "progressbar");
409
426
  const label = this.getAttribute("label");
410
- if (label && !this.hasAttribute("aria-label")) this.setAttribute("aria-label", label);
427
+ if (!this.hasAttribute("aria-label")) this.setAttribute("aria-label", label || "Progress");
411
428
  const min = this.getAttribute("min");
412
429
  const max = this.getAttribute("max");
430
+ const minV = min !== null ? Number(min) : 0;
431
+ const maxV = max !== null ? Number(max) : 100;
413
432
  if (min !== null) this.setAttribute("aria-valuemin", min);
414
433
  else if (!this.hasAttribute("aria-valuemin")) this.setAttribute("aria-valuemin", "0");
415
434
  if (max !== null) this.setAttribute("aria-valuemax", max);
416
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
+ }
417
441
  if (this.hasAttribute("paused")) this.classList.add("c-progress--paused");
418
442
  else Array.from(this.classList).forEach((c) => { if (c === "c-progress--paused") this.classList.remove(c); });
419
443
  if (this.hasAttribute("pausable")) {
420
- this.ensure(".c-progress__pause", () => {
421
- const btn = document.createElement("button");
422
- btn.className = "c-progress__pause";
423
- btn.type = "button";
424
- btn.setAttribute("aria-label", "Pause");
425
- btn.textContent = "⏸";
426
- 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;
427
450
  });
451
+ btn.setAttribute("aria-label", paused ? "Resume" : "Pause");
452
+ btn.textContent = paused ? "▶" : "⏸";
428
453
  } else {
429
454
  const btn = this.querySelector(".c-progress__pause");
430
455
  if (btn) btn.remove();
431
456
  }
432
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
+ }
433
470
  }
434
471
  define("contour-progress", ContourProgress);
435
472
  /**
@@ -445,11 +482,20 @@ class ContourMark extends ContourBase {
445
482
  * Loading: a spinner wrapped in a container. No attributes.
446
483
  */
447
484
  class ContourLoading extends ContourBase {
485
+ static get observed() { return ["label"]; }
486
+ static get properties() { return { label: { attribute: "label" } }; }
448
487
  render() {
449
488
  this.classList.add("c-loading");
450
489
  if (!this.hasAttribute("role")) this.setAttribute("role", "status");
451
490
  if (!this.hasAttribute("aria-live")) this.setAttribute("aria-live", "polite");
452
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);
453
499
  }
454
500
  }
455
501
  define("contour-loading", ContourLoading);
@@ -477,10 +523,14 @@ class ContourVersionBannerFull extends ContourBase {
477
523
  static get properties() { return { message: { attribute: "message" }, link: { attribute: "link" }, href: { attribute: "href" }, dismissible: { attribute: "dismissible", type: Boolean } }; }
478
524
  render() {
479
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");
480
528
  Array.from(this.children).forEach((n) => n.remove());
481
529
  const message = this.getAttribute("message");
482
530
  if (message) {
483
- 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");
484
534
  icon.setAttribute("aria-hidden", "true");
485
535
  icon.innerHTML = '<use href="#i-info" />';
486
536
  this.appendChild(icon);
@@ -493,7 +543,7 @@ class ContourVersionBannerFull extends ContourBase {
493
543
  if (link && href) {
494
544
  const a = document.createElement("a");
495
545
  a.className = "c-version-banner__link";
496
- a.href = href;
546
+ a.href = safeHref(href);
497
547
  a.textContent = link;
498
548
  this.appendChild(a);
499
549
  }
@@ -530,6 +580,7 @@ class ContourBanner extends ContourBase {
530
580
  render() {
531
581
  this.classList.add("c-banner");
532
582
  const variant = this.getAttribute("variant");
583
+ Array.from(this.classList).forEach((c) => { if (c.startsWith("c-banner--")) this.classList.remove(c); });
533
584
  if (variant) this.classList.add("c-banner--" + variant);
534
585
  const message = this.getAttribute("message");
535
586
  if (message) {
@@ -700,6 +751,9 @@ class ContourSkeletonGroup extends ContourBase {
700
751
  for (let i = 0; i < count; i++) {
701
752
  const sk = document.createElement("div");
702
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");
703
757
  this.appendChild(sk);
704
758
  }
705
759
  }
@@ -712,7 +766,7 @@ class ContourSkeletonGroup extends ContourBase {
712
766
  * `cluster-count`, `cluster-expanded`.
713
767
  */
714
768
  class ContourMapPopup extends ContourBase {
715
- 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"]; }
716
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" } }; }
717
771
  render() {
718
772
  this.classList.add("c-map-popup");
@@ -778,6 +832,46 @@ class ContourMapPopup extends ContourBase {
778
832
  this.dispatchEvent(new CustomEvent("contour:cluster-toggle", { bubbles: true, composed: true, detail: { count: Number(this.getAttribute("cluster-count")), expanded } }));
779
833
  }
780
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"); });
781
875
  }
782
876
  }
783
877
  define("contour-map-popup", ContourMapPopup);
@@ -788,8 +882,8 @@ class ContourMapPopup extends ContourBase {
788
882
  * `caption`, `show-thumb`, `show-thumb-caption`.
789
883
  */
790
884
  class ContourAnimationControls extends ContourBase {
791
- static get observed() { return ["playing", "speed", "progress", "min", "max", "caption", "show-thumb", "show-thumb-caption"]; }
792
- 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" } }; }
793
887
  render() {
794
888
  this.classList.add("c-animation-controls");
795
889
  this.setAttribute("role", "toolbar");
@@ -800,16 +894,56 @@ class ContourAnimationControls extends ContourBase {
800
894
  const speed = this.getAttribute("speed") || "1x";
801
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; });
802
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;
803
905
  // scrubber
804
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; });
805
907
  if (this.getAttribute("show-thumb") === "false") scrubber.classList.remove("c-animation-controls__scrubber--thumb");
806
908
  else scrubber.classList.add("c-animation-controls__scrubber--thumb");
807
909
  scrubber.min = this.getAttribute("min") || "0";
808
910
  scrubber.max = this.getAttribute("max") || "100";
911
+ scrubber.step = this.getAttribute("step") || "1";
809
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));
810
922
  const caption = this.getAttribute("caption");
811
923
  if (caption) scrubber.setAttribute("aria-label", caption);
812
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
+ }
813
947
  // caption display
814
948
  const showCaption = this.hasAttribute("show-thumb-caption") || this.hasAttribute("show-thumb");
815
949
  if (caption && showCaption) {
@@ -819,41 +953,71 @@ class ContourAnimationControls extends ContourBase {
819
953
  const cap = this.querySelector(".c-animation-controls__caption");
820
954
  if (cap) cap.remove();
821
955
  }
956
+ // loop indicator
957
+ if (this.hasAttribute("loop")) {
958
+ this.setAttribute("aria-label", "Animation controls, loop");
959
+ }
822
960
  // showThumb: hide thumb via attribute? keep default
823
961
  }
824
962
  enhance() {
825
963
  if (this._wiredAnimControls) return;
826
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 });
827
976
  this.addEventListener("click", (e) => {
828
977
  const play = e.target && e.target.closest ? e.target.closest(".c-animation-controls__play") : null;
829
- const speed = e.target && e.target.closest ? e.target.closest(".c-animation-controls__speed") : null;
830
978
  if (play && this.contains(play)) {
831
- 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;
832
985
  }
986
+ const speed = e.target && e.target.closest ? e.target.closest(".c-animation-controls__speed") : null;
833
987
  if (speed && this.contains(speed)) {
834
- 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 } }));
835
1000
  }
836
1001
  });
837
1002
  this.addEventListener("input", (e) => {
838
1003
  const scrubber = e.target && e.target.closest ? e.target.closest(".c-animation-controls__scrubber") : null;
839
1004
  if (scrubber && this.contains(scrubber)) {
840
1005
  const v = Number(scrubber.value);
1006
+ writeProgress(v);
841
1007
  this.dispatchEvent(new CustomEvent("contour:seek", { bubbles: true, composed: true, detail: { progress: v, value: v } }));
842
1008
  }
843
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.
844
1016
  this.addEventListener("keydown", (e) => {
845
- if (e.key === " " || e.key === "Enter") {
846
- const play = this.querySelector(".c-animation-controls__play");
847
- if (play && (e.target === play || !e.target || e.target === this)) { e.preventDefault(); play.click(); }
848
- } else if (e.key === "ArrowRight" || e.key === "ArrowLeft") {
849
- const scrubber = this.querySelector(".c-animation-controls__scrubber");
850
- if (scrubber) {
851
- e.preventDefault();
852
- const step = e.key === "ArrowRight" ? 1 : -1;
853
- scrubber.value = String(Number(scrubber.value) + step);
854
- scrubber.dispatchEvent(new Event("input", { bubbles: true }));
855
- }
856
- }
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(); } });
857
1021
  });
858
1022
  // Playback ownership: when `playing` is set, advance the playhead on a
859
1023
  // timer and emit contour:time-change so a consumer can sync its data.
@@ -869,9 +1033,18 @@ class ContourAnimationControls extends ContourBase {
869
1033
  const min = Number(scrubber.min || 0);
870
1034
  const max = Number(scrubber.max || 100);
871
1035
  let v = Number(scrubber.value || 0) + speedFactor();
872
- 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
+ }
873
1041
  scrubber.value = String(v);
1042
+ writeProgress(v);
874
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
+ }
875
1048
  };
876
1049
  const start = () => { if (timer) return; timer = setInterval(tick, 100); };
877
1050
  const stop = () => { if (timer) { clearInterval(timer); timer = null; } };
@@ -892,9 +1065,16 @@ class ContourDropdown extends ContourBase {
892
1065
  static get properties() { return { label: { attribute: "label" }, items: { attribute: "items" } }; }
893
1066
  render() {
894
1067
  this.classList.add("c-dropdown");
1068
+ if (!this.hasAttribute("aria-label")) this.setAttribute("aria-label", "Dropdown");
895
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; });
896
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");
897
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);
898
1078
  // Slotted content: authored .c-menu__item children take precedence over
899
1079
  // the JSON `items` attribute.
900
1080
  const authoredItems = Array.from(this.querySelectorAll(":scope > .c-menu__item"));
@@ -913,7 +1093,7 @@ class ContourDropdown extends ContourBase {
913
1093
  li.textContent = typeof it === "string" ? it : (it.label || it.title || "");
914
1094
  menu.appendChild(li);
915
1095
  });
916
- } catch (e) { /* keep existing */ }
1096
+ } catch (e) { warnBadJson(this, "attribute", e); }
917
1097
  }
918
1098
  if (menu.parentNode !== this) this.appendChild(menu);
919
1099
  if (btn.parentNode !== this) this.insertBefore(btn, menu);
@@ -955,18 +1135,12 @@ class ContourDropdown extends ContourBase {
955
1135
  };
956
1136
  document.addEventListener("click", docClick);
957
1137
  onDispose(this, () => document.removeEventListener("click", docClick));
958
- const keyHandler = (e) => {
1138
+ const keyHandler = (e) => {
959
1139
  const m = menu(); const b = btn();
960
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; }
961
1141
  if (!m || m.hidden) return;
962
1142
  const items = Array.from(m.querySelectorAll(".c-menu__item"));
963
- const active = document.activeElement;
964
- const idx = items.indexOf(active);
965
- 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) {} }
966
- 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) {} }
967
- else if (e.key === "Enter" || e.key === " ") {
968
- if (active && items.includes(active)) { e.preventDefault(); active.click(); }
969
- }
1143
+ navKey(e, items, { wrap: true, enter: false, onKey: (k) => { if (k === "Enter" || k === " ") document.activeElement.click(); } });
970
1144
  };
971
1145
  document.addEventListener("keydown", keyHandler);
972
1146
  onDispose(this, () => document.removeEventListener("keydown", keyHandler));
@@ -975,8 +1149,11 @@ class ContourDropdown extends ContourBase {
975
1149
  define("contour-dropdown", ContourDropdown);
976
1150
 
977
1151
  /**
978
- * Annotation: a positioned note with label and x/y coordinates. Attributes:
979
- * `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).
980
1157
  */
981
1158
  class ContourAnnotation extends ContourBase {
982
1159
  static get observed() { return ["label", "x", "y"]; }
@@ -984,6 +1161,7 @@ class ContourAnnotation extends ContourBase {
984
1161
  render() {
985
1162
  this.classList.add("c-annotation");
986
1163
  this.setAttribute("role", "note");
1164
+ if (!this.hasAttribute("tabindex")) this.setAttribute("tabindex", "0");
987
1165
  const label = this.getAttribute("label");
988
1166
  if (label) this.setAttribute("aria-label", label);
989
1167
  if (label) {
@@ -995,22 +1173,87 @@ class ContourAnnotation extends ContourBase {
995
1173
  if (x !== null) this.style.setProperty("--annotation-x", x);
996
1174
  if (y !== null) this.style.setProperty("--annotation-y", y);
997
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
+ }
998
1233
  }
999
1234
  define("contour-annotation", ContourAnnotation);
1000
1235
 
1001
1236
  /**
1002
- * Style Switcher: web component wrapper.
1003
- * 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.
1004
1242
  */
1005
1243
  class ContourStyleSwitcher extends ContourBase {
1006
1244
  static get observed() { return ["items", "value"]; }
1007
1245
  static get properties() { return { items: { attribute: "items" }, value: { attribute: "value" } }; }
1008
1246
  render() {
1009
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");
1010
1250
  const items = this.getAttribute("items");
1011
1251
  const value = this.getAttribute("value");
1012
- Array.from(this.querySelectorAll(".c-style-switcher__option")).forEach((n) => n.remove());
1013
- 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());
1014
1257
  try {
1015
1258
  const parsed = JSON.parse(items);
1016
1259
  parsed.forEach((it) => {
@@ -1019,21 +1262,42 @@ class ContourStyleSwitcher extends ContourBase {
1019
1262
  btn.className = "c-style-switcher__option c-btn c-btn--sm";
1020
1263
  btn.type = "button";
1021
1264
  btn.textContent = name;
1022
- if (name === value) btn.classList.add("c-style-switcher__option--active");
1023
1265
  btn.dataset.value = name;
1024
1266
  this.appendChild(btn);
1025
1267
  });
1026
- } catch (e) { /* keep existing */ }
1268
+ } catch (e) { warnBadJson(this, "attribute", e); }
1027
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");
1028
1283
  }
1029
1284
  enhance() {
1030
1285
  if (this._wiredStyleSwitcher) return;
1031
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
+ };
1032
1294
  this.addEventListener("click", (e) => {
1033
1295
  const btn = e.target && e.target.closest ? e.target.closest(".c-style-switcher__option") : null;
1034
- if (btn && this.contains(btn)) {
1035
- this.dispatchEvent(new CustomEvent("contour:change", { bubbles: true, composed: true, detail: { value: btn.dataset.value } }));
1036
- }
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); } } });
1037
1301
  });
1038
1302
  }
1039
1303
  }
@@ -1048,6 +1312,12 @@ class ContourStylePanel extends ContourBase {
1048
1312
  static get properties() { return { title: { attribute: "title" }, layers: { attribute: "layers" }, classification: { attribute: "classification" }, palette: { attribute: "palette" }, breaks: { attribute: "breaks" }, opacity: { attribute: "opacity" } }; }
1049
1313
  render() {
1050
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
+ }
1051
1321
  this.setAttribute("role", "group");
1052
1322
  this.setAttribute("aria-label", "Style panel");
1053
1323
  const title = this.getAttribute("title");
@@ -1059,29 +1329,36 @@ class ContourStylePanel extends ContourBase {
1059
1329
  if (singleMode) {
1060
1330
  const body = this.ensure(".c-style-panel__body", () => { const el = document.createElement("div"); el.className = "c-style-panel__body"; return el; });
1061
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";
1062
1339
  // property field
1063
- const propLabel = document.createElement("label"); propLabel.textContent = "Colour field"; propLabel.setAttribute("for", "property"); body.appendChild(propLabel);
1064
- 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"));
1065
1342
  const pv = this.getAttribute("property"); if (pv) propIn.value = pv;
1066
1343
  body.appendChild(propIn);
1067
1344
  // classification method selector (policy)
1068
- const clsLabel = document.createElement("label"); clsLabel.textContent = "Classification"; clsLabel.setAttribute("for", "policy"); body.appendChild(clsLabel);
1069
- 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"));
1070
1347
  ["equal","quantile","jenks","manual"].forEach((m) => { const o = document.createElement("option"); o.value = m; o.textContent = m; clsSel.appendChild(o); });
1071
1348
  const cls = this.getAttribute("classification"); if (cls) clsSel.value = cls;
1072
1349
  body.appendChild(clsSel);
1073
1350
  // palette picker
1074
- const palLabel = document.createElement("label"); palLabel.textContent = "Palette"; palLabel.setAttribute("for", "palette"); body.appendChild(palLabel);
1075
- 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"));
1076
1353
  const palv = this.getAttribute("palette"); if (palv) pal.value = palv;
1077
1354
  body.appendChild(pal);
1078
1355
  // n (class count)
1079
- const nLabel = document.createElement("label"); nLabel.textContent = "Classes"; nLabel.setAttribute("for", "n"); body.appendChild(nLabel);
1080
- 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"));
1081
1358
  const nv = this.getAttribute("n"); if (nv) nIn.value = nv; else nIn.value = "5";
1082
1359
  body.appendChild(nIn);
1083
1360
  // opacity slider
1084
- 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";
1085
1362
  const ov = this.getAttribute("opacity"); op.value = ov != null ? ov : "100";
1086
1363
  body.appendChild(op);
1087
1364
  // breaks as .break elements per class
@@ -1093,7 +1370,7 @@ class ContourStylePanel extends ContourBase {
1093
1370
  breaksArr.forEach((b, i) => {
1094
1371
  const br = document.createElement("div"); br.className = "break";
1095
1372
  const span = document.createElement("span"); span.textContent = String(b); br.appendChild(span);
1096
- 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);
1097
1374
  br.appendChild(inp);
1098
1375
  breaksWrap.appendChild(br);
1099
1376
  });
@@ -1106,17 +1383,18 @@ class ContourStylePanel extends ContourBase {
1106
1383
  if (Array.isArray(colors)) {
1107
1384
  const list = document.createElement("div"); list.className = "c-style-panel__colors";
1108
1385
  colors.forEach((c, i) => {
1109
- 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));
1110
1387
  sw.value = c;
1111
- 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.
1112
1390
  list.appendChild(sw);
1113
1391
  });
1114
1392
  body.appendChild(list);
1115
1393
  }
1116
1394
  // Apply/Revert buttons
1117
- const actions = document.createElement("div"); actions.className = "c-style-panel__actions";
1118
- const applyBtn = document.createElement("button"); applyBtn.type = "button"; applyBtn.className = "c-btn c-btn--primary"; applyBtn.textContent = "Apply";
1119
- const revertBtn = document.createElement("button"); revertBtn.type = "button"; revertBtn.className = "c-btn"; revertBtn.textContent = "Revert";
1395
+ const actions = document.createElement("div"); actions.className = "c-style-panel__actions c-btn-group";
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";
1120
1398
  actions.appendChild(applyBtn); actions.appendChild(revertBtn);
1121
1399
  body.appendChild(actions);
1122
1400
  return;
@@ -1160,7 +1438,7 @@ class ContourStylePanel extends ContourBase {
1160
1438
  // classification method selector
1161
1439
  const clsSel = document.createElement("select");
1162
1440
  clsSel.className = "c-style-panel__classification";
1163
- clsSel.setAttribute("aria-label", "Classification method");
1441
+ clsSel.setAttribute("aria-label", labelText(this, "classification-method", "Classification method"));
1164
1442
  ["equal","quantile","jenks","manual"].forEach((m) => { const o = document.createElement("option"); o.value = m; o.textContent = m; clsSel.appendChild(o); });
1165
1443
  if (typeof l === "object" && l.classification) clsSel.value = l.classification;
1166
1444
  row.appendChild(clsSel);
@@ -1177,13 +1455,14 @@ class ContourStylePanel extends ContourBase {
1177
1455
  breaks.type = "text";
1178
1456
  breaks.className = "c-style-panel__breaks";
1179
1457
  breaks.placeholder = "breaks";
1458
+ breaks.setAttribute("aria-label", "Class breaks");
1180
1459
  if (typeof l === "object" && l.breaks) breaks.value = (Array.isArray(l.breaks) ? l.breaks.join(",") : l.breaks);
1181
1460
  row.appendChild(breaks);
1182
1461
  // opacity control
1183
1462
  const op = document.createElement("input");
1184
1463
  op.type = "range";
1185
1464
  op.className = "c-style-panel__opacity";
1186
- op.setAttribute("aria-label", "Opacity");
1465
+ op.setAttribute("aria-label", labelText(this, "opacity", "Opacity"));
1187
1466
  op.min = "0"; op.max = "100";
1188
1467
  op.value = (typeof l === "object" && l.opacity != null) ? l.opacity : "100";
1189
1468
  row.appendChild(op);
@@ -1214,6 +1493,7 @@ class ContourStylePanel extends ContourBase {
1214
1493
  this.addEventListener("input", (e) => {
1215
1494
  const t = e.target;
1216
1495
  if (!t || !this.contains(t)) return;
1496
+ if (t.classList.contains("c-style-panel__color")) t.setAttribute("data-edited", "true");
1217
1497
  if (t.classList.contains("c-style-panel__palette") || t.classList.contains("c-style-panel__breaks")) {
1218
1498
  const row = t.closest(".c-style-panel__row");
1219
1499
  const name = row ? (row.querySelector(".c-style-panel__name")?.textContent || "") : "";
@@ -1223,9 +1503,47 @@ class ContourStylePanel extends ContourBase {
1223
1503
  this.addEventListener("click", (e) => {
1224
1504
  const t = e.target && e.target.closest ? e.target.closest("button") : null;
1225
1505
  if (!t || !this.contains(t)) return;
1226
- if (t.textContent.trim() === "Apply") {
1227
- this.dispatchEvent(new CustomEvent("contour:style-resolved", { detail: { applied: true }, bubbles: true, composed: true }));
1228
- } 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
+ }
1229
1547
  this.dispatchEvent(new CustomEvent("contour:style-resolved", { detail: { applied: false }, bubbles: true, composed: true }));
1230
1548
  }
1231
1549
  });
@@ -1278,7 +1596,7 @@ class ContourAvatarGroup extends ContourBase {
1278
1596
  overflow.textContent = "+" + (parsed.length - max);
1279
1597
  this.appendChild(overflow);
1280
1598
  }
1281
- } catch (e) { /* keep existing */ }
1599
+ } catch (e) { warnBadJson(this, "attribute", e); }
1282
1600
  }
1283
1601
  }
1284
1602
  }
@@ -1315,7 +1633,12 @@ class ContourStatusLight extends ContourBase {
1315
1633
  this.classList.add("c-status-light");
1316
1634
  const status = this.getAttribute("status") || "neutral";
1317
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");
1318
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);
1319
1642
  if (label) {
1320
1643
  const l = this.ensure(".c-status-light__label", () => { const el = document.createElement("span"); el.className = "c-status-light__label"; return el; });
1321
1644
  l.textContent = label;
@@ -1337,6 +1660,12 @@ class ContourSplitButton extends ContourBase {
1337
1660
  main.textContent = this.getAttribute("label") || "Action";
1338
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; });
1339
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));
1340
1669
  const items = this.getAttribute("menu");
1341
1670
  if (items) {
1342
1671
  try {
@@ -1349,7 +1678,7 @@ class ContourSplitButton extends ContourBase {
1349
1678
  li.textContent = typeof it === "string" ? it : (it.label || it.title || "");
1350
1679
  menu.appendChild(li);
1351
1680
  });
1352
- } catch (e) { /* keep existing */ }
1681
+ } catch (e) { warnBadJson(this, "attribute", e); }
1353
1682
  }
1354
1683
  if (main.parentNode !== this) this.appendChild(main);
1355
1684
  if (toggle.parentNode !== this) this.appendChild(toggle);
@@ -1360,34 +1689,67 @@ class ContourSplitButton extends ContourBase {
1360
1689
  this._wiredSplitButton = true;
1361
1690
  const toggle = () => this.querySelector(".c-split-button__toggle");
1362
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
+ };
1363
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
+ }
1364
1712
  const t = toggle();
1365
1713
  if (e.target === t || (t && t.contains(e.target))) {
1366
1714
  const m = menu();
1367
- 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;
1368
1717
  }
1369
1718
  const item = e.target && e.target.closest ? e.target.closest(".c-menu__item") : null;
1370
1719
  if (item && this.contains(item)) {
1371
- const m = menu();
1372
- if (m) { m.hidden = true; const t = toggle(); if (t) t.setAttribute("aria-expanded", "false"); }
1373
- 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 } }));
1374
1724
  }
1375
1725
  });
1376
1726
  this.addEventListener("keydown", (e) => {
1377
1727
  const t = toggle();
1378
- 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")) {
1379
1733
  e.preventDefault();
1380
- const m = menu();
1381
- if (m) { m.hidden = !m.hidden; t.setAttribute("aria-expanded", String(!m.hidden)); }
1382
- } else if (e.key === "Escape") {
1383
- const m = menu();
1384
- 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) {}
1385
1748
  }
1386
1749
  });
1387
1750
  const docClick = (e) => {
1388
1751
  const m = menu();
1389
- const t = toggle();
1390
- 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);
1391
1753
  };
1392
1754
  document.addEventListener("click", docClick);
1393
1755
  onDispose(this, () => document.removeEventListener("click", docClick));
@@ -1402,57 +1764,157 @@ class ContourSplitButton extends ContourBase {
1402
1764
  class ContourPaletteEditor extends ContourBase {
1403
1765
  static get observed() { return ["colors"]; }
1404
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
+ }
1405
1778
  render() {
1406
1779
  this.classList.add("c-palette-editor");
1407
- const colors = this.getAttribute("colors");
1408
- Array.from(this.querySelectorAll(".c-palette-editor__swatch")).forEach((n) => n.remove());
1409
- if (colors) {
1410
- try {
1411
- const parsed = JSON.parse(colors);
1412
- parsed.forEach((c) => {
1413
- const sw = document.createElement("button");
1414
- sw.className = "c-palette-editor__swatch c-swatch";
1415
- sw.type = "button";
1416
- sw.style.background = typeof c === "string" ? c : (c.color || c.value || "");
1417
- sw.dataset.color = typeof c === "string" ? c : (c.color || c.value || "");
1418
- sw.setAttribute("aria-label", typeof c === "string" ? c : (c.name || c.label || "color"));
1419
- this.appendChild(sw);
1420
- });
1421
- } 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);
1422
1840
  }
1423
1841
  }
1424
1842
  enhance() {
1425
1843
  if (this._wiredPaletteEditor) return;
1426
1844
  this._wiredPaletteEditor = true;
1427
1845
  this.addEventListener("click", (e) => {
1428
- 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");
1429
1849
  if (sw && this.contains(sw)) {
1430
- 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;
1431
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 } }));
1872
+ }
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) } }));
1432
1884
  });
1433
1885
  this.addEventListener("keydown", (e) => {
1434
1886
  const swatches = Array.from(this.querySelectorAll(".c-palette-editor__swatch"));
1435
- const active = document.activeElement;
1436
- const idx = swatches.indexOf(active);
1437
- 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) {} }
1438
- 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) {} }
1439
- 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(); } });
1440
1889
  });
1441
1890
  }
1442
1891
  }
1443
1892
  define("contour-palette-editor", ContourPaletteEditor);
1444
1893
 
1445
1894
  /**
1446
- * Date Range: web component wrapper.
1447
- * 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`).
1448
1904
  */
1449
1905
  class ContourDateRange extends ContourBase {
1450
- static get observed() { return ["start", "end", "label", "time", "min", "max", "locale"]; }
1451
- 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; }
1452
1909
  render() {
1453
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
+ }
1454
1916
  this.setAttribute("role", "group");
1455
- this.setAttribute("aria-label", "Date range");
1917
+ this.setAttribute("aria-label", this.getAttribute("label") || "Date range");
1456
1918
  const label = this.getAttribute("label");
1457
1919
  if (label) {
1458
1920
  const l = this.ensure(".c-date-range__label", () => { const el = document.createElement("span"); el.className = "c-date-range__label"; return el; });
@@ -1461,16 +1923,26 @@ class ContourDateRange extends ContourBase {
1461
1923
  const start = this.ensure(".c-date-range__start", () => { const el = document.createElement("input"); el.className = "c-input c-date-range__start"; return el; });
1462
1924
  start.type = this.hasAttribute("time") ? "datetime-local" : "date";
1463
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");
1464
1929
  const end = this.ensure(".c-date-range__end", () => { const el = document.createElement("input"); el.className = "c-input c-date-range__end"; return el; });
1465
1930
  end.type = start.type;
1466
1931
  end.value = this.getAttribute("end") || "";
1932
+ end.setAttribute("aria-label", label ? label + " — end" : "End date");
1467
1933
  const min = this.getAttribute("min");
1468
1934
  const max = this.getAttribute("max");
1469
1935
  [start, end].forEach((input) => {
1470
1936
  if (min) input.min = min; else input.removeAttribute("min");
1471
1937
  if (max) input.max = max; else input.removeAttribute("max");
1472
1938
  if (this.getAttribute("locale")) input.lang = this.getAttribute("locale");
1939
+ if (this.hasAttribute("disabled")) input.setAttribute("disabled", ""); else input.removeAttribute("disabled");
1473
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();
1474
1946
  }
1475
1947
  enhance() {
1476
1948
  if (this._wiredDateRange) return;
@@ -1478,10 +1950,62 @@ class ContourDateRange extends ContourBase {
1478
1950
  this.addEventListener("change", (e) => {
1479
1951
  const t = e.target;
1480
1952
  if (t && (t.classList.contains("c-date-range__start") || t.classList.contains("c-date-range__end"))) {
1481
- 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 } }));
1482
1963
  }
1483
1964
  });
1484
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
+ }
1485
2009
  }
1486
2010
  define("contour-date-range", ContourDateRange);
1487
2011
 
@@ -1494,6 +2018,8 @@ class ContourShortcut extends ContourBase {
1494
2018
  static get properties() { return { key: { attribute: "key" }, label: { attribute: "label" } }; }
1495
2019
  render() {
1496
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");
1497
2023
  const key = this.getAttribute("key") || "";
1498
2024
  const label = this.getAttribute("label") || "";
1499
2025
  if (key) {
@@ -1591,6 +2117,7 @@ class ContourPopover extends ContourBase {
1591
2117
  * Attributes: `value`, `range`, `range-start`, `range-end`, `label`, `disabled`, `error`, `help`, `time`, `min`, `max`, `locale`.
1592
2118
  */
1593
2119
  class ContourDatePicker extends ContourBase {
2120
+ static get formAssociated() { return true; }
1594
2121
  static get observed() { return ["value", "range", "range-start", "range-end", "label", "disabled", "error", "help", "time", "min", "max", "locale"]; }
1595
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" } }; }
1596
2123
  render() {
@@ -1607,7 +2134,12 @@ class ContourDatePicker extends ContourBase {
1607
2134
  const type = this.hasAttribute("time") ? "datetime-local" : "date";
1608
2135
  const configure = (control, value, name) => {
1609
2136
  control.type = type;
1610
- 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;
1611
2143
  control.setAttribute("aria-label", name);
1612
2144
  if (this.hasAttribute("min")) control.min = this.getAttribute("min"); else control.removeAttribute("min");
1613
2145
  if (this.hasAttribute("max")) control.max = this.getAttribute("max"); else control.removeAttribute("max");
@@ -1660,32 +2192,86 @@ class ContourDatePicker extends ContourBase {
1660
2192
  const grid = document.createElement("div");
1661
2193
  grid.className = "c-date-picker__calendar-grid";
1662
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
+ };
1663
2213
  const weekdays = ["Su","Mo","Tu","We","Th","Fr","Sa"];
1664
- weekdays.forEach((w) => { const h = document.createElement("div"); h.className = "c-date-picker__calendar-weekday"; h.textContent = w; grid.appendChild(h); });
1665
- 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
+ }
1666
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;
1667
2233
  for (let d = 1; d <= daysInMonth; d++) {
1668
2234
  const btn = document.createElement("button");
1669
2235
  btn.type = "button";
1670
2236
  btn.className = "c-date-picker__calendar-day";
1671
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" }));
1672
2243
  const iso = `${y}-${String(m + 1).padStart(2, "0")}-${String(d).padStart(2, "0")}`;
1673
- 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"); }
1674
2245
  btn.addEventListener("click", () => {
1675
2246
  if (input) { input.value = iso; input.dispatchEvent(new Event("change", { bubbles: true })); }
1676
2247
  cal.setAttribute("hidden", "");
1677
2248
  const tgl = this.querySelector(".c-date-picker__calendar-toggle");
1678
2249
  if (tgl) tgl.setAttribute("aria-expanded", "false");
1679
2250
  });
1680
- grid.appendChild(btn);
2251
+ push(btn);
1681
2252
  }
1682
2253
  cal.appendChild(grid);
1683
2254
  prev.addEventListener("click", () => { this._calMonth = new Date(y, m - 1, 1); this._renderCalendar(); });
1684
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));
1685
2269
  }
1686
2270
  enhance() {
1687
2271
  if (this._wiredDatePicker) return;
1688
2272
  this._wiredDatePicker = true;
2273
+ this._syncFormValue();
2274
+ this.addEventListener("change", () => { this._syncFormValue(); });
1689
2275
  this.addEventListener("change", (e) => {
1690
2276
  const t = e.target;
1691
2277
  if (t && t.classList.contains("c-date-picker__input")) {
@@ -1706,6 +2292,34 @@ class ContourDatePicker extends ContourBase {
1706
2292
  const btn = e.target && e.target.closest ? e.target.closest(".c-date-picker__calendar-toggle") : null;
1707
2293
  if (btn && this.contains(btn)) { e.preventDefault(); toggle(); }
1708
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
+ });
1709
2323
  }
1710
2324
  }
1711
2325
  define("contour-date-picker", ContourDatePicker);
@@ -1719,19 +2333,32 @@ class ContourRating extends ContourBase {
1719
2333
  static get properties() { return { value: { attribute: "value", type: Number }, max: { attribute: "max", type: Number }, color: { attribute: "color" } }; }
1720
2334
  render() {
1721
2335
  this.classList.add("c-rating");
1722
- this.setAttribute("role", "radiogroup");
1723
- 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");
1724
2339
  const max = parseInt(this.getAttribute("max") || "5", 10) || 5;
1725
2340
  const value = parseInt(this.getAttribute("value") || "0", 10) || 0;
1726
2341
  const color = this.getAttribute("color");
1727
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;
1728
2346
  for (let i = 1; i <= max; i++) {
1729
2347
  const star = document.createElement("button");
1730
2348
  star.className = "c-rating__star" + (i <= value ? " c-rating__star--filled" : "");
1731
2349
  star.type = "button";
1732
2350
  star.setAttribute("role", "radio");
1733
2351
  star.setAttribute("aria-checked", String(i === value));
1734
- 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
+ }
1735
2362
  star.dataset.value = String(i);
1736
2363
  star.setAttribute("aria-label", i + " star" + (i > 1 ? "s" : ""));
1737
2364
  this.appendChild(star);
@@ -1740,32 +2367,34 @@ class ContourRating extends ContourBase {
1740
2367
  enhance() {
1741
2368
  if (this._wiredRating) return;
1742
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
+ };
1743
2385
  this.addEventListener("click", (e) => {
1744
2386
  const star = e.target && e.target.closest ? e.target.closest(".c-rating__star") : null;
1745
- if (star && this.contains(star)) {
1746
- const v = parseInt(star.dataset.value, 10);
1747
- Array.from(this.querySelectorAll(".c-rating__star")).forEach((st) => st.setAttribute("aria-checked", String(parseInt(st.dataset.value, 10) === v)));
1748
- this.dispatchEvent(new CustomEvent("contour:change", { bubbles: true, composed: true, detail: { value: v } }));
1749
- }
2387
+ if (star && this.contains(star)) select(parseInt(star.dataset.value, 10));
1750
2388
  });
1751
2389
  this.addEventListener("keydown", (e) => {
1752
- const stars = Array.from(this.querySelectorAll(".c-rating__star"));
1753
- const active = document.activeElement;
1754
- const idx = stars.indexOf(active);
1755
- if (e.key === "ArrowRight" || e.key === "ArrowUp") {
1756
- e.preventDefault();
1757
- const next = stars[Math.min(stars.length - 1, idx + 1)] || stars[0];
1758
- if (next) { try { next.focus(); } catch (err) {} }
1759
- } else if (e.key === "ArrowLeft" || e.key === "ArrowDown") {
1760
- e.preventDefault();
1761
- const prev = stars[Math.max(0, idx - 1)] || stars[stars.length - 1];
1762
- if (prev) { try { prev.focus(); } catch (err) {} }
1763
- } else if (e.key === "Enter" || e.key === " ") {
1764
- e.preventDefault();
1765
- if (active && active.classList.contains("c-rating__star")) {
1766
- this.dispatchEvent(new CustomEvent("contour:change", { bubbles: true, composed: true, detail: { value: parseInt(active.dataset.value, 10) } }));
1767
- }
1768
- }
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
+ });
1769
2398
  });
1770
2399
  }
1771
2400
  }
@@ -1776,6 +2405,7 @@ class ContourRating extends ContourBase {
1776
2405
  * Attributes: `value`, `label`, `disabled`, `error`, `help`.
1777
2406
  */
1778
2407
  class ContourTimePicker extends ContourBase {
2408
+ static get formAssociated() { return true; }
1779
2409
  static get observed() { return ["value", "label", "disabled", "error", "help"]; }
1780
2410
  static get properties() { return { value: { attribute: "value" }, label: { attribute: "label" }, disabled: { attribute: "disabled", type: Boolean }, error: { attribute: "error" }, help: { attribute: "help" } }; }
1781
2411
  render() {
@@ -1787,7 +2417,7 @@ class ContourTimePicker extends ContourBase {
1787
2417
  const l = this.ensure(".c-time-picker__label", () => { const el = document.createElement("label"); el.className = "c-time-picker__label"; return el; });
1788
2418
  l.textContent = label;
1789
2419
  }
1790
- 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; });
1791
2421
  input.value = this.getAttribute("value") || "";
1792
2422
  if (this.hasAttribute("disabled")) { input.setAttribute("disabled", ""); this.classList.add("is-disabled"); }
1793
2423
  else { input.removeAttribute("disabled"); this.classList.remove("is-disabled"); }
@@ -1804,10 +2434,13 @@ class ContourTimePicker extends ContourBase {
1804
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; });
1805
2435
  let cal = this.querySelector(".c-date-picker__calendar");
1806
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();
1807
2438
  }
1808
2439
  enhance() {
1809
2440
  if (this._wiredTimePicker) return;
1810
2441
  this._wiredTimePicker = true;
2442
+ this._syncFormValue();
2443
+ this.addEventListener("change", () => { this._syncFormValue(); });
1811
2444
  this.addEventListener("change", (e) => {
1812
2445
  const t = e.target;
1813
2446
  if (t && t.classList.contains("c-time-picker__input")) {
@@ -1823,6 +2456,7 @@ class ContourTimePicker extends ContourBase {
1823
2456
  * Attributes: `value`, `label`, `disabled`, `error`, `help`, `alpha`, `presets`.
1824
2457
  */
1825
2458
  class ContourColorPicker extends ContourBase {
2459
+ static get formAssociated() { return true; }
1826
2460
  static get observed() { return ["value", "label", "disabled", "error", "help", "alpha", "presets"]; }
1827
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" } }; }
1828
2462
  render() {
@@ -1836,6 +2470,7 @@ class ContourColorPicker extends ContourBase {
1836
2470
  }
1837
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; });
1838
2472
  input.value = (this.getAttribute("value") || "#000000").slice(0, 7);
2473
+ if (!input.hasAttribute("aria-label")) input.setAttribute("aria-label", label || "Color");
1839
2474
  if (this.hasAttribute("disabled")) { input.setAttribute("disabled", ""); this.classList.add("is-disabled"); }
1840
2475
  else { input.removeAttribute("disabled"); this.classList.remove("is-disabled"); }
1841
2476
  // Alpha channel (optional).
@@ -1864,14 +2499,14 @@ class ContourColorPicker extends ContourBase {
1864
2499
  btn.className = "c-color-picker__preset";
1865
2500
  btn.style.background = c;
1866
2501
  btn.dataset.color = c;
1867
- btn.setAttribute("aria-label", "Preset " + c);
2502
+ btn.setAttribute("aria-label", labelText(this, "preset", "Preset") + " " + c);
1868
2503
  wrap.appendChild(btn);
1869
2504
  });
1870
2505
  this.appendChild(wrap);
1871
2506
  }
1872
2507
  // Eyedropper (if supported).
1873
2508
  if (typeof window !== "undefined" && "EyeDropper" in window) {
1874
- 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; });
1875
2510
  if (this.hasAttribute("disabled")) ed.setAttribute("disabled", "");
1876
2511
  else ed.removeAttribute("disabled");
1877
2512
  } else {
@@ -1891,10 +2526,14 @@ class ContourColorPicker extends ContourBase {
1891
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; });
1892
2527
  let cal = this.querySelector(".c-date-picker__calendar");
1893
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();
1894
2530
  }
1895
2531
  enhance() {
1896
2532
  if (this._wiredColorPicker) return;
1897
2533
  this._wiredColorPicker = true;
2534
+ this._syncFormValue();
2535
+ this.addEventListener("change", () => { this._syncFormValue(); });
2536
+ this.addEventListener("contour:change", () => { this._syncFormValue(); });
1898
2537
  this.addEventListener("change", (e) => {
1899
2538
  const t = e.target;
1900
2539
  if (t && t.classList.contains("c-color-picker__input")) {
@@ -1942,6 +2581,7 @@ class ContourColorPicker extends ContourBase {
1942
2581
  * Attributes: `value`, `min`, `max`, `step`, `label`, `disabled`, `error`, `help`.
1943
2582
  */
1944
2583
  class ContourNumberField extends ContourBase {
2584
+ static get formAssociated() { return true; }
1945
2585
  static get observed() { return ["value", "min", "max", "step", "label", "disabled", "error", "help"]; }
1946
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" } }; }
1947
2587
  render() {
@@ -1960,6 +2600,7 @@ class ContourNumberField extends ContourBase {
1960
2600
  input.setAttribute("aria-valuenow", v === "" ? "" : v);
1961
2601
  if (input.min !== "") input.setAttribute("aria-valuemin", input.min);
1962
2602
  if (input.max !== "") input.setAttribute("aria-valuemax", input.max);
2603
+ if (!input.hasAttribute("aria-label")) input.setAttribute("aria-label", label || "Number");
1963
2604
  if (this.hasAttribute("disabled")) { input.setAttribute("disabled", ""); this.classList.add("is-disabled"); }
1964
2605
  else { input.removeAttribute("disabled"); this.classList.remove("is-disabled"); }
1965
2606
  const err = this.getAttribute("error");
@@ -1975,10 +2616,13 @@ class ContourNumberField extends ContourBase {
1975
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; });
1976
2617
  let cal = this.querySelector(".c-date-picker__calendar");
1977
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();
1978
2620
  }
1979
2621
  enhance() {
1980
2622
  if (this._wiredNumberField) return;
1981
2623
  this._wiredNumberField = true;
2624
+ this._syncFormValue();
2625
+ this.addEventListener("change", () => { this._syncFormValue(); });
1982
2626
  this.addEventListener("change", (e) => {
1983
2627
  const t = e.target;
1984
2628
  if (t && t.classList.contains("c-number-field__input")) {
@@ -2044,11 +2688,23 @@ class ContourHoverCard extends ContourBase {
2044
2688
  const hasPopover = typeof this.showPopover === "function";
2045
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 })); };
2046
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 })); };
2047
- trigger.addEventListener("mouseenter", () => { showTimer = setTimeout(show, 300); });
2048
- trigger.addEventListener("mouseleave", () => { hide(); });
2049
- trigger.addEventListener("focus", show);
2050
- trigger.addEventListener("blur", () => { setTimeout(hide, 100); });
2051
- 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
+ });
2052
2708
  }
2053
2709
  }
2054
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 })); } };
@@ -2063,11 +2719,12 @@ class ContourHoverCard extends ContourBase {
2063
2719
  * Attributes: `items`.
2064
2720
  */
2065
2721
  class ContourContextMenu extends ContourBase {
2066
- static get observed() { return ["items"]; }
2067
- 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" } }; }
2068
2724
  render() {
2069
2725
  this.classList.add("c-context-menu");
2070
2726
  if (!this.hasAttribute("role")) this.setAttribute("role", "menu");
2727
+ if (!this.hasAttribute("aria-label")) this.setAttribute("aria-label", "Context menu");
2071
2728
  if (!this.hasAttribute("popover")) this.setAttribute("popover", "auto");
2072
2729
  if (!this.id) this.id = contourId("context-menu");
2073
2730
  const items = this.getAttribute("items");
@@ -2082,16 +2739,36 @@ class ContourContextMenu extends ContourBase {
2082
2739
  btn.textContent = typeof it === "string" ? it : (it.label || it.title || "");
2083
2740
  this.appendChild(btn);
2084
2741
  });
2085
- } catch (e) { /* keep existing */ }
2742
+ } catch (e) { warnBadJson(this, "attribute", e); }
2086
2743
  }
2087
2744
  }
2088
2745
  enhance() {
2089
2746
  if (this._wiredContextMenu) return;
2090
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
+ }
2091
2769
  this.addEventListener("contextmenu", (e) => {
2092
2770
  e.preventDefault();
2093
- if (typeof this.showPopover === "function") { try { this.showPopover(); } catch (err) {} }
2094
- else this.classList.toggle("is-open");
2771
+ openAt(e.clientX, e.clientY);
2095
2772
  });
2096
2773
  this.addEventListener("click", (e) => {
2097
2774
  const item = e.target && e.target.closest ? e.target.closest(".c-menu__item") : null;
@@ -2103,12 +2780,8 @@ class ContourContextMenu extends ContourBase {
2103
2780
  });
2104
2781
  this.addEventListener("keydown", (e) => {
2105
2782
  const items = Array.from(this.querySelectorAll(".c-menu__item"));
2106
- const active = document.activeElement;
2107
- const idx = items.indexOf(active);
2108
- 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) {} }
2109
- 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) {} }
2110
- else if (e.key === "Enter" || e.key === " ") { e.preventDefault(); if (active && active.classList.contains("c-menu__item")) active.click(); }
2111
- 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"); }
2112
2785
  });
2113
2786
  }
2114
2787
  }
@@ -2128,7 +2801,16 @@ class ContourFab extends ContourBase {
2128
2801
  const label = this.getAttribute("label");
2129
2802
  if (label) this.setAttribute("aria-label", label);
2130
2803
  const icon = this.getAttribute("icon");
2131
- 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
+ }
2132
2814
  }
2133
2815
  enhance() {
2134
2816
  if (this._wiredFab) return;
@@ -2148,10 +2830,12 @@ class ContourFab extends ContourBase {
2148
2830
  * Attributes: `label`, `accept`, `multiple`, `progress`.
2149
2831
  */
2150
2832
  class ContourFileUpload extends ContourBase {
2151
- static get observed() { return ["label", "accept", "multiple", "progress"]; }
2152
- 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" } }; }
2153
2836
  render() {
2154
2837
  this.classList.add("c-file-upload");
2838
+ if (!this.hasAttribute("aria-label")) this.setAttribute("aria-label", this.getAttribute("label") || "File upload");
2155
2839
  const label = this.getAttribute("label") || "Drop files here or click to browse";
2156
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; });
2157
2841
  dz.textContent = label;
@@ -2169,10 +2853,13 @@ class ContourFileUpload extends ContourBase {
2169
2853
  }
2170
2854
  const preview = this.ensure(".c-file-upload__preview", () => { const el = document.createElement("div"); el.className = "c-file-upload__preview"; return el; });
2171
2855
  if (!preview) {}
2856
+ if (this._internals) this._syncFormValue();
2172
2857
  }
2173
2858
  enhance() {
2174
2859
  if (this._wiredFileUpload) return;
2175
2860
  this._wiredFileUpload = true;
2861
+ this._syncFormValue();
2862
+ this.addEventListener("change", () => { this._syncFormValue(); });
2176
2863
  const dz = () => this.querySelector(".c-file-upload__dropzone");
2177
2864
  const input = () => this.querySelector(".c-file-upload__input");
2178
2865
  const activate = () => { const i = input(); if (i) i.click(); };
@@ -2181,6 +2868,9 @@ class ContourFileUpload extends ContourBase {
2181
2868
  const renderPreview = (files) => {
2182
2869
  const preview = this.querySelector(".c-file-upload__preview");
2183
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();
2184
2874
  preview.innerHTML = "";
2185
2875
  Array.from(files || []).forEach((f) => {
2186
2876
  const item = document.createElement("div");
@@ -2189,7 +2879,9 @@ class ContourFileUpload extends ContourBase {
2189
2879
  const img = document.createElement("img");
2190
2880
  img.className = "c-file-upload__preview-thumb";
2191
2881
  img.alt = f.name;
2192
- try { img.src = URL.createObjectURL(f); } catch (e) {}
2882
+ img.loading = "lazy";
2883
+ img.decoding = "async";
2884
+ try { const u = URL.createObjectURL(f); img.src = u; (this._objectUrls || (this._objectUrls = [])).push(u); } catch (e) {}
2193
2885
  item.appendChild(img);
2194
2886
  } else {
2195
2887
  const name = document.createElement("span");
@@ -2204,7 +2896,32 @@ class ContourFileUpload extends ContourBase {
2204
2896
  // drag-drop already dispatches contour:change; also render preview there
2205
2897
  this.addEventListener("dragover", (e) => { e.preventDefault(); this.classList.add("is-dragover"); });
2206
2898
  this.addEventListener("dragleave", () => this.classList.remove("is-dragover"));
2207
- 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
+ }
2208
2925
  }
2209
2926
  }
2210
2927
  define("contour-file-upload", ContourFileUpload);
@@ -2218,73 +2935,186 @@ class ContourNotificationCenter extends ContourBase {
2218
2935
  static get properties() { return { count: { attribute: "count" }, items: { attribute: "items" }, color: { attribute: "color" } }; }
2219
2936
  render() {
2220
2937
  this.classList.add("c-notification-center");
2221
- 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; });
2222
2940
  const color = this.getAttribute("color");
2223
2941
  const bullet = btn.querySelector(".c-notification-center__bullet");
2224
- if (bullet && color) { bullet.style.background = color; bullet.dataset.color = color; }
2225
- const count = this.getAttribute("count");
2226
- let badge = btn.querySelector(".c-notification-center__badge");
2227
- if (count && Number(count) > 0) {
2228
- if (!badge) { badge = document.createElement("span"); badge.className = "c-notification-center__badge c-badge c-badge--dot"; btn.appendChild(badge); }
2229
- badge.textContent = count;
2230
- } else if (badge) { badge.remove(); }
2942
+ if (bullet && color) { bullet.style.background = safeColor(color); bullet.dataset.color = color; }
2231
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));
2232
2948
  // Slotted content: authored .c-notification-center__item children take
2233
2949
  // precedence over the JSON `items` attribute.
2234
2950
  const authoredItems = Array.from(this.querySelectorAll(":scope > .c-notification-center__item"));
2235
2951
  const items = this.getAttribute("items");
2236
2952
  if (authoredItems.length) {
2237
2953
  panel.innerHTML = "";
2238
- 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);
2239
2959
  } else if (items) {
2240
- try {
2241
- const parsed = JSON.parse(items);
2242
- panel.innerHTML = "";
2243
- 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) => {
2244
2978
  const row = document.createElement("div");
2245
- row.className = "c-notification-center__item";
2246
- row.setAttribute("tabindex", "0");
2979
+ row.className = "c-notification-center__item" + (it && it.read ? " is-read" : "");
2980
+ row.setAttribute("tabindex", "-1");
2247
2981
  row.setAttribute("role", "option");
2248
- row.textContent = typeof it === "string" ? it : (it.text || it.title || "");
2249
- 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);
2250
3003
  });
2251
- } 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
+ }
2252
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(); }
2253
3038
  }
2254
3039
  enhance() {
2255
3040
  if (this._wiredNotifCenter) return;
2256
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
+ };
2257
3060
  this.addEventListener("click", (e) => {
2258
3061
  const btn = this.querySelector(".c-notification-center__trigger");
2259
3062
  const panel = this.querySelector(".c-notification-center__panel");
2260
3063
  if (btn && (e.target === btn || btn.contains(e.target))) {
2261
- 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;
2262
3066
  }
2263
- });
2264
- this.addEventListener("click", (e) => {
2265
- const item = e.target && e.target.closest ? e.target.closest(".c-notification-center__item") : null;
2266
- if (item && this.contains(item)) {
2267
- 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;
2268
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);
2269
3087
  });
2270
3088
  const docClick = (e) => {
2271
3089
  const panel = this.querySelector(".c-notification-center__panel");
2272
3090
  const btn = this.querySelector(".c-notification-center__trigger");
2273
- 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"); }
2274
3092
  };
2275
3093
  document.addEventListener("click", docClick);
2276
3094
  onDispose(this, () => document.removeEventListener("click", docClick));
2277
3095
  const keyHandler = (e) => {
2278
3096
  const panel = this.querySelector(".c-notification-center__panel");
2279
3097
  const btn = this.querySelector(".c-notification-center__trigger");
2280
- 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; }
2281
3099
  if (!panel || panel.hidden) return;
2282
3100
  const items = Array.from(panel.querySelectorAll(".c-notification-center__item"));
2283
3101
  if (!items.length) return;
2284
- const active = document.activeElement;
2285
- const idx = items.indexOf(active);
2286
- 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) {} }
2287
- 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; }); } });
2288
3118
  };
2289
3119
  document.addEventListener("keydown", keyHandler);
2290
3120
  onDispose(this, () => document.removeEventListener("keydown", keyHandler));
@@ -2301,6 +3131,8 @@ class ContourStepper extends ContourBase {
2301
3131
  static get properties() { return { steps: { attribute: "steps" }, current: { attribute: "current" } }; }
2302
3132
  render() {
2303
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");
2304
3136
  const steps = this.getAttribute("steps");
2305
3137
  const current = Number(this.getAttribute("current") || 0);
2306
3138
  const list = this.ensure(".c-stepper__list", () => { const el = document.createElement("ol"); el.className = "c-stepper__list"; return el; });
@@ -2321,9 +3153,13 @@ class ContourStepper extends ContourBase {
2321
3153
  li.textContent = typeof s === "string" ? s : (s.title || s.label || "");
2322
3154
  list.appendChild(li);
2323
3155
  });
2324
- const nav = this.ensure(".c-stepper__nav", () => { const el = document.createElement("div"); el.className = "c-stepper__nav"; return el; });
2325
- 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; });
2326
- 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; });
3156
+ const nav = this.ensure(".c-stepper__nav", () => { const el = document.createElement("div"); el.className = "c-stepper__nav c-btn-group"; 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");
2327
3163
  if (!nav.contains(prev)) nav.appendChild(prev);
2328
3164
  if (!nav.contains(next)) nav.appendChild(next);
2329
3165
  if (nav.parentNode !== this) this.appendChild(nav);
@@ -2344,8 +3180,18 @@ class ContourStepper extends ContourBase {
2344
3180
  this.addEventListener("click", (e) => {
2345
3181
  const prev = e.target && e.target.closest ? e.target.closest(".c-stepper__prev") : null;
2346
3182
  const next = e.target && e.target.closest ? e.target.closest(".c-stepper__next") : null;
2347
- if (prev && this.contains(prev)) go("prev");
2348
- 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
+ }
2349
3195
  });
2350
3196
  this.addEventListener("keydown", (e) => {
2351
3197
  if (e.key === "ArrowLeft") { e.preventDefault(); go("prev"); }
@@ -2371,7 +3217,8 @@ class ContourVirtualList extends ContourBase {
2371
3217
  }
2372
3218
  _itemHeight() {
2373
3219
  const h = Number(this.getAttribute("item-height"));
2374
- 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);
2375
3222
  }
2376
3223
  _autoHeight() {
2377
3224
  return this.getAttribute("item-height") === "auto";
@@ -2379,6 +3226,7 @@ class ContourVirtualList extends ContourBase {
2379
3226
  render() {
2380
3227
  this.classList.add("c-virtual-list");
2381
3228
  this.setAttribute("role", "list");
3229
+ if (!this.hasAttribute("aria-label")) this.setAttribute("aria-label", "Virtual list");
2382
3230
  const scroller = this.ensure(".c-virtual-list__scroller", () => { const el = document.createElement("div"); el.className = "c-virtual-list__scroller"; return el; });
2383
3231
  scroller.setAttribute("role", "presentation");
2384
3232
  const horizontal = this.getAttribute("orientation") === "horizontal";
@@ -2390,7 +3238,7 @@ class ContourVirtualList extends ContourBase {
2390
3238
  }
2391
3239
  _measureHeights(inner, horizontal) {
2392
3240
  const rows = Array.from(inner.querySelectorAll(".c-virtual-list__item"));
2393
- 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()));
2394
3242
  }
2395
3243
  _renderWindow(scroller, inner, scrollTop) {
2396
3244
  const items = this._items();
@@ -2405,9 +3253,9 @@ class ContourVirtualList extends ContourBase {
2405
3253
  let cumulative = null;
2406
3254
  if (autoHeight && heights && heights.length === total) {
2407
3255
  cumulative = [0];
2408
- 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()));
2409
3257
  }
2410
- 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);
2411
3259
  let start = 0;
2412
3260
  if (autoHeight && cumulative) {
2413
3261
  // binary search for start
@@ -2439,7 +3287,10 @@ class ContourVirtualList extends ContourBase {
2439
3287
  const row = document.createElement("div");
2440
3288
  row.className = "c-virtual-list__item";
2441
3289
  row.setAttribute("role", "listitem");
2442
- // 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));
2443
3294
  row.setAttribute("tabindex", i === 0 ? "0" : "-1");
2444
3295
  row.textContent = typeof items[i] === "string" ? items[i] : (items[i].label || items[i].text || JSON.stringify(items[i]));
2445
3296
  if (this.hasAttribute("sticky") && items[i] && items[i].sticky) {
@@ -2491,23 +3342,30 @@ class ContourVirtualList extends ContourBase {
2491
3342
  this.addEventListener("keydown", (e) => {
2492
3343
  const rows = Array.from(this.querySelectorAll(".c-virtual-list__item"));
2493
3344
  if (!rows.length) return;
2494
- const active = this.querySelector(".c-virtual-list__item:focus") || rows[0];
2495
- const idx = rows.indexOf(active);
2496
- let next = -1;
2497
- if (e.key === "ArrowDown") next = Math.min(idx + 1, rows.length - 1);
2498
- else if (e.key === "ArrowUp") next = Math.max(idx - 1, 0);
2499
- else if (e.key === "Home") next = 0;
2500
- else if (e.key === "End") next = rows.length - 1;
2501
- 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)) {
2502
3355
  e.preventDefault();
2503
- const i = Number(active.dataset.index);
2504
- 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
+ }
2505
3366
  return;
2506
3367
  }
2507
- if (next < 0 || next === idx) return;
2508
- e.preventDefault();
2509
- rows.forEach((r, i) => r.setAttribute("tabindex", i === next ? "0" : "-1"));
2510
- 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 } })); } } });
2511
3369
  });
2512
3370
  this.addEventListener("click", (e) => {
2513
3371
  const row = e.target && e.target.closest ? e.target.closest(".c-virtual-list__item") : null;
@@ -2526,44 +3384,126 @@ class ContourVirtualList extends ContourBase {
2526
3384
  class ContourCommandPalette extends ContourBase {
2527
3385
  static get observed() { return ["open", "items"]; }
2528
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
+ }
2529
3417
  render() {
2530
3418
  this.classList.add("c-command-palette");
2531
3419
  if (!this.hasAttribute("role")) this.setAttribute("role", "dialog");
2532
3420
  if (!this.hasAttribute("aria-modal")) this.setAttribute("aria-modal", "true");
2533
3421
  if (!this.hasAttribute("popover")) this.setAttribute("popover", "auto");
2534
- 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; });
2535
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 = [];
2536
3428
  const items = this.getAttribute("items");
2537
- if (items) {
2538
- try {
2539
- const parsed = JSON.parse(items);
2540
- list.innerHTML = "";
2541
- parsed.forEach((it, i) => {
2542
- const row = document.createElement("div");
2543
- row.className = "c-command-palette__item";
2544
- row.setAttribute("role", "option");
2545
- row.id = this.id + "-opt-" + i;
2546
- row.textContent = typeof it === "string" ? it : (it.label || it.title || "");
2547
- row.dataset.index = String(i);
2548
- row.dataset.label = row.textContent;
2549
- list.appendChild(row);
2550
- });
2551
- } 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;
2552
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");
2553
3486
  }
2554
- show() { if (typeof this.showPopover === "function") { try { this.showPopover(); } catch (e) {} } this.classList.add("is-open"); }
2555
- hide() { if (typeof this.hidePopover === "function") { try { this.hidePopover(); } catch (e) {} } this.classList.remove("is-open"); }
2556
3487
  toggle() { if (this.classList.contains("is-open") || this.matches(":popover-open")) this.hide(); else this.show(); }
2557
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;
2558
3493
  this._wiredCmdPalette = true;
2559
3494
  const search = () => this.querySelector(".c-command-palette__search");
2560
3495
  const list = () => this.querySelector(".c-command-palette__list");
2561
3496
  const items = () => Array.from(this.querySelectorAll(".c-command-palette__item"));
2562
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.
2563
3501
  const setActive = (idx) => {
2564
3502
  const vis = visibleItems();
2565
- vis.forEach((it, i) => it.classList.toggle("is-active", i === idx));
2566
- 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];
2567
3507
  const s = search();
2568
3508
  if (s && active) s.setAttribute("aria-activedescendant", active.id);
2569
3509
  else if (s) s.removeAttribute("aria-activedescendant");
@@ -2574,35 +3514,59 @@ class ContourCommandPalette extends ContourBase {
2574
3514
  const label = (it.dataset.label || it.textContent || "").toLowerCase();
2575
3515
  it.hidden = needle !== "" && !label.includes(needle);
2576
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;
2577
3535
  setActive(0);
2578
3536
  };
2579
3537
  const select = (it) => {
2580
3538
  if (!it) return;
2581
- this.dispatchEvent(new CustomEvent("contour:select", { bubbles: true, composed: true, detail: { index: Number(it.dataset.index), label: it.dataset.label || it.textContent } }));
2582
- try { this.hidePopover(); } catch (e) {}
2583
- 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();
2584
3546
  };
2585
- const s = search();
2586
- if (s) {
2587
- s.setAttribute("role", "combobox");
2588
- s.setAttribute("aria-autocomplete", "list");
2589
- s.setAttribute("aria-controls", list() ? list().id || "" : "");
2590
- if (!list().id) list().id = this.id + "-list";
2591
- s.setAttribute("aria-controls", list().id);
2592
- s.addEventListener("input", (e) => filter(e.target.value));
2593
- s.addEventListener("keydown", (e) => {
2594
- const vis = visibleItems();
2595
- const active = this.querySelector(".c-command-palette__item.is-active");
2596
- let idx = active ? vis.indexOf(active) : -1;
2597
- if (e.key === "ArrowDown") { e.preventDefault(); idx = Math.min(vis.length - 1, idx + 1); if (idx < 0) idx = 0; setActive(idx); }
2598
- else if (e.key === "ArrowUp") { e.preventDefault(); idx = Math.max(0, idx - 1); if (vis.length && idx < 0) idx = 0; setActive(idx); }
2599
- else if (e.key === "Home") { e.preventDefault(); setActive(0); }
2600
- else if (e.key === "End") { e.preventDefault(); setActive(vis.length - 1); }
2601
- else if (e.key === "Enter") { e.preventDefault(); if (active) select(active); }
2602
- else if (e.key === "Escape") { e.preventDefault(); try { this.hidePopover(); } catch (e) {} this.classList.remove("is-open"); }
2603
- });
2604
- }
2605
- // 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
+ });
2606
3570
  this.addEventListener("click", (e) => {
2607
3571
  const it = e.target && e.target.closest ? e.target.closest(".c-command-palette__item") : null;
2608
3572
  if (it && this.contains(it) && !it.hidden) select(it);
@@ -2610,10 +3574,14 @@ class ContourCommandPalette extends ContourBase {
2610
3574
  // focus return on close
2611
3575
  let lastFocus = null;
2612
3576
  this.addEventListener("beforetoggle", (e) => {
2613
- if (e.newState === "open") lastFocus = document.activeElement;
2614
- 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
+ }
2615
3584
  });
2616
- // Escape via popover light dismiss is handled by keydown above; also close on outside handled by popover.
2617
3585
  setActive(0);
2618
3586
  }
2619
3587
  }
@@ -2631,7 +3599,10 @@ class ContourBadgeOverflow extends ContourBase {
2631
3599
  const count = Number(this.getAttribute("count") || 0);
2632
3600
  const max = Number(this.getAttribute("max") || 3);
2633
3601
  const extra = Math.max(0, count - max);
2634
- 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();
2635
3606
  if (extra > 0) {
2636
3607
  const b = document.createElement("span");
2637
3608
  b.className = "c-badge c-badge-overflow__more";
@@ -2647,15 +3618,36 @@ class ContourBadgeOverflow extends ContourBase {
2647
3618
  * Attributes: `open`, `side`, `title`.
2648
3619
  */
2649
3620
  class ContourSideSheet extends ContourBase {
2650
- static get observed() { return ["open", "side", "title"]; }
2651
- 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"; }
2652
3634
  render() {
2653
3635
  this.classList.add("c-side-sheet");
2654
3636
  this.setAttribute("role", "dialog");
2655
- this.setAttribute("aria-modal", "true");
2656
- if (!this.hasAttribute("aria-label")) this.setAttribute("aria-label", "Side sheet");
2657
- 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";
2658
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);
2659
3651
  if (this.hasAttribute("open")) this.classList.add("is-open"); else this.classList.remove("is-open");
2660
3652
  const title = this.getAttribute("title");
2661
3653
  if (title) {
@@ -2667,10 +3659,10 @@ class ContourSideSheet extends ContourBase {
2667
3659
  if (this._wiredSideSheet) return;
2668
3660
  this._wiredSideSheet = true;
2669
3661
  let lastFocus = null;
2670
- const close = () => this.removeAttribute("open");
2671
3662
  const keyHandler = (e) => {
2672
- if (e.key === "Escape" && this.hasAttribute("open")) { e.preventDefault(); close(); return; }
2673
- 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()) {
2674
3666
  const focusables = Array.from(this.querySelectorAll("button, [href], input, select, textarea, [tabindex]:not([tabindex='-1'])")).filter((el) => !el.hasAttribute("disabled"));
2675
3667
  if (!focusables.length) { e.preventDefault(); return; }
2676
3668
  const first = focusables[0], last = focusables[focusables.length - 1];
@@ -2681,60 +3673,196 @@ class ContourSideSheet extends ContourBase {
2681
3673
  document.addEventListener("keydown", keyHandler);
2682
3674
  onDispose(this, () => document.removeEventListener("keydown", keyHandler));
2683
3675
  this.addEventListener("click", (e) => {
2684
- if (e.target === this) close();
3676
+ if (e.target === this) this.close();
2685
3677
  });
2686
- // Focus management: capture focus on open, restore on close.
2687
- const obs = new MutationObserver(() => {
2688
- 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;
2689
3686
  lastFocus = document.activeElement;
3687
+ if (this._modal()) modalContain(this, true);
2690
3688
  const first = this.querySelector("button, [href], input, select, textarea, [tabindex]:not([tabindex='-1'])");
2691
3689
  if (first) try { first.focus(); } catch (err) {}
2692
- } else if (lastFocus) {
2693
- 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) {}
2694
3696
  lastFocus = null;
3697
+ this.dispatchEvent(new CustomEvent("contour:close", { bubbles: true, composed: true }));
2695
3698
  }
2696
- });
3699
+ };
3700
+ const obs = new MutationObserver(transition);
2697
3701
  obs.observe(this, { attributes: true, attributeFilter: ["open"] });
2698
- onDispose(this, () => obs.disconnect());
3702
+ if (this.hasAttribute("open")) transition();
3703
+ onDispose(this, () => { obs.disconnect(); if (this.hasAttribute("open") && this._modal()) modalContain(this, false); });
2699
3704
  }
2700
3705
  }
2701
3706
  define("contour-side-sheet", ContourSideSheet);
2702
3707
 
2703
3708
  /**
2704
- * Tour: web component wrapper.
2705
- * 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.
2706
3716
  */
2707
3717
  class ContourTour extends ContourBase {
2708
- static get observed() { return ["steps", "current"]; }
2709
- 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
+ }
2710
3747
  render() {
2711
3748
  this.classList.add("c-tour");
2712
3749
  this.setAttribute("role", "dialog");
2713
- this.setAttribute("aria-modal", "true");
2714
- this.setAttribute("aria-label", "Tour");
2715
- const steps = this.getAttribute("steps");
2716
- const current = Number(this.getAttribute("current") || 0);
2717
- let parsed = [];
2718
- 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);
2719
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;
2720
3769
  const tip = this.ensure(".c-tour__tip", () => { const el = document.createElement("div"); el.className = "c-tour__tip"; return el; });
2721
3770
  tip.textContent = typeof step === "string" ? step : (step.text || step.title || "");
2722
- const nav = this.ensure(".c-tour__nav", () => { const el = document.createElement("div"); el.className = "c-tour__nav"; return el; });
2723
- 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; });
2724
- if (!nav.contains(next)) nav.appendChild(next);
3771
+ if (counter.nextSibling !== tip) this.insertBefore(counter, tip);
3772
+ const nav = this.ensure(".c-tour__nav", () => { const el = document.createElement("div"); el.className = "c-tour__nav c-btn-group"; return el; });
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
+ }
2725
3818
  }
2726
3819
  enhance() {
2727
3820
  if (this._wiredTour) return;
2728
3821
  this._wiredTour = true;
2729
- const nextBtn = this.querySelector(".c-tour__next");
2730
- 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;
2731
3841
  this.addEventListener("click", (e) => {
2732
- const next = e.target && e.target.closest ? e.target.closest(".c-tour__next") : null;
2733
- 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();
2734
3847
  });
2735
- 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
+ };
2736
3856
  document.addEventListener("keydown", keyHandler);
2737
- 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
+ });
2738
3866
  }
2739
3867
  }
2740
3868
  define("contour-tour", ContourTour);
@@ -2744,10 +3872,13 @@ class ContourTour extends ContourBase {
2744
3872
  * Attributes: `value`, `placeholder`, `disabled`, `error`, `help`.
2745
3873
  */
2746
3874
  class ContourTagsInput extends ContourBase {
2747
- static get observed() { return ["value", "placeholder", "disabled", "error", "help"]; }
2748
- 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" } }; }
2749
3878
  render() {
2750
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");
2751
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; });
2752
3883
  input.placeholder = this.getAttribute("placeholder") || "Add tag…";
2753
3884
  if (this.hasAttribute("disabled")) { input.setAttribute("disabled", ""); this.classList.add("is-disabled"); }
@@ -2777,33 +3908,74 @@ class ContourTagsInput extends ContourBase {
2777
3908
  chip.appendChild(rm);
2778
3909
  this.insertBefore(chip, input);
2779
3910
  });
3911
+ if (this._internals) this._syncFormValue();
2780
3912
  }
2781
3913
  enhance() {
2782
3914
  if (this._wiredTagsInput) return;
2783
3915
  this._wiredTagsInput = true;
2784
- let live = this.querySelector(".c-tags-input__live");
2785
- 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); }
2786
- 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
+ };
2787
3966
  this.addEventListener("keydown", (e) => {
2788
3967
  const input = this.querySelector(".c-tags-input__input");
2789
- if (!input) return;
3968
+ if (!input || this.hasAttribute("disabled")) return;
2790
3969
  if (e.key === "Enter" && e.target === input) {
2791
3970
  e.preventDefault();
2792
- const v = input.value.trim();
2793
- if (v) {
2794
- let tags = [];
2795
- try { tags = JSON.parse(this.getAttribute("value") || "[]"); } catch (err) { tags = (this.getAttribute("value") || "").split(",").map((s) => s.trim()).filter(Boolean); }
2796
- if (!Array.isArray(tags)) tags = [];
2797
- if (!tags.includes(v)) tags.push(v);
2798
- this.setAttribute("value", JSON.stringify(tags));
2799
- input.value = "";
2800
- announce("Added " + v);
2801
- this.dispatchEvent(new CustomEvent("contour:add", { bubbles: true, composed: true, detail: { value: v } }));
2802
- }
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]);
2803
3977
  } else if (e.key === "Backspace" && e.target === input && input.value === "") {
2804
- let tags = [];
2805
- try { tags = JSON.parse(this.getAttribute("value") || "[]"); } catch (err) { tags = (this.getAttribute("value") || "").split(",").map((s) => s.trim()).filter(Boolean); }
2806
- if (!Array.isArray(tags)) tags = [];
3978
+ const tags = readTags();
2807
3979
  if (tags.length) {
2808
3980
  const removed = tags.pop();
2809
3981
  this.setAttribute("value", JSON.stringify(tags));
@@ -2812,53 +3984,109 @@ class ContourTagsInput extends ContourBase {
2812
3984
  }
2813
3985
  }
2814
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
+ });
2815
4007
  this.addEventListener("click", (e) => {
2816
4008
  const rm = e.target && e.target.closest ? e.target.closest(".c-tags-input__remove") : null;
2817
- 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")) {
2818
4011
  const val = rm.dataset.value;
2819
- let tags = [];
2820
- try { tags = JSON.parse(this.getAttribute("value") || "[]"); } catch (err) { tags = (this.getAttribute("value") || "").split(",").map((s) => s.trim()).filter(Boolean); }
2821
- if (!Array.isArray(tags)) tags = [];
2822
- const next = tags.filter((t) => t !== val);
4012
+ const next = readTags().filter((t) => t !== val);
2823
4013
  this.setAttribute("value", JSON.stringify(next));
2824
4014
  announce("Removed " + val);
2825
4015
  this.dispatchEvent(new CustomEvent("contour:remove", { bubbles: true, composed: true, detail: { value: val } }));
2826
4016
  }
2827
4017
  });
2828
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
+ }
2829
4030
  }
2830
4031
  define("contour-tags-input", ContourTagsInput);
2831
4032
 
2832
4033
  /**
2833
- * Sortable List: web component wrapper.
2834
- * 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).
2835
4041
  */
2836
4042
  class ContourSortableList extends ContourBase {
2837
- static get updateMode() { return "keyed"; }
2838
- static get observed() { return ["items"]; }
2839
- 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" } }; }
2840
4045
  render() {
2841
4046
  this.classList.add("c-sortable-list");
2842
4047
  const list = this.ensure(".c-sortable-list__list", () => { const el = document.createElement("ul"); el.className = "c-sortable-list__list"; return el; });
2843
4048
  const items = this.getAttribute("items");
2844
4049
  let parsed = [];
2845
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;
2846
4067
  list.innerHTML = "";
2847
4068
  parsed.forEach((it, i) => {
2848
4069
  const li = document.createElement("li");
2849
4070
  li.className = "c-sortable-list__item";
2850
4071
  li.setAttribute("draggable", "true");
2851
4072
  li.dataset.index = String(i);
4073
+ const itemLabel = typeof it === "string" ? it : (it.label || it.text || "");
2852
4074
  const handle = document.createElement("span");
2853
4075
  handle.className = "c-sortable-list__handle";
2854
4076
  handle.textContent = "⋮⋮";
2855
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));
2856
4084
  handle.tabIndex = 0;
2857
4085
  li.appendChild(handle);
2858
- const label = document.createElement("span");
2859
- label.className = "c-sortable-list__label";
2860
- label.textContent = typeof it === "string" ? it : (it.label || it.text || "");
2861
- li.appendChild(label);
4086
+ const labelEl = document.createElement("span");
4087
+ labelEl.className = "c-sortable-list__label";
4088
+ labelEl.textContent = itemLabel;
4089
+ li.appendChild(labelEl);
2862
4090
  list.appendChild(li);
2863
4091
  });
2864
4092
  }
@@ -2866,11 +4094,32 @@ class ContourSortableList extends ContourBase {
2866
4094
  if (this._wiredSortableList) return;
2867
4095
  this._wiredSortableList = true;
2868
4096
  const list = () => this.querySelector(".c-sortable-list__list");
2869
- // Live region for position announcements.
2870
- let live = this.querySelector(".c-sortable-list__live");
2871
- 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); }
2872
- 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
+ };
2873
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
+ };
2874
4123
  // Pointer drag reorder.
2875
4124
  let dragFrom = null;
2876
4125
  this.addEventListener("dragstart", (e) => {
@@ -2898,7 +4147,9 @@ class ContourSortableList extends ContourBase {
2898
4147
  else l.insertBefore(fromLi, l.children[to]);
2899
4148
  const item = fromLi.querySelector(".c-sortable-list__label");
2900
4149
  announce((item ? item.textContent : "Item") + " moved to position " + (to + 1));
2901
- 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 } }));
2902
4153
  }
2903
4154
  dragFrom = null;
2904
4155
  Array.from(l.children).forEach((n) => n.classList.remove("is-dragging"));
@@ -2916,23 +4167,29 @@ class ContourSortableList extends ContourBase {
2916
4167
  if (!li) return;
2917
4168
  const l = list();
2918
4169
  const from = index(li);
2919
- if (e.key === "ArrowUp" && li.previousElementSibling) {
2920
- e.preventDefault();
2921
- l.insertBefore(li, li.previousElementSibling);
2922
- const to = index(li);
4170
+ const moved = (direction, to) => {
2923
4171
  const label = li.querySelector(".c-sortable-list__label");
2924
4172
  announce((label ? label.textContent : "Item") + " moved to position " + (to + 1));
2925
- 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 } }));
2926
4175
  this.dispatchEvent(new CustomEvent("contour:reorder", { bubbles: true, composed: true, detail: { from, to } }));
2927
- }
2928
- 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) {
2929
4182
  e.preventDefault();
2930
4183
  l.insertBefore(li.nextElementSibling, li);
2931
- const to = index(li);
2932
- const label = li.querySelector(".c-sortable-list__label");
2933
- announce((label ? label.textContent : "Item") + " moved to position " + (to + 1));
2934
- this.dispatchEvent(new CustomEvent("contour:move", { bubbles: true, composed: true, detail: { direction: "down", from, to } }));
2935
- 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);
2936
4193
  }
2937
4194
  });
2938
4195
  }
@@ -2948,6 +4205,11 @@ class ContourSwatch extends ContourBase {
2948
4205
  static get properties() { return { color: { attribute: "color" }, selected: { attribute: "selected", type: Boolean }, label: { attribute: "label" } }; }
2949
4206
  render() {
2950
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");
2951
4213
  const color = this.getAttribute("color") || "#000";
2952
4214
  this.style.setProperty("--swatch-color", color);
2953
4215
  if (this.hasAttribute("selected")) this.classList.add("is-selected");
@@ -2957,10 +4219,10 @@ class ContourSwatch extends ContourBase {
2957
4219
  this.setAttribute("aria-label", label);
2958
4220
  }
2959
4221
  if (!this.querySelector("button") && !this.querySelector("span")) {
2960
- const btn = document.createElement("button");
2961
- btn.className = "c-swatch__btn";
2962
- btn.type = "button";
2963
- 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);
2964
4226
  }
2965
4227
  }
2966
4228
  enhance() {
@@ -2969,119 +4231,206 @@ class ContourSwatch extends ContourBase {
2969
4231
  this.addEventListener("click", () => {
2970
4232
  this.dispatchEvent(new CustomEvent("contour:select", { bubbles: true, composed: true, detail: { value: this.getAttribute("color") } }));
2971
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
+ });
2972
4240
  }
2973
4241
  }
2974
4242
  define("contour-swatch", ContourSwatch);
2975
4243
 
2976
4244
  /**
2977
- * Calendar: web component wrapper.
2978
- * 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] }.
2979
4254
  */
2980
4255
  class ContourCalendar extends ContourBase {
2981
- static get observed() { return ["value"]; }
2982
- 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
+ }
2983
4269
  render() {
2984
4270
  this.classList.add("c-calendar");
2985
4271
  const now = new Date();
2986
- const year = Number(this.getAttribute("year")) || now.getFullYear();
2987
- const month = Number(this.getAttribute("month")) || now.getMonth();
4272
+ const { year, month } = this._ym();
2988
4273
  const header = this.ensure(".c-calendar__header", () => { const el = document.createElement("div"); el.className = "c-calendar__header"; return el; });
2989
4274
  header.innerHTML = "";
2990
- const prev = document.createElement("button");
2991
- 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");
2992
4282
  const title = document.createElement("span");
2993
4283
  title.className = "c-calendar__title";
2994
4284
  title.textContent = new Date(year, month, 1).toLocaleString(undefined, { month: "long", year: "numeric" });
2995
- const next = document.createElement("button");
2996
- next.type = "button"; next.className = "c-btn c-btn--sm c-calendar__next"; next.textContent = "›"; next.setAttribute("aria-label", "Next month");
2997
- 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);
2998
4288
  const grid = this.ensure(".c-calendar__grid", () => { const el = document.createElement("div"); el.className = "c-calendar__grid"; el.setAttribute("role", "grid"); return el; });
2999
4289
  grid.setAttribute("aria-label", title.textContent);
3000
4290
  grid.innerHTML = "";
3001
4291
  const first = new Date(year, month, 1);
3002
4292
  const startDay = first.getDay();
3003
4293
  const daysInMonth = new Date(year, month + 1, 0).getDate();
4294
+ const isRange = this.hasAttribute("range");
3004
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();
3005
4312
  for (let i = 0; i < startDay; i++) {
3006
4313
  const empty = document.createElement("div");
3007
4314
  empty.className = "c-calendar__day c-calendar__day--empty";
3008
- grid.appendChild(empty);
4315
+ row.appendChild(empty);
4316
+ col++;
4317
+ if (col === 7) newRow();
3009
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");
3010
4323
  for (let d = 1; d <= daysInMonth; d++) {
3011
4324
  const cell = document.createElement("button");
3012
4325
  cell.className = "c-calendar__day";
3013
4326
  cell.type = "button";
3014
4327
  cell.setAttribute("role", "gridcell");
3015
- cell.setAttribute("tabindex", "0");
3016
4328
  cell.textContent = String(d);
3017
4329
  const iso = year + "-" + String(month + 1).padStart(2, "0") + "-" + String(d).padStart(2, "0");
3018
- if (iso === selected) { cell.classList.add("is-selected"); cell.setAttribute("aria-selected", "true"); }
3019
- else cell.setAttribute("aria-selected", "false");
3020
- 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));
3021
4334
  if (iso === todayIso) cell.setAttribute("aria-current", "date");
4335
+ cell.setAttribute("tabindex", iso === focusIso ? "0" : "-1");
3022
4336
  cell.dataset.value = iso;
3023
- grid.appendChild(cell);
4337
+ row.appendChild(cell);
4338
+ col++;
4339
+ if (col === 7) newRow();
3024
4340
  }
3025
4341
  if (header.parentNode !== this) this.insertBefore(header, grid);
3026
4342
  }
3027
4343
  enhance() {
3028
4344
  if (this._wiredCalendar) return;
3029
4345
  this._wiredCalendar = true;
3030
- this.addEventListener("click", (e) => {
3031
- const prev = e.target && e.target.closest ? e.target.closest(".c-calendar__prev") : null;
3032
- const next = e.target && e.target.closest ? e.target.closest(".c-calendar__next") : null;
3033
- if (prev && this.contains(prev)) {
3034
- let m = Number(this.getAttribute("month")) || new Date().getMonth();
3035
- let y = Number(this.getAttribute("year")) || new Date().getFullYear();
3036
- m -= 1;
3037
- if (m < 0) { m = 11; y -= 1; }
3038
- this.setAttribute("month", String(m));
3039
- this.setAttribute("year", String(y));
3040
- this.render();
3041
- this.dispatchEvent(new CustomEvent("contour:change", { bubbles: true, composed: true, detail: { month: m, year: y } }));
3042
- return;
3043
- }
3044
- if (next && this.contains(next)) {
3045
- let m = Number(this.getAttribute("month")) || new Date().getMonth();
3046
- let y = Number(this.getAttribute("year")) || new Date().getFullYear();
3047
- m += 1;
3048
- if (m > 11) { m = 0; y += 1; }
4346
+ const navigate = (m, y) => {
4347
+ this.batch(() => {
3049
4348
  this.setAttribute("month", String(m));
3050
4349
  this.setAttribute("year", String(y));
3051
- this.render();
3052
- this.dispatchEvent(new CustomEvent("contour:change", { bubbles: true, composed: true, detail: { month: m, year: y } }));
3053
- return;
3054
- }
3055
- 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");
3056
4373
  if (cell && this.contains(cell) && cell.dataset.value) {
3057
- this.setAttribute("value", cell.dataset.value);
3058
- 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
+ }
3059
4390
  }
3060
4391
  });
3061
4392
  this.addEventListener("keydown", (e) => {
3062
- const cell = e.target && e.target.closest ? e.target.closest(".c-calendar__day") : null;
3063
- if (!cell || !this.contains(cell)) return;
3064
- const cells = Array.from(this.querySelectorAll(".c-calendar__day:not(.c-calendar__day--empty)"));
3065
- const idx = cells.indexOf(cell);
3066
- let next = null;
3067
- if (e.key === "ArrowRight") next = cells[idx + 1];
3068
- else if (e.key === "ArrowLeft") next = cells[idx - 1];
3069
- else if (e.key === "ArrowDown") next = cells[idx + 7];
3070
- else if (e.key === "ArrowUp") next = cells[idx - 7];
3071
- else if (e.key === "Enter" || e.key === " ") { e.preventDefault(); cell.click(); return; }
3072
- 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
+ }
3073
4419
  });
3074
4420
  }
3075
4421
  }
3076
4422
  define("contour-calendar", ContourCalendar);
3077
4423
 
3078
4424
  /**
3079
- * Carousel: web component wrapper.
3080
- * 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.
3081
4430
  */
3082
4431
  class ContourCarousel extends ContourBase {
3083
- static get observed() { return ["items", "index"]; }
3084
- 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 } }; }
3085
4434
  _items() {
3086
4435
  const items = this.getAttribute("items");
3087
4436
  let parsed = [];
@@ -3117,10 +4466,59 @@ class ContourCarousel extends ContourBase {
3117
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; });
3118
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; });
3119
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; }
3120
4500
  }
3121
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
+ }
3122
4519
  if (this._wiredCarousel) return;
3123
4520
  this._wiredCarousel = true;
4521
+ onDispose(this, () => { if (this._carouselTimer) { clearInterval(this._carouselTimer); this._carouselTimer = null; } });
3124
4522
  const go = (dir) => {
3125
4523
  const items = this._items();
3126
4524
  if (!items.length) return;
@@ -3131,16 +4529,47 @@ class ContourCarousel extends ContourBase {
3131
4529
  this.dispatchEvent(new CustomEvent("contour:change", { bubbles: true, composed: true, detail: { index: idx, direction: dir } }));
3132
4530
  };
3133
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
+ }
3134
4542
  const prev = e.target && e.target.closest ? e.target.closest(".c-carousel__prev") : null;
3135
4543
  const next = e.target && e.target.closest ? e.target.closest(".c-carousel__next") : null;
3136
- if (prev && this.contains(prev)) go("prev");
3137
- 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"); }
3138
4563
  });
4564
+ this.addEventListener("pointercancel", () => { startX = null; });
3139
4565
  this.addEventListener("keydown", (e) => {
3140
4566
  if (e.key === "ArrowLeft") { e.preventDefault(); go("prev"); }
3141
4567
  else if (e.key === "ArrowRight") { e.preventDefault(); go("next"); }
3142
- 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" } })); }
3143
- 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" } })); } }
3144
4573
  });
3145
4574
  }
3146
4575
  }
@@ -3152,8 +4581,8 @@ class ContourCarousel extends ContourBase {
3152
4581
  */
3153
4582
  class ContourDataGrid extends ContourBase {
3154
4583
  static get updateMode() { return "keyed"; }
3155
- static get observed() { return ["columns", "rows", "page", "filter", "page-size", "resizable", "virtual", "row-height"]; }
3156
- 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" } }; }
3157
4586
  render() {
3158
4587
  this.classList.add("c-data-grid");
3159
4588
  if (this.hasAttribute("loading") || this.hasAttribute("error") || this.hasAttribute("empty")) {
@@ -3173,7 +4602,7 @@ class ContourDataGrid extends ContourBase {
3173
4602
  tbody.appendChild(tr);
3174
4603
  // Wrap in a scroll container for virtualization of large datasets.
3175
4604
  let wrap = this.querySelector(".c-data-grid__wrap");
3176
- 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"; }
3177
4606
  if (table.parentNode !== wrap) wrap.appendChild(table);
3178
4607
  if (wrap.parentNode !== this) this.appendChild(wrap);
3179
4608
  return;
@@ -3234,7 +4663,7 @@ class ContourDataGrid extends ContourBase {
3234
4663
  const key = typeof c === "string" ? c : (c.key || c.label || "");
3235
4664
  const td = document.createElement("td");
3236
4665
  td.setAttribute("role", "gridcell");
3237
- td.setAttribute("tabindex", "0");
4666
+ td.setAttribute("tabindex", "-1");
3238
4667
  td.textContent = r && r[key] != null ? r[key] : "";
3239
4668
  if (!String(td.textContent).trim()) td.setAttribute("aria-label", "Empty");
3240
4669
  tr.appendChild(td);
@@ -3244,13 +4673,21 @@ class ContourDataGrid extends ContourBase {
3244
4673
  }
3245
4674
  // Wrap in a scroll container for virtualization of large datasets.
3246
4675
  let wrap = this.querySelector(".c-data-grid__wrap");
3247
- 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"; }
3248
4677
  if (table.parentNode !== wrap) wrap.appendChild(table);
3249
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
+ }
3250
4685
  }
3251
4686
  _rowHeight() {
3252
4687
  const h = Number(this.getAttribute("row-height"));
3253
- 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);
3254
4691
  }
3255
4692
  _renderDataGridWindow(scrollTop) {
3256
4693
  const table = this.querySelector(".c-data-grid__table");
@@ -3284,7 +4721,7 @@ class ContourDataGrid extends ContourBase {
3284
4721
  const key = typeof c === "string" ? c : (c.key || c.label || "");
3285
4722
  const td = document.createElement("td");
3286
4723
  td.setAttribute("role", "gridcell");
3287
- td.setAttribute("tabindex", "0");
4724
+ td.setAttribute("tabindex", "-1");
3288
4725
  td.textContent = r && r[key] != null ? r[key] : "";
3289
4726
  if (!String(td.textContent).trim()) td.setAttribute("aria-label", "Empty");
3290
4727
  tr.appendChild(td);
@@ -3300,6 +4737,12 @@ class ContourDataGrid extends ContourBase {
3300
4737
  sp.appendChild(td);
3301
4738
  tbody.appendChild(sp);
3302
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
+ }
3303
4746
  }
3304
4747
  enhance() {
3305
4748
  if (this._wiredDataGrid) return;
@@ -3329,7 +4772,13 @@ class ContourDataGrid extends ContourBase {
3329
4772
  else if (e.key === "ArrowLeft") target = row.children[ci - 1];
3330
4773
  else if (e.key === "ArrowDown") target = rows[ri + 1] && rows[ri + 1].children[ci];
3331
4774
  else if (e.key === "ArrowUp") target = rows[ri - 1] && rows[ri - 1].children[ci];
3332
- 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
+ }
3333
4782
  });
3334
4783
  this.addEventListener("click", (e) => {
3335
4784
  const tr = e.target && e.target.closest ? e.target.closest("tr") : null;
@@ -3342,28 +4791,43 @@ class ContourDataGrid extends ContourBase {
3342
4791
  const idx = Array.from(th.parentElement.children).indexOf(th);
3343
4792
  if (sortCol === idx) sortDir = sortDir === "asc" ? "desc" : "asc";
3344
4793
  else { sortCol = idx; sortDir = "asc"; }
3345
- // 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.
3346
4796
  const table = this.querySelector(".c-data-grid__table");
3347
4797
  const tbody = table && table.querySelector("tbody");
3348
4798
  const thead = table && table.querySelector("thead");
3349
- if (tbody && thead) {
3350
- const cols = Array.from(thead.querySelectorAll("th")).map((h) => h.textContent);
3351
- const rows = Array.from(tbody.querySelectorAll("tr")).map((tr) => Array.from(tr.querySelectorAll("td")).map((td) => td.textContent));
3352
- rows.sort((a, b) => {
3353
- const va = a[idx] || "", vb = b[idx] || "";
3354
- const na = Number(va), nb = Number(vb);
3355
- const cmp = (!isNaN(na) && !isNaN(nb)) ? na - nb : String(va).localeCompare(String(vb));
3356
- return sortDir === "asc" ? cmp : -cmp;
3357
- });
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); }
3358
4815
  tbody.innerHTML = "";
3359
- rows.forEach((r) => {
4816
+ pageRows.forEach((r) => {
3360
4817
  const tr = document.createElement("tr");
3361
- 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
+ });
3362
4826
  tbody.appendChild(tr);
3363
4827
  });
3364
4828
  }
3365
4829
  // Update aria-sort on headers.
3366
- Array.from(thead.querySelectorAll("th")).forEach((h, i) => {
4830
+ if (thead) Array.from(thead.querySelectorAll("th")).forEach((h, i) => {
3367
4831
  h.setAttribute("aria-sort", i === idx ? (sortDir === "asc" ? "ascending" : "descending") : "none");
3368
4832
  });
3369
4833
  this.dispatchEvent(new CustomEvent("contour:sort", { bubbles: true, composed: true, detail: { column: idx, direction: sortDir } }));
@@ -3397,8 +4861,8 @@ class ContourDataGrid extends ContourBase {
3397
4861
  */
3398
4862
  class ContourTreeGrid extends ContourBase {
3399
4863
  static get updateMode() { return "keyed"; }
3400
- static get observed() { return ["items", "expanded"]; }
3401
- 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" } }; }
3402
4866
  _expandedSet() {
3403
4867
  const raw = this.getAttribute("expanded");
3404
4868
  if (!raw) return new Set();
@@ -3450,7 +4914,12 @@ class ContourTreeGrid extends ContourBase {
3450
4914
  }
3451
4915
  };
3452
4916
  parsed.forEach((n, i) => renderNode(n, 0, String(i)));
3453
- 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);
3454
4923
  }
3455
4924
  enhance() {
3456
4925
  if (this._wiredTreeGrid) return;
@@ -3510,46 +4979,94 @@ class ContourPullToRefresh extends ContourBase {
3510
4979
  static get properties() { return { threshold: { attribute: "threshold" } }; }
3511
4980
  render() {
3512
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"));
3513
4984
  const ind = this.ensure(".c-pull-to-refresh__indicator", () => {
3514
4985
  const e = document.createElement("div");
3515
4986
  e.className = "c-pull-to-refresh__indicator";
3516
- e.textContent = "Pull to refresh";
3517
4987
  return e;
3518
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);
3519
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 }));
3520
5032
  }
3521
5033
  enhance() {
3522
5034
  if (this._wiredPullToRefresh) return;
3523
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.
3524
5041
  let startY = 0;
3525
5042
  let pulling = false;
3526
- this.addEventListener("touchstart", (e) => {
3527
- if (this.scrollTop > 0) return;
3528
- const t = e.touches && e.touches[0];
3529
- if (t) { startY = t.clientY; pulling = true; }
3530
- }, { passive: true });
3531
- 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) => {
3532
5053
  if (!pulling) return;
3533
- const t = e.touches && e.touches[0];
3534
- if (!t) return;
3535
- const dy = t.clientY - startY;
3536
- if (dy > 0 && dy < 120) {
3537
- 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");
3538
5058
  }
3539
- }, { passive: true });
3540
- this.addEventListener("touchend", (e) => {
5059
+ });
5060
+ const end = () => {
3541
5061
  if (!pulling) return;
3542
5062
  pulling = false;
3543
- const t = e.changedTouches && e.changedTouches[0];
3544
- const dy = t ? t.clientY - startY : 0;
3545
5063
  const thr = Number(this.getAttribute("threshold")) || 60;
3546
- if (dy >= thr) {
3547
- this.classList.add("is-refreshing");
3548
- this.dispatchEvent(new CustomEvent("contour:refresh", { bubbles: true, composed: true }));
3549
- setTimeout(() => this.classList.remove("is-refreshing"), 800);
3550
- }
3551
- this.style.removeProperty("--ptr-offset");
3552
- }, { 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);
3553
5070
  }
3554
5071
  }
3555
5072
  define("contour-pull-to-refresh", ContourPullToRefresh);