contour-ds 1.7.2 → 1.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +244 -326
- package/dist/agent-cookbook.json +960 -0
- package/dist/agent-examples.json +65 -0
- package/dist/agent-map-wiring.json +152 -0
- package/dist/agent-rules.json +16 -0
- package/dist/build-manifest.json +344 -126
- package/dist/contour-wc-content.esm.js +1939 -0
- package/dist/contour-wc-content.esm.min.js +1 -0
- package/dist/contour-wc-core.esm.js +3724 -0
- package/dist/contour-wc-core.esm.min.js +1 -0
- package/dist/contour-wc-dashboard.esm.js +6986 -0
- package/dist/contour-wc-dashboard.esm.min.js +1 -0
- package/dist/contour-wc-data.esm.js +6572 -0
- package/dist/contour-wc-data.esm.min.js +1 -0
- package/dist/contour-wc-docs.esm.js +976 -0
- package/dist/contour-wc-docs.esm.min.js +1 -0
- package/dist/contour-wc-feedback.esm.js +1742 -0
- package/dist/contour-wc-feedback.esm.min.js +1 -0
- package/dist/contour-wc-forms.esm.js +2437 -0
- package/dist/contour-wc-forms.esm.min.js +1 -0
- package/dist/contour-wc-interaction.esm.js +1343 -0
- package/dist/contour-wc-interaction.esm.min.js +1 -0
- package/dist/contour-wc-layout.esm.js +845 -0
- package/dist/contour-wc-layout.esm.min.js +1 -0
- package/dist/contour-wc-map.esm.js +2411 -0
- package/dist/contour-wc-map.esm.min.js +1 -0
- package/dist/contour-wc-misc.esm.js +945 -0
- package/dist/contour-wc-misc.esm.min.js +1 -0
- package/dist/contour-wc-navigation.esm.js +2842 -0
- package/dist/contour-wc-navigation.esm.min.js +1 -0
- package/dist/contour-wc-ui.esm.js +6519 -0
- package/dist/contour-wc-ui.esm.min.js +1 -0
- package/dist/contour-wc.esm.js +14435 -5723
- package/dist/contour-wc.esm.min.js +1 -1
- package/dist/contour-wc.js +14436 -5725
- package/dist/contour-wc.min.js +1 -1
- package/dist/contour.a11y.json +402 -0
- package/dist/contour.code-snippets +4534 -0
- package/dist/contour.components.json +4870 -1222
- package/dist/contour.css +6672 -4711
- package/dist/contour.d.ts +753 -1085
- package/dist/contour.esm.js +440 -18
- package/dist/contour.esm.min.js +1 -1
- package/dist/contour.html-data.json +11343 -0
- package/dist/contour.js +440 -18
- package/dist/contour.min.css +1 -1
- package/dist/contour.min.js +1 -1
- package/dist/contour.react.d.ts +422 -0
- package/dist/contour.single.html +17 -0
- package/dist/contour.single.min.css +1 -0
- package/dist/contour.themes.json +56 -12
- package/dist/contour.tokens.json +1318 -1053
- package/dist/contour.vue.d.ts +420 -0
- package/dist/contour.web-types.json +11703 -0
- package/dist/custom-elements.json +36120 -0
- package/dist/docs/actions.md +16 -6
- package/dist/docs/affordances.md +21 -85
- package/dist/docs/apireference.md +9 -5
- package/dist/docs/colour.md +10 -4
- package/dist/docs/componentindex.md +9 -22
- package/dist/docs/data.md +39 -58
- package/dist/docs/docs.md +12 -7
- package/dist/docs/feedback.md +30 -12
- package/dist/docs/field.md +28 -13
- package/dist/docs/forms.md +35 -19
- package/dist/docs/index.json +70 -61
- package/dist/docs/install.md +12 -7
- package/dist/docs/landing.md +7 -4
- package/dist/docs/mapengine.md +30 -8
- package/dist/docs/motion.md +12 -6
- package/dist/docs/navigation.md +31 -7
- package/dist/docs/overlays.md +32 -25
- package/dist/docs/overview.md +3 -2
- package/dist/docs/patterns.md +20 -10
- package/dist/docs/playground.md +11 -4
- package/dist/docs/principles.md +8 -6
- package/dist/docs/recipes.md +117 -13
- package/dist/docs/space.md +10 -6
- package/dist/docs/status.md +13 -14
- package/dist/docs/surfaces.md +17 -22
- package/dist/docs/theming.md +18 -32
- package/dist/docs/type.md +12 -5
- package/dist/docs/webcomponents.md +75 -33
- package/dist/hljs.css +1 -20
- package/dist/map-chrome.mapbox.css +68 -92
- package/dist/map-chrome.maplibre.css +68 -92
- package/dist/registry/items/contour-core.json +2 -2
- package/dist/registry/items/contour-data.json +2 -2
- package/dist/registry/items/contour-docs.json +2 -2
- package/dist/registry/items/contour-landing.json +2 -2
- package/dist/registry/registry.json +8 -8
- package/dist/surfaces/contour-core.min.css +1 -1
- package/dist/surfaces/contour-data.min.css +1 -1
- package/dist/surfaces/contour-docs.min.css +1 -1
- package/dist/surfaces/contour-landing.min.css +1 -1
- package/dist/svg/icons.svg +367 -0
- package/dist/wc/behaviours.mjs +222 -192
- package/dist/wc/content.mjs +486 -142
- package/dist/wc/core.mjs +917 -395
- package/dist/wc/dashboard.mjs +252 -25
- package/dist/wc/data-chart.mjs +1333 -0
- package/dist/wc/data-export.mjs +391 -0
- package/dist/wc/data-gauge.mjs +779 -0
- package/dist/wc/data-geo.mjs +696 -0
- package/dist/wc/data-glyphs.mjs +133 -0
- package/dist/wc/data-legend.mjs +431 -0
- package/dist/wc/data-readout.mjs +227 -0
- package/dist/wc/data-series.mjs +1004 -0
- package/dist/wc/data-table.mjs +751 -0
- package/dist/wc/data.mjs +15 -3707
- package/dist/wc/docs.mjs +113 -19
- package/dist/wc/feedback.mjs +320 -116
- package/dist/wc/forms-controls.mjs +635 -0
- package/dist/wc/forms-field.mjs +547 -0
- package/dist/wc/forms-groups.mjs +347 -0
- package/dist/wc/forms-input.mjs +292 -0
- package/dist/wc/forms.mjs +10 -1122
- package/dist/wc/glyph.mjs +204 -0
- package/dist/wc/index.mjs +16 -7
- package/dist/wc/interaction.mjs +322 -75
- package/dist/wc/layout.mjs +100 -29
- package/dist/wc/map.mjs +888 -285
- package/dist/wc/misc.mjs +137 -26
- package/dist/wc/navigation-menu.mjs +735 -0
- package/dist/wc/navigation-shell.mjs +495 -0
- package/dist/wc/navigation-tree.mjs +995 -0
- package/dist/wc/navigation.mjs +9 -1636
- package/dist/wc/registration.mjs +1 -8
- package/dist/wc/shadow.mjs +285 -113
- package/dist/wc/states.mjs +75 -78
- package/dist/wc/svg.mjs +209 -34
- package/dist/wc/ui-atoms.mjs +608 -0
- package/dist/wc/ui-data.mjs +1404 -0
- package/dist/wc/ui-feedback.mjs +419 -0
- package/dist/wc/ui-inputs.mjs +1570 -0
- package/dist/wc/ui-menus.mjs +307 -0
- package/dist/wc/ui-overlays.mjs +1605 -0
- package/integrations/README.md +25 -5
- package/integrations/ai/CLAUDE.md +6 -3
- package/integrations/ai/COPILOT.md +14 -0
- package/integrations/ai/GEMINI.md +14 -0
- package/integrations/ai/WINDSURF.md +14 -0
- package/integrations/ai/v0-prompt.md +13 -1
- package/integrations/frameworks/README.md +235 -0
- package/integrations/native/README.md +0 -3
- package/integrations/native/style-dictionary.config.json +1 -1
- package/integrations/tailwind/contour-theme.css +71 -13
- package/integrations/validate-markup.mjs +172 -0
- package/package.json +103 -39
- package/dist/wc/ui.mjs +0 -3560
|
@@ -0,0 +1,3724 @@
|
|
|
1
|
+
export var CONTOUR_VERSION = "1.9.0";
|
|
2
|
+
/* CONTOUR Web Components — two light-DOM layers over ds.css blocks; publishes the frozen `window.ContourElements` registry. */
|
|
3
|
+
"use strict";
|
|
4
|
+
|
|
5
|
+
/** Names registered by this module, in registration order. */
|
|
6
|
+
export const REGISTERED = [];
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* R31-38: a real scroller is an element whose computed overflow is
|
|
10
|
+
* auto/scroll AND that actually overflows. The re-render layout pass used to
|
|
11
|
+
* read scrollHeight/clientHeight on EVERY element (4,018 layout reads per
|
|
12
|
+
* 500-row density change); the overflow pre-check is a style query (no
|
|
13
|
+
* layout) and short-circuits, so the layout reads happen only on scrollers.
|
|
14
|
+
*/
|
|
15
|
+
const isScroller = (el) => {
|
|
16
|
+
if (typeof getComputedStyle !== "function") return false;
|
|
17
|
+
const s = getComputedStyle(el);
|
|
18
|
+
if (s.overflowY !== "auto" && s.overflowY !== "scroll" && s.overflowX !== "auto" && s.overflowX !== "scroll") return false;
|
|
19
|
+
return el.scrollHeight > el.clientHeight || el.scrollWidth > el.clientWidth;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
// Anything a host starts against the document (fetch, timer, observer) registers
|
|
23
|
+
// cleanup here; `disconnectedCallback` runs the list, one disposal per mount.
|
|
24
|
+
const DISPOSERS = new WeakMap();
|
|
25
|
+
/** Register teardown work for the host's current connection. */
|
|
26
|
+
export const onDispose = (host, fn) => {
|
|
27
|
+
let list = DISPOSERS.get(host);
|
|
28
|
+
if (!list) { list = []; DISPOSERS.set(host, list); }
|
|
29
|
+
list.push(fn);
|
|
30
|
+
};
|
|
31
|
+
function contourDebugEnabled() {
|
|
32
|
+
try {
|
|
33
|
+
if (typeof window !== "undefined" && (window.ContourDebug || window.__CONTOUR_DEBUG__)) return true;
|
|
34
|
+
} catch (e) {}
|
|
35
|
+
try {
|
|
36
|
+
if (typeof process !== "undefined" && process.env && process.env.NODE_ENV !== "production" && process.env.CONTOUR_DEBUG) return true;
|
|
37
|
+
} catch (e) {}
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
const runDisposers = (host) => {
|
|
41
|
+
const list = DISPOSERS.get(host);
|
|
42
|
+
if (!list) return;
|
|
43
|
+
DISPOSERS.delete(host);
|
|
44
|
+
for (const fn of list) {
|
|
45
|
+
try { fn(); }
|
|
46
|
+
catch (e) {
|
|
47
|
+
// One bad cleanup cannot strand the rest. Surface the failure in
|
|
48
|
+
// development/debug mode so a leaking disposer is not invisible.
|
|
49
|
+
if (contourDebugEnabled()) {
|
|
50
|
+
try { console.warn("Contour disposer failed for", host && host.tagName, e); } catch (err) {}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
// Monotonic counter for unique IDs (avoids Math.random() collision risk).
|
|
57
|
+
let _contourIdCounter = 0;
|
|
58
|
+
/** Return a unique, document-safe id with the supplied prefix. */
|
|
59
|
+
export const contourId = (prefix) => prefix + "-" + (++_contourIdCounter).toString(36);
|
|
60
|
+
|
|
61
|
+
/** Define a custom element once, while remaining safe in SSR runtimes. */
|
|
62
|
+
export const define = (name, cls) => {
|
|
63
|
+
// No-op when the Custom Elements registry is unavailable (SSR-safe); the tag
|
|
64
|
+
// stays unknown until a browser defines it.
|
|
65
|
+
if (typeof customElements === "undefined" || !customElements || typeof customElements.define !== "function") return;
|
|
66
|
+
if (customElements.get(name)) return;
|
|
67
|
+
// Opt-in lazy hydration (data-hydrate="lazy"): definitions defer until near viewport; REGISTERED names only handed elements.
|
|
68
|
+
if (typeof window !== "undefined" && typeof window.__contourDefineDefer === "function" && window.__contourDefineDefer(name, cls)) return;
|
|
69
|
+
customElements.define(name, cls);
|
|
70
|
+
REGISTERED.push(name);
|
|
71
|
+
// Publish on every registration: raw-fragment imports never load shadow.mjs, so each slice is frozen and current.
|
|
72
|
+
if (typeof window !== "undefined") {
|
|
73
|
+
window.ContourElements = Object.freeze(REGISTERED.slice());
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
// One list for both layers — a separate modifier list is how light and shadow
|
|
78
|
+
// drifted apart over "color".
|
|
79
|
+
/** Attribute names that map to component modifier classes. */
|
|
80
|
+
export const MODS = ["variant", "size", "color"];
|
|
81
|
+
|
|
82
|
+
// The count — the gate compares emitted names against this object, so no
|
|
83
|
+
// number is written anywhere else; payload keys are the union across sites.
|
|
84
|
+
/**
|
|
85
|
+
* Sentinel type for JSON-typed reflected properties (R24-90). A property
|
|
86
|
+
* declared `type: JSON_TYPE` serialises objects/arrays with JSON.stringify and
|
|
87
|
+
* parses JSON-looking attribute values back on read, so a framework that
|
|
88
|
+
* assigns `el.items = [{label:"Alpha"}]` writes a JSON string instead of
|
|
89
|
+
* "[object Object]".
|
|
90
|
+
*/
|
|
91
|
+
const JSON_TYPE = Symbol("JSON");
|
|
92
|
+
|
|
93
|
+
/** Frozen event vocabulary with the public detail keys for each event. */
|
|
94
|
+
export const CONTOUR_EVENTS = Object.freeze({
|
|
95
|
+
"contour:activate": { payload: ["files", "label", "row", "value"], composed: true },
|
|
96
|
+
"contour:add": { payload: ["value"], composed: true },
|
|
97
|
+
"contour:activity-clear": { payload: [], composed: true },
|
|
98
|
+
"contour:activity-filter": { payload: ["unread"], composed: true },
|
|
99
|
+
"contour:activity-select": { payload: ["index", "text"], composed: true },
|
|
100
|
+
"contour:rendered": { payload: ["renderCount"], composed: true },
|
|
101
|
+
"contour:cap": { payload: ["series", "total", "shown"], composed: true },
|
|
102
|
+
"contour:action": { payload: ["label"], composed: true },
|
|
103
|
+
"contour:break-change": { payload: ["layer", "value"], composed: true },
|
|
104
|
+
"contour:style-resolved": { payload: ["applied", "classification", "colors", "items", "layer", "n", "palette", "property", "value"], composed: true },
|
|
105
|
+
"contour:advanced-toggle": { payload: ["title"], composed: true },
|
|
106
|
+
"contour:affordance-activate": { payload: ["name"], composed: true },
|
|
107
|
+
"contour:aggregate": { payload: ["aggregate"], composed: true },
|
|
108
|
+
"contour:bearing": { payload: ["direction", "degrees"], composed: true },
|
|
109
|
+
"contour:btn-group-change": { payload: ["index", "label"], composed: true },
|
|
110
|
+
"contour:brush-start": { payload: ["end", "range", "start", "value"], composed: true },
|
|
111
|
+
"contour:brush-end": { payload: ["end", "range", "start", "value"], composed: true },
|
|
112
|
+
"contour:brush": { payload: ["end", "range", "start", "value"], composed: true },
|
|
113
|
+
"contour:change": { payload: ["checked", "color", "direction", "end", "files", "high", "index", "low", "month", "name", "paused", "query", "speed", "start", "unit", "value", "values", "year"], composed: true },
|
|
114
|
+
"contour:collapse": { payload: ["collapsed"], composed: true },
|
|
115
|
+
"contour:cluster-toggle": { payload: ["count", "expanded"], composed: true },
|
|
116
|
+
"contour:clear": { payload: [], composed: true },
|
|
117
|
+
"contour:clear-all": { payload: [], composed: true },
|
|
118
|
+
"contour:close": { payload: ["count", "index", "label", "message", "open", "value"], composed: true },
|
|
119
|
+
"contour:copy": { payload: ["text"], composed: true },
|
|
120
|
+
"contour:apply": { payload: ["name"], composed: true },
|
|
121
|
+
"contour:dash-action": { payload: ["label"], composed: true },
|
|
122
|
+
"contour:diff-activate": { payload: ["kind", "text"], composed: true },
|
|
123
|
+
"contour:dismiss": { payload: ["label"], composed: true },
|
|
124
|
+
"contour:draw-start": { payload: ["mode"], composed: true },
|
|
125
|
+
"contour:drag": { payload: ["delta", "key", "value"], composed: true },
|
|
126
|
+
"contour:do-dont-activate": { payload: ["kind", "text"], composed: true },
|
|
127
|
+
"contour:docs-nav-select": { payload: ["label", "href"], composed: true },
|
|
128
|
+
"contour:dragend": { payload: ["value"], composed: true },
|
|
129
|
+
"contour:dragstart": { payload: ["value"], composed: true },
|
|
130
|
+
"contour:drop": { payload: ["value", "label"], composed: true },
|
|
131
|
+
"contour:empty-action": { payload: ["state"], composed: true },
|
|
132
|
+
"contour:filter": { payload: ["query"], composed: true },
|
|
133
|
+
"contour:filter-change": { payload: ["source", "filter"], composed: true },
|
|
134
|
+
"contour:error": { payload: ["src", "message", "name", "status"], composed: true },
|
|
135
|
+
"contour:export": { payload: ["format"], composed: true },
|
|
136
|
+
"contour:refresh": { payload: [], composed: true },
|
|
137
|
+
"contour:hide": { payload: [], composed: true, deprecated: "use contour:close instead" },
|
|
138
|
+
"contour:hover": { payload: ["row"], composed: true },
|
|
139
|
+
"contour:input": { payload: ["name", "value", "checked"], composed: true },
|
|
140
|
+
"contour:invalid": { payload: ["field", "input", "message"], composed: true, cancelable: true },
|
|
141
|
+
"contour:inspect-action": { payload: ["label", "value"], composed: true },
|
|
142
|
+
"contour:layer-opacity": { payload: ["layerId", "name", "opacity"], composed: true },
|
|
143
|
+
"contour:layer-rename": { payload: ["layerId", "name", "newName"], composed: true },
|
|
144
|
+
"contour:layer-duplicate": { payload: ["layerId", "name"], composed: true },
|
|
145
|
+
"contour:layer-zoom": { payload: ["layerId", "name"], composed: true },
|
|
146
|
+
"contour:zoom": { payload: ["data", "index", "row"], composed: true },
|
|
147
|
+
"contour:layer-projection": { payload: ["layerId", "name", "projection"], composed: true },
|
|
148
|
+
"contour:layer-remove": { payload: ["layerId", "name"], composed: true },
|
|
149
|
+
"contour:layer-reorder": { payload: ["layerIds"], composed: true },
|
|
150
|
+
"contour:layer-toggle": { payload: ["layerId", "name", "visible"], composed: true },
|
|
151
|
+
"contour:layer-visibility": { payload: ["layerId", "name", "visible"], composed: true },
|
|
152
|
+
"contour:legend-toggle": { payload: ["index", "key", "label", "pressed"], composed: true },
|
|
153
|
+
"contour:leave": { payload: [], composed: true },
|
|
154
|
+
"contour:load": { payload: ["src", "count"], composed: true },
|
|
155
|
+
"contour:map-control": { payload: ["control"], composed: true },
|
|
156
|
+
"contour:map-style": { payload: ["style", "name"], composed: true },
|
|
157
|
+
"contour:map-attach": { payload: [], composed: true },
|
|
158
|
+
"contour:map-ready": { payload: [], composed: true },
|
|
159
|
+
"contour:map-detach": { payload: [], composed: true },
|
|
160
|
+
"contour:map-popup-reposition": { payload: ["anchor", "flippedX", "flippedY", "left", "top"], composed: true },
|
|
161
|
+
"contour:map-viewport": { payload: ["crossesAntimeridian", "west", "south", "east", "north", "zoom", "center"], composed: true },
|
|
162
|
+
"contour:mode-change": { payload: ["mode"], composed: true },
|
|
163
|
+
"contour:scope-change": { payload: ["scope"], composed: true },
|
|
164
|
+
"contour:move": { payload: ["direction", "from", "to", "dx", "dy"], composed: true },
|
|
165
|
+
"contour:open": { payload: [], composed: true },
|
|
166
|
+
"contour:page": { payload: ["page"], composed: true },
|
|
167
|
+
"contour:ready": { payload: ["version", "count"], composed: true },
|
|
168
|
+
"contour:read": { payload: ["label"], composed: true },
|
|
169
|
+
"contour:remove": { payload: ["key", "label", "name", "value"], composed: true },
|
|
170
|
+
"contour:reorder": { payload: ["from", "to"], composed: true },
|
|
171
|
+
"contour:range-change": { payload: ["value"], composed: true },
|
|
172
|
+
"contour:resize": { payload: ["column", "delta", "height", "value", "width"], composed: true },
|
|
173
|
+
"contour:retry": { payload: ["src"], composed: true },
|
|
174
|
+
"contour:loop-change": { payload: ["loop"], composed: true },
|
|
175
|
+
"contour:pause": { payload: [], composed: true },
|
|
176
|
+
"contour:play": { payload: [], composed: true },
|
|
177
|
+
"contour:seek": { payload: ["progress", "value"], composed: true },
|
|
178
|
+
"contour:select": { payload: ["area", "col", "expanded", "href", "index", "key", "label", "labels", "level", "path", "range", "result", "row", "rows", "series", "value"], composed: true },
|
|
179
|
+
"contour:search": { payload: ["query"], composed: true },
|
|
180
|
+
"contour:spatial-filter": { payload: ["action", "mode", "operator"], composed: true },
|
|
181
|
+
"contour:split-change": { payload: ["value", "width", "height"], composed: true },
|
|
182
|
+
"contour:speed-change": { payload: ["speed"], composed: true },
|
|
183
|
+
"contour:showcase-activate": { payload: ["title"], composed: true },
|
|
184
|
+
"contour:step-activate": { payload: ["index", "title"], composed: true },
|
|
185
|
+
"contour:step-change": { payload: ["direction", "index", "title"], composed: true },
|
|
186
|
+
"contour:show": { payload: [], composed: true, deprecated: "use contour:open instead" },
|
|
187
|
+
"contour:sort": { payload: ["column", "direction"], composed: true },
|
|
188
|
+
"contour:column-toggle": { payload: ["column", "visible"], composed: true },
|
|
189
|
+
"contour:submit": { payload: ["submitting"], composed: true },
|
|
190
|
+
"contour:stream-state": { payload: ["running"], composed: true },
|
|
191
|
+
"contour:tab-change": { payload: ["index", "label"], composed: true },
|
|
192
|
+
"contour:theme-change": { payload: ["theme"], composed: true },
|
|
193
|
+
"contour:tick": { payload: ["frame"], composed: true },
|
|
194
|
+
"contour:time-change": { payload: ["progress", "value"], composed: true },
|
|
195
|
+
"contour:time-range-change": { payload: ["value"], composed: true },
|
|
196
|
+
"contour:toggle": { payload: ["collapsed", "expanded", "label", "open", "path", "playing"], composed: true },
|
|
197
|
+
"contour:view-enter": { payload: [], composed: true },
|
|
198
|
+
"contour:view-leave": { payload: [], composed: true },
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
// DOMParser allowlist (blocklist regexes let `javascript:` variants through); `style` dropped (UI-redress), colour via safeColor.
|
|
202
|
+
const SANITIZE_DROP = new Set(["script", "iframe", "object", "embed", "style", "link", "meta", "base", "form", "input", "button"]);
|
|
203
|
+
const SANITIZE_ANIMATE = new Set(["animate", "animatemotion", "animatetransform", "set", "discard"]);
|
|
204
|
+
const SANITIZE_URL_ATTRS = new Set(["href", "src", "xlink:href", "from", "to", "values", "by", "attributename"]);
|
|
205
|
+
/**
|
|
206
|
+
* Normalise a candidate URL the way the URL parser does before testing its
|
|
207
|
+
* scheme: strip ASCII tab/newline/CR anywhere, strip leading and trailing C0
|
|
208
|
+
* controls and spaces, then percent-decode. `javascript:…` and
|
|
209
|
+
* `java\tscript:…` both collapse to `javascript:` here.
|
|
210
|
+
*
|
|
211
|
+
* @param {string} value raw attribute value
|
|
212
|
+
* @returns {string} the normalised candidate, lowercased
|
|
213
|
+
*/
|
|
214
|
+
function normalizeUrlCandidate(value) {
|
|
215
|
+
let v = String(value == null ? "" : value);
|
|
216
|
+
v = v.replace(/[\t\n\r]/g, "");
|
|
217
|
+
// Leading C0 controls and spaces are what `trim()` misses and the URL
|
|
218
|
+
// parser drops; trailing ones are harmless but stripped for symmetry.
|
|
219
|
+
v = v.replace(/^[\u0000-\u0020]+/, "").replace(/[\u0000-\u0020]+$/, "");
|
|
220
|
+
try { v = decodeURIComponent(v); } catch (e) { /* malformed escape: test as-is */ }
|
|
221
|
+
return v.toLowerCase();
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Whether a URL attribute value names a scheme the sanitizer refuses.
|
|
225
|
+
*
|
|
226
|
+
* @param {string} value raw attribute value
|
|
227
|
+
* @returns {boolean} true when the value must be removed
|
|
228
|
+
*/
|
|
229
|
+
function isUnsafeUrl(value) {
|
|
230
|
+
const v = normalizeUrlCandidate(value);
|
|
231
|
+
// Strip any remaining embedded controls so `java\tscript:` cannot re-form
|
|
232
|
+
// after decoding, then test the scheme prefix.
|
|
233
|
+
const flat = v.replace(/[\u0000-\u001f\u007f]/g, "");
|
|
234
|
+
return flat.startsWith("javascript:") || flat.startsWith("vbscript:") || flat.startsWith("data:text/html") || flat.startsWith("data:image/svg+xml");
|
|
235
|
+
}
|
|
236
|
+
/** Sanitize consumer-provided HTML using a DOM allowlist. */
|
|
237
|
+
export function sanitizeHtml(input) {
|
|
238
|
+
const str = String(input == null ? "" : input);
|
|
239
|
+
// Fail closed when no parser is available (SSR): return input as inert text, never treat "no parser" as trusted markup.
|
|
240
|
+
if (typeof DOMParser === "undefined") {
|
|
241
|
+
return str.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
242
|
+
}
|
|
243
|
+
const doc = new DOMParser().parseFromString(str, "text/html");
|
|
244
|
+
const walk = (node) => {
|
|
245
|
+
// Snapshot: the loop mutates the child list (removals, template walks).
|
|
246
|
+
const children = Array.from(node.childNodes);
|
|
247
|
+
for (const c of children) {
|
|
248
|
+
if (c.nodeType !== 1) continue;
|
|
249
|
+
const tag = c.tagName.toLowerCase();
|
|
250
|
+
if (SANITIZE_DROP.has(tag)) { c.remove(); continue; }
|
|
251
|
+
// SMIL animation can rewrite a URL-bearing attribute after the walk,
|
|
252
|
+
// so the element goes before its target attribute is ever read.
|
|
253
|
+
if (SANITIZE_ANIMATE.has(tag)) {
|
|
254
|
+
const attrNames = Array.from(c.attributes).map((a) => a.name.toLowerCase());
|
|
255
|
+
const target = String(c.getAttribute("attributename") || "").toLowerCase();
|
|
256
|
+
const carriesUrl = attrNames.some((n) => SANITIZE_URL_ATTRS.has(n));
|
|
257
|
+
if (carriesUrl || SANITIZE_URL_ATTRS.has(target)) { c.remove(); continue; }
|
|
258
|
+
}
|
|
259
|
+
for (const attr of Array.from(c.attributes)) {
|
|
260
|
+
const name = attr.name.toLowerCase();
|
|
261
|
+
if (name.startsWith("on")) { c.removeAttribute(attr.name); continue; }
|
|
262
|
+
if (name === "style") { c.removeAttribute(attr.name); continue; }
|
|
263
|
+
if (name === "srcdoc") { c.removeAttribute(attr.name); continue; }
|
|
264
|
+
if (SANITIZE_URL_ATTRS.has(name) && isUnsafeUrl(attr.value)) { c.removeAttribute(attr.name); }
|
|
265
|
+
}
|
|
266
|
+
// `<template>` keeps its markup in a separate document fragment, so
|
|
267
|
+
// the walk has to descend into `.content` explicitly.
|
|
268
|
+
if (tag === "template") { walk(c.content || c); continue; }
|
|
269
|
+
walk(c);
|
|
270
|
+
}
|
|
271
|
+
};
|
|
272
|
+
walk(doc.body);
|
|
273
|
+
return doc.body.innerHTML;
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* Validate a CSS colour for use in an inline style.
|
|
277
|
+
*
|
|
278
|
+
* Returns the trimmed value when it is a plain colour (named, hex, or a
|
|
279
|
+
* known colour function) and an empty string otherwise. Anything that could
|
|
280
|
+
* break out of the declaration, load a resource, or run script is rejected,
|
|
281
|
+
* so a consumer-supplied `color` attribute cannot become an injection sink.
|
|
282
|
+
*
|
|
283
|
+
* @param {unknown} value candidate colour
|
|
284
|
+
* @returns {string} the safe colour, or "" when rejected
|
|
285
|
+
*/
|
|
286
|
+
export function safeColor(value) {
|
|
287
|
+
const raw = String(value == null ? "" : value).trim();
|
|
288
|
+
if (!raw) return "";
|
|
289
|
+
if (/[;{}<>"'`\\]/.test(raw)) return "";
|
|
290
|
+
if (/url\s*\(/i.test(raw) || /expression\s*\(/i.test(raw)) return "";
|
|
291
|
+
if (/^#[0-9a-f]{3,8}$/i.test(raw)) return raw;
|
|
292
|
+
if (/^(rgb|rgba|hsl|hsla|hwb|lab|lch|oklab|oklch|color)\(/i.test(raw)) return raw;
|
|
293
|
+
// Token-driven colours are the system's own vocabulary: `var(--color-…)`, `light-dark(…)` and `color-mix(…)` are all le...
|
|
294
|
+
if (/^(var|light-dark|color-mix)\(/i.test(raw)) {
|
|
295
|
+
let depth = 0;
|
|
296
|
+
for (let i = 0; i < raw.length; i++) {
|
|
297
|
+
const ch = raw[i];
|
|
298
|
+
if (ch === "(") depth++;
|
|
299
|
+
else if (ch === ")") { depth--; if (depth < 0) return ""; }
|
|
300
|
+
}
|
|
301
|
+
return depth === 0 ? raw : "";
|
|
302
|
+
}
|
|
303
|
+
if (/^[a-z]+$/i.test(raw)) return raw;
|
|
304
|
+
return "";
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* Resolve an href candidate to a value that is safe to assign to a sink.
|
|
308
|
+
*
|
|
309
|
+
* Fragments, relative paths and the schemes we can vouch for pass through
|
|
310
|
+
* unchanged; `javascript:`, `data:` and any other scheme collapse to "#".
|
|
311
|
+
* This closes the attribute-to-property path that `sanitizeHtml` does not
|
|
312
|
+
* cover, because assigning `a.href = "javascript:…"` executes on click.
|
|
313
|
+
*
|
|
314
|
+
* @param {unknown} value candidate href
|
|
315
|
+
* @returns {string} the safe href, or "#"
|
|
316
|
+
*/
|
|
317
|
+
export function safeHref(value) {
|
|
318
|
+
const raw = String(value == null ? "" : value).trim();
|
|
319
|
+
if (!raw) return "#";
|
|
320
|
+
if (raw.startsWith("#") || raw.startsWith("/") || raw.startsWith("./") || raw.startsWith("../") || raw.startsWith("?")) return raw;
|
|
321
|
+
if (typeof document === "undefined" || !document.baseURI) return "#";
|
|
322
|
+
try {
|
|
323
|
+
const url = new URL(raw, document.baseURI);
|
|
324
|
+
return ["http:", "https:", "mailto:", "tel:"].includes(url.protocol) ? raw : "#";
|
|
325
|
+
} catch (e) {
|
|
326
|
+
return "#";
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* Read a length token from the document root, in pixels.
|
|
331
|
+
*
|
|
332
|
+
* Virtualized components used to hard-code 36/32/28 px row heights, which
|
|
333
|
+
* disagreed with the rendered row and ignored density. The height is now a
|
|
334
|
+
* token (`--data-grid-row-height`, …) and this reads its computed value.
|
|
335
|
+
*
|
|
336
|
+
* @param {string} name custom-property name
|
|
337
|
+
* @param {number} fallback pixels to use when the token is absent or invalid
|
|
338
|
+
* @returns {number} the resolved length in pixels
|
|
339
|
+
*/
|
|
340
|
+
export function cssLength(name, fallback) {
|
|
341
|
+
if (typeof getComputedStyle === "undefined" || typeof document === "undefined") return fallback;
|
|
342
|
+
const v = parseFloat(getComputedStyle(document.documentElement).getPropertyValue(name));
|
|
343
|
+
return Number.isFinite(v) && v > 0 ? v : fallback;
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* Surface a malformed JSON attribute instead of swallowing it.
|
|
347
|
+
*
|
|
348
|
+
* A bare `catch (e) { /* keep existing *\/ }` turns a typo in a component
|
|
349
|
+
* attribute into a silent no-op: the render keeps whatever was there before
|
|
350
|
+
* and the defect is invisible. This warns once, with the component name and
|
|
351
|
+
* the parser message, so the author can find it.
|
|
352
|
+
*
|
|
353
|
+
* @param {Element|null} host the component that owns the attribute
|
|
354
|
+
* @param {string} label the attribute (or a short description)
|
|
355
|
+
* @param {unknown} error the thrown parse error
|
|
356
|
+
*/
|
|
357
|
+
export function warnBadJson(host, label, error) {
|
|
358
|
+
if (typeof console === "undefined" || !console.warn) return;
|
|
359
|
+
const name = host && host.tagName ? host.tagName.toLowerCase() : "component";
|
|
360
|
+
const msg = (error && error.message) || String(error);
|
|
361
|
+
console.warn(`[contour] ${name}: malformed ${label || "attribute"} — ${msg}`);
|
|
362
|
+
}
|
|
363
|
+
// contract: an attribute that is not here cannot ask an element to re-render, and an attribute a component WRITES to it...
|
|
364
|
+
/** Shared attribute vocabulary used by components that opt into defaults. */
|
|
365
|
+
export const OBSERVED = [
|
|
366
|
+
"accept", "action", "actions", "active", "after", "allow-duplicate", "allow-remove", "allow-rename", "allow-zoom", "alpha", "anchor", "answer", "area", "article", "attribution", "attribution-mark", "audit", "autoplay", "axis", "axis-x", "axis-y", "brownout", "brownout-level", "before", "body", "brand", "bounds", "breakpoint", "breaks", "brush", "brush-end", "brush-max", "brush-min", "brush-start", "cache-key", "canvas", "center", "clearable", "cols", "columns", "color", "command",
|
|
367
|
+
"cells", "checked", "chrome", "confidence", "coverage", "debounce", "closable", "collapsed", "collapsible", "classification", "continuous", "content", "controls", "copyable", "count", "data", "data-table", "date", "delta", "description", "glyphs", "graduated", "demo", "density", "desc", "dir", "direction", "disabled", "distance", "dismissible", "divider", "do", "dont", "dot", "ends", "high", "input", "layer", "low", "mode", "modes", "n", "opacity", "palette", "polarity", "precision", "range", "single",
|
|
368
|
+
"empty", "exclusive", "fallback", "filename", "format", "heading", "help", "hint", "href", "icon", "illustration", "instrument", "interval", "items", "key", "layers", "level", "markers",
|
|
369
|
+
"label", "labels", "latitude", "lazy", "lede", "legend", "left-label", "right-label", "line", "limit", "link", "links", "live", "loading", "locale", "loop", "max", "media", "message", "method", "methodology", "menu", "min", "multiple", "name", "needle", "next", "no", "no-cache", "no-data-message", "nodes", "note", "norm",
|
|
370
|
+
"options", "orientation", "page-size", "pages", "pause", "paused", "pausable", "persist", "placeholder", "playing", "point", "points", "prev", "presets", "prompt", "question", "recent", "required",
|
|
371
|
+
"quote", "ramp", "refresh", "removable", "resolution", "reverse", "rings", "retry", "results", "rows", "scale", "selectable", "segments", "show-header", "sparkline", "threshold", "thresholds", "selected", "separator", "series", "shortcut", "side", "size", "skeleton", "sort", "sort-dir", "status", "step", "submit", "submitting", "timeout", "trigger", "virtual", "sticky", "cluster-count", "cluster-expanded", "time", "resizable",
|
|
372
|
+
"state", "steps", "style", "subtitle", "summary", "src", "source", "table", "tabs", "tag", "text", "ticks", "title", "type", "unread-only", "unit", "updated", "row-height",
|
|
373
|
+
"variant", "values", "viewport", "warning", "yes", "zoom", "zoomable",
|
|
374
|
+
"caption", "current-time", "is-playing", "loop-label", "no-data-color", "no-data-label", "property", "show-loop", "show-thumb", "show-thumb-caption", "speeds", "item-height", "pause-label", "play-label", "speed-label", "time-label", "shimmer",
|
|
375
|
+
"search",
|
|
376
|
+
"numbered",
|
|
377
|
+
"bucket-count", "limit-values",
|
|
378
|
+
"autocomplete", "levels", "submit-label",
|
|
379
|
+
"fields", "gap",
|
|
380
|
+
"flush", "head", "preview", "tags", "url",
|
|
381
|
+
"custom-error",
|
|
382
|
+
];
|
|
383
|
+
|
|
384
|
+
/** Resolve an authored heading level while keeping the fallback valid. */
|
|
385
|
+
export function headingTag(host, fallback = "h3") {
|
|
386
|
+
const v = host && host.getAttribute ? host.getAttribute("heading") : null;
|
|
387
|
+
return /^h[1-6]$/.test(v || "") ? v : fallback;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* Read a boolean attribute the way an author means it.
|
|
392
|
+
*
|
|
393
|
+
* `hasAttribute()` answers "is it there", not "is it on": a consumer who
|
|
394
|
+
* writes `closable="false"` or `sparkline="0"` from a template still has the
|
|
395
|
+
* attribute, so a presence test renders the close button / the sparkline they
|
|
396
|
+
* explicitly switched off (F-RO19, F-RO20, F-FC11). The HTML boolean
|
|
397
|
+
* convention is presence-only, but these attributes are commonly rendered by
|
|
398
|
+
* frameworks that stringify `false`, so the explicit negative values win.
|
|
399
|
+
*
|
|
400
|
+
* A bare attribute (`closable`) is present with an empty value and is ON —
|
|
401
|
+
* that is the HTML boolean convention, and treating `""` as off broke every
|
|
402
|
+
* plain `closable` in the guide.
|
|
403
|
+
*/
|
|
404
|
+
export function flagOn(host, name) {
|
|
405
|
+
if (!host || !host.getAttribute) return false;
|
|
406
|
+
const raw = host.getAttribute(name);
|
|
407
|
+
if (raw === null) return false;
|
|
408
|
+
const v = raw.trim().toLowerCase();
|
|
409
|
+
return v !== "0" && v !== "false" && v !== "no" && v !== "off" && v !== "null" && v !== "undefined";
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/**
|
|
413
|
+
* R24-91: Resolve a boolean value the way an author means it, for the
|
|
414
|
+
* property-setter path. `el.disabled = "false"` must turn the feature OFF
|
|
415
|
+
* (string negatives route through the same vocabulary as flagOn), while
|
|
416
|
+
* `el.disabled = true` turns it ON. The attribute path keeps HTML presence
|
|
417
|
+
* semantics (`disabled="false"` stays ON) — that's a deliberate judgment call
|
|
418
|
+
* (R24-83), not a bug.
|
|
419
|
+
*/
|
|
420
|
+
export function flagOnValue(v) {
|
|
421
|
+
if (v === null || v === undefined || v === false) return false;
|
|
422
|
+
if (typeof v === "string") {
|
|
423
|
+
const s = v.trim().toLowerCase();
|
|
424
|
+
return s !== "0" && s !== "false" && s !== "no" && s !== "off" && s !== "null" && s !== "undefined";
|
|
425
|
+
}
|
|
426
|
+
return Boolean(v);
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/** R31-148: the default shape for a status variant, so a state never rides
|
|
430
|
+
* on hue alone. `icon="none"` is the explicit opt-out at each call site. */
|
|
431
|
+
export function statusIcon(variant) {
|
|
432
|
+
switch (String(variant || "").toLowerCase()) {
|
|
433
|
+
case "success": return "i-check-circle";
|
|
434
|
+
case "warning": return "i-alert";
|
|
435
|
+
case "danger":
|
|
436
|
+
case "error": return "i-x";
|
|
437
|
+
case "info":
|
|
438
|
+
case "note":
|
|
439
|
+
case "tip":
|
|
440
|
+
case "accent": return "i-info";
|
|
441
|
+
default: return "";
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/**
|
|
446
|
+
* R24-93: Emit an overlay visibility event. `contour:open`/`contour:close`
|
|
447
|
+
* are the canonical pair; `contour:show`/`contour:hide` are deprecated
|
|
448
|
+
* aliases emitted alongside for one minor release with a console warning
|
|
449
|
+
* (per the repo's deprecation policy). `contour:toggle` is kept for
|
|
450
|
+
* non-visibility transitions (tree expansion, accordion, sidebar collapse)
|
|
451
|
+
* and is not aliased here.
|
|
452
|
+
*
|
|
453
|
+
* Consumers listening to `show`/`hide` will still receive their event during
|
|
454
|
+
* the deprecation window, but each emission logs a warning directing them to
|
|
455
|
+
* migrate to `open`/`close`. The aliases are removed in v2.0.
|
|
456
|
+
*/
|
|
457
|
+
export function wcEmitOverlay(host, type, detail) {
|
|
458
|
+
if (!host || !host.dispatchEvent) return;
|
|
459
|
+
const isOpen = type === "contour:open";
|
|
460
|
+
const isClose = type === "contour:close";
|
|
461
|
+
if (!isOpen && !isClose) {
|
|
462
|
+
host.dispatchEvent(new CustomEvent(type, { detail, bubbles: true, composed: true }));
|
|
463
|
+
return;
|
|
464
|
+
}
|
|
465
|
+
// Canonical event first.
|
|
466
|
+
host.dispatchEvent(new CustomEvent(type, { detail, bubbles: true, composed: true }));
|
|
467
|
+
// Deprecated alias with a one-minor deprecation warning.
|
|
468
|
+
const alias = isOpen ? "contour:show" : "contour:hide";
|
|
469
|
+
console.warn(
|
|
470
|
+
`[Contour] ${alias} is deprecated, use ${type} instead. ` +
|
|
471
|
+
`Will be removed in v2.0. (host: ${host.tagName || host.constructor.name})`
|
|
472
|
+
);
|
|
473
|
+
host.dispatchEvent(new CustomEvent(alias, { detail, bubbles: true, composed: true }));
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/**
|
|
477
|
+
* Resolve a localised label for a host (R18-63). A consumer supplies a
|
|
478
|
+
* `labels` JSON attribute (e.g. `labels='{"clear":"Effacer"}'`); it is merged
|
|
479
|
+
* over the English `fallback`, so a partial object localises only the keys it
|
|
480
|
+
* names. A malformed attribute is ignored rather than thrown — a bad label
|
|
481
|
+
* must not take the widget down. Returns `fallback` when no override exists.
|
|
482
|
+
*/
|
|
483
|
+
export function labelText(host, key, fallback) {
|
|
484
|
+
const def = fallback !== undefined ? fallback : key;
|
|
485
|
+
const raw = host && host.getAttribute ? host.getAttribute("labels") : null;
|
|
486
|
+
if (!raw) return def;
|
|
487
|
+
try {
|
|
488
|
+
const parsed = JSON.parse(raw);
|
|
489
|
+
if (parsed && typeof parsed === "object" && typeof parsed[key] === "string" && parsed[key]) return parsed[key];
|
|
490
|
+
} catch (e) { /* a malformed labels attribute is ignored, not fatal */ }
|
|
491
|
+
return def;
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/**
|
|
495
|
+
* R31-147: the one way to write a sprite icon. Every icon-only control used
|
|
496
|
+
* to inline the same `<svg><use href="#i-…">` string; a helper keeps the
|
|
497
|
+
* shape (and the aria-hidden) in one place, so a new glyph cannot forget it.
|
|
498
|
+
*
|
|
499
|
+
* @param {string} id symbol id, e.g. "i-check"
|
|
500
|
+
* @returns {string} svg markup
|
|
501
|
+
*/
|
|
502
|
+
export function iconMarkup(id) {
|
|
503
|
+
return '<svg aria-hidden="true" viewBox="0 0 24 24"><use href="#' + id + '" /></svg>';
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/**
|
|
507
|
+
* R31-160: write markup through a Trusted Types policy, when the page has one.
|
|
508
|
+
*
|
|
509
|
+
* The system has ~86 `innerHTML` sinks. Under
|
|
510
|
+
* `Content-Security-Policy: require-trusted-types-for 'script'` a raw
|
|
511
|
+
* `el.innerHTML = "..."` throws even for a constant string, because the sink
|
|
512
|
+
* demands a TrustedHTML. This helper is the one place that crosses that
|
|
513
|
+
* boundary: it routes the string through a named policy (`contour-html`) whose
|
|
514
|
+
* `createHTML` is the identity for the strings this system already controls
|
|
515
|
+
* (constants, `sanitizeHtml()` output, `iconMarkup()`), so a page that sets
|
|
516
|
+
* the policy is satisfied and a page that does not is unaffected.
|
|
517
|
+
*
|
|
518
|
+
* The policy is created lazily and only when `window.trustedTypes` exists, so
|
|
519
|
+
* a browser without Trusted Types (or a page without the CSP) takes the plain
|
|
520
|
+
* path. It never installs a global default policy — a consumer that wants to
|
|
521
|
+
* audit every sink names its own policy and this helper uses it if present.
|
|
522
|
+
*/
|
|
523
|
+
let _contourHtmlPolicy = null;
|
|
524
|
+
export function setHTML(el, html) {
|
|
525
|
+
if (!el) return;
|
|
526
|
+
const empty = html == null || html === "";
|
|
527
|
+
if (!empty && typeof window !== "undefined" && window.trustedTypes && typeof window.trustedTypes.createPolicy === "function") {
|
|
528
|
+
if (!_contourHtmlPolicy) {
|
|
529
|
+
try { _contourHtmlPolicy = window.trustedTypes.createPolicy("contour-html", { createHTML: (s) => s }); }
|
|
530
|
+
catch (e) { _contourHtmlPolicy = null; /* a consumer already named it */ }
|
|
531
|
+
}
|
|
532
|
+
el.innerHTML = _contourHtmlPolicy ? _contourHtmlPolicy.createHTML(html) : html;
|
|
533
|
+
return;
|
|
534
|
+
}
|
|
535
|
+
el.innerHTML = empty ? "" : html;
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
/**
|
|
539
|
+
* Write localised copy onto a node without stealing an author's words (R18-63).
|
|
540
|
+
*
|
|
541
|
+
* `labelText()` resolves the string; this decides whether the node may take it.
|
|
542
|
+
* A node the component generated on an earlier render carries
|
|
543
|
+
* `data-contour-label`, so a `labels` change reaches it. A node the AUTHOR
|
|
544
|
+
* wrote — a `.c-saved-view__apply` button with its own text, a
|
|
545
|
+
* `.c-spatial-filter__clear-all` — has no such mark and keeps its words,
|
|
546
|
+
* because a default must never overwrite copy a consumer chose.
|
|
547
|
+
*
|
|
548
|
+
* This exists because the rule is not obvious and the failure is silent: an
|
|
549
|
+
* unconditional `node.textContent = labelText(...)` looks like the fix and is a
|
|
550
|
+
* regression for every consumer who supplied their own button.
|
|
551
|
+
*/
|
|
552
|
+
export function applyLabel(node, host, key, fallback) {
|
|
553
|
+
if (!node) return;
|
|
554
|
+
if (node.dataset && node.dataset.contourLabel === "true") {
|
|
555
|
+
node.textContent = labelText(host, key, fallback);
|
|
556
|
+
} else if (!node.textContent) {
|
|
557
|
+
node.textContent = labelText(host, key, fallback);
|
|
558
|
+
if (node.dataset) node.dataset.contourLabel = "true";
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
/**
|
|
563
|
+
* Base class for all Contour web components.
|
|
564
|
+
*
|
|
565
|
+
* Lifecycle: the first `connectedCallback` snapshots the author's nodes and
|
|
566
|
+
* class attribute, then calls `render()`. On attribute change, the snapshot
|
|
567
|
+
* is restored and `render()` runs again, so subclasses stay reactive.
|
|
568
|
+
*
|
|
569
|
+
* All components use light DOM so that `ds.css` styles apply directly.
|
|
570
|
+
*/
|
|
571
|
+
// Base class: the lifecycle belongs here, the markup belongs to the subclass. A render body is written to run more than...
|
|
572
|
+
const _ContourBaseParent = (typeof HTMLElement !== "undefined") ? HTMLElement : Object;
|
|
573
|
+
// R31-39: constructors whose property accessors are already installed.
|
|
574
|
+
const INSTALLED_PROPS = new WeakSet();
|
|
575
|
+
export class ContourBase extends _ContourBaseParent {
|
|
576
|
+
static formAssociated = false;
|
|
577
|
+
constructor() {
|
|
578
|
+
super();
|
|
579
|
+
if (this.constructor.formAssociated && typeof this.attachInternals === "function") {
|
|
580
|
+
this._internals = this.attachInternals();
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
// Per-component observed attributes. Subclasses override `static get observed()` with only the attributes they read; th...
|
|
584
|
+
static get observed() {
|
|
585
|
+
return OBSERVED;
|
|
586
|
+
}
|
|
587
|
+
/**
|
|
588
|
+
* The attribute list the platform is told about.
|
|
589
|
+
*
|
|
590
|
+
* `labels` is appended here rather than left to each subclass's `observed`,
|
|
591
|
+
* because the reader is a SHARED helper: `labelText()` below resolves copy for
|
|
592
|
+
* whichever component asks, so a per-class list has to remember it once per
|
|
593
|
+
* class or a `labels` change silently does nothing on every host that forgot.
|
|
594
|
+
* That is exactly how it stood — one component listed it and eleven did not.
|
|
595
|
+
* A component that writes `labels` to itself would recurse, and none does.
|
|
596
|
+
*/
|
|
597
|
+
static get observedAttributes() {
|
|
598
|
+
const list = this.observed;
|
|
599
|
+
return list.includes("labels") ? list : [...list, "labels"];
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
// Subclasses override to declare reflected properties: static get properties() { return { value: { attribute: "value", ...
|
|
603
|
+
static get properties() {
|
|
604
|
+
return {};
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
// Update policy : "scaffold" components may rebuild their generated DOM on attribute change (the default lifecycle). Hi...
|
|
608
|
+
static get updateMode() {
|
|
609
|
+
return "scaffold";
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
// Brownout helpers : components read their degraded level from the `brownout` / `brownout-level` attribute and shed non...
|
|
613
|
+
brownoutLevel() {
|
|
614
|
+
const raw = this.getAttribute("brownout-level") || this.getAttribute("brownout") || "0";
|
|
615
|
+
const n = parseInt(raw, 10);
|
|
616
|
+
return Number.isFinite(n) ? n : 0;
|
|
617
|
+
}
|
|
618
|
+
shed(kind, threshold) {
|
|
619
|
+
return this.brownoutLevel() >= (threshold || 1);
|
|
620
|
+
}
|
|
621
|
+
// Read-only and diagnostic: it exists so a page can show that `batch()` did what it claims instead of asking the reader...
|
|
622
|
+
get renderCount() {
|
|
623
|
+
return this._contourRenderCount || 0;
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
/**
|
|
627
|
+
* Resolves one microtask after the last render has settled (render →
|
|
628
|
+
* enhance → restore for a re-render, render → enhance for a first paint).
|
|
629
|
+
* Read it when a caller needs the measured result of an attribute change —
|
|
630
|
+
* a box that has been laid out, a control that exists — instead of waiting
|
|
631
|
+
* on a timer. Also announced as `contour:rendered`; a caller may listen for
|
|
632
|
+
* the event when it holds the element before it is connected.
|
|
633
|
+
*/
|
|
634
|
+
get updateComplete() {
|
|
635
|
+
return this._renderTicket || Promise.resolve(this);
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
// R31-93: a re-render is synchronous, but its *effects* are not observable
|
|
639
|
+
// from outside, so consumers reached for `setTimeout(50)`. One microtask
|
|
640
|
+
// after the render settles, the promise resolves and the event fires with
|
|
641
|
+
// the render count that produced it.
|
|
642
|
+
_announceRendered() {
|
|
643
|
+
// The count is read now: two renders in one task each announce, and the
|
|
644
|
+
// later one would otherwise relabel the earlier event with its own count.
|
|
645
|
+
const renderCount = this.renderCount;
|
|
646
|
+
this._renderTicket = new Promise((resolve) => {
|
|
647
|
+
queueMicrotask(() => {
|
|
648
|
+
this._renderTicket = null;
|
|
649
|
+
resolve(this);
|
|
650
|
+
if (!this.isConnected) return;
|
|
651
|
+
this.dispatchEvent(new CustomEvent("contour:rendered", {
|
|
652
|
+
bubbles: true,
|
|
653
|
+
composed: true,
|
|
654
|
+
detail: { renderCount },
|
|
655
|
+
}));
|
|
656
|
+
});
|
|
657
|
+
});
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
_countRender() {
|
|
661
|
+
this._contourRenderCount = (this._contourRenderCount || 0) + 1;
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
// Install accessors once per class, so `el.value = 42` writes the attribute
|
|
665
|
+
// and triggers the normal re-render path instead of being a silent no-op.
|
|
666
|
+
// R31-39: track installed constructors in a module-level WeakSet, not a
|
|
667
|
+
// static flag read through the prototype chain. A subclass that installs
|
|
668
|
+
// after its parent saw the inherited `true` and skipped its own property
|
|
669
|
+
// declarations, so a child-only property was missing on pages that
|
|
670
|
+
// instantiated the parent first.
|
|
671
|
+
_installProperties() {
|
|
672
|
+
const ctor = this.constructor;
|
|
673
|
+
if (INSTALLED_PROPS.has(ctor)) return;
|
|
674
|
+
INSTALLED_PROPS.add(ctor);
|
|
675
|
+
const props = ctor.properties || {};
|
|
676
|
+
const declared = new Set();
|
|
677
|
+
// R24-90: JSON-typed property support. When a framework sets `el.items = [{label:"Alpha"}]`, the setter must write a JS...
|
|
678
|
+
const serialize = (v) => (typeof v === "object" && v !== null) ? JSON.stringify(v) : String(v);
|
|
679
|
+
const deserialize = (raw) => {
|
|
680
|
+
if (raw === null) return null;
|
|
681
|
+
const t = raw.trim();
|
|
682
|
+
if (t.startsWith("[") || t.startsWith("{")) {
|
|
683
|
+
try { return JSON.parse(t); } catch { /* not JSON, return raw */ }
|
|
684
|
+
}
|
|
685
|
+
return raw;
|
|
686
|
+
};
|
|
687
|
+
for (const [name, spec] of Object.entries(props)) {
|
|
688
|
+
const attr = (spec && spec.attribute) || name;
|
|
689
|
+
declared.add(attr);
|
|
690
|
+
const type = (spec && spec.type) || String;
|
|
691
|
+
Object.defineProperty(ctor.prototype, name, {
|
|
692
|
+
get() {
|
|
693
|
+
const raw = this.getAttribute(attr);
|
|
694
|
+
// R31-37: a boolean property must agree with what render() draws.
|
|
695
|
+
// The render path reads flags through flagOn()/flagOnValue(), which
|
|
696
|
+
// treat "false"/"0"/"off" as OFF; returning `raw !== null` here made
|
|
697
|
+
// `el.closable` true for `closable="false"` while the close button
|
|
698
|
+
// was absent. Presence with a false-y string is off.
|
|
699
|
+
if (type === Boolean) return flagOnValue(raw);
|
|
700
|
+
if (raw === null) return spec && spec.default !== undefined ? spec.default : null;
|
|
701
|
+
if (type === Number) { const n = Number(raw); return Number.isNaN(n) ? null : n; }
|
|
702
|
+
if (type === JSON_TYPE) return deserialize(raw);
|
|
703
|
+
return raw;
|
|
704
|
+
},
|
|
705
|
+
set(v) {
|
|
706
|
+
if (v === null || v === undefined || v === false) this.removeAttribute(attr);
|
|
707
|
+
else if (type === Boolean) {
|
|
708
|
+
// R24-91: route string negatives ("false", "0", "no", "off", …) through the flagOn vocabulary so el.disabled = "false" ...
|
|
709
|
+
if (!flagOnValue(v)) this.removeAttribute(attr);
|
|
710
|
+
else this.setAttribute(attr, "");
|
|
711
|
+
}
|
|
712
|
+
else this.setAttribute(attr, serialize(v));
|
|
713
|
+
},
|
|
714
|
+
configurable: true,
|
|
715
|
+
});
|
|
716
|
+
}
|
|
717
|
+
// Default reflection : every observed attribute a component reads but does not declare in properties() still gets an ac...
|
|
718
|
+
const observed = ctor.observedAttributes;
|
|
719
|
+
for (const attr of observed) {
|
|
720
|
+
if (declared.has(attr)) continue;
|
|
721
|
+
const prop = attr.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
|
|
722
|
+
if (!/^[a-zA-Z_$][\w$]*$/.test(prop)) continue;
|
|
723
|
+
if (prop in ctor.prototype) continue; // an inherited accessor already exists
|
|
724
|
+
const isBool = attr === "disabled" || attr === "checked" || attr === "required" || attr === "readonly" || attr === "multiple" || attr === "selected" || attr === "open" || attr === "hidden";
|
|
725
|
+
Object.defineProperty(ctor.prototype, prop, {
|
|
726
|
+
get() {
|
|
727
|
+
const raw = this.getAttribute(attr);
|
|
728
|
+
// R31-37: same as the declared-property getter — a reflected boolean
|
|
729
|
+
// agrees with the rendered state, not with raw presence.
|
|
730
|
+
if (isBool) return flagOnValue(raw);
|
|
731
|
+
return deserialize(raw);
|
|
732
|
+
},
|
|
733
|
+
set(v) {
|
|
734
|
+
if (v === null || v === undefined || v === false) this.removeAttribute(attr);
|
|
735
|
+
else if (isBool) {
|
|
736
|
+
// R24-91: route string negatives through the flagOn vocabulary.
|
|
737
|
+
if (!flagOnValue(v)) this.removeAttribute(attr);
|
|
738
|
+
else this.setAttribute(attr, "");
|
|
739
|
+
}
|
|
740
|
+
else this.setAttribute(attr, serialize(v));
|
|
741
|
+
},
|
|
742
|
+
configurable: true,
|
|
743
|
+
});
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
connectedCallback() {
|
|
748
|
+
if (this._contourAuthored) {
|
|
749
|
+
// R24-01 / R28-09: reconnected, not re-specified. Reset _wired* flags and re-run enhance() so disposables (document/win...
|
|
750
|
+
this._wireFormData();
|
|
751
|
+
for (const key of Object.keys(this)) {
|
|
752
|
+
// CI-11: _wiredFormData and _wiredValueTracking are NOT reset here.
|
|
753
|
+
// Their listeners live on the host and survive a disconnect (they are
|
|
754
|
+
// added outside _runEnhance, so _contourHostListeners does not track
|
|
755
|
+
// them and disconnectedCallback does not remove them). Resetting the
|
|
756
|
+
// flag would re-add a duplicate pair on every reconnect. _wireFormData
|
|
757
|
+
// re-wires against a new form owner via its own disposer; value
|
|
758
|
+
// tracking is host-bound and needs no re-wire.
|
|
759
|
+
if (key.startsWith("_wired") && key !== "_wiredFormData" && key !== "_wiredValueTracking") {
|
|
760
|
+
this[key] = false;
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
// R24-01 residue (INF-5/6): re-render on reconnect, not just re-enhance. disconnectedCallback cleared _remoteStatus/_re...
|
|
764
|
+
this.attributeChangedCallback("__contour_reconnect__", null, "");
|
|
765
|
+
return;
|
|
766
|
+
}
|
|
767
|
+
this._installProperties();
|
|
768
|
+
this._contourAuthored = {
|
|
769
|
+
nodes: Array.from(this.childNodes),
|
|
770
|
+
};
|
|
771
|
+
// R31-02: the base owns only the classes IT generates, never the whole
|
|
772
|
+
// `class` attribute. A framework's state class, `hidden`, a Tailwind
|
|
773
|
+
// utility or any app-owned modifier added after mount must survive a
|
|
774
|
+
// re-render; the old code restored a frozen snapshot and deleted them.
|
|
775
|
+
this._contourOwnedClasses = new Set();
|
|
776
|
+
// R24-02: mark authored nodes so the refresh can find them inside generated wrappers. A component that moves authored c...
|
|
777
|
+
for (const n of this._contourAuthored.nodes) {
|
|
778
|
+
if (n.nodeType === 1) n.setAttribute("data-contour-authored", "");
|
|
779
|
+
}
|
|
780
|
+
const before = Array.from(this.childNodes);
|
|
781
|
+
this._contourRenderGen = (this._contourRenderGen || 0) + 1;
|
|
782
|
+
this._ensureCache = new Map();
|
|
783
|
+
this._ensureCacheGen = this._contourRenderGen;
|
|
784
|
+
this._countRender();
|
|
785
|
+
const _preRenderClasses = new Set(Array.from(this.classList));
|
|
786
|
+
try { this.render(); }
|
|
787
|
+
catch (e) { console.error("Contour render error:", e); this.textContent = labelText(this, "render-error", "Component failed to render."); }
|
|
788
|
+
this._contourGenerated = Array.from(this.childNodes).filter((n) => !before.includes(n));
|
|
789
|
+
// R31-02: the classes render() just added are the ones this component
|
|
790
|
+
// owns; remember them so the next render removes only those.
|
|
791
|
+
this._contourOwnedClasses = new Set(Array.from(this.classList).filter((c) => !_preRenderClasses.has(c)));
|
|
792
|
+
this._applyDensity();
|
|
793
|
+
this._runEnhance();
|
|
794
|
+
this._detachInnerFormControls();
|
|
795
|
+
this._wireFormData();
|
|
796
|
+
this._wireValueTracking();
|
|
797
|
+
this._announceRendered();
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
attributeChangedCallback(name, oldValue, newValue) {
|
|
801
|
+
if (oldValue === newValue) return;
|
|
802
|
+
// Fires before connectedCallback during an upgrade: nothing to reset to
|
|
803
|
+
// yet, and connectedCallback will render with the final attributes.
|
|
804
|
+
if (!this.isConnected || !this._contourAuthored) return;
|
|
805
|
+
// Opt-in batching: when inside batch(), attribute changes are coalesced into a single render that fires when the batch ...
|
|
806
|
+
if (this._batchDepth > 0) {
|
|
807
|
+
this._batchDirty = true;
|
|
808
|
+
return;
|
|
809
|
+
}
|
|
810
|
+
// Re-entrant change (an attribute set while a render is in flight): do not drop it, defer a single re-render to the nex...
|
|
811
|
+
if (this._contourRendering) {
|
|
812
|
+
if (!this._pendingRerender) {
|
|
813
|
+
this._pendingRerender = true;
|
|
814
|
+
queueMicrotask(() => {
|
|
815
|
+
this._pendingRerender = false;
|
|
816
|
+
if (!this.isConnected || !this._contourAuthored) return;
|
|
817
|
+
// Re-run with a sentinel old value so the equality guard does not
|
|
818
|
+
// short-circuit; the render reads current attribute values.
|
|
819
|
+
this.attributeChangedCallback("__rerender__", null, "");
|
|
820
|
+
});
|
|
821
|
+
}
|
|
822
|
+
return;
|
|
823
|
+
}
|
|
824
|
+
if (name === "checked") this._checkedAttrChanged = true;
|
|
825
|
+
this._contourRendering = true;
|
|
826
|
+
try {
|
|
827
|
+
// Preserve form control values across a re-render: generated inputs are dropped and rebuilt, so without this a host att...
|
|
828
|
+
const savedControls = Array.from(this.querySelectorAll("input, textarea, select"));
|
|
829
|
+
const savedValues = savedControls.map((el) => ({
|
|
830
|
+
key: el.name || el.id || null,
|
|
831
|
+
preserveKey: el.getAttribute("data-contour-preserve-key") || null,
|
|
832
|
+
value: el.value,
|
|
833
|
+
checked: el.checked,
|
|
834
|
+
type: el.type,
|
|
835
|
+
// User-dirty tracking (R20 T-02): a control the user edited keeps its value until the host's `value` attribute changes....
|
|
836
|
+
dirty: !!el._contourUserDirty,
|
|
837
|
+
attrAtDirty: el._contourAttrAtDirty,
|
|
838
|
+
selected: el.tagName === "SELECT" && el.multiple ? Array.from(el.selectedOptions).map((o) => o.value) : null,
|
|
839
|
+
}));
|
|
840
|
+
// Preserve focus, scroll position and <details> open state across the rebuild, so a host attribute change does not yank...
|
|
841
|
+
const hadFocus = this.contains(document.activeElement) ? document.activeElement : null;
|
|
842
|
+
// Capture a recovery key for unkeyed active elements: an id is the strongest key, then a `data-contour-preserve-key`, t...
|
|
843
|
+
const _focusableSelector = "button, [href], input, select, textarea, [tabindex]:not([tabindex='-1'])";
|
|
844
|
+
const _focusablesBefore = Array.from(this.querySelectorAll(_focusableSelector));
|
|
845
|
+
const hadFocusIndex = hadFocus ? _focusablesBefore.indexOf(hadFocus) : -1;
|
|
846
|
+
const hadFocusKey = hadFocus ? (hadFocus.id || null) : null;
|
|
847
|
+
const hadFocusPreserveKey = hadFocus ? (hadFocus.getAttribute("data-contour-preserve-key") || null) : null;
|
|
848
|
+
const hadFocusName = hadFocus ? (hadFocus.getAttribute("name") || null) : null;
|
|
849
|
+
const savedScrolls = Array.from(this.querySelectorAll("*")).filter(isScroller).map((el) => ({ el, id: el.id || null, preserveKey: el.getAttribute("data-contour-preserve-key") || null, top: el.scrollTop, left: el.scrollLeft }));
|
|
850
|
+
const savedDetails = Array.from(this.querySelectorAll("details")).map((d) => ({ id: d.id || null, preserveKey: d.getAttribute("data-contour-preserve-key") || null, open: d.open }));
|
|
851
|
+
// Unwrap authored content from generated wrappers before dropping them, so an attribute re-render cannot destroy author...
|
|
852
|
+
for (const g of (this._contourGenerated || [])) {
|
|
853
|
+
if (!g || g.parentNode !== this) continue;
|
|
854
|
+
let wrapper = null;
|
|
855
|
+
if (g.classList && (g.classList.contains("c-panel__body") || g.classList.contains("c-dialog__body") || g.classList.contains("c-popover__body") || g.classList.contains("c-map-popup__body") || g.classList.contains("c-hover-card__body") || g.classList.contains("c-drawer__body") || g.classList.contains("c-sheet__body") || g.classList.contains("c-alert__body"))) wrapper = g;
|
|
856
|
+
else if (g.tagName === "PRE") wrapper = g.querySelector("code") || g;
|
|
857
|
+
if (wrapper) {
|
|
858
|
+
while (wrapper.firstChild) this.insertBefore(wrapper.firstChild, g);
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
// Drop generated nodes from the previous render. Drop generated nodes from the previous render — except the ones the co...
|
|
862
|
+
const persistent = this._contourPersistent;
|
|
863
|
+
const isPersistent = (n) => !!(persistent && persistent.size && persistent.has(n));
|
|
864
|
+
// R24-02: before dropping a generated wrapper, extract any authored children it holds back to the host. A component tha...
|
|
865
|
+
const authoredSet = new Set(this._contourAuthored.nodes || []);
|
|
866
|
+
for (const g of (this._contourGenerated || [])) {
|
|
867
|
+
if (isPersistent(g)) continue;
|
|
868
|
+
// Extract authored children before dropping the wrapper.
|
|
869
|
+
for (const child of Array.from(g.childNodes)) {
|
|
870
|
+
if (authoredSet.has(child)) {
|
|
871
|
+
g.parentNode.insertBefore(child, g);
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
if (g.parentNode === this) this.removeChild(g);
|
|
875
|
+
}
|
|
876
|
+
// Refresh the authored snapshot so content added after connect survives. Persistent nodes are generated, not authored: ...
|
|
877
|
+
const generated = new Set(this._contourGenerated || []);
|
|
878
|
+
const authoredNow = Array.from(this.childNodes).filter((n) => !generated.has(n) && !isPersistent(n));
|
|
879
|
+
// Find authored nodes inside generated wrappers.
|
|
880
|
+
for (const g of (this._contourGenerated || [])) {
|
|
881
|
+
if (isPersistent(g)) continue;
|
|
882
|
+
const marked = g.querySelectorAll ? g.querySelectorAll("[data-contour-authored]") : [];
|
|
883
|
+
for (const m of marked) {
|
|
884
|
+
if (!authoredNow.includes(m)) authoredNow.push(m);
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
this._contourAuthored.nodes = authoredNow;
|
|
888
|
+
// Clear and restore authored nodes. Persistent nodes stay connected: they are lifted to the end of the child list and t...
|
|
889
|
+
const kept = Array.from(this.childNodes).filter(isPersistent);
|
|
890
|
+
for (const node of kept) this.appendChild(node); // move to end, no detach
|
|
891
|
+
while (this.firstChild && !isPersistent(this.firstChild)) this.removeChild(this.firstChild);
|
|
892
|
+
for (const node of this._contourAuthored.nodes) this.insertBefore(node, this.firstChild && isPersistent(this.firstChild) ? this.firstChild : null);
|
|
893
|
+
for (const node of kept) this.appendChild(node); // re-assert order after authored inserts
|
|
894
|
+
// R31-02: remove only the classes the previous render generated, then
|
|
895
|
+
// let render() re-add them. Authored and app-added classes are left
|
|
896
|
+
// untouched, so a consumer's own classList edits survive every render.
|
|
897
|
+
for (const c of this._contourOwnedClasses) this.classList.remove(c);
|
|
898
|
+
const _preRenderClasses = new Set(Array.from(this.classList));
|
|
899
|
+
const before = Array.from(this.childNodes);
|
|
900
|
+
this._contourRenderGen = (this._contourRenderGen || 0) + 1;
|
|
901
|
+
this._ensureCache = new Map();
|
|
902
|
+
this._ensureCacheGen = this._contourRenderGen;
|
|
903
|
+
this._countRender();
|
|
904
|
+
try { this.render(); }
|
|
905
|
+
catch (e) { console.error("Contour render error:", e); this.textContent = labelText(this, "render-error", "Component failed to render."); }
|
|
906
|
+
this._contourGenerated = Array.from(this.childNodes).filter((n) => !before.includes(n));
|
|
907
|
+
// R31-02: remember the classes this render added, so the next pass
|
|
908
|
+
// removes only those and never a consumer's own class.
|
|
909
|
+
this._contourOwnedClasses = new Set(Array.from(this.classList).filter((c) => !_preRenderClasses.has(c)));
|
|
910
|
+
this._applyDensity();
|
|
911
|
+
// Restore preserved form control values. A re-render that adds or removes a control must not wipe the rest: keyed contr...
|
|
912
|
+
const newControls = Array.from(this.querySelectorAll("input, textarea, select"));
|
|
913
|
+
const keyed = savedValues.filter((sv) => sv.key || sv.preserveKey);
|
|
914
|
+
const unkeyed = savedValues.filter((sv) => !sv.key && !sv.preserveKey);
|
|
915
|
+
const used = new Set();
|
|
916
|
+
for (const el of newControls) {
|
|
917
|
+
const key = el.name || el.id || el.getAttribute("data-contour-preserve-key") || null;
|
|
918
|
+
if (!key) continue;
|
|
919
|
+
const match = keyed.find((sv) => (sv.key === key || sv.preserveKey === key) && !used.has(sv));
|
|
920
|
+
if (!match) continue;
|
|
921
|
+
used.add(match);
|
|
922
|
+
if (!this._contourResetting) this._restoreControlValue(el, match);
|
|
923
|
+
if ((el.type === "checkbox" || el.type === "radio") && typeof match.checked === "boolean" && !this._checkedAttrChanged && !this._contourResetting) {
|
|
924
|
+
el.checked = match.checked;
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
// Restore unkeyed controls by type-aware index matching: group saved unkeyed controls by type, then match new unkeyed c...
|
|
928
|
+
const savedByType = new Map();
|
|
929
|
+
for (const sv of unkeyed) {
|
|
930
|
+
const group = savedByType.get(sv.type) || [];
|
|
931
|
+
group.push(sv);
|
|
932
|
+
savedByType.set(sv.type, group);
|
|
933
|
+
}
|
|
934
|
+
const usedByType = new Map();
|
|
935
|
+
for (const el of newControls) {
|
|
936
|
+
if (el.name || el.id) continue;
|
|
937
|
+
const type = el.type;
|
|
938
|
+
const group = savedByType.get(type) || [];
|
|
939
|
+
const used = usedByType.get(type) || 0;
|
|
940
|
+
if (used >= group.length) continue;
|
|
941
|
+
const saved = group[used];
|
|
942
|
+
usedByType.set(type, used + 1);
|
|
943
|
+
if (!this._contourResetting) this._restoreControlValue(el, saved);
|
|
944
|
+
if ((el.type === "checkbox" || el.type === "radio") && typeof saved.checked === "boolean" && !this._checkedAttrChanged && !this._contourResetting) {
|
|
945
|
+
el.checked = saved.checked;
|
|
946
|
+
}
|
|
947
|
+
}
|
|
948
|
+
// Restore <details> open state. A disclosure carries an `id` when it is stable across renders (a faq item, a doc sectio...
|
|
949
|
+
const newDetails = Array.from(this.querySelectorAll("details"));
|
|
950
|
+
const keyedDetails = savedDetails.filter((sd) => sd.id || sd.preserveKey);
|
|
951
|
+
const usedIds = new Set();
|
|
952
|
+
for (const d of newDetails) {
|
|
953
|
+
const id = d.id || null;
|
|
954
|
+
const preserveKey = d.getAttribute("data-contour-preserve-key") || null;
|
|
955
|
+
if (!id && !preserveKey) continue;
|
|
956
|
+
const match = keyedDetails.find((sd) => (sd.id === id || sd.preserveKey === preserveKey) && !usedIds.has(sd.id || sd.preserveKey));
|
|
957
|
+
if (!match) continue;
|
|
958
|
+
usedIds.add(match.id || match.preserveKey);
|
|
959
|
+
d.open = match.open;
|
|
960
|
+
}
|
|
961
|
+
let di = 0;
|
|
962
|
+
const plainSaved = savedDetails.filter((sd) => !sd.id);
|
|
963
|
+
for (const d of newDetails) {
|
|
964
|
+
if (d.id) continue;
|
|
965
|
+
const sd = plainSaved[di];
|
|
966
|
+
di += 1;
|
|
967
|
+
if (!sd) break;
|
|
968
|
+
d.open = sd.open;
|
|
969
|
+
}
|
|
970
|
+
// Restore scroll positions. A scroller that carries an `id` is matched by id so inserting another scroller above it doe...
|
|
971
|
+
const newScrolls = Array.from(this.querySelectorAll("*")).filter(isScroller);
|
|
972
|
+
const keyedScrolls = savedScrolls.filter((s) => s.id || s.preserveKey);
|
|
973
|
+
const usedScrolls = new Set();
|
|
974
|
+
for (const el of newScrolls) {
|
|
975
|
+
const id = el.id || null;
|
|
976
|
+
const preserveKey = el.getAttribute("data-contour-preserve-key") || null;
|
|
977
|
+
if (!id && !preserveKey) continue;
|
|
978
|
+
const match = keyedScrolls.find((s) => (s.id === id || s.preserveKey === preserveKey) && !usedScrolls.has(s.el));
|
|
979
|
+
if (!match) continue;
|
|
980
|
+
usedScrolls.add(match.el);
|
|
981
|
+
el.scrollTop = match.top;
|
|
982
|
+
el.scrollLeft = match.left;
|
|
983
|
+
}
|
|
984
|
+
let si = 0;
|
|
985
|
+
const plainScrolls = savedScrolls.filter((s) => !s.id && !s.preserveKey);
|
|
986
|
+
for (const el of newScrolls) {
|
|
987
|
+
if (el.id) continue;
|
|
988
|
+
const s = plainScrolls[si];
|
|
989
|
+
si += 1;
|
|
990
|
+
if (!s) break;
|
|
991
|
+
el.scrollTop = s.top;
|
|
992
|
+
el.scrollLeft = s.left;
|
|
993
|
+
}
|
|
994
|
+
// A persistent node kept its identity but not necessarily its offset: the rebuild clears its subtree, and the browser c...
|
|
995
|
+
for (const s of savedScrolls) {
|
|
996
|
+
if (!s.el || !s.el.isConnected) continue;
|
|
997
|
+
// _contourPersistent only exists once keepNode() has been called; a host with scrollable descendants but no persistent ...
|
|
998
|
+
if (!persistent || !persistent.has(s.el)) continue;
|
|
999
|
+
if (s.el.scrollTop === s.top && s.el.scrollLeft === s.left) continue;
|
|
1000
|
+
s.el.scrollTop = s.top;
|
|
1001
|
+
s.el.scrollLeft = s.left;
|
|
1002
|
+
}
|
|
1003
|
+
// Restore focus if it was inside the host. Keyed elements (id) are matched first; unkeyed ones fall back to a `name` at...
|
|
1004
|
+
if (hadFocus) {
|
|
1005
|
+
let target = null;
|
|
1006
|
+
if (hadFocusKey) {
|
|
1007
|
+
try { target = this.querySelector("#" + CSS.escape(hadFocusKey)); } catch (e) { target = null; }
|
|
1008
|
+
}
|
|
1009
|
+
if (!target && hadFocusPreserveKey) {
|
|
1010
|
+
try { target = this.querySelector('[data-contour-preserve-key="' + CSS.escape(hadFocusPreserveKey) + '"]'); } catch (e) { target = null; }
|
|
1011
|
+
}
|
|
1012
|
+
if (!target && hadFocusName) {
|
|
1013
|
+
try { target = this.querySelector('[name="' + CSS.escape(hadFocusName) + '"]'); } catch (e) { target = null; }
|
|
1014
|
+
}
|
|
1015
|
+
if (!target && hadFocusIndex >= 0) {
|
|
1016
|
+
const after = Array.from(this.querySelectorAll(_focusableSelector));
|
|
1017
|
+
if (after.length) {
|
|
1018
|
+
target = after[Math.min(hadFocusIndex, after.length - 1)];
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
if (target && typeof target.focus === "function") {
|
|
1022
|
+
try { target.focus(); } catch (e) {}
|
|
1023
|
+
} else if (document.contains(hadFocus)) {
|
|
1024
|
+
try { hadFocus.focus(); } catch (e) {}
|
|
1025
|
+
} else {
|
|
1026
|
+
const first = this.querySelector(_focusableSelector);
|
|
1027
|
+
if (first) try { first.focus(); } catch (e) {}
|
|
1028
|
+
else try { this.focus(); } catch (e) {}
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
this._runEnhance();
|
|
1032
|
+
this._detachInnerFormControls();
|
|
1033
|
+
this._checkedAttrChanged = false;
|
|
1034
|
+
this._contourResetting = false;
|
|
1035
|
+
} finally {
|
|
1036
|
+
this._contourRendering = false;
|
|
1037
|
+
}
|
|
1038
|
+
this._announceRendered();
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
disconnectedCallback() {
|
|
1042
|
+
this._pendingRerender = false;
|
|
1043
|
+
this._ensureCache = null;
|
|
1044
|
+
this._batchDepth = 0;
|
|
1045
|
+
this._batchDirty = false;
|
|
1046
|
+
// Form listeners were removed by runDisposers below; clear the guard so
|
|
1047
|
+
// a reconnected host re-attaches them (connectedCallback re-wires).
|
|
1048
|
+
this._wiredFormData = false;
|
|
1049
|
+
// R24-98: clear remote-load state so a reconnect re-fetches. A host detached mid-fetch has _remoteStatus="loading" and ...
|
|
1050
|
+
this._remoteStatus = null;
|
|
1051
|
+
this._remoteSrc = null;
|
|
1052
|
+
runDisposers(this);
|
|
1053
|
+
// R28-09 : drop the host listeners enhance() added this mount. They live on the host element and would otherwise surviv...
|
|
1054
|
+
const hostListeners = this._contourHostListeners;
|
|
1055
|
+
if (hostListeners) {
|
|
1056
|
+
for (const { type, listener, options } of hostListeners) {
|
|
1057
|
+
try { this.removeEventListener(type, listener, options); } catch (e) { /* already gone */ }
|
|
1058
|
+
}
|
|
1059
|
+
this._contourHostListeners = null;
|
|
1060
|
+
}
|
|
1061
|
+
// Override in subclasses that attach event listeners or timers.
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
adoptedCallback() {
|
|
1065
|
+
// Re-apply parts and the density mirror when the node is moved to a new
|
|
1066
|
+
// document.
|
|
1067
|
+
if (this._contourAuthored) { this._applyDensity(); }
|
|
1068
|
+
}
|
|
1069
|
+
|
|
1070
|
+
// Default no-op: subclasses with behaviour override this.
|
|
1071
|
+
enhance() {}
|
|
1072
|
+
|
|
1073
|
+
// R28-09 : a host listener added by enhance() lives on the host element, which a disconnect does not destroy, so it sur...
|
|
1074
|
+
addEventListener(type, listener, options) {
|
|
1075
|
+
// Behaviour listeners (behaviours.mjs wcTrack) carry _contourBehaviour: their claim persists across a light reconnect, ...
|
|
1076
|
+
if (this._contourHostWiring && listener && !listener._contourBehaviour) {
|
|
1077
|
+
let list = this._contourHostListeners;
|
|
1078
|
+
if (!list) { list = []; this._contourHostListeners = list; }
|
|
1079
|
+
list.push({ type, listener, options });
|
|
1080
|
+
}
|
|
1081
|
+
return super.addEventListener(type, listener, options);
|
|
1082
|
+
}
|
|
1083
|
+
_runEnhance() {
|
|
1084
|
+
this._contourHostWiring = true;
|
|
1085
|
+
try { this.enhance(); }
|
|
1086
|
+
finally { this._contourHostWiring = false; }
|
|
1087
|
+
}
|
|
1088
|
+
|
|
1089
|
+
// Form lifecycle (form-associated components only). The platform calls these on <form>.reset(), on disable by a fieldse...
|
|
1090
|
+
_syncFormValue() {
|
|
1091
|
+
if (!this._internals) return;
|
|
1092
|
+
// A boolean group (a contour-radio-list) submits the *checked* item's
|
|
1093
|
+
// value, so prefer the checked control over the first one found.
|
|
1094
|
+
const ctl = this.querySelector("input:checked, textarea, select") || this.querySelector("input, textarea, select");
|
|
1095
|
+
if (!ctl) return;
|
|
1096
|
+
const boolean = ctl.type === "checkbox" || ctl.type === "radio";
|
|
1097
|
+
const value = boolean ? (ctl.checked ? (ctl.value || "on") : null) : ctl.value;
|
|
1098
|
+
this._internals.setFormValue(value);
|
|
1099
|
+
this._syncValidity(this.hasAttribute("required") && !value);
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
// The single validity writer . Every form class used to repeat the required-check + setValidity pair; the copies in for...
|
|
1103
|
+
// R31-61: mirror the inner control's NATIVE validity onto the host, not only
|
|
1104
|
+
// `required`. A `contour-input type="email" value="not-an-email"` must make
|
|
1105
|
+
// the host and its form invalid (typeMismatch), and number/pattern/min/max
|
|
1106
|
+
// must do the same. `valueMissing` is the authored-required fallback for
|
|
1107
|
+
// groups that have no single inner control to read.
|
|
1108
|
+
_syncValidity(valueMissing) {
|
|
1109
|
+
if (!this._internals) return;
|
|
1110
|
+
const flags = valueMissing ? { valueMissing: true } : {};
|
|
1111
|
+
let msg = valueMissing ? "This field is required." : "";
|
|
1112
|
+
const ctl = this.querySelector("input, textarea, select");
|
|
1113
|
+
const v = ctl && ctl.validity;
|
|
1114
|
+
if (v) {
|
|
1115
|
+
if (v.valueMissing) { flags.valueMissing = true; msg = msg || "This field is required."; }
|
|
1116
|
+
if (v.typeMismatch) { flags.typeMismatch = true; msg = msg || "Please enter a valid value."; }
|
|
1117
|
+
if (v.patternMismatch) { flags.patternMismatch = true; msg = msg || "Please match the requested format."; }
|
|
1118
|
+
if (v.rangeUnderflow) { flags.rangeUnderflow = true; msg = msg || "Value is too low."; }
|
|
1119
|
+
if (v.rangeOverflow) { flags.rangeOverflow = true; msg = msg || "Value is too high."; }
|
|
1120
|
+
if (v.tooLong) { flags.tooLong = true; msg = msg || "Value is too long."; }
|
|
1121
|
+
if (v.tooShort) { flags.tooShort = true; msg = msg || "Value is too short."; }
|
|
1122
|
+
if (v.badInput) { flags.badInput = true; msg = msg || "Invalid input."; }
|
|
1123
|
+
}
|
|
1124
|
+
this._internals.setValidity(flags, msg);
|
|
1125
|
+
this._setCustomState("data-invalid", Object.keys(flags).length > 0);
|
|
1126
|
+
}
|
|
1127
|
+
|
|
1128
|
+
// Custom-state mirror . `ElementInternals.states` exposes a host's own boolean to CSS as `:state(name)` — a consumer wr...
|
|
1129
|
+
_setCustomState(name, on) {
|
|
1130
|
+
let internals = this._internals;
|
|
1131
|
+
if (!internals) {
|
|
1132
|
+
if (this._stateInternals) internals = this._stateInternals;
|
|
1133
|
+
else if (typeof this.attachInternals === "function") {
|
|
1134
|
+
try { internals = this._stateInternals = this.attachInternals(); } catch (e) { return; }
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
const states = internals && internals.states;
|
|
1138
|
+
if (!states) return;
|
|
1139
|
+
if (on) { if (!states.has(name)) states.add(name); }
|
|
1140
|
+
else if (states.has(name)) states.delete(name);
|
|
1141
|
+
}
|
|
1142
|
+
|
|
1143
|
+
// The form value events . §23 promises interactive components emit bubbling contour:* events; the form family had 16 us...
|
|
1144
|
+
_emitForm(type) {
|
|
1145
|
+
if (!this._internals) return;
|
|
1146
|
+
const ctl = this.querySelector("input:checked, textarea, select") || this.querySelector("input, textarea, select");
|
|
1147
|
+
if (!ctl) return;
|
|
1148
|
+
const boolean = ctl.type === "checkbox" || ctl.type === "radio";
|
|
1149
|
+
this.dispatchEvent(new CustomEvent(type, {
|
|
1150
|
+
bubbles: true,
|
|
1151
|
+
composed: true,
|
|
1152
|
+
detail: {
|
|
1153
|
+
name: this.getAttribute("name"),
|
|
1154
|
+
value: boolean ? (ctl.checked ? (ctl.value || "on") : null) : ctl.value,
|
|
1155
|
+
checked: boolean ? ctl.checked : null,
|
|
1156
|
+
},
|
|
1157
|
+
}));
|
|
1158
|
+
}
|
|
1159
|
+
formResetCallback() {
|
|
1160
|
+
// Reset synchronously: re-rendering would restore the base class's *preserved* typed value, not the authored default. T...
|
|
1161
|
+
for (const ctl of this.querySelectorAll("input, textarea, select")) {
|
|
1162
|
+
ctl._contourUserDirty = false;
|
|
1163
|
+
if (ctl.type === "checkbox" || ctl.type === "radio") {
|
|
1164
|
+
ctl.checked = this.hasAttribute("checked");
|
|
1165
|
+
} else if (ctl.tagName === "SELECT") {
|
|
1166
|
+
const chosen = ctl.querySelector("option[selected], option:first-of-type");
|
|
1167
|
+
ctl.value = chosen ? chosen.value : "";
|
|
1168
|
+
} else {
|
|
1169
|
+
// The authored default lives on the host (`value` attribute), not
|
|
1170
|
+
// necessarily on the generated inner control.
|
|
1171
|
+
ctl.value = this.hasAttribute("value") ? this.getAttribute("value") : (ctl.getAttribute("value") || "");
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
this._syncFormValue();
|
|
1175
|
+
}
|
|
1176
|
+
formDisabledCallback(disabled) {
|
|
1177
|
+
for (const ctl of this.querySelectorAll("input, textarea, select, button")) {
|
|
1178
|
+
if (disabled) ctl.setAttribute("disabled", "");
|
|
1179
|
+
else ctl.removeAttribute("disabled");
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
formStateRestoreCallback(state) {
|
|
1183
|
+
if (!this._internals || state === null || state === undefined) return;
|
|
1184
|
+
const controls = Array.from(this.querySelectorAll("input, textarea, select"));
|
|
1185
|
+
const str = String(state);
|
|
1186
|
+
// The restore state is the value the host last submitted; for a boolean
|
|
1187
|
+
// group it names which inner control to check.
|
|
1188
|
+
const match = controls.find((c) => (c.type === "checkbox" || c.type === "radio") && c.value === str);
|
|
1189
|
+
if (match) {
|
|
1190
|
+
match.checked = true;
|
|
1191
|
+
for (const other of controls) {
|
|
1192
|
+
if (other !== match && other.type === "radio" && other.name === match.name) other.checked = false;
|
|
1193
|
+
}
|
|
1194
|
+
} else if (controls.length) {
|
|
1195
|
+
controls[0].value = str;
|
|
1196
|
+
}
|
|
1197
|
+
this._syncFormValue();
|
|
1198
|
+
}
|
|
1199
|
+
checkValidity() {
|
|
1200
|
+
return this._internals ? this._internals.checkValidity() : true;
|
|
1201
|
+
}
|
|
1202
|
+
reportValidity() {
|
|
1203
|
+
return this._internals ? this._internals.reportValidity() : true;
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
// Keep internals in step with the group. Checking radio B fires `change` on B only — the deselected host A hears nothin...
|
|
1207
|
+
_wireFormData() {
|
|
1208
|
+
if (!this._internals || this._wiredFormData) return;
|
|
1209
|
+
const form = this._internals.form;
|
|
1210
|
+
if (!form) return;
|
|
1211
|
+
this._wiredFormData = true;
|
|
1212
|
+
const myName = this.getAttribute("name");
|
|
1213
|
+
const onFormChange = (e) => {
|
|
1214
|
+
const t = e.target;
|
|
1215
|
+
if (t && t.type === "radio" && t.name && t.name === myName) this._syncFormValue();
|
|
1216
|
+
};
|
|
1217
|
+
form.addEventListener("change", onFormChange);
|
|
1218
|
+
const onFormData = () => this._syncFormValue();
|
|
1219
|
+
form.addEventListener("formdata", onFormData);
|
|
1220
|
+
onDispose(this, () => {
|
|
1221
|
+
form.removeEventListener("change", onFormChange);
|
|
1222
|
+
form.removeEventListener("formdata", onFormData);
|
|
1223
|
+
});
|
|
1224
|
+
}
|
|
1225
|
+
|
|
1226
|
+
// User-dirty value tracking (R20 T-02). The restore path only fills controls a render left empty, so a host with an aut...
|
|
1227
|
+
_wireValueTracking() {
|
|
1228
|
+
if (!this._internals || this._wiredValueTracking) return;
|
|
1229
|
+
this._wiredValueTracking = true;
|
|
1230
|
+
const mark = (e) => {
|
|
1231
|
+
const t = e.target;
|
|
1232
|
+
if (!t || !t.matches || !t.matches("input, textarea, select")) return;
|
|
1233
|
+
if (this._ownerBetween(t, this)) return;
|
|
1234
|
+
t._contourUserDirty = true;
|
|
1235
|
+
t._contourAttrAtDirty = this.getAttribute("value");
|
|
1236
|
+
};
|
|
1237
|
+
this.addEventListener("input", mark);
|
|
1238
|
+
this.addEventListener("change", mark);
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
// Restore one control's value from its snapshot (R20 T-02/T-06). A user-dirty control keeps its typed value — a multi-s...
|
|
1242
|
+
_restoreControlValue(el, saved) {
|
|
1243
|
+
// R24-116: a file input's `.value` is read-only — assigning it throws an InvalidStateError (the value is a synthetic "C...
|
|
1244
|
+
if (el.type === "file") return;
|
|
1245
|
+
if (saved.dirty && saved.attrAtDirty === this.getAttribute("value")) {
|
|
1246
|
+
if (saved.selected && el.tagName === "SELECT" && el.multiple) {
|
|
1247
|
+
const wanted = new Set(saved.selected);
|
|
1248
|
+
for (const o of el.options) o.selected = wanted.has(o.value);
|
|
1249
|
+
} else {
|
|
1250
|
+
el.value = saved.value;
|
|
1251
|
+
}
|
|
1252
|
+
el._contourUserDirty = true;
|
|
1253
|
+
el._contourAttrAtDirty = saved.attrAtDirty;
|
|
1254
|
+
return;
|
|
1255
|
+
}
|
|
1256
|
+
if (el.value === "" && el.getAttribute("value") === null) el.value = saved.value;
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1259
|
+
// The inner native control(s) are scaffolding; the host reports through ElementInternals. A same-name native control in...
|
|
1260
|
+
_detachInnerFormControls() {
|
|
1261
|
+
if (!this._internals) return;
|
|
1262
|
+
for (const ctl of this.querySelectorAll("input, textarea, select")) {
|
|
1263
|
+
if (ctl.hasAttribute("name") && ctl.getAttribute("form") !== "") ctl.setAttribute("form", "");
|
|
1264
|
+
}
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
// Opt-in batching: coalesce multiple attribute changes into a single render. Usage: el.batch(() => { el.value = 42; el....
|
|
1268
|
+
/** Coalesce synchronous property changes into one render. */
|
|
1269
|
+
batch(fn) {
|
|
1270
|
+
if (typeof fn !== "function") return;
|
|
1271
|
+
this._batchDepth = (this._batchDepth || 0) + 1;
|
|
1272
|
+
this._batchDirty = this._batchDirty || false;
|
|
1273
|
+
try {
|
|
1274
|
+
fn();
|
|
1275
|
+
} finally {
|
|
1276
|
+
this._batchDepth -= 1;
|
|
1277
|
+
if (this._batchDepth === 0 && this._batchDirty) {
|
|
1278
|
+
this._batchDirty = false;
|
|
1279
|
+
// Trigger a single re-render with current attribute values.
|
|
1280
|
+
if (this.isConnected && this._contourAuthored) {
|
|
1281
|
+
this.attributeChangedCallback("__rerender__", null, "");
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
}
|
|
1286
|
+
|
|
1287
|
+
// Request a re-render without naming the changed attribute (for host-driven work: a resolved fetch, a timer, an observer). A render body must never call attributeChangedCallback directly — on the connect path that nests a synchronous render. Deferring to a microtask coalesces N asks into one render through the same reset/restore path.
|
|
1288
|
+
requestRender() {
|
|
1289
|
+
if (this._contourRerenderQueued) return;
|
|
1290
|
+
this._contourRerenderQueued = true;
|
|
1291
|
+
queueMicrotask(() => {
|
|
1292
|
+
this._contourRerenderQueued = false;
|
|
1293
|
+
if (!this.isConnected || !this._contourAuthored) return;
|
|
1294
|
+
this.attributeChangedCallback("__rerender__", null, "");
|
|
1295
|
+
});
|
|
1296
|
+
}
|
|
1297
|
+
|
|
1298
|
+
// R31-15: the light layer no longer writes `part=` on generated nodes.
|
|
1299
|
+
// `::part()` matches only shadow parts, so the attribute was inert on every
|
|
1300
|
+
// light component while `_applyParts` scanned every `[class]` on every
|
|
1301
|
+
// render (~12% of steady-state re-render on a 500-row table). The light
|
|
1302
|
+
// theming seam is `contour-<block> .c-<block>__<element>`; the shadow layer
|
|
1303
|
+
// keeps its real `::part()` hooks (shadow.mjs).
|
|
1304
|
+
|
|
1305
|
+
// Density modifier: mirror `density` attribute to `data-density` on the host (the sheet hooks on it); not in OBSERVED so the write can't re-enter render.
|
|
1306
|
+
_applyDensity() {
|
|
1307
|
+
const density = this.getAttribute("density");
|
|
1308
|
+
if (density !== null) this.setAttribute("data-density", density);
|
|
1309
|
+
else if (this.hasAttribute("data-density")) this.removeAttribute("data-density");
|
|
1310
|
+
}
|
|
1311
|
+
|
|
1312
|
+
// Closest host above `node` up to `root`, or null. ensure() may only reuse a node its own host owns: querySelector reaches through a nested host's boundary, so two blocks with a `__title` would share one element.
|
|
1313
|
+
_ownerBetween(node, root) {
|
|
1314
|
+
for (let p = node.parentElement; p && p !== root; p = p.parentElement) {
|
|
1315
|
+
if (p instanceof ContourBase) return p;
|
|
1316
|
+
}
|
|
1317
|
+
return null;
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
// Helper for update-or-create reactivity: returns the first node matching
|
|
1321
|
+
// `selector`, creating it via `factory()` and appending if absent, so an attribute change updates the existing node. A per-render cache (keyed by scope and selector) avoids re-querying the subtree for every ensure() call.
|
|
1322
|
+
/**
|
|
1323
|
+
* Register a generated node as persistent across re-renders.
|
|
1324
|
+
*
|
|
1325
|
+
* The base class drops every generated node on each render and rebuilds it
|
|
1326
|
+
* from `render()`. That is right for markup and wrong for a node whose
|
|
1327
|
+
* identity carries state the markup does not: a scroller's `scrollTop`, a
|
|
1328
|
+
* canvas' drawn pixels, a media element's `currentTime`. Registering the
|
|
1329
|
+
* node here keeps it alive across the rebuild; `render()` re-attaches it.
|
|
1330
|
+
*
|
|
1331
|
+
* @param {Node} node generated node to keep
|
|
1332
|
+
* @returns {Node} the same node, for chaining
|
|
1333
|
+
*/
|
|
1334
|
+
keepNode(node) {
|
|
1335
|
+
if (!node) return node;
|
|
1336
|
+
if (!this._contourPersistent) this._contourPersistent = new Set();
|
|
1337
|
+
this._contourPersistent.add(node);
|
|
1338
|
+
return node;
|
|
1339
|
+
}
|
|
1340
|
+
|
|
1341
|
+
ensure(selector, factory, parent) {
|
|
1342
|
+
const root = parent || this;
|
|
1343
|
+
if (!root._ensureCache || root._ensureCacheGen !== this._contourRenderGen) {
|
|
1344
|
+
root._ensureCache = new Map();
|
|
1345
|
+
root._ensureCacheGen = this._contourRenderGen;
|
|
1346
|
+
}
|
|
1347
|
+
const cache = root._ensureCache;
|
|
1348
|
+
const key = root === this ? selector : "\u0000" + root + "\u0000" + selector;
|
|
1349
|
+
let node = cache.get(key);
|
|
1350
|
+
if (node === undefined) {
|
|
1351
|
+
// First match this host owns, skipping anything inside a nested host.
|
|
1352
|
+
node = null;
|
|
1353
|
+
for (const candidate of root.querySelectorAll(selector)) {
|
|
1354
|
+
if (!this._ownerBetween(candidate, root)) { node = candidate; break; }
|
|
1355
|
+
}
|
|
1356
|
+
cache.set(key, node);
|
|
1357
|
+
}
|
|
1358
|
+
if (!node) {
|
|
1359
|
+
node = factory();
|
|
1360
|
+
// R31-15: no `part=` write here — it is inert on light DOM (see the
|
|
1361
|
+
// removed _applyParts). Shadow wrappers set their own real parts.
|
|
1362
|
+
root.appendChild(node);
|
|
1363
|
+
cache.set(key, node);
|
|
1364
|
+
}
|
|
1365
|
+
return node;
|
|
1366
|
+
}
|
|
1367
|
+
}
|
|
1368
|
+
|
|
1369
|
+
// Brownout mixin : opt-in base for components that shed non-essential chrome under degraded conditions. Merges `brownou...
|
|
1370
|
+
export function withBrownout(Base) {
|
|
1371
|
+
return class extends Base {
|
|
1372
|
+
static get observed() {
|
|
1373
|
+
const base = (super.observed && Array.isArray(super.observed)) ? super.observed : [];
|
|
1374
|
+
const extra = ["brownout", "brownout-level"];
|
|
1375
|
+
return Array.from(new Set(base.concat(extra)));
|
|
1376
|
+
}
|
|
1377
|
+
brownoutLevel() { return super.brownoutLevel ? super.brownoutLevel() : (parseInt(this.getAttribute("brownout-level") || this.getAttribute("brownout") || "0", 10) || 0); }
|
|
1378
|
+
shed(kind, threshold) { return this.brownoutLevel() >= (threshold || 1); }
|
|
1379
|
+
};
|
|
1380
|
+
}
|
|
1381
|
+
/** Pure helper: compute brownout level from an attribute bag (framework-neutral). */
|
|
1382
|
+
export function levelFromAttributes(attrs = {}) {
|
|
1383
|
+
const raw = (attrs && (attrs["brownout-level"] || attrs["brownout"])) || "0";
|
|
1384
|
+
return parseInt(raw, 10) || 0;
|
|
1385
|
+
}
|
|
1386
|
+
|
|
1387
|
+
// Simple component: just adds CSS classes.
|
|
1388
|
+
/** Create a light-DOM component that only applies block and modifier classes. */
|
|
1389
|
+
export const simple = (classes) => class extends ContourBase {
|
|
1390
|
+
render() {
|
|
1391
|
+
classes.forEach((c) => this.classList.add(c));
|
|
1392
|
+
// Remove stale modifier classes first so attribute removal is reflected.
|
|
1393
|
+
for (const c of Array.from(this.classList)) {
|
|
1394
|
+
if (classes.some((base) => c.startsWith(base + "--"))) this.classList.remove(c);
|
|
1395
|
+
}
|
|
1396
|
+
MODS.forEach((attr) => {
|
|
1397
|
+
if (this.hasAttribute(attr)) {
|
|
1398
|
+
const val = this.getAttribute(attr);
|
|
1399
|
+
classes.forEach((c) => {
|
|
1400
|
+
const prefix = c.replace("c-", "");
|
|
1401
|
+
this.classList.add(`c-${prefix}--${val}`);
|
|
1402
|
+
});
|
|
1403
|
+
}
|
|
1404
|
+
});
|
|
1405
|
+
}
|
|
1406
|
+
};
|
|
1407
|
+
|
|
1408
|
+
// ---- Class-only blocks ----
|
|
1409
|
+
// A block here needs only its own class: element `contour-<block>`, class `c-<block>`. Blocks needing scaffolding declare a class above; the registration loop skips a name an explicit component already claimed.
|
|
1410
|
+
/** Blocks whose custom elements need no generated markup. */
|
|
1411
|
+
export const CLASS_ONLY = [
|
|
1412
|
+
"box", "cluster", "container", "row", "scrim", "stack"
|
|
1413
|
+
];
|
|
1414
|
+
|
|
1415
|
+
// Feature detection for `hidden="until-found"`: unsupported browsers treat the value as boolean hidden (permanent hide), so only upgrade where supported.
|
|
1416
|
+
/** Detect support for the non-destructive `hidden="until-found"` value. */
|
|
1417
|
+
export function supportsUntilFound() {
|
|
1418
|
+
try {
|
|
1419
|
+
const t = document.createElement("div");
|
|
1420
|
+
t.setAttribute("hidden", "until-found");
|
|
1421
|
+
return t.getAttribute("hidden") === "until-found";
|
|
1422
|
+
} catch (e) { return false; }
|
|
1423
|
+
}
|
|
1424
|
+
|
|
1425
|
+
// Value formatting: opt-in Intl formatting for kpi/stat/readout/coordinate. `format` is a preset or JSON of Intl options; `locale` defaults to runtime locale; returns raw value on failure.
|
|
1426
|
+
/** Format a value with the component's supported Intl presets. */
|
|
1427
|
+
export function formatValue(value, format, locale, unit) {
|
|
1428
|
+
if (!format) return value;
|
|
1429
|
+
const loc = locale || (typeof navigator !== "undefined" && navigator.language) || "en";
|
|
1430
|
+
if (format === "date" || format === "time") {
|
|
1431
|
+
try {
|
|
1432
|
+
const opts = format === "time" ? { timeStyle: "short" } : undefined;
|
|
1433
|
+
return new Intl.DateTimeFormat(loc, opts).format(new Date(value));
|
|
1434
|
+
} catch (e) { return value; }
|
|
1435
|
+
}
|
|
1436
|
+
if (format === "relative") {
|
|
1437
|
+
try {
|
|
1438
|
+
const num = Number(value);
|
|
1439
|
+
// Interpret the value as seconds from now unless it is an ISO date.
|
|
1440
|
+
let seconds = num;
|
|
1441
|
+
if (Number.isNaN(num)) {
|
|
1442
|
+
const then = new Date(value).getTime();
|
|
1443
|
+
if (Number.isFinite(then)) seconds = (then - Date.now()) / 1000;
|
|
1444
|
+
}
|
|
1445
|
+
const rtf = new Intl.RelativeTimeFormat(loc, { numeric: "auto" });
|
|
1446
|
+
if (Math.abs(seconds) < 60) return rtf.format(Math.round(seconds), "second");
|
|
1447
|
+
if (Math.abs(seconds) < 3600) return rtf.format(Math.round(seconds / 60), "minute");
|
|
1448
|
+
if (Math.abs(seconds) < 86400) return rtf.format(Math.round(seconds / 3600), "hour");
|
|
1449
|
+
return rtf.format(Math.round(seconds / 86400), "day");
|
|
1450
|
+
} catch (e) { return value; }
|
|
1451
|
+
}
|
|
1452
|
+
let opts = {};
|
|
1453
|
+
if (format === "currency") opts = { style: "currency", currency: "USD" };
|
|
1454
|
+
else if (format === "percent") opts = { style: "percent" };
|
|
1455
|
+
else if (format === "compact") opts = { notation: "compact" };
|
|
1456
|
+
else if (format === "unit") opts = { style: "unit", unit: unit || "meter" };
|
|
1457
|
+
else if (format !== "number") {
|
|
1458
|
+
try { opts = JSON.parse(format); } catch (e) { return value; }
|
|
1459
|
+
}
|
|
1460
|
+
try { return new Intl.NumberFormat(loc, opts).format(Number(value)); }
|
|
1461
|
+
catch (e) { return value; }
|
|
1462
|
+
}
|
|
1463
|
+
|
|
1464
|
+
// Shared keyboard navigation for roving-tabindex patterns. Options: { wrap=true, enter=true, homeEnd=false, onKey(key,idx,item)→truthy prevents default, onNavigate(newIdx), rtl (defaults to dir attr) }.
|
|
1465
|
+
/** Navigate a roving-tabindex group with arrow keys, Home/End, Enter/Space. */
|
|
1466
|
+
export function navKey(e, items, { wrap = true, enter = true, homeEnd = false, onKey, onNavigate, rtl } = {}) {
|
|
1467
|
+
const idx = items.indexOf(document.activeElement);
|
|
1468
|
+
if (idx < 0) return;
|
|
1469
|
+
let next = -1;
|
|
1470
|
+
// Determine direction: ArrowRight/Down always advance forward in LTR.
|
|
1471
|
+
// With RTL, ArrowRight goes back and ArrowLeft goes forward.
|
|
1472
|
+
const fwdKey = rtl ? "ArrowLeft" : "ArrowRight";
|
|
1473
|
+
const revKey = rtl ? "ArrowRight" : "ArrowLeft";
|
|
1474
|
+
if (e.key === fwdKey || e.key === "ArrowDown") next = wrap ? (idx + 1) % items.length : Math.min(idx + 1, items.length - 1);
|
|
1475
|
+
else if (e.key === revKey || e.key === "ArrowUp") next = wrap ? (idx - 1 + items.length) % items.length : Math.max(0, idx - 1);
|
|
1476
|
+
else if ((homeEnd || wrap) && e.key === "Home") next = 0;
|
|
1477
|
+
else if ((homeEnd || wrap) && e.key === "End") next = items.length - 1;
|
|
1478
|
+
if (next >= 0 && next !== idx) {
|
|
1479
|
+
e.preventDefault();
|
|
1480
|
+
try { items[next].focus(); } catch (_) {}
|
|
1481
|
+
if (onNavigate) onNavigate(next);
|
|
1482
|
+
if (onKey) onKey(e.key, idx, items[idx]);
|
|
1483
|
+
} else if ((enter || wrap) && (e.key === "Enter" || e.key === " ")) {
|
|
1484
|
+
e.preventDefault();
|
|
1485
|
+
if (onKey) onKey(e.key, idx, items[idx]);
|
|
1486
|
+
}
|
|
1487
|
+
}
|
|
1488
|
+
|
|
1489
|
+
// Resolve RTL direction from element or document. Returns true for RTL layout.
|
|
1490
|
+
/** Check whether the given element uses right-to-left text direction. */
|
|
1491
|
+
export function isRtl(el) {
|
|
1492
|
+
let node = el;
|
|
1493
|
+
while (node && node.nodeType === 1) {
|
|
1494
|
+
const d = node.getAttribute && node.getAttribute("dir");
|
|
1495
|
+
if (d) return d.toLowerCase() === "rtl";
|
|
1496
|
+
node = node.parentElement;
|
|
1497
|
+
}
|
|
1498
|
+
try { return (typeof document !== "undefined" && (document.documentElement.getAttribute("dir") || "").toLowerCase() === "rtl"); }
|
|
1499
|
+
catch (e) { return false; }
|
|
1500
|
+
}
|
|
1501
|
+
|
|
1502
|
+
// Spatial maths (BY-23): pure functions on the host's own attributes.
|
|
1503
|
+
// Haversine distance in meters between two lat/lon points.
|
|
1504
|
+
/** Return the great-circle distance between two latitude/longitude points. */
|
|
1505
|
+
export function haversine(lat1, lon1, lat2, lon2) {
|
|
1506
|
+
const R = 6371000;
|
|
1507
|
+
const toRad = (d) => d * Math.PI / 180;
|
|
1508
|
+
const dLat = toRad(lat2 - lat1);
|
|
1509
|
+
const dLon = toRad(lon2 - lon1);
|
|
1510
|
+
const a = Math.sin(dLat / 2) ** 2 + Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(dLon / 2) ** 2;
|
|
1511
|
+
return 2 * R * Math.asin(Math.sqrt(a));
|
|
1512
|
+
}
|
|
1513
|
+
// Bearing in degrees (clockwise from north) from point 1 to point 2.
|
|
1514
|
+
/** Return the initial bearing from one latitude/longitude point to another. */
|
|
1515
|
+
export function bearing(lat1, lon1, lat2, lon2) {
|
|
1516
|
+
const toRad = (d) => d * Math.PI / 180;
|
|
1517
|
+
const toDeg = (r) => r * 180 / Math.PI;
|
|
1518
|
+
const dLon = toRad(lon2 - lon1);
|
|
1519
|
+
const y = Math.sin(dLon) * Math.cos(toRad(lat2));
|
|
1520
|
+
const x = Math.cos(toRad(lat1)) * Math.sin(toRad(lat2)) - Math.sin(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.cos(dLon);
|
|
1521
|
+
return (toDeg(Math.atan2(y, x)) + 360) % 360;
|
|
1522
|
+
}
|
|
1523
|
+
// Mercator resolution (meters per pixel) at a given latitude and zoom.
|
|
1524
|
+
/** The latitude Web Mercator can represent; beyond it the projection diverges. */
|
|
1525
|
+
export const MERCATOR_MAX_LAT = 85.05112878;
|
|
1526
|
+
|
|
1527
|
+
/** Clamp a latitude into the Mercator domain; NaN when the input is not a number. */
|
|
1528
|
+
export function clampLat(lat) {
|
|
1529
|
+
const v = Number(lat);
|
|
1530
|
+
if (!Number.isFinite(v)) return NaN;
|
|
1531
|
+
return Math.max(-MERCATOR_MAX_LAT, Math.min(MERCATOR_MAX_LAT, v));
|
|
1532
|
+
}
|
|
1533
|
+
|
|
1534
|
+
/** Wrap a longitude into [-180, 180). NaN when the input is not a number. */
|
|
1535
|
+
export function normaliseLng(lng) {
|
|
1536
|
+
const v = Number(lng);
|
|
1537
|
+
if (!Number.isFinite(v)) return NaN;
|
|
1538
|
+
return ((((v + 180) % 360) + 360) % 360) - 180;
|
|
1539
|
+
}
|
|
1540
|
+
|
|
1541
|
+
/**
|
|
1542
|
+
* Normalise a west/south/east/north box. A box that crosses the antimeridian
|
|
1543
|
+
* arrives as `west > east` (MapLibre reports 170 → -170 that way), which makes
|
|
1544
|
+
* `east - west` negative and hides the crossing. The returned box is unwrapped
|
|
1545
|
+
* — `east` continues past 180 — and says so, so a span is always positive and
|
|
1546
|
+
* a consumer that needs the engine's own numbers can subtract 360 from `east`
|
|
1547
|
+
* when `crossesAntimeridian` is true.
|
|
1548
|
+
*/
|
|
1549
|
+
export function unwrapBounds(bounds) {
|
|
1550
|
+
const b = bounds || {};
|
|
1551
|
+
const west = normaliseLng(b.west);
|
|
1552
|
+
const eastRaw = normaliseLng(b.east);
|
|
1553
|
+
const crossesAntimeridian = Number.isFinite(west) && Number.isFinite(eastRaw) && west > eastRaw;
|
|
1554
|
+
return {
|
|
1555
|
+
west,
|
|
1556
|
+
south: clampLat(b.south),
|
|
1557
|
+
east: crossesAntimeridian ? eastRaw + 360 : eastRaw,
|
|
1558
|
+
north: clampLat(b.north),
|
|
1559
|
+
crossesAntimeridian,
|
|
1560
|
+
};
|
|
1561
|
+
}
|
|
1562
|
+
|
|
1563
|
+
/** Return meters per pixel for Web Mercator at a latitude and zoom level. */
|
|
1564
|
+
export function mercatorResolution(lat, zoom) {
|
|
1565
|
+
// Beyond ±85.05112878° the projection is undefined and cos() collapses
|
|
1566
|
+
// toward zero (resolution 6e-17 at the pole instead of a finite number).
|
|
1567
|
+
const phi = clampLat(lat);
|
|
1568
|
+
if (!Number.isFinite(phi)) return NaN;
|
|
1569
|
+
return 156543.03392 * Math.cos(phi * Math.PI / 180) / Math.pow(2, zoom);
|
|
1570
|
+
}
|
|
1571
|
+
|
|
1572
|
+
// Event vocabulary is static, so publish once here (frozen) rather than per-registration; any import path reaching core.mjs exposes it.
|
|
1573
|
+
if (typeof window !== "undefined") {
|
|
1574
|
+
window.ContourEvents = Object.freeze(CONTOUR_EVENTS);
|
|
1575
|
+
}
|
|
1576
|
+
|
|
1577
|
+
/* CONTOUR — SVG geometry helpers: pure path generators, zero dependencies. */
|
|
1578
|
+
"use strict";
|
|
1579
|
+
|
|
1580
|
+
/**
|
|
1581
|
+
* R31-50: the one null/NaN policy. A value is "missing" when it is null or
|
|
1582
|
+
* undefined, a non-finite number (NaN/Infinity), the `__missing` sentinel, or
|
|
1583
|
+
* an empty string. Missing values are NOT zero: a line breaks at them, a bar
|
|
1584
|
+
* is not drawn, and the data table leaves the cell empty. Every geometry
|
|
1585
|
+
* helper and the chart renderer share this predicate so the three agree.
|
|
1586
|
+
*
|
|
1587
|
+
* @param {*} v
|
|
1588
|
+
* @returns {boolean}
|
|
1589
|
+
*/
|
|
1590
|
+
export function isMissing(v) {
|
|
1591
|
+
if (v == null) return true;
|
|
1592
|
+
if (typeof v === "number") return !Number.isFinite(v);
|
|
1593
|
+
if (typeof v === "string") {
|
|
1594
|
+
const t = v.trim();
|
|
1595
|
+
return t === "" || t === "__missing";
|
|
1596
|
+
}
|
|
1597
|
+
return false;
|
|
1598
|
+
}
|
|
1599
|
+
|
|
1600
|
+
/**
|
|
1601
|
+
* Build an SVG arc path for a single donut slice.
|
|
1602
|
+
*
|
|
1603
|
+
* @param {number} cx centre x
|
|
1604
|
+
* @param {number} cy centre y
|
|
1605
|
+
* @param {number} r outer radius
|
|
1606
|
+
* @param {number} inner inner radius (0 for a pie)
|
|
1607
|
+
* @param {number} startAngle start angle in radians
|
|
1608
|
+
* @param {number} endAngle end angle in radians
|
|
1609
|
+
* @returns {string} SVG path `d` attribute
|
|
1610
|
+
*/
|
|
1611
|
+
/** Build an SVG arc path string. */
|
|
1612
|
+
export function arcPath(cx, cy, r, inner, startAngle, endAngle) {
|
|
1613
|
+
// Clamp non-finite inputs so a bad value cannot emit NaN/Infinity into the path.
|
|
1614
|
+
cx = Number.isFinite(cx) ? cx : 0;
|
|
1615
|
+
cy = Number.isFinite(cy) ? cy : 0;
|
|
1616
|
+
r = Number.isFinite(r) && r > 0 ? r : 0;
|
|
1617
|
+
inner = Number.isFinite(inner) && inner >= 0 ? inner : 0;
|
|
1618
|
+
startAngle = Number.isFinite(startAngle) ? startAngle : 0;
|
|
1619
|
+
endAngle = Number.isFinite(endAngle) ? endAngle : 0;
|
|
1620
|
+
const largeArc = endAngle - startAngle > Math.PI ? 1 : 0;
|
|
1621
|
+
const x1 = cx + r * Math.cos(startAngle);
|
|
1622
|
+
const y1 = cy + r * Math.sin(startAngle);
|
|
1623
|
+
const x2 = cx + r * Math.cos(endAngle);
|
|
1624
|
+
const y2 = cy + r * Math.sin(endAngle);
|
|
1625
|
+
if (inner <= 0) {
|
|
1626
|
+
return `M ${cx} ${cy} L ${x1} ${y1} A ${r} ${r} 0 ${largeArc} 1 ${x2} ${y2} Z`;
|
|
1627
|
+
}
|
|
1628
|
+
const ix1 = cx + inner * Math.cos(endAngle);
|
|
1629
|
+
const iy1 = cy + inner * Math.sin(endAngle);
|
|
1630
|
+
const ix2 = cx + inner * Math.cos(startAngle);
|
|
1631
|
+
const iy2 = cy + inner * Math.sin(startAngle);
|
|
1632
|
+
return `M ${x1} ${y1} A ${r} ${r} 0 ${largeArc} 1 ${x2} ${y2} L ${ix1} ${iy1} A ${inner} ${inner} 0 ${largeArc} 0 ${ix2} ${iy2} Z`;
|
|
1633
|
+
}
|
|
1634
|
+
|
|
1635
|
+
/**
|
|
1636
|
+
* Convert a list of values into donut slice paths.
|
|
1637
|
+
*
|
|
1638
|
+
* @param {number[]} values
|
|
1639
|
+
* @param {object} [opts]
|
|
1640
|
+
* @param {number} [opts.cx=100]
|
|
1641
|
+
* @param {number} [opts.cy=100]
|
|
1642
|
+
* @param {number} [opts.r=90]
|
|
1643
|
+
* @param {number} [opts.inner=55]
|
|
1644
|
+
* @param {number} [opts.gap=0.02] angular gap between slices in radians
|
|
1645
|
+
* @returns {{path: string, value: number, index: number}[]}
|
|
1646
|
+
*/
|
|
1647
|
+
/** Compute donut slice geometry. */
|
|
1648
|
+
export function donutSlices(values, opts) {
|
|
1649
|
+
opts = opts || {};
|
|
1650
|
+
const cx = opts.cx != null ? opts.cx : 100;
|
|
1651
|
+
const cy = opts.cy != null ? opts.cy : 100;
|
|
1652
|
+
const r = opts.r != null ? opts.r : 90;
|
|
1653
|
+
const inner = opts.inner != null ? opts.inner : 55;
|
|
1654
|
+
const gap = opts.gap != null ? opts.gap : 0.02;
|
|
1655
|
+
// R31-51: the total is the sum of the POSITIVE slices only. A negative value
|
|
1656
|
+
// is not a slice (it is skipped below), so including it in the total made the
|
|
1657
|
+
// drawn sweeps overflow 360° (e.g. [10,-5,20] swept 432°). Excluding it keeps
|
|
1658
|
+
// the ring a full circle and the centre total honest.
|
|
1659
|
+
const total = values.reduce((a, b) => a + (Number(b) > 0 ? Number(b) : 0), 0) || 1;
|
|
1660
|
+
let angle = -Math.PI / 2;
|
|
1661
|
+
const out = [];
|
|
1662
|
+
values.forEach((v, i) => {
|
|
1663
|
+
const num = Number(v) || 0;
|
|
1664
|
+
const frac = num / total;
|
|
1665
|
+
if (!(num > 0)) { angle += frac * Math.PI * 2; return; }
|
|
1666
|
+
const sweep = frac * Math.PI * 2 - gap;
|
|
1667
|
+
const start = angle + gap / 2;
|
|
1668
|
+
const end = start + Math.max(0, sweep);
|
|
1669
|
+
out.push({ path: arcPath(cx, cy, r, inner, start, end), value: num, index: i });
|
|
1670
|
+
angle += frac * Math.PI * 2;
|
|
1671
|
+
});
|
|
1672
|
+
return out;
|
|
1673
|
+
}
|
|
1674
|
+
|
|
1675
|
+
/**
|
|
1676
|
+
* Compute bar rectangles for a histogram.
|
|
1677
|
+
*
|
|
1678
|
+
* @param {number[]} values
|
|
1679
|
+
* @param {object} [opts]
|
|
1680
|
+
* @param {number} [opts.width=300]
|
|
1681
|
+
* @param {number} [opts.height=120]
|
|
1682
|
+
* @param {number} [opts.gap=2]
|
|
1683
|
+
* @param {number} [opts.max] override max value (defaults to max of values)
|
|
1684
|
+
* @returns {{x:number,y:number,width:number,height:number}[]}
|
|
1685
|
+
*/
|
|
1686
|
+
/** Compute bar rectangle geometry. */
|
|
1687
|
+
export function barRects(values, opts) {
|
|
1688
|
+
opts = opts || {};
|
|
1689
|
+
const width = opts.width != null ? opts.width : 300;
|
|
1690
|
+
const height = opts.height != null ? opts.height : 120;
|
|
1691
|
+
const gap = opts.gap != null ? opts.gap : 2;
|
|
1692
|
+
// R31-50: a missing value is not a zero-height bar. It is flagged so the
|
|
1693
|
+
// renderer can skip it, and it does not contribute to the domain.
|
|
1694
|
+
const missing = values.map(isMissing);
|
|
1695
|
+
const nums = values.map((v, i) => (missing[i] ? 0 : Number(v) || 0));
|
|
1696
|
+
// R31-44: the domain includes 0, so a negative value hangs below a zero
|
|
1697
|
+
// baseline instead of being clamped to a zero-height bar at the foot. Each
|
|
1698
|
+
// rect carries `zeroY` (the baseline) so the axis and the bars agree.
|
|
1699
|
+
let lo = Math.min(0, Math.min.apply(null, nums.length ? nums : [0]));
|
|
1700
|
+
let hi = Math.max(0, Math.max.apply(null, nums.length ? nums : [0]));
|
|
1701
|
+
if (opts.min != null) lo = Math.min(lo, Number(opts.min) || 0);
|
|
1702
|
+
if (opts.max != null) hi = Math.max(hi, Number(opts.max) || 0);
|
|
1703
|
+
if (!Number.isFinite(lo) || !Number.isFinite(hi)) { lo = 0; hi = 1; }
|
|
1704
|
+
if (hi === lo) hi = lo + 1;
|
|
1705
|
+
const span = hi - lo;
|
|
1706
|
+
const n = values.length || 1;
|
|
1707
|
+
const slot = width / n;
|
|
1708
|
+
const barW = Math.max(1, slot - gap);
|
|
1709
|
+
const zeroY = height - ((0 - lo) / span) * height;
|
|
1710
|
+
return nums.map((v, i) => {
|
|
1711
|
+
const yv = height - ((v - lo) / span) * height;
|
|
1712
|
+
return { x: i * slot + gap / 2, y: Math.min(yv, zeroY), width: barW, height: missing[i] ? 0 : Math.abs(zeroY - yv), zeroY, missing: missing[i] };
|
|
1713
|
+
});
|
|
1714
|
+
}
|
|
1715
|
+
|
|
1716
|
+
/**
|
|
1717
|
+
* Nice value-axis ticks for a chart, independent of `ds.js`. The wc layer used
|
|
1718
|
+
* to read `window.Contour.chart.ticks`, which only exists when the optional
|
|
1719
|
+
* guide script is loaded; a wc-only consumer got two ticks.
|
|
1720
|
+
*/
|
|
1721
|
+
export function niceTicks(min, max, count) {
|
|
1722
|
+
count = count || 5;
|
|
1723
|
+
const span = max - min || 1;
|
|
1724
|
+
let step = Math.pow(10, Math.floor(Math.log10(span / count)));
|
|
1725
|
+
if (!Number.isFinite(step) || step <= 0) return [min, max];
|
|
1726
|
+
const err = (count * step) / span;
|
|
1727
|
+
if (err <= 0.15) step *= 10;
|
|
1728
|
+
else if (err <= 0.35) step *= 5;
|
|
1729
|
+
else if (err <= 0.75) step *= 2;
|
|
1730
|
+
const lo = Math.floor(min / step) * step;
|
|
1731
|
+
const hi = Math.ceil(max / step) * step;
|
|
1732
|
+
const ticks = [];
|
|
1733
|
+
for (let v = lo; v <= hi + step / 2; v += step) {
|
|
1734
|
+
ticks.push(Math.round(v * 1e9) / 1e9);
|
|
1735
|
+
}
|
|
1736
|
+
return ticks;
|
|
1737
|
+
}
|
|
1738
|
+
|
|
1739
|
+
/**
|
|
1740
|
+
* Build an SVG polyline `points` attribute from a list of numbers.
|
|
1741
|
+
*
|
|
1742
|
+
* @param {number[]} values
|
|
1743
|
+
* @param {object} [opts]
|
|
1744
|
+
* @param {number} [opts.width=300]
|
|
1745
|
+
* @param {number} [opts.height=120]
|
|
1746
|
+
* @param {number} [opts.max] override max
|
|
1747
|
+
* @param {number} [opts.min] override min
|
|
1748
|
+
* @returns {string} "x,y x,y ..."
|
|
1749
|
+
*/
|
|
1750
|
+
/** Compute polyline point string. */
|
|
1751
|
+
export function polylinePoints(values, opts) {
|
|
1752
|
+
opts = opts || {};
|
|
1753
|
+
const width = opts.width != null ? opts.width : 300;
|
|
1754
|
+
const height = opts.height != null ? opts.height : 120;
|
|
1755
|
+
const nums = values.map((v) => Number(v) || 0);
|
|
1756
|
+
if (!nums.length) return "";
|
|
1757
|
+
const max = opts.max != null ? opts.max : Math.max.apply(null, nums);
|
|
1758
|
+
const min = opts.min != null ? opts.min : Math.min.apply(null, nums);
|
|
1759
|
+
const range = (Number.isFinite(max - min) && (max - min) !== 0) ? (max - min) : 1;
|
|
1760
|
+
const n = nums.length || 1;
|
|
1761
|
+
return nums.map((v, i) => {
|
|
1762
|
+
const x = (i / Math.max(1, n - 1)) * width;
|
|
1763
|
+
const y = height - ((v - min) / range) * height;
|
|
1764
|
+
return x.toFixed(2) + "," + y.toFixed(2);
|
|
1765
|
+
}).join(" ");
|
|
1766
|
+
}
|
|
1767
|
+
|
|
1768
|
+
/**
|
|
1769
|
+
* Build a smooth (monotone) SVG path through a list of numbers.
|
|
1770
|
+
*
|
|
1771
|
+
* @param {number[]} values
|
|
1772
|
+
* @param {object} [opts] same as polylinePoints
|
|
1773
|
+
* @returns {string} SVG path `d` attribute
|
|
1774
|
+
*/
|
|
1775
|
+
/** Compute a smoothed SVG path. */
|
|
1776
|
+
export function smoothPath(values, opts) {
|
|
1777
|
+
// R31-50: a missing value breaks the path into a new subpath (a gap), it is
|
|
1778
|
+
// not drawn as zero. The domain ignores missing values.
|
|
1779
|
+
opts = opts || {};
|
|
1780
|
+
const width = opts.width != null ? opts.width : 300;
|
|
1781
|
+
const height = opts.height != null ? opts.height : 120;
|
|
1782
|
+
const finite = values.filter((v) => !isMissing(v)).map(Number).filter((v) => Number.isFinite(v));
|
|
1783
|
+
const max = opts.max != null ? opts.max : (finite.length ? Math.max.apply(null, finite) : 1);
|
|
1784
|
+
const min = opts.min != null ? opts.min : (finite.length ? Math.min.apply(null, finite) : 0);
|
|
1785
|
+
const range = (Number.isFinite(max - min) && (max - min) !== 0) ? (max - min) : 1;
|
|
1786
|
+
const n = values.length || 1;
|
|
1787
|
+
const pts = values.map((v, i) => {
|
|
1788
|
+
if (isMissing(v)) return null;
|
|
1789
|
+
const num = Number(v);
|
|
1790
|
+
if (!Number.isFinite(num)) return null;
|
|
1791
|
+
const x = (i / Math.max(1, n - 1)) * width;
|
|
1792
|
+
const y = height - ((num - min) / range) * height;
|
|
1793
|
+
return [x, y];
|
|
1794
|
+
});
|
|
1795
|
+
let d = "";
|
|
1796
|
+
let seg = [];
|
|
1797
|
+
const flush = () => {
|
|
1798
|
+
if (!seg.length) return;
|
|
1799
|
+
d += ` M ${seg[0][0]} ${seg[0][1]}`;
|
|
1800
|
+
for (let k = 1; k < seg.length; k++) {
|
|
1801
|
+
const prev = seg[k - 1];
|
|
1802
|
+
const cur = seg[k];
|
|
1803
|
+
const cpx = (prev[0] + cur[0]) / 2;
|
|
1804
|
+
d += ` C ${cpx} ${prev[1]}, ${cpx} ${cur[1]}, ${cur[0]} ${cur[1]}`;
|
|
1805
|
+
}
|
|
1806
|
+
seg = [];
|
|
1807
|
+
};
|
|
1808
|
+
pts.forEach((p) => { if (p) seg.push(p); else flush(); });
|
|
1809
|
+
flush();
|
|
1810
|
+
return d.trim();
|
|
1811
|
+
}
|
|
1812
|
+
|
|
1813
|
+
/**
|
|
1814
|
+
* Build an SVG path for a compass needle pointing at `angleDeg` (clockwise
|
|
1815
|
+
* from north/up). The needle is a thin triangle from the centre to the tip,
|
|
1816
|
+
* with a short tail in the opposite direction.
|
|
1817
|
+
*
|
|
1818
|
+
* @param {number} cx centre x
|
|
1819
|
+
* @param {number} cy centre y
|
|
1820
|
+
* @param {number} length needle length (tip distance from centre)
|
|
1821
|
+
* @param {number} [angleDeg=0] bearing in degrees, clockwise from up
|
|
1822
|
+
* @param {number} [width=3] half-width of the needle at the base
|
|
1823
|
+
* @returns {string} SVG path `d` attribute
|
|
1824
|
+
*/
|
|
1825
|
+
/** Compute compass needle geometry. */
|
|
1826
|
+
export function compassNeedle(cx, cy, length, angleDeg, width) {
|
|
1827
|
+
cx = Number.isFinite(Number(cx)) ? Number(cx) : 0;
|
|
1828
|
+
cy = Number.isFinite(Number(cy)) ? Number(cy) : 0;
|
|
1829
|
+
length = Number.isFinite(Number(length)) ? Number(length) : 0;
|
|
1830
|
+
angleDeg = angleDeg == null ? 0 : (Number.isFinite(Number(angleDeg)) ? Number(angleDeg) : 0);
|
|
1831
|
+
width = width == null ? 3 : (Number.isFinite(Number(width)) ? Number(width) : 3);
|
|
1832
|
+
const a = (angleDeg - 90) * Math.PI / 180; // 0deg = up
|
|
1833
|
+
const tipX = cx + length * Math.cos(a);
|
|
1834
|
+
const tipY = cy + length * Math.sin(a);
|
|
1835
|
+
const tail = length * 0.25;
|
|
1836
|
+
const tailX = cx - tail * Math.cos(a);
|
|
1837
|
+
const tailY = cy - tail * Math.sin(a);
|
|
1838
|
+
const perpX = Math.cos(a + Math.PI / 2);
|
|
1839
|
+
const perpY = Math.sin(a + Math.PI / 2);
|
|
1840
|
+
const b1x = cx + width * perpX;
|
|
1841
|
+
const b1y = cy + width * perpY;
|
|
1842
|
+
const b2x = cx - width * perpX;
|
|
1843
|
+
const b2y = cy - width * perpY;
|
|
1844
|
+
return `M ${tipX.toFixed(2)} ${tipY.toFixed(2)} L ${b1x.toFixed(2)} ${b1y.toFixed(2)} L ${tailX.toFixed(2)} ${tailY.toFixed(2)} L ${b2x.toFixed(2)} ${b2y.toFixed(2)} Z`;
|
|
1845
|
+
}
|
|
1846
|
+
|
|
1847
|
+
/**
|
|
1848
|
+
* Compute tick values for a scale bar.
|
|
1849
|
+
*
|
|
1850
|
+
* @param {number} value total value (max)
|
|
1851
|
+
* @param {number} [segments=4] number of segments
|
|
1852
|
+
* @returns {number[]} tick values from 0 to value inclusive
|
|
1853
|
+
*/
|
|
1854
|
+
/** Compute scale bar tick positions. */
|
|
1855
|
+
export function scaleBarTicks(value, segments) {
|
|
1856
|
+
value = Number(value) || 0;
|
|
1857
|
+
segments = Math.max(1, Math.round(segments || 4));
|
|
1858
|
+
const out = [];
|
|
1859
|
+
for (let i = 0; i <= segments; i++) {
|
|
1860
|
+
out.push((value / segments) * i);
|
|
1861
|
+
}
|
|
1862
|
+
return out;
|
|
1863
|
+
}
|
|
1864
|
+
// Marker shape encoding utility (G-13)
|
|
1865
|
+
/** Supported marker shapes for chart series. */
|
|
1866
|
+
export const MARKER_SHAPES = ["circle", "square", "triangle", "diamond", "star"];
|
|
1867
|
+
/** Return CSS styles for a marker shape. */
|
|
1868
|
+
export function markerStyles(shape) {
|
|
1869
|
+
const map = {
|
|
1870
|
+
circle: "border-radius:50%",
|
|
1871
|
+
square: "border-radius:0",
|
|
1872
|
+
triangle: "clip-path:polygon(50% 0%,0% 100%,100% 100%)",
|
|
1873
|
+
diamond: "transform:rotate(45deg)",
|
|
1874
|
+
star: "clip-path:polygon(50% 0%,61% 35%,98% 35%,68% 57%,79% 91%,50% 70%,21% 91%,32% 57%,2% 35%,39% 35%)",
|
|
1875
|
+
};
|
|
1876
|
+
return map[shape] || "";
|
|
1877
|
+
}
|
|
1878
|
+
/** Assign marker shapes to chart items. */
|
|
1879
|
+
export function assignMarkers(items) {
|
|
1880
|
+
return (items || []).map((it, i) => ({ ...it, marker: MARKER_SHAPES[i % MARKER_SHAPES.length] }));
|
|
1881
|
+
}
|
|
1882
|
+
|
|
1883
|
+
/* Contour lines — marching squares over a 2D field; iso-lines of one field cannot cross. */
|
|
1884
|
+
|
|
1885
|
+
/**
|
|
1886
|
+
* Extract the iso-line segments of a scalar field at one level.
|
|
1887
|
+
*
|
|
1888
|
+
* @param {number[][]} grid row-major field values
|
|
1889
|
+
* @param {number} level iso-level to extract
|
|
1890
|
+
* @returns {Array<[{x:number,y:number},{x:number,y:number}]>} segments in grid space
|
|
1891
|
+
*/
|
|
1892
|
+
export function marchingSquares(grid, level) {
|
|
1893
|
+
const rows = grid.length;
|
|
1894
|
+
const cols = rows ? grid[0].length : 0;
|
|
1895
|
+
const segments = [];
|
|
1896
|
+
if (!rows || !cols) return segments;
|
|
1897
|
+
|
|
1898
|
+
const lerp = (a, b, va, vb) => (vb === va ? 0.5 : (level - va) / (vb - va));
|
|
1899
|
+
|
|
1900
|
+
for (let y = 0; y < rows - 1; y++) {
|
|
1901
|
+
for (let x = 0; x < cols - 1; x++) {
|
|
1902
|
+
const tl = grid[y][x];
|
|
1903
|
+
const tr = grid[y][x + 1];
|
|
1904
|
+
const bl = grid[y + 1][x];
|
|
1905
|
+
const br = grid[y + 1][x + 1];
|
|
1906
|
+
const code =
|
|
1907
|
+
(tl >= level ? 8 : 0) |
|
|
1908
|
+
(tr >= level ? 4 : 0) |
|
|
1909
|
+
(br >= level ? 2 : 0) |
|
|
1910
|
+
(bl >= level ? 1 : 0);
|
|
1911
|
+
if (code === 0 || code === 15) continue;
|
|
1912
|
+
|
|
1913
|
+
const top = { x: x + lerp(tl, tr, tl, tr), y };
|
|
1914
|
+
const right = { x: x + 1, y: y + lerp(tr, br, tr, br) };
|
|
1915
|
+
const bottom = { x: x + lerp(bl, br, bl, br), y: y + 1 };
|
|
1916
|
+
const left = { x, y: y + lerp(tl, bl, tl, bl) };
|
|
1917
|
+
|
|
1918
|
+
let connect;
|
|
1919
|
+
// R31-47: the asymptotic decider (as tools/contour-gen.py uses), not the
|
|
1920
|
+
// plain corner average. The bilinear interpolant's saddle value is
|
|
1921
|
+
// (tl*br - tr*bl) / (tl - tr - bl + br); the average misclassifies
|
|
1922
|
+
// asymmetric cells and produces the wrong pairing (crossed shelves).
|
|
1923
|
+
const saddle = (() => {
|
|
1924
|
+
const denom = tl - tr - bl + br;
|
|
1925
|
+
return Math.abs(denom) < 1e-12 ? (tl + tr + bl + br) / 4 : (tl * br - tr * bl) / denom;
|
|
1926
|
+
})();
|
|
1927
|
+
if (code === 5) {
|
|
1928
|
+
connect = saddle >= level ? "top-bottom" : "left-right";
|
|
1929
|
+
} else if (code === 10) {
|
|
1930
|
+
connect = saddle >= level ? "left-right" : "top-bottom";
|
|
1931
|
+
}
|
|
1932
|
+
|
|
1933
|
+
switch (code) {
|
|
1934
|
+
case 1: case 14: segments.push([left, bottom]); break;
|
|
1935
|
+
case 2: case 13: segments.push([bottom, right]); break;
|
|
1936
|
+
case 3: case 12: segments.push([left, right]); break;
|
|
1937
|
+
case 4: case 11: segments.push([top, right]); break;
|
|
1938
|
+
case 6: case 9: segments.push([top, bottom]); break;
|
|
1939
|
+
case 7: case 8: segments.push([left, top]); break;
|
|
1940
|
+
case 5:
|
|
1941
|
+
if (connect === "top-bottom") {
|
|
1942
|
+
segments.push([top, bottom], [left, right]);
|
|
1943
|
+
} else {
|
|
1944
|
+
segments.push([top, right], [left, bottom]);
|
|
1945
|
+
}
|
|
1946
|
+
break;
|
|
1947
|
+
case 10:
|
|
1948
|
+
if (connect === "left-right") {
|
|
1949
|
+
segments.push([left, right], [top, bottom]);
|
|
1950
|
+
} else {
|
|
1951
|
+
segments.push([top, right], [left, bottom]);
|
|
1952
|
+
}
|
|
1953
|
+
break;
|
|
1954
|
+
}
|
|
1955
|
+
}
|
|
1956
|
+
}
|
|
1957
|
+
return segments;
|
|
1958
|
+
}
|
|
1959
|
+
|
|
1960
|
+
/**
|
|
1961
|
+
* Build the SVG `d` path for every level of a field.
|
|
1962
|
+
*
|
|
1963
|
+
* @param {number[][]} grid row-major field values
|
|
1964
|
+
* @param {number[]} levels iso-levels, one path per level
|
|
1965
|
+
* @param {number} width viewBox width in px
|
|
1966
|
+
* @param {number} height viewBox height in px
|
|
1967
|
+
* @returns {Array<{level:number, d:string}>} one entry per level
|
|
1968
|
+
*/
|
|
1969
|
+
export function contourPaths(grid, levels, width, height) {
|
|
1970
|
+
const rows = grid.length;
|
|
1971
|
+
const cols = rows ? grid[0].length : 0;
|
|
1972
|
+
if (rows < 2 || cols < 2) return [];
|
|
1973
|
+
const sx = width / (cols - 1);
|
|
1974
|
+
const sy = height / (rows - 1);
|
|
1975
|
+
return (levels || []).map((level) => {
|
|
1976
|
+
const segs = marchingSquares(grid, level);
|
|
1977
|
+
let d = "";
|
|
1978
|
+
for (const [a, b] of segs) {
|
|
1979
|
+
d += `M ${(a.x * sx).toFixed(2)} ${(a.y * sy).toFixed(2)} L ${(b.x * sx).toFixed(2)} ${(b.y * sy).toFixed(2)} `;
|
|
1980
|
+
}
|
|
1981
|
+
return { level, d: d.trim() };
|
|
1982
|
+
});
|
|
1983
|
+
}
|
|
1984
|
+
|
|
1985
|
+
/* ============================================================================
|
|
1986
|
+
CONTOUR — shared behaviour
|
|
1987
|
+
----------------------------------------------------------------------------
|
|
1988
|
+
One implementation of each interaction, called by both layers: the light-DOM
|
|
1989
|
+
wrappers and the `contour-shadow-*` wrappers.
|
|
1990
|
+
|
|
1991
|
+
Before this file the two layers each carried a copy, and the copies had
|
|
1992
|
+
already drifted in the one direction source review cannot see: the shadow copy
|
|
1993
|
+
queried its own root for nodes the author slots into the light DOM, so it
|
|
1994
|
+
found nothing and wired nothing. Measured against the shipped artifact
|
|
1995
|
+
(tmp/r3/behaviour-baseline.mjs):
|
|
1996
|
+
|
|
1997
|
+
PASS light contour-tabs renders 2 tabs, ArrowRight moves selection
|
|
1998
|
+
PASS light segmented emits contour:change
|
|
1999
|
+
PASS light pagination emits contour:page
|
|
2000
|
+
FAIL shadow tabs: inner query sees slotted tabs [inside shadow root: 0; slotted: 2]
|
|
2001
|
+
FAIL shadow segmented / shadow menu: event reaches the document
|
|
2002
|
+
|
|
2003
|
+
Two rules fall out of that, and they are the whole design of this file:
|
|
2004
|
+
a behaviour looks in BOTH trees, because slotted content lives in the light
|
|
2005
|
+
DOM; and it dispatches on the HOST, because a bubbling event from a node
|
|
2006
|
+
inside a shadow root reaches neither the host nor the document:
|
|
2007
|
+
|
|
2008
|
+
bubbles-only -> reachedHost:false reachedDoc:false
|
|
2009
|
+
|
|
2010
|
+
Names are prefixed where they could collide: `stripWc` concatenates every
|
|
2011
|
+
fragment into one IIFE scope, so `emit`, `on` or `once` as bare top-level
|
|
2012
|
+
consts would silently shadow another module's. Nothing here owns markup or
|
|
2013
|
+
styling; a component decides what to render, this file only what happens when
|
|
2014
|
+
the reader acts on it.
|
|
2015
|
+
========================================================================= */
|
|
2016
|
+
|
|
2017
|
+
// `contourId` is the shared counter: a generated node that needs an id (a
|
|
2018
|
+
|
|
2019
|
+
// A host is wired once per behaviour. Re-entering is normal — the base class
|
|
2020
|
+
const WIRED_HOSTS = new WeakMap();
|
|
2021
|
+
// R28-09 (CD-06): the listeners a behaviour attaches for a host. wcReset (the
|
|
2022
|
+
const WIRED_LISTENERS = new WeakMap();
|
|
2023
|
+
const wcTrack = (host, target, type, fn, options) => {
|
|
2024
|
+
let arr = WIRED_LISTENERS.get(host);
|
|
2025
|
+
if (!arr) { arr = []; WIRED_LISTENERS.set(host, arr); }
|
|
2026
|
+
arr.push({ target, type, fn, options });
|
|
2027
|
+
// Mark the listener as behaviour-managed so the light base class's host
|
|
2028
|
+
try { fn._contourBehaviour = true; } catch (e) { /* frozen fn */ }
|
|
2029
|
+
target.addEventListener(type, fn, options);
|
|
2030
|
+
};
|
|
2031
|
+
/** Reset the wired-host claim for a host, allowing re-wiring after disconnect. */
|
|
2032
|
+
export const wcReset = (host) => {
|
|
2033
|
+
WIRED_HOSTS.delete(host);
|
|
2034
|
+
const arr = WIRED_LISTENERS.get(host);
|
|
2035
|
+
if (arr) {
|
|
2036
|
+
for (const { target, type, fn, options } of arr) {
|
|
2037
|
+
try { target.removeEventListener(type, fn, options); } catch (e) { /* already gone */ }
|
|
2038
|
+
}
|
|
2039
|
+
WIRED_LISTENERS.delete(host);
|
|
2040
|
+
}
|
|
2041
|
+
};
|
|
2042
|
+
const wcClaim = (host, name) => {
|
|
2043
|
+
let set = WIRED_HOSTS.get(host);
|
|
2044
|
+
if (!set) { set = new Set(); WIRED_HOSTS.set(host, set); }
|
|
2045
|
+
if (set.has(name)) return false;
|
|
2046
|
+
set.add(name);
|
|
2047
|
+
return true;
|
|
2048
|
+
};
|
|
2049
|
+
|
|
2050
|
+
// Authored content sits in the light DOM even when a shadow template slots it,
|
|
2051
|
+
// and a template's own parts sit in the root: a behaviour owns both.
|
|
2052
|
+
const wcScopes = (host) => (host.shadowRoot ? [host, host.shadowRoot] : [host]);
|
|
2053
|
+
const wcAll = (host, sel) => {
|
|
2054
|
+
const found = [];
|
|
2055
|
+
for (const scope of wcScopes(host)) {
|
|
2056
|
+
for (const el of scope.querySelectorAll(sel)) if (!found.includes(el)) found.push(el);
|
|
2057
|
+
}
|
|
2058
|
+
return found;
|
|
2059
|
+
};
|
|
2060
|
+
const wcOne = (host, sel) => wcAll(host, sel)[0] || null;
|
|
2061
|
+
// A custom element carries its own block class, and `querySelectorAll` never
|
|
2062
|
+
const wcSelfOrAll = (host, sel) => {
|
|
2063
|
+
const found = typeof host.matches === "function" && host.matches(sel) ? [host] : [];
|
|
2064
|
+
for (const el of wcAll(host, sel)) if (!found.includes(el)) found.push(el);
|
|
2065
|
+
return found;
|
|
2066
|
+
};
|
|
2067
|
+
// The flat tree is not the node tree. A group element inside a shadow root and
|
|
2068
|
+
const wcShadowOf = (node) => {
|
|
2069
|
+
const root = node && node.getRootNode ? node.getRootNode() : null;
|
|
2070
|
+
return root && root.host ? root : null;
|
|
2071
|
+
};
|
|
2072
|
+
const wcGroup = (host, group, sel) => {
|
|
2073
|
+
const found = Array.from(group.querySelectorAll(sel));
|
|
2074
|
+
if (wcShadowOf(group) && wcShadowOf(group).host === host) {
|
|
2075
|
+
for (const el of host.querySelectorAll(sel)) if (!found.includes(el)) found.push(el);
|
|
2076
|
+
}
|
|
2077
|
+
return found;
|
|
2078
|
+
};
|
|
2079
|
+
// Both scopes are listened to because retargeting is the asymmetry that decides
|
|
2080
|
+
const HEARD = new WeakMap();
|
|
2081
|
+
const wcListen = (host, type, handler) => {
|
|
2082
|
+
const scoped = (e) => {
|
|
2083
|
+
let seen = HEARD.get(e);
|
|
2084
|
+
if (!seen) { seen = new Set(); HEARD.set(e, seen); }
|
|
2085
|
+
if (seen.has(scoped)) return;
|
|
2086
|
+
seen.add(scoped);
|
|
2087
|
+
handler(e);
|
|
2088
|
+
};
|
|
2089
|
+
for (const scope of wcScopes(host)) wcTrack(host, scope, type, scoped);
|
|
2090
|
+
};
|
|
2091
|
+
const wcOwned = (host, node) =>
|
|
2092
|
+
!!node && wcScopes(host).some((scope) => scope.contains(node));
|
|
2093
|
+
// `closest` is asked of the event's own target, which is unretargeted inside the
|
|
2094
|
+
// tree that heard it; `wcOwned` then rejects a match outside this host.
|
|
2095
|
+
const wcClosest = (host, target, sel) =>
|
|
2096
|
+
(typeof target?.closest === "function" && wcOwned(host, target)) ? target.closest(sel) : null;
|
|
2097
|
+
// Dispatched on the HOST, so a listener outside this layer hears it whatever the flag
|
|
2098
|
+
const wcEmit = (host, name, detail) => {
|
|
2099
|
+
host.dispatchEvent(new CustomEvent(name, { detail, bubbles: true, composed: true }));
|
|
2100
|
+
};
|
|
2101
|
+
|
|
2102
|
+
/**
|
|
2103
|
+
* Tabs and code-tabs: roving tabindex, Arrow/Home/End, panel show-hide.
|
|
2104
|
+
* The active tab is `[aria-selected="true"]`, which is the rule the sheet
|
|
2105
|
+
* paints, so no state class is ever written — and none is invented either.
|
|
2106
|
+
*/
|
|
2107
|
+
/** Wire tab keyboard navigation and selection for a host. */
|
|
2108
|
+
export function wireTabs(host) {
|
|
2109
|
+
if (!wcClaim(host, "tabs")) return;
|
|
2110
|
+
for (const list of wcSelfOrAll(host, ".c-tabs__list, .c-code-tabs__list")) {
|
|
2111
|
+
const isCode = list.classList.contains("c-code-tabs__list");
|
|
2112
|
+
const panelSel = isCode ? ".c-code-tabs__panel" : ".c-tabs__panel";
|
|
2113
|
+
// `list.contains(tab)` is the test that fails on a shadow wrapper: the list
|
|
2114
|
+
const tabsOf = () => wcGroup(host, list, "[role='tab']");
|
|
2115
|
+
const activate = (tab, focus) => {
|
|
2116
|
+
const tabs = tabsOf();
|
|
2117
|
+
if (!tab.id) tab.id = contourId("c-tab");
|
|
2118
|
+
tabs.forEach((t) => {
|
|
2119
|
+
const selected = t === tab;
|
|
2120
|
+
t.setAttribute("aria-selected", String(selected));
|
|
2121
|
+
t.tabIndex = selected ? 0 : -1;
|
|
2122
|
+
const ctrl = t.getAttribute("aria-controls");
|
|
2123
|
+
if (!ctrl) return;
|
|
2124
|
+
const panel = wcOne(host, "#" + CSS.escape(ctrl)) || document.getElementById(ctrl);
|
|
2125
|
+
if (panel) {
|
|
2126
|
+
panel.hidden = !selected;
|
|
2127
|
+
// A tabpanel is named by its tab: without this a screen reader
|
|
2128
|
+
// announces the panel with no name.
|
|
2129
|
+
if (selected) panel.setAttribute("aria-labelledby", t.id);
|
|
2130
|
+
}
|
|
2131
|
+
});
|
|
2132
|
+
const panels = wcAll(host, panelSel);
|
|
2133
|
+
if (panels.length) {
|
|
2134
|
+
const index = tabs.indexOf(tab);
|
|
2135
|
+
panels.forEach((p, i) => { p.hidden = i !== index; });
|
|
2136
|
+
}
|
|
2137
|
+
if (focus) try { tab.focus(); } catch (e) { /* detached mid-key */ }
|
|
2138
|
+
// Emit activation so consumers can observe tab changes (B3-10). The label
|
|
2139
|
+
const name = tab.textContent.trim() || tab.getAttribute("aria-controls") || "";
|
|
2140
|
+
host.dispatchEvent(new CustomEvent("contour:tab-change", { bubbles: true, composed: true, detail: { index: tabs.indexOf(tab), label: name } }));
|
|
2141
|
+
};
|
|
2142
|
+
// Same-document View Transitions (BY-24). A tab swap runs inside
|
|
2143
|
+
const runActivation = (tab, focus) => {
|
|
2144
|
+
// Keyboard activation must update aria-selected synchronously so assistive
|
|
2145
|
+
const can = !focus && typeof document.startViewTransition === "function"
|
|
2146
|
+
&& !(typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches);
|
|
2147
|
+
if (can) {
|
|
2148
|
+
try {
|
|
2149
|
+
const vt = document.startViewTransition(() => activate(tab, focus));
|
|
2150
|
+
if (vt && vt.ready) vt.ready.catch(() => {});
|
|
2151
|
+
if (vt && vt.finished) vt.finished.catch(() => {});
|
|
2152
|
+
return;
|
|
2153
|
+
}
|
|
2154
|
+
catch (e) { /* an in-flight transition or a private context: plain swap */ }
|
|
2155
|
+
}
|
|
2156
|
+
activate(tab, focus);
|
|
2157
|
+
};
|
|
2158
|
+
wcListen(host, "click", (e) => {
|
|
2159
|
+
const tab = wcClosest(host, e.target, "[role='tab']");
|
|
2160
|
+
if (tab && tabsOf().includes(tab)) {
|
|
2161
|
+
// A button nested inside a tab (a close control, say) is its own
|
|
2162
|
+
// target: activating the tab underneath it would be a surprise.
|
|
2163
|
+
const inner = e.target && e.target.closest ? e.target.closest("button") : null;
|
|
2164
|
+
if (inner && inner !== tab && tab.contains(inner)) return;
|
|
2165
|
+
runActivation(tab, false);
|
|
2166
|
+
}
|
|
2167
|
+
});
|
|
2168
|
+
wcListen(host, "keydown", (e) => {
|
|
2169
|
+
let tab = wcClosest(host, e.target, "[role='tab']");
|
|
2170
|
+
if (!tab && e.target && e.target.getAttribute && e.target.getAttribute("role") === "tab" && wcOwned(host, e.target)) tab = e.target;
|
|
2171
|
+
const tabs = tabsOf();
|
|
2172
|
+
const index = tabs.indexOf(tab);
|
|
2173
|
+
if (index < 0) return;
|
|
2174
|
+
const vertical = host.getAttribute("orientation") === "vertical";
|
|
2175
|
+
const rtl = isRtl(host);
|
|
2176
|
+
const move = vertical
|
|
2177
|
+
? (rtl
|
|
2178
|
+
? { ArrowDown: index - 1, ArrowUp: index + 1, Home: tabs.length - 1, End: 0 }
|
|
2179
|
+
: { ArrowDown: index + 1, ArrowUp: index - 1, Home: 0, End: tabs.length - 1 })
|
|
2180
|
+
: (rtl
|
|
2181
|
+
? { ArrowRight: index - 1, ArrowLeft: index + 1, Home: tabs.length - 1, End: 0 }
|
|
2182
|
+
: { ArrowRight: index + 1, ArrowLeft: index - 1, Home: 0, End: tabs.length - 1 });
|
|
2183
|
+
if (!(e.key in move)) return;
|
|
2184
|
+
e.preventDefault();
|
|
2185
|
+
const next = tabs[(move[e.key] + tabs.length) % tabs.length];
|
|
2186
|
+
if (next) runActivation(next, true);
|
|
2187
|
+
});
|
|
2188
|
+
// Respect an author-marked selected tab; fall back to the first. With
|
|
2189
|
+
const tabs = tabsOf();
|
|
2190
|
+
const persist = host.getAttribute("persist");
|
|
2191
|
+
let restored = null;
|
|
2192
|
+
if (persist === "storage" && host.id) {
|
|
2193
|
+
try { restored = localStorage.getItem("contour-tabs:" + host.id); } catch (e) { restored = null; }
|
|
2194
|
+
} else if (persist === "url") {
|
|
2195
|
+
try {
|
|
2196
|
+
const params = new URLSearchParams(window.location.search);
|
|
2197
|
+
const v = params.get("c-tabs");
|
|
2198
|
+
if (v !== null) restored = v;
|
|
2199
|
+
} catch (e) { restored = null; }
|
|
2200
|
+
}
|
|
2201
|
+
const marked = tabs.find((t) => t.getAttribute("aria-selected") === "true");
|
|
2202
|
+
let first = marked || tabs[0];
|
|
2203
|
+
if (restored !== null) {
|
|
2204
|
+
const idx = parseInt(restored, 10);
|
|
2205
|
+
if (Number.isFinite(idx) && tabs[idx]) first = tabs[idx];
|
|
2206
|
+
}
|
|
2207
|
+
if (first) activate(first, false);
|
|
2208
|
+
// Persist on every subsequent activation.
|
|
2209
|
+
if (persist === "storage" && host.id) {
|
|
2210
|
+
wcTrack(host, host, "contour:tab-change", (e) => {
|
|
2211
|
+
try { localStorage.setItem("contour-tabs:" + host.id, String(e.detail && e.detail.index)); } catch (err) { /* quota/private mode */ }
|
|
2212
|
+
});
|
|
2213
|
+
} else if (persist === "url") {
|
|
2214
|
+
wcTrack(host, host, "contour:tab-change", (e) => {
|
|
2215
|
+
try {
|
|
2216
|
+
const url = new URL(window.location.href);
|
|
2217
|
+
url.searchParams.set("c-tabs", String(e.detail && e.detail.index));
|
|
2218
|
+
window.history.replaceState(null, "", url.toString());
|
|
2219
|
+
} catch (err) { /* no history API */ }
|
|
2220
|
+
});
|
|
2221
|
+
}
|
|
2222
|
+
}
|
|
2223
|
+
}
|
|
2224
|
+
|
|
2225
|
+
/**
|
|
2226
|
+
* Segmented control: one pressed option, and `contour:change`. The guide's own
|
|
2227
|
+
* markup carries the option value in a `data-*-value` hook, so the event reads
|
|
2228
|
+
* the hook it can see and falls back to the label the reader sees.
|
|
2229
|
+
*/
|
|
2230
|
+
/** Wire segmented-control selection for a host. */
|
|
2231
|
+
export function wireSegmented(host) {
|
|
2232
|
+
const groups = wcSelfOrAll(host, ".c-segmented");
|
|
2233
|
+
// The block's contract is the option class, a group role and an explicit
|
|
2234
|
+
const normalize = () => {
|
|
2235
|
+
// Who owns the pressed state. The author's `value` wins when it CHANGES — an
|
|
2236
|
+
const authored = host.getAttribute("value");
|
|
2237
|
+
const chosen = authored !== host._segAuthorValue ? authored : null;
|
|
2238
|
+
if (chosen !== null) host._segAuthorValue = authored;
|
|
2239
|
+
let seen = 0;
|
|
2240
|
+
for (const g of groups) {
|
|
2241
|
+
if (!g.hasAttribute("role")) g.setAttribute("role", "group");
|
|
2242
|
+
const label = host.getAttribute("label");
|
|
2243
|
+
if (label && !g.hasAttribute("aria-label")) g.setAttribute("aria-label", label);
|
|
2244
|
+
const opts = wcGroup(host, g, "button");
|
|
2245
|
+
seen += opts.length;
|
|
2246
|
+
opts.forEach((b) => {
|
|
2247
|
+
b.classList.add("c-segmented__option");
|
|
2248
|
+
b.setAttribute("aria-pressed", chosen !== null && chosen !== undefined ? String(b.dataset.value === chosen) : (b.getAttribute("aria-pressed") === "true" ? "true" : "false"));
|
|
2249
|
+
});
|
|
2250
|
+
// One tab stop for the group, on the pressed option — or the first when the
|
|
2251
|
+
// author chose none. Arrow keys then move it along with focus.
|
|
2252
|
+
const chosenOpt = opts.find((b) => b.getAttribute("aria-pressed") === "true") || opts[0];
|
|
2253
|
+
opts.forEach((b) => { b.tabIndex = b === chosenOpt ? 0 : -1; });
|
|
2254
|
+
}
|
|
2255
|
+
return seen;
|
|
2256
|
+
};
|
|
2257
|
+
// A classic `<script src="dist/contour-wc.js">` in `<head>` upgrades the host
|
|
2258
|
+
if (!normalize()) {
|
|
2259
|
+
if (!host._segRetryScheduled) {
|
|
2260
|
+
host._segRetryScheduled = true;
|
|
2261
|
+
setTimeout(() => { host._segRetryScheduled = false; normalize(); }, 0);
|
|
2262
|
+
}
|
|
2263
|
+
}
|
|
2264
|
+
if (!wcClaim(host, "segmented")) return;
|
|
2265
|
+
const activate = (btn) => {
|
|
2266
|
+
const seg = groups.find((g) => wcGroup(host, g, "button").includes(btn));
|
|
2267
|
+
if (!seg) return;
|
|
2268
|
+
// `value` is deliberately not written back to the host here: it sits in the
|
|
2269
|
+
wcGroup(host, seg, "button").forEach((o) => {
|
|
2270
|
+
const on = o === btn;
|
|
2271
|
+
o.setAttribute("aria-pressed", String(on));
|
|
2272
|
+
o.tabIndex = on ? 0 : -1;
|
|
2273
|
+
});
|
|
2274
|
+
wcEmit(host, "contour:change", { value: btn.dataset.value || btn.textContent.trim() });
|
|
2275
|
+
};
|
|
2276
|
+
wcListen(host, "click", (e) => {
|
|
2277
|
+
const btn = wcClosest(host, e.target, "button");
|
|
2278
|
+
if (!btn) return;
|
|
2279
|
+
activate(btn);
|
|
2280
|
+
});
|
|
2281
|
+
wcListen(host, "keydown", (e) => {
|
|
2282
|
+
const btn = wcClosest(host, e.target, "button");
|
|
2283
|
+
if (!btn) return;
|
|
2284
|
+
const seg = groups.find((g) => wcGroup(host, g, "button").includes(btn));
|
|
2285
|
+
if (!seg) return;
|
|
2286
|
+
const opts = wcGroup(host, seg, "button");
|
|
2287
|
+
navKey(e, opts, { wrap: false, homeEnd: true, rtl: isRtl(host), onNavigate: (i) => activate(opts[i]), onKey: (key) => { if (key === "Enter" || key === " ") activate(btn); } });
|
|
2288
|
+
});
|
|
2289
|
+
}
|
|
2290
|
+
|
|
2291
|
+
/**
|
|
2292
|
+
* Combobox: filter, arrow-cursor the visible options, commit, dismiss outside.
|
|
2293
|
+
* Native `<select>` stays native elsewhere — its popup cannot be styled — so the
|
|
2294
|
+
* one list this file drives is the one the system does draw.
|
|
2295
|
+
*/
|
|
2296
|
+
/** Wire combobox filtering, keyboard nav and selection for a host. */
|
|
2297
|
+
export function wireCombobox(host) {
|
|
2298
|
+
wireComboboxDocDismiss();
|
|
2299
|
+
const input = wcOne(host, ".c-combobox__input");
|
|
2300
|
+
const list = wcOne(host, ".c-combobox__list");
|
|
2301
|
+
if (!input || !list) return;
|
|
2302
|
+
const optionList = () => wcAll(host, ".c-combobox__option");
|
|
2303
|
+
|
|
2304
|
+
// Roles are re-applied on every pass, not claimed once. A re-render drops the
|
|
2305
|
+
if (!list.id) list.id = contourId("c-combobox-list");
|
|
2306
|
+
list.setAttribute("role", "listbox");
|
|
2307
|
+
input.setAttribute("role", "combobox");
|
|
2308
|
+
input.setAttribute("aria-haspopup", "listbox");
|
|
2309
|
+
input.setAttribute("aria-controls", list.id);
|
|
2310
|
+
input.setAttribute("aria-expanded", list.hasAttribute("hidden") ? "false" : "true");
|
|
2311
|
+
if (!input.hasAttribute("aria-autocomplete")) input.setAttribute("aria-autocomplete", "list");
|
|
2312
|
+
optionList().forEach((opt, i) => {
|
|
2313
|
+
if (!opt.id) opt.id = contourId("c-combobox-option");
|
|
2314
|
+
opt.setAttribute("role", "option");
|
|
2315
|
+
if (!opt.hasAttribute("aria-selected")) opt.setAttribute("aria-selected", "false");
|
|
2316
|
+
});
|
|
2317
|
+
|
|
2318
|
+
// Listeners are claimed once, and they are delegated on the HOST for the same
|
|
2319
|
+
if (!wcClaim(host, "combobox")) return;
|
|
2320
|
+
const liveInput = () => wcOne(host, ".c-combobox__input");
|
|
2321
|
+
const liveList = () => wcOne(host, ".c-combobox__list");
|
|
2322
|
+
let cursor = -1;
|
|
2323
|
+
const mark = (visible) => {
|
|
2324
|
+
const field = liveInput();
|
|
2325
|
+
// R31-05: in a multi-select the cursor is tracked by aria-activedescendant
|
|
2326
|
+
// and the --active class; aria-selected is the SELECTION and must survive
|
|
2327
|
+
// arrowing and Escape. Only a single-select listbox conflates the two.
|
|
2328
|
+
const multiple = host.hasAttribute("multiple");
|
|
2329
|
+
visible.forEach((o, i) => {
|
|
2330
|
+
const on = i === cursor;
|
|
2331
|
+
o.classList.toggle("c-combobox__option--active", on);
|
|
2332
|
+
if (!multiple) o.setAttribute("aria-selected", String(on));
|
|
2333
|
+
});
|
|
2334
|
+
if (field) {
|
|
2335
|
+
const active = cursor >= 0 ? visible[cursor] : null;
|
|
2336
|
+
if (active) field.setAttribute("aria-activedescendant", active.id);
|
|
2337
|
+
else field.removeAttribute("aria-activedescendant");
|
|
2338
|
+
}
|
|
2339
|
+
};
|
|
2340
|
+
const filter = (query) => {
|
|
2341
|
+
const q = (query || "").toLowerCase();
|
|
2342
|
+
if (host._comboboxVirtual && typeof host._renderComboboxWindow === "function") {
|
|
2343
|
+
host._renderComboboxWindow(q, true);
|
|
2344
|
+
cursor = -1;
|
|
2345
|
+
return;
|
|
2346
|
+
}
|
|
2347
|
+
optionList().forEach((o) => { o.hidden = !!(q && !o.textContent.toLowerCase().includes(q)); });
|
|
2348
|
+
cursor = -1;
|
|
2349
|
+
// R31-24: an authored list that matches nothing used to render as an empty
|
|
2350
|
+
// box — indistinguishable from a list that has not loaded. The virtual
|
|
2351
|
+
// renderer already says "No matches"; this is the same row for the
|
|
2352
|
+
// authored path.
|
|
2353
|
+
const list = liveList();
|
|
2354
|
+
if (!list) return;
|
|
2355
|
+
const total = optionList().length;
|
|
2356
|
+
const visible = optionList().filter((o) => !o.hidden).length;
|
|
2357
|
+
const empty = list.querySelector(".c-combobox__empty");
|
|
2358
|
+
if (total > 0 && visible === 0) {
|
|
2359
|
+
if (!empty) {
|
|
2360
|
+
const row = document.createElement(list.tagName === "UL" || list.tagName === "OL" ? "li" : "div");
|
|
2361
|
+
row.className = "c-combobox__empty";
|
|
2362
|
+
// A listbox may only contain `option`, so the row is a disabled option
|
|
2363
|
+
// rather than a live region: `role="status"` here is an axe violation
|
|
2364
|
+
// (aria-required-children) and an option that cannot be chosen says the
|
|
2365
|
+
// same thing to a screen reader walking the list.
|
|
2366
|
+
row.setAttribute("role", "option");
|
|
2367
|
+
row.setAttribute("aria-disabled", "true");
|
|
2368
|
+
row.setAttribute("aria-selected", "false");
|
|
2369
|
+
row.textContent = labelText(host, "no-matches", "No matches");
|
|
2370
|
+
list.appendChild(row);
|
|
2371
|
+
}
|
|
2372
|
+
} else if (empty) empty.remove();
|
|
2373
|
+
};
|
|
2374
|
+
const open = () => {
|
|
2375
|
+
const l = liveList();
|
|
2376
|
+
if (!l) return;
|
|
2377
|
+
const field = liveInput();
|
|
2378
|
+
// Fixed positioning from the input rect: the list escapes any ancestor
|
|
2379
|
+
// overflow:hidden that would clip an absolutely-positioned list.
|
|
2380
|
+
if (field) {
|
|
2381
|
+
const r = field.getBoundingClientRect();
|
|
2382
|
+
l.style.position = "fixed";
|
|
2383
|
+
l.style.insetBlockStart = `${Math.round(r.bottom + 4)}px`;
|
|
2384
|
+
l.style.insetInlineStart = `${Math.round(r.left)}px`;
|
|
2385
|
+
l.style.insetInlineEnd = "auto";
|
|
2386
|
+
l.style.inlineSize = `${Math.round(r.width)}px`;
|
|
2387
|
+
}
|
|
2388
|
+
l.removeAttribute("hidden");
|
|
2389
|
+
if (field) field.setAttribute("aria-expanded", "true");
|
|
2390
|
+
};
|
|
2391
|
+
const close = () => {
|
|
2392
|
+
const l = liveList();
|
|
2393
|
+
if (l) l.setAttribute("hidden", "");
|
|
2394
|
+
const field = liveInput();
|
|
2395
|
+
if (field) {
|
|
2396
|
+
field.setAttribute("aria-expanded", "false");
|
|
2397
|
+
field.removeAttribute("aria-activedescendant");
|
|
2398
|
+
}
|
|
2399
|
+
cursor = -1;
|
|
2400
|
+
// R31-05: clear the cursor highlight, but keep the multi-select selection —
|
|
2401
|
+
// Escape/close must not wipe the aria-selected the consumer picked.
|
|
2402
|
+
const multiple = host.hasAttribute("multiple");
|
|
2403
|
+
optionList().forEach((o) => {
|
|
2404
|
+
o.classList.remove("c-combobox__option--active");
|
|
2405
|
+
if (!multiple) o.setAttribute("aria-selected", "false");
|
|
2406
|
+
});
|
|
2407
|
+
};
|
|
2408
|
+
if (host._comboboxVirtual && list && !list._contourVirtualScroll) {
|
|
2409
|
+
list._contourVirtualScroll = true;
|
|
2410
|
+
list.addEventListener("scroll", () => {
|
|
2411
|
+
if (typeof host._renderComboboxWindow === "function") host._renderComboboxWindow(host._comboboxQuery || "");
|
|
2412
|
+
}, { passive: true });
|
|
2413
|
+
}
|
|
2414
|
+
const commit = (opt) => {
|
|
2415
|
+
const field = liveInput();
|
|
2416
|
+
if (!field) return;
|
|
2417
|
+
if (host.hasAttribute("multiple")) {
|
|
2418
|
+
const now = opt.getAttribute("aria-selected") === "true";
|
|
2419
|
+
opt.setAttribute("aria-selected", String(!now));
|
|
2420
|
+
opt.classList.toggle("c-combobox__option--selected", !now);
|
|
2421
|
+
const selected = (host.getAttribute("value") || "").split(",").map((v) => v.trim()).filter(Boolean);
|
|
2422
|
+
const value = host._comboboxVirtual && host._comboboxFiltered
|
|
2423
|
+
? host._comboboxFiltered.find((item) => item.index === Number(opt.dataset.optionIndex))?.value
|
|
2424
|
+
: (opt.dataset.optionValue != null ? opt.dataset.optionValue : opt.textContent.trim());
|
|
2425
|
+
const position = selected.indexOf(String(value));
|
|
2426
|
+
if (now && position >= 0) selected.splice(position, 1);
|
|
2427
|
+
if (!now && position < 0) selected.push(String(value));
|
|
2428
|
+
host.setAttribute("value", selected.join(","));
|
|
2429
|
+
if (typeof host._syncFormValue === "function") host._syncFormValue();
|
|
2430
|
+
wcEmit(host, "contour:select", { value: selected });
|
|
2431
|
+
field.focus();
|
|
2432
|
+
return;
|
|
2433
|
+
}
|
|
2434
|
+
// Commit the option's value, not its label: the field shows the label, the
|
|
2435
|
+
// form submits the value, and `contour:select` carries the value.
|
|
2436
|
+
const value = opt.dataset.optionValue != null ? opt.dataset.optionValue : opt.textContent.trim();
|
|
2437
|
+
field.value = opt.textContent;
|
|
2438
|
+
host.setAttribute("value", value);
|
|
2439
|
+
if (typeof host._syncFormValue === "function") host._syncFormValue();
|
|
2440
|
+
wcEmit(host, "contour:select", { value });
|
|
2441
|
+
close();
|
|
2442
|
+
field.focus();
|
|
2443
|
+
};
|
|
2444
|
+
|
|
2445
|
+
// `input` and `focus` do not both bubble out of a shadow root in the same way,
|
|
2446
|
+
const isField = (target) => wcClosest(host, target, ".c-combobox__input") !== null;
|
|
2447
|
+
wcListen(host, "input", (e) => {
|
|
2448
|
+
if (!isField(e.target)) return;
|
|
2449
|
+
host._comboboxQuery = e.target.value;
|
|
2450
|
+
filter(e.target.value);
|
|
2451
|
+
open();
|
|
2452
|
+
// The form-value event (BY-44) rides on the same interaction; the shadow
|
|
2453
|
+
// wrappers share this behaviour but have no `_emitForm`, so guard it.
|
|
2454
|
+
if (typeof host._emitForm === "function") host._emitForm("contour:input");
|
|
2455
|
+
});
|
|
2456
|
+
wcListen(host, "focusin", (e) => {
|
|
2457
|
+
if (!isField(e.target)) return;
|
|
2458
|
+
filter(e.target.value);
|
|
2459
|
+
open();
|
|
2460
|
+
});
|
|
2461
|
+
wcListen(host, "keydown", (e) => {
|
|
2462
|
+
if (!isField(e.target)) return;
|
|
2463
|
+
const visible = optionList().filter((o) => !o.hidden);
|
|
2464
|
+
if (e.key === "ArrowDown") { e.preventDefault(); cursor = Math.min(cursor + 1, visible.length - 1); mark(visible); }
|
|
2465
|
+
else if (e.key === "ArrowUp") { e.preventDefault(); cursor = Math.max(cursor - 1, 0); mark(visible); }
|
|
2466
|
+
else if (e.key === "Home") { e.preventDefault(); cursor = 0; mark(visible); }
|
|
2467
|
+
else if (e.key === "End") { e.preventDefault(); cursor = Math.max(0, visible.length - 1); mark(visible); }
|
|
2468
|
+
else if (e.key === "Enter" || e.key === " ") { e.preventDefault(); if (cursor >= 0 && visible[cursor]) commit(visible[cursor]); }
|
|
2469
|
+
else if (e.key === "Escape") close();
|
|
2470
|
+
});
|
|
2471
|
+
wcListen(host, "click", (e) => {
|
|
2472
|
+
const opt = wcClosest(host, e.target, ".c-combobox__option");
|
|
2473
|
+
if (opt) { commit(opt); return; }
|
|
2474
|
+
if (!wcOwned(host, e.target) || !host.contains(e.target)) close();
|
|
2475
|
+
});
|
|
2476
|
+
}
|
|
2477
|
+
|
|
2478
|
+
// Outside-click dismissal for comboboxes. A single document listener is cheaper and
|
|
2479
|
+
let _comboboxDocWired = false;
|
|
2480
|
+
function wireComboboxDocDismiss() {
|
|
2481
|
+
if (_comboboxDocWired) return;
|
|
2482
|
+
_comboboxDocWired = true;
|
|
2483
|
+
document.addEventListener("click", (e) => {
|
|
2484
|
+
for (const host of document.querySelectorAll("contour-combobox, contour-shadow-combobox")) {
|
|
2485
|
+
const list = host.shadowRoot ? host.shadowRoot.querySelector(".c-combobox__list") : host.querySelector(".c-combobox__list");
|
|
2486
|
+
const input = host.shadowRoot ? host.shadowRoot.querySelector(".c-combobox__input") : host.querySelector(".c-combobox__input");
|
|
2487
|
+
if (!list || list.hasAttribute("hidden")) continue;
|
|
2488
|
+
const root = host.shadowRoot || host;
|
|
2489
|
+
if (root.contains(e.target)) continue;
|
|
2490
|
+
list.setAttribute("hidden", "");
|
|
2491
|
+
}
|
|
2492
|
+
});
|
|
2493
|
+
}
|
|
2494
|
+
|
|
2495
|
+
/**
|
|
2496
|
+
* The tree items a keyboard reader can actually reach. A collapsed branch carries
|
|
2497
|
+
* `hidden`, and a hidden element is not focusable, so a tab stop placed on one is
|
|
2498
|
+
* a stop the reader never arrives at — measured when this was missed: ArrowDown
|
|
2499
|
+
* left focus where it was and moved the only stop onto a hidden child.
|
|
2500
|
+
*/
|
|
2501
|
+
const visibleStops = (host) => wcAll(host, ".c-tree__toggle, .c-tree__leaf").filter((el) => !el.closest(".c-tree__children[hidden]"));
|
|
2502
|
+
|
|
2503
|
+
/** Tree: one toggle per branch, and `contour:toggle` so a page can persist it. */
|
|
2504
|
+
/** Wire tree toggle and keyboard navigation for a host. */
|
|
2505
|
+
export function wireTree(host) {
|
|
2506
|
+
// The ARIA shape and the tab stop are re-applied on every pass, before the
|
|
2507
|
+
const nodes = () => wcAll(host, ".c-tree__node");
|
|
2508
|
+
const rootList = wcSelfOrAll(host, "ul.c-tree")[0];
|
|
2509
|
+
if (rootList && !rootList.hasAttribute("role")) rootList.setAttribute("role", "tree");
|
|
2510
|
+
wcAll(host, ".c-tree__children").forEach((ul) => {
|
|
2511
|
+
if (!ul.hasAttribute("role")) ul.setAttribute("role", "group");
|
|
2512
|
+
});
|
|
2513
|
+
const levelOf = (node) => {
|
|
2514
|
+
let level = 1;
|
|
2515
|
+
for (let p = node.parentElement; p; p = p.parentElement) if (p.classList && p.classList.contains("c-tree__children")) level++;
|
|
2516
|
+
return level;
|
|
2517
|
+
};
|
|
2518
|
+
nodes().forEach((node) => {
|
|
2519
|
+
if (node.getAttribute("role") !== "treeitem") node.setAttribute("role", "treeitem");
|
|
2520
|
+
node.setAttribute("aria-level", String(levelOf(node)));
|
|
2521
|
+
const row = node.querySelector(":scope > .c-tree__row");
|
|
2522
|
+
if (row) node.setAttribute("aria-expanded", row.querySelector(":scope > .c-tree__toggle")?.getAttribute("aria-expanded") || "false");
|
|
2523
|
+
else if (node.hasAttribute("aria-expanded")) node.removeAttribute("aria-expanded");
|
|
2524
|
+
});
|
|
2525
|
+
// Exactly one tab stop. The author's own `tabindex="0"` is the choice, then the
|
|
2526
|
+
const stops = visibleStops(host);
|
|
2527
|
+
const authored = stops.find((el) => el.getAttribute("tabindex") === "0");
|
|
2528
|
+
const active = authored || stops.find((el) => el === document.activeElement) || stops[0];
|
|
2529
|
+
stops.forEach((el) => el.setAttribute("tabindex", el === active ? "0" : "-1"));
|
|
2530
|
+
// Hidden items are taken out of the sequence entirely, not left at whatever
|
|
2531
|
+
// value a previous pass gave them.
|
|
2532
|
+
wcAll(host, ".c-tree__toggle, .c-tree__leaf").forEach((el) => {
|
|
2533
|
+
if (!stops.includes(el)) el.setAttribute("tabindex", "-1");
|
|
2534
|
+
});
|
|
2535
|
+
|
|
2536
|
+
if (!wcClaim(host, "tree")) return;
|
|
2537
|
+
// Checkbox selection (F-08): track checked nodes and emit contour:select.
|
|
2538
|
+
host._selectedTree = host._selectedTree || new Set();
|
|
2539
|
+
let lastTreeIndex = -1;
|
|
2540
|
+
let treeModShift = false;
|
|
2541
|
+
let treeModCtrl = false;
|
|
2542
|
+
wcListen(host, "pointerdown", (e) => {
|
|
2543
|
+
treeModShift = Boolean(e.shiftKey);
|
|
2544
|
+
treeModCtrl = Boolean(e.ctrlKey || e.metaKey);
|
|
2545
|
+
});
|
|
2546
|
+
wcListen(host, "keydown", (e) => {
|
|
2547
|
+
treeModShift = Boolean(e.shiftKey);
|
|
2548
|
+
treeModCtrl = Boolean(e.ctrlKey || e.metaKey);
|
|
2549
|
+
});
|
|
2550
|
+
wcListen(host, "change", (e) => {
|
|
2551
|
+
const cb = e.target && e.target.closest ? e.target.closest(".c-tree__select") : null;
|
|
2552
|
+
if (!cb || !host.contains(cb)) return;
|
|
2553
|
+
const cbs = Array.from(host.querySelectorAll(".c-tree__select"));
|
|
2554
|
+
const idx = cbs.indexOf(cb);
|
|
2555
|
+
const nodeOf = (el) => el && el.closest ? el.closest(".c-tree__node") : null;
|
|
2556
|
+
const pathOf = (el) => { const n = nodeOf(el); return n && n.dataset ? n.dataset.path : null; };
|
|
2557
|
+
const path = pathOf(cb);
|
|
2558
|
+
const shift = Boolean(e.shiftKey || treeModShift);
|
|
2559
|
+
const mod = Boolean(e.ctrlKey || e.metaKey || treeModCtrl);
|
|
2560
|
+
treeModShift = false;
|
|
2561
|
+
treeModCtrl = false;
|
|
2562
|
+
if (shift && lastTreeIndex >= 0) {
|
|
2563
|
+
const from = Math.min(lastTreeIndex, idx);
|
|
2564
|
+
const to = Math.max(lastTreeIndex, idx);
|
|
2565
|
+
for (let i = from; i <= to; i++) {
|
|
2566
|
+
cbs[i].checked = cb.checked;
|
|
2567
|
+
const p = pathOf(cbs[i]);
|
|
2568
|
+
if (p) { if (cb.checked) host._selectedTree.add(p); else host._selectedTree.delete(p); }
|
|
2569
|
+
}
|
|
2570
|
+
} else if (!mod) {
|
|
2571
|
+
// single select: clear others unless ctrl
|
|
2572
|
+
if (cb.checked) {
|
|
2573
|
+
cbs.forEach((c, i) => {
|
|
2574
|
+
if (i !== idx && c.checked) {
|
|
2575
|
+
c.checked = false;
|
|
2576
|
+
const p = pathOf(c);
|
|
2577
|
+
if (p) host._selectedTree.delete(p);
|
|
2578
|
+
}
|
|
2579
|
+
});
|
|
2580
|
+
}
|
|
2581
|
+
if (path) { if (cb.checked) host._selectedTree.add(path); else host._selectedTree.delete(path); }
|
|
2582
|
+
} else {
|
|
2583
|
+
if (path) { if (cb.checked) host._selectedTree.add(path); else host._selectedTree.delete(path); }
|
|
2584
|
+
}
|
|
2585
|
+
lastTreeIndex = idx;
|
|
2586
|
+
wcEmit(host, "contour:select", { paths: Array.from(host._selectedTree) });
|
|
2587
|
+
});
|
|
2588
|
+
// Drag-and-drop (F-08): nodes are draggable; drop emits contour:move.
|
|
2589
|
+
wcAll(host, ".c-tree__node, .c-tree__leaf").forEach((n) => { if (!n.hasAttribute("draggable")) n.setAttribute("draggable", "true"); });
|
|
2590
|
+
let dragLabel = null;
|
|
2591
|
+
wcListen(host, "dragstart", (e) => {
|
|
2592
|
+
const node = wcClosest(host, e.target, ".c-tree__node, .c-tree__leaf");
|
|
2593
|
+
if (!node) return;
|
|
2594
|
+
dragLabel = (node.textContent || "").trim().slice(0, 120);
|
|
2595
|
+
if (e.dataTransfer) { e.dataTransfer.effectAllowed = "move"; try { e.dataTransfer.setData("text/plain", dragLabel); } catch (err) {} }
|
|
2596
|
+
});
|
|
2597
|
+
wcListen(host, "dragover", (e) => {
|
|
2598
|
+
const node = wcClosest(host, e.target, ".c-tree__node, .c-tree__leaf");
|
|
2599
|
+
if (!node) return;
|
|
2600
|
+
e.preventDefault();
|
|
2601
|
+
if (e.dataTransfer) e.dataTransfer.dropEffect = "move";
|
|
2602
|
+
});
|
|
2603
|
+
wcListen(host, "drop", (e) => {
|
|
2604
|
+
const node = wcClosest(host, e.target, ".c-tree__node, .c-tree__leaf");
|
|
2605
|
+
if (!node || !dragLabel) return;
|
|
2606
|
+
e.preventDefault();
|
|
2607
|
+
const toLabel = (node.textContent || "").trim().slice(0, 120);
|
|
2608
|
+
if (toLabel && toLabel !== dragLabel) {
|
|
2609
|
+
wcEmit(host, "contour:move", { from: dragLabel, to: toLabel });
|
|
2610
|
+
}
|
|
2611
|
+
dragLabel = null;
|
|
2612
|
+
});
|
|
2613
|
+
// Expanded-state persistence (BY-49), one path per component like tabs:
|
|
2614
|
+
const persist = host.getAttribute("persist");
|
|
2615
|
+
if (persist === "storage" && host.id) {
|
|
2616
|
+
try {
|
|
2617
|
+
const saved = localStorage.getItem("contour-tree:" + host.id);
|
|
2618
|
+
if (saved !== null) {
|
|
2619
|
+
const labels = JSON.parse(saved);
|
|
2620
|
+
if (Array.isArray(labels)) {
|
|
2621
|
+
const want = new Set(labels.map((l) => String(l)));
|
|
2622
|
+
wcAll(host, ".c-tree__row").forEach((row) => {
|
|
2623
|
+
const currentToggle = row.querySelector(":scope > .c-tree__toggle");
|
|
2624
|
+
if (currentToggle?.getAttribute("aria-expanded") === "true") return;
|
|
2625
|
+
const label = (row.textContent || "").trim().slice(0, 120);
|
|
2626
|
+
if (!want.has(label)) return;
|
|
2627
|
+
const toggle = row.querySelector(":scope > .c-tree__toggle");
|
|
2628
|
+
if (!toggle) return;
|
|
2629
|
+
const node = row.closest(".c-tree__node");
|
|
2630
|
+
const children = node ? node.querySelector(":scope > .c-tree__children") : null;
|
|
2631
|
+
toggle.setAttribute("aria-expanded", "true");
|
|
2632
|
+
if (node) node.setAttribute("aria-expanded", "true");
|
|
2633
|
+
if (children) children.removeAttribute("hidden");
|
|
2634
|
+
});
|
|
2635
|
+
}
|
|
2636
|
+
}
|
|
2637
|
+
} catch (e) { /* private mode / malformed: keep the authored state */ }
|
|
2638
|
+
} else if (persist === "url") {
|
|
2639
|
+
try {
|
|
2640
|
+
const v = new URLSearchParams(window.location.search).get("c-tree");
|
|
2641
|
+
if (v !== null) {
|
|
2642
|
+
const labels = JSON.parse(v);
|
|
2643
|
+
if (Array.isArray(labels)) {
|
|
2644
|
+
const want = new Set(labels.map((l) => String(l)));
|
|
2645
|
+
wcAll(host, ".c-tree__row").forEach((row) => {
|
|
2646
|
+
const currentToggle = row.querySelector(":scope > .c-tree__toggle");
|
|
2647
|
+
if (currentToggle?.getAttribute("aria-expanded") === "true") return;
|
|
2648
|
+
const label = (row.textContent || "").trim().slice(0, 120);
|
|
2649
|
+
if (!want.has(label)) return;
|
|
2650
|
+
const toggle = row.querySelector(":scope > .c-tree__toggle");
|
|
2651
|
+
if (!toggle) return;
|
|
2652
|
+
const node = row.closest(".c-tree__node");
|
|
2653
|
+
const children = node ? node.querySelector(":scope > .c-tree__children") : null;
|
|
2654
|
+
toggle.setAttribute("aria-expanded", "true");
|
|
2655
|
+
if (node) node.setAttribute("aria-expanded", "true");
|
|
2656
|
+
if (children) children.removeAttribute("hidden");
|
|
2657
|
+
});
|
|
2658
|
+
}
|
|
2659
|
+
}
|
|
2660
|
+
} catch (e) { /* malformed param: keep the authored state */ }
|
|
2661
|
+
}
|
|
2662
|
+
const toggleNode = (toggle) => {
|
|
2663
|
+
const wasOpen = toggle.getAttribute("aria-expanded") === "true";
|
|
2664
|
+
toggle.setAttribute("aria-expanded", String(!wasOpen));
|
|
2665
|
+
const row = toggle.closest(".c-tree__row") || toggle.parentElement;
|
|
2666
|
+
const node = toggle.closest(".c-tree__node");
|
|
2667
|
+
const children = node ? node.querySelector(":scope > .c-tree__children") : null;
|
|
2668
|
+
if (children) {
|
|
2669
|
+
if (wasOpen) {
|
|
2670
|
+
if (supportsUntilFound()) children.setAttribute("hidden", "until-found");
|
|
2671
|
+
else children.hidden = true;
|
|
2672
|
+
} else {
|
|
2673
|
+
children.removeAttribute("hidden");
|
|
2674
|
+
}
|
|
2675
|
+
}
|
|
2676
|
+
if (node) node.setAttribute("aria-expanded", String(!wasOpen));
|
|
2677
|
+
wcEmit(host, "contour:toggle", { open: !wasOpen, label: (row ? row.textContent : "").trim().slice(0, 120) });
|
|
2678
|
+
// Persist expanded state (BY-49): collect all currently-open rows.
|
|
2679
|
+
if (persist === "storage" && host.id) {
|
|
2680
|
+
try {
|
|
2681
|
+
const open = [];
|
|
2682
|
+
wcAll(host, ".c-tree__row").forEach((r) => {
|
|
2683
|
+
const toggle = r.querySelector(":scope > .c-tree__toggle");
|
|
2684
|
+
if (toggle?.getAttribute("aria-expanded") === "true") open.push((r.textContent || "").trim().slice(0, 120));
|
|
2685
|
+
});
|
|
2686
|
+
localStorage.setItem("contour-tree:" + host.id, JSON.stringify(open));
|
|
2687
|
+
} catch (e) {}
|
|
2688
|
+
} else if (persist === "url") {
|
|
2689
|
+
try {
|
|
2690
|
+
const open = [];
|
|
2691
|
+
wcAll(host, ".c-tree__row").forEach((r) => {
|
|
2692
|
+
const toggle = r.querySelector(":scope > .c-tree__toggle");
|
|
2693
|
+
if (toggle?.getAttribute("aria-expanded") === "true") open.push((r.textContent || "").trim().slice(0, 120));
|
|
2694
|
+
});
|
|
2695
|
+
const url = new URL(window.location.href);
|
|
2696
|
+
url.searchParams.set("c-tree", JSON.stringify(open));
|
|
2697
|
+
window.history.replaceState(null, "", url.toString());
|
|
2698
|
+
} catch (e) {}
|
|
2699
|
+
}
|
|
2700
|
+
};
|
|
2701
|
+
const branchOf = (el) => (el.classList && el.classList.contains("c-tree__toggle") ? el : null);
|
|
2702
|
+
const stopsOf = () => visibleStops(host);
|
|
2703
|
+
// The kept element takes the single stop; every other item — visible or hidden —
|
|
2704
|
+
// is dropped to -1, so opening a branch cannot leave two stops behind.
|
|
2705
|
+
const rove = (keep) => {
|
|
2706
|
+
wcAll(host, ".c-tree__toggle, .c-tree__leaf").forEach((el) => el.setAttribute("tabindex", el === keep ? "0" : "-1"));
|
|
2707
|
+
};
|
|
2708
|
+
// R24-17: virtual trees render from host._expanded (a Set of paths), so a
|
|
2709
|
+
const virtualToggle = (toggle, open) => {
|
|
2710
|
+
const nodeEl = toggle.closest(".c-tree__node");
|
|
2711
|
+
const path = nodeEl && nodeEl.dataset ? nodeEl.dataset.path : null;
|
|
2712
|
+
if (path && host._expanded) { if (open) host._expanded.add(path); else host._expanded.delete(path); }
|
|
2713
|
+
const s = host._treeRoot;
|
|
2714
|
+
if (s) {
|
|
2715
|
+
host._treeScrollTop = s.scrollTop || 0;
|
|
2716
|
+
host._renderWindow(s, host._treeScrollTop);
|
|
2717
|
+
try { s.scrollTop = host._treeScrollTop; } catch (err) {}
|
|
2718
|
+
const again = path ? s.querySelector('.c-tree__node[data-path="' + path + '"] > .c-tree__row > .c-tree__toggle') : null;
|
|
2719
|
+
if (again) { again.focus(); rove(again); }
|
|
2720
|
+
}
|
|
2721
|
+
if (host._persistExpanded) host._persistExpanded();
|
|
2722
|
+
};
|
|
2723
|
+
wcListen(host, "click", (e) => {
|
|
2724
|
+
// Virtual trees are handled by ContourTree's own click handler in
|
|
2725
|
+
if (host.hasAttribute("virtual")) return;
|
|
2726
|
+
let toggle = wcClosest(host, e.target, ".c-tree__toggle");
|
|
2727
|
+
if (!toggle) {
|
|
2728
|
+
const row = wcClosest(host, e.target, ".c-tree__row");
|
|
2729
|
+
if (row) toggle = row.querySelector(":scope > .c-tree__toggle");
|
|
2730
|
+
}
|
|
2731
|
+
if (!toggle) return;
|
|
2732
|
+
e.preventDefault();
|
|
2733
|
+
e.stopPropagation();
|
|
2734
|
+
toggleNode(toggle);
|
|
2735
|
+
});
|
|
2736
|
+
wcListen(host, "focusin", (e) => {
|
|
2737
|
+
// Roving the tab stop with focus, so the tree is one Tab and not N.
|
|
2738
|
+
if (!wcClosest(host, e.target, ".c-tree__toggle, .c-tree__leaf")) return;
|
|
2739
|
+
rove(e.target);
|
|
2740
|
+
});
|
|
2741
|
+
wcListen(host, "keydown", (e) => {
|
|
2742
|
+
const toggle = wcClosest(host, e.target, ".c-tree__toggle, .c-tree__leaf");
|
|
2743
|
+
if (!toggle) return;
|
|
2744
|
+
const items = stopsOf();
|
|
2745
|
+
const idx = items.indexOf(toggle);
|
|
2746
|
+
if (e.key === "Enter" || e.key === " ") {
|
|
2747
|
+
const branch = branchOf(toggle);
|
|
2748
|
+
if (branch) {
|
|
2749
|
+
e.preventDefault();
|
|
2750
|
+
if (host.hasAttribute("virtual")) {
|
|
2751
|
+
// Virtual trees own their model + re-render; drive it directly.
|
|
2752
|
+
virtualToggle(branch, branch.getAttribute("aria-expanded") !== "true");
|
|
2753
|
+
} else {
|
|
2754
|
+
toggleNode(branch);
|
|
2755
|
+
}
|
|
2756
|
+
return;
|
|
2757
|
+
}
|
|
2758
|
+
// R24-73: keyboard selection of a leaf matches clicking its checkbox, so
|
|
2759
|
+
// click and keyboard behave consistently.
|
|
2760
|
+
if (host.hasAttribute("selectable")) {
|
|
2761
|
+
const leaf = toggle.classList.contains("c-tree__leaf") ? toggle : toggle.closest(".c-tree__leaf");
|
|
2762
|
+
const cb = leaf ? leaf.querySelector(".c-tree__select") : null;
|
|
2763
|
+
if (cb) {
|
|
2764
|
+
e.preventDefault();
|
|
2765
|
+
cb.click();
|
|
2766
|
+
}
|
|
2767
|
+
}
|
|
2768
|
+
return;
|
|
2769
|
+
}
|
|
2770
|
+
// Right opens a branch, Left closes it — the pair a tree reader expects, and
|
|
2771
|
+
// the only way to reach a collapsed branch's children without a mouse.
|
|
2772
|
+
if (e.key === "ArrowRight") {
|
|
2773
|
+
const branch = branchOf(toggle);
|
|
2774
|
+
const closed = branch && branch.getAttribute("aria-expanded") === "false";
|
|
2775
|
+
e.preventDefault();
|
|
2776
|
+
if (closed) {
|
|
2777
|
+
if (host.hasAttribute("virtual")) {
|
|
2778
|
+
virtualToggle(branch, true);
|
|
2779
|
+
} else {
|
|
2780
|
+
toggleNode(branch);
|
|
2781
|
+
rove(toggle);
|
|
2782
|
+
}
|
|
2783
|
+
}
|
|
2784
|
+
else { const next = items[idx + 1]; if (next) { next.focus(); rove(next); } }
|
|
2785
|
+
return;
|
|
2786
|
+
}
|
|
2787
|
+
if (e.key === "ArrowLeft") {
|
|
2788
|
+
const branch = branchOf(toggle);
|
|
2789
|
+
if (branch && branch.getAttribute("aria-expanded") === "true") {
|
|
2790
|
+
e.preventDefault();
|
|
2791
|
+
if (host.hasAttribute("virtual")) {
|
|
2792
|
+
virtualToggle(branch, false);
|
|
2793
|
+
} else {
|
|
2794
|
+
toggleNode(branch);
|
|
2795
|
+
rove(toggle);
|
|
2796
|
+
}
|
|
2797
|
+
} else {
|
|
2798
|
+
const parent = toggle.closest(".c-tree__children");
|
|
2799
|
+
const owner = parent ? parent.closest(".c-tree__node") : null;
|
|
2800
|
+
const up = owner ? owner.querySelector(":scope > .c-tree__row > .c-tree__toggle") : null;
|
|
2801
|
+
if (up) { e.preventDefault(); up.focus(); rove(up); }
|
|
2802
|
+
}
|
|
2803
|
+
return;
|
|
2804
|
+
}
|
|
2805
|
+
navKey(e, items, { wrap: false, homeEnd: true, onNavigate: (i) => rove(items[i]) });
|
|
2806
|
+
});
|
|
2807
|
+
}
|
|
2808
|
+
|
|
2809
|
+
/** Menu: roving focus over items, `contour:select` from key or pointer. */
|
|
2810
|
+
/** Wire menu keyboard navigation and selection for a host. */
|
|
2811
|
+
export function wireMenu(host) {
|
|
2812
|
+
// R24-37: include menuitemcheckbox and menuitemradio in the selector.
|
|
2813
|
+
const SEL = "[role='menuitem'], [role='menuitemcheckbox'], [role='menuitemradio']";
|
|
2814
|
+
wcAll(host, SEL).forEach((it) => { if (!it.hasAttribute("tabindex")) it.setAttribute("tabindex", it.getAttribute("aria-disabled") === "true" ? "-1" : "-1"); });
|
|
2815
|
+
const all = () => wcAll(host, SEL);
|
|
2816
|
+
if (!all().some((it) => it.getAttribute("tabindex") === "0") && all().length) {
|
|
2817
|
+
const first = all().find((it) => it.getAttribute("aria-disabled") !== "true");
|
|
2818
|
+
if (first) first.setAttribute("tabindex", "0");
|
|
2819
|
+
}
|
|
2820
|
+
if (!wcClaim(host, "menu")) return;
|
|
2821
|
+
|
|
2822
|
+
const submenusOf = (item) => item.querySelector(":scope > ul.c-menu, :scope > .c-menu");
|
|
2823
|
+
const closeAllSubmenus = () => {
|
|
2824
|
+
wcAll(host, "[aria-haspopup='menu']").forEach((it) => it.setAttribute("aria-expanded", "false"));
|
|
2825
|
+
};
|
|
2826
|
+
|
|
2827
|
+
wcListen(host, "keydown", (e) => {
|
|
2828
|
+
const its = all().filter((it) => it.getAttribute("aria-disabled") !== "true");
|
|
2829
|
+
if (!its.length) return;
|
|
2830
|
+
const index = its.indexOf(e.target);
|
|
2831
|
+
const target = index >= 0 ? its[index] : null;
|
|
2832
|
+
const sub = target ? submenusOf(target) : null;
|
|
2833
|
+
|
|
2834
|
+
// Submenu open (F-02): ArrowRight / Enter on a haspopup item opens it.
|
|
2835
|
+
if (target && target.getAttribute("aria-haspopup") === "menu" && (e.key === "ArrowRight" || e.key === "Enter" || e.key === " ")) {
|
|
2836
|
+
if (sub) {
|
|
2837
|
+
e.preventDefault();
|
|
2838
|
+
closeAllSubmenus();
|
|
2839
|
+
target.setAttribute("aria-expanded", "true");
|
|
2840
|
+
const firstSub = sub.querySelector("[role='menuitem']");
|
|
2841
|
+
if (firstSub) { firstSub.setAttribute("tabindex", "0"); try { firstSub.focus(); } catch (err) {} }
|
|
2842
|
+
return;
|
|
2843
|
+
}
|
|
2844
|
+
}
|
|
2845
|
+
// Submenu close: ArrowLeft / Escape.
|
|
2846
|
+
if (e.key === "ArrowLeft" || e.key === "Escape") {
|
|
2847
|
+
const parent = target ? target.closest("ul.c-menu") : null;
|
|
2848
|
+
// find the haspopup ancestor item
|
|
2849
|
+
let ancestor = null;
|
|
2850
|
+
if (target) {
|
|
2851
|
+
const ul = target.parentElement && target.parentElement.tagName === "UL" ? target.parentElement : null;
|
|
2852
|
+
// walk up to find a li with aria-haspopup whose submenu contains target
|
|
2853
|
+
let node = target.parentElement;
|
|
2854
|
+
while (node && node !== host) {
|
|
2855
|
+
if (node.getAttribute && node.getAttribute("aria-haspopup") === "menu" && node.contains(target) && node !== target) { ancestor = node; break; }
|
|
2856
|
+
node = node.parentElement;
|
|
2857
|
+
}
|
|
2858
|
+
}
|
|
2859
|
+
if (ancestor) {
|
|
2860
|
+
e.preventDefault();
|
|
2861
|
+
ancestor.setAttribute("aria-expanded", "false");
|
|
2862
|
+
try { ancestor.focus(); } catch (err) {}
|
|
2863
|
+
return;
|
|
2864
|
+
}
|
|
2865
|
+
if (e.key === "Escape") {
|
|
2866
|
+
closeAllSubmenus();
|
|
2867
|
+
}
|
|
2868
|
+
}
|
|
2869
|
+
|
|
2870
|
+
navKey(e, its, { wrap: true, homeEnd: true, onKey: () => { if (e.key === "Enter" || e.key === " ") { const idx = its.indexOf(document.activeElement); if (idx >= 0 && !(target && target.getAttribute("aria-haspopup") === "menu")) { const role = its[idx].getAttribute("role"); if (role === "menuitemcheckbox" || role === "menuitemradio") { const checked = its[idx].getAttribute("aria-checked") === "true"; if (role === "menuitemradio") its.forEach((x) => { if (x !== its[idx] && x.getAttribute("role") === "menuitemradio") x.setAttribute("aria-checked", "false"); }); its[idx].setAttribute("aria-checked", String(!checked)); wcEmit(host, "contour:select", { index: idx, label: its[idx].textContent.trim(), checked: !checked }); } else { wcEmit(host, "contour:select", { index: idx, label: its[idx].textContent.trim() }); } closeAllSubmenus(); } } } });
|
|
2871
|
+
// Typeahead (F-21): printable char jumps to the first item whose label
|
|
2872
|
+
// starts with the typed character.
|
|
2873
|
+
if (e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey) {
|
|
2874
|
+
const ch = e.key.toLowerCase();
|
|
2875
|
+
const match = its.findIndex((it) => (it.textContent || "").trim().toLowerCase().startsWith(ch));
|
|
2876
|
+
if (match >= 0) { e.preventDefault(); its[match].focus(); }
|
|
2877
|
+
}
|
|
2878
|
+
});
|
|
2879
|
+
wcListen(host, "click", (e) => {
|
|
2880
|
+
const item = wcClosest(host, e.target, SEL);
|
|
2881
|
+
if (!item) return;
|
|
2882
|
+
if (item.getAttribute("aria-disabled") === "true") return;
|
|
2883
|
+
// R24-37: toggle aria-checked on checkbox/radio items.
|
|
2884
|
+
const role = item.getAttribute("role");
|
|
2885
|
+
if (role === "menuitemcheckbox" || role === "menuitemradio") {
|
|
2886
|
+
const checked = item.getAttribute("aria-checked") === "true";
|
|
2887
|
+
if (role === "menuitemradio") {
|
|
2888
|
+
all().forEach((x) => { if (x !== item && x.getAttribute("role") === "menuitemradio") x.setAttribute("aria-checked", "false"); });
|
|
2889
|
+
}
|
|
2890
|
+
item.setAttribute("aria-checked", String(!checked));
|
|
2891
|
+
wcEmit(host, "contour:select", { index: all().indexOf(item), label: item.textContent.trim(), checked: !checked });
|
|
2892
|
+
return;
|
|
2893
|
+
}
|
|
2894
|
+
// Toggle submenu on click for haspopup items.
|
|
2895
|
+
if (item.getAttribute("aria-haspopup") === "menu") {
|
|
2896
|
+
const sub = submenusOf(item);
|
|
2897
|
+
if (sub) {
|
|
2898
|
+
const open = item.getAttribute("aria-expanded") === "true";
|
|
2899
|
+
closeAllSubmenus();
|
|
2900
|
+
item.setAttribute("aria-expanded", open ? "false" : "true");
|
|
2901
|
+
return;
|
|
2902
|
+
}
|
|
2903
|
+
}
|
|
2904
|
+
const index = all().indexOf(item);
|
|
2905
|
+
if (index >= 0) {
|
|
2906
|
+
wcEmit(host, "contour:select", { index, label: item.textContent.trim() });
|
|
2907
|
+
closeAllSubmenus();
|
|
2908
|
+
// close-on-select: if the menu is a popover, hide it.
|
|
2909
|
+
if (typeof host.hidePopover === "function") { try { host.hidePopover(); } catch (e) {} }
|
|
2910
|
+
}
|
|
2911
|
+
});
|
|
2912
|
+
}
|
|
2913
|
+
|
|
2914
|
+
/** Pagination: `[aria-current="page"]` is the state the sheet paints. */
|
|
2915
|
+
/** Wire pagination controls for a host. */
|
|
2916
|
+
export function wirePagination(host) {
|
|
2917
|
+
wcAll(host, ".c-pagination__link").forEach((b) => { if (!b.hasAttribute("tabindex")) b.setAttribute("tabindex", "0"); });
|
|
2918
|
+
if (!wcClaim(host, "pagination")) return;
|
|
2919
|
+
const activate = (btn) => {
|
|
2920
|
+
const page = parseInt(btn.textContent, 10);
|
|
2921
|
+
if (!Number.isFinite(page)) return;
|
|
2922
|
+
wcAll(host, ".c-pagination__link").forEach((b) => {
|
|
2923
|
+
if (parseInt(b.textContent, 10) === page) b.setAttribute("aria-current", "page");
|
|
2924
|
+
else b.removeAttribute("aria-current");
|
|
2925
|
+
});
|
|
2926
|
+
host.setAttribute("page", String(page));
|
|
2927
|
+
wcEmit(host, "contour:page", { page });
|
|
2928
|
+
if (host.getAttribute("persist") === "storage" && host.id) {
|
|
2929
|
+
try { localStorage.setItem("contour-pagination:" + host.id, String(page)); } catch (e) {}
|
|
2930
|
+
} else if (host.getAttribute("persist") === "url") {
|
|
2931
|
+
try { const url = new URL(window.location.href); url.searchParams.set("c-pagination", String(page)); window.history.replaceState(null, "", url.toString()); } catch (e) {}
|
|
2932
|
+
}
|
|
2933
|
+
};
|
|
2934
|
+
wcListen(host, "click", (e) => {
|
|
2935
|
+
const btn = wcClosest(host, e.target, ".c-pagination__link");
|
|
2936
|
+
if (!btn) return;
|
|
2937
|
+
e.preventDefault();
|
|
2938
|
+
const action = btn.getAttribute("data-action");
|
|
2939
|
+
if (action === "prev" || action === "next") {
|
|
2940
|
+
const links = wcAll(host, ".c-pagination__link").filter((b) => !b.getAttribute("data-action"));
|
|
2941
|
+
const cur = links.find((b) => b.getAttribute("aria-current") === "page");
|
|
2942
|
+
const curPage = cur ? (parseInt(cur.textContent, 10) || 1) : 1;
|
|
2943
|
+
const page = action === "prev" ? Math.max(1, curPage - 1) : Math.min(links.length, curPage + 1);
|
|
2944
|
+
const target = links.find((b) => parseInt(b.textContent, 10) === page);
|
|
2945
|
+
if (target) { activate(target); return; }
|
|
2946
|
+
}
|
|
2947
|
+
activate(btn);
|
|
2948
|
+
});
|
|
2949
|
+
wcListen(host, "keydown", (e) => {
|
|
2950
|
+
const btn = wcClosest(host, e.target, ".c-pagination__link");
|
|
2951
|
+
if (!btn) return;
|
|
2952
|
+
const links = wcAll(host, ".c-pagination__link");
|
|
2953
|
+
const idx = links.indexOf(btn);
|
|
2954
|
+
let next = -1;
|
|
2955
|
+
const rtl = isRtl(host);
|
|
2956
|
+
if (e.key === "ArrowRight") next = rtl ? Math.max(idx - 1, 0) : Math.min(idx + 1, links.length - 1);
|
|
2957
|
+
else if (e.key === "ArrowLeft") next = rtl ? Math.min(idx + 1, links.length - 1) : Math.max(idx - 1, 0);
|
|
2958
|
+
else if (e.key === "Home") next = 0;
|
|
2959
|
+
else if (e.key === "End") next = links.length - 1;
|
|
2960
|
+
else if (e.key === "Enter" || e.key === " ") { e.preventDefault(); activate(btn); return; }
|
|
2961
|
+
if (next >= 0 && next !== idx) { e.preventDefault(); links[next].focus(); }
|
|
2962
|
+
});
|
|
2963
|
+
}
|
|
2964
|
+
|
|
2965
|
+
/**
|
|
2966
|
+
* Copy. `.c-code__copy` copies its block, `.c-install__copy` its command — one
|
|
2967
|
+
* handler because both need the same three things: the text, the clipboard, and
|
|
2968
|
+
* a `contour:copy` a page can toast from when the clipboard is denied.
|
|
2969
|
+
*/
|
|
2970
|
+
/** Wire copy-to-clipboard behaviour for a host. */
|
|
2971
|
+
export function wireCopy(host) {
|
|
2972
|
+
if (!wcClaim(host, "copy")) return;
|
|
2973
|
+
wcListen(host, "click", (e) => {
|
|
2974
|
+
const btn = wcClosest(host, e.target, ".c-code__copy, .c-install__copy");
|
|
2975
|
+
if (!btn) return;
|
|
2976
|
+
const owner = wcClosest(host, btn, ".c-code") || wcClosest(host, btn, ".c-install") || host;
|
|
2977
|
+
const src = owner.querySelector("code, .c-install__command");
|
|
2978
|
+
// A numbered block carries its gutter as elements inside the <code>, so
|
|
2979
|
+
const readSource = (el) => {
|
|
2980
|
+
const lines = el && el.querySelectorAll ? el.querySelectorAll(".c-code__line") : null;
|
|
2981
|
+
if (!lines || !lines.length) return el ? el.textContent || "" : "";
|
|
2982
|
+
return Array.from(lines).map((l) => Array.from(l.childNodes)
|
|
2983
|
+
.filter((n) => !(n.classList && n.classList.contains("c-code__line-number")))
|
|
2984
|
+
.map((n) => n.textContent).join("")).join("\n");
|
|
2985
|
+
};
|
|
2986
|
+
const text = readSource(src) || (src ? "" : owner.textContent) || "";
|
|
2987
|
+
// The confirmation is the one the system script paints for the guide's own
|
|
2988
|
+
const confirm = (ok) => {
|
|
2989
|
+
const icon = btn.querySelector("use");
|
|
2990
|
+
const originalHref = icon && icon.getAttribute("href");
|
|
2991
|
+
const originalLabel = btn.getAttribute("aria-label") || btn.title || "";
|
|
2992
|
+
if (ok && icon) icon.setAttribute("href", "#i-check");
|
|
2993
|
+
btn.setAttribute("aria-label", ok ? "Copied" : "Copy failed");
|
|
2994
|
+
btn.dataset.copied = String(ok);
|
|
2995
|
+
const timer = setTimeout(() => {
|
|
2996
|
+
if (!btn.isConnected) return;
|
|
2997
|
+
if (icon && originalHref) icon.setAttribute("href", originalHref);
|
|
2998
|
+
btn.setAttribute("aria-label", originalLabel);
|
|
2999
|
+
delete btn.dataset.copied;
|
|
3000
|
+
btn._copyTimer = null;
|
|
3001
|
+
}, 1600);
|
|
3002
|
+
if (btn._copyTimer) clearTimeout(btn._copyTimer);
|
|
3003
|
+
btn._copyTimer = timer;
|
|
3004
|
+
};
|
|
3005
|
+
const doCopy = async () => {
|
|
3006
|
+
try {
|
|
3007
|
+
if (navigator.clipboard && navigator.clipboard.writeText) {
|
|
3008
|
+
await navigator.clipboard.writeText(text);
|
|
3009
|
+
return true;
|
|
3010
|
+
}
|
|
3011
|
+
} catch (e) { /* fall through */ }
|
|
3012
|
+
try {
|
|
3013
|
+
const ta = document.createElement("textarea");
|
|
3014
|
+
ta.value = text;
|
|
3015
|
+
ta.setAttribute("readonly", "");
|
|
3016
|
+
ta.style.position = "fixed";
|
|
3017
|
+
ta.style.top = "-9999px";
|
|
3018
|
+
ta.style.opacity = "0";
|
|
3019
|
+
document.body.append(ta);
|
|
3020
|
+
ta.select();
|
|
3021
|
+
const ok = document.execCommand("copy");
|
|
3022
|
+
ta.remove();
|
|
3023
|
+
return ok;
|
|
3024
|
+
} catch (e) {
|
|
3025
|
+
return false;
|
|
3026
|
+
}
|
|
3027
|
+
};
|
|
3028
|
+
doCopy().then((ok) => confirm(ok));
|
|
3029
|
+
wcEmit(host, "contour:copy", { text });
|
|
3030
|
+
});
|
|
3031
|
+
}
|
|
3032
|
+
|
|
3033
|
+
/**
|
|
3034
|
+
* Removable things: a tag, a filter pill, and the empty state's retry. The
|
|
3035
|
+
* affordance is the control's job to remove and to say so; keeping the node in
|
|
3036
|
+
* sync with the event is what makes the two copies of this rule agree.
|
|
3037
|
+
*/
|
|
3038
|
+
/** Wire removable-item (chip/tag) dismissal for a host. */
|
|
3039
|
+
export function wireRemovable(host) {
|
|
3040
|
+
if (!wcClaim(host, "removable")) return;
|
|
3041
|
+
wcListen(host, "click", (e) => {
|
|
3042
|
+
const drop = (node) => { if (node && node.parentNode) node.parentNode.removeChild(node); };
|
|
3043
|
+
const tagBtn = wcClosest(host, e.target, ".c-tag__remove");
|
|
3044
|
+
if (tagBtn) {
|
|
3045
|
+
e.preventDefault();
|
|
3046
|
+
const tag = wcClosest(host, tagBtn, ".c-tag");
|
|
3047
|
+
wcEmit(host, "contour:remove", { label: (tag && tag.getAttribute("label")) || (tag ? tag.textContent.trim() : "") });
|
|
3048
|
+
drop(tag);
|
|
3049
|
+
return;
|
|
3050
|
+
}
|
|
3051
|
+
const pillBtn = wcClosest(host, e.target, ".c-filter-pill__remove");
|
|
3052
|
+
if (pillBtn) {
|
|
3053
|
+
e.preventDefault();
|
|
3054
|
+
const pill = wcClosest(host, pillBtn, ".c-filter-pill");
|
|
3055
|
+
wcEmit(host, "contour:remove", { key: pill && pill.getAttribute("key"), value: pill && pill.getAttribute("value") });
|
|
3056
|
+
drop(pill);
|
|
3057
|
+
return;
|
|
3058
|
+
}
|
|
3059
|
+
if (wcClosest(host, e.target, "[data-empty-action]")) {
|
|
3060
|
+
wcEmit(host, "contour:empty-action", { state: host.getAttribute("state") || "empty" });
|
|
3061
|
+
}
|
|
3062
|
+
const alertClose = wcClosest(host, e.target, ".c-alert__close");
|
|
3063
|
+
if (alertClose) {
|
|
3064
|
+
e.preventDefault();
|
|
3065
|
+
wcEmit(host, "contour:close", {});
|
|
3066
|
+
if (host.shadowRoot ? host.shadowRoot.contains(alertClose) : true) {
|
|
3067
|
+
try { host.remove(); } catch (err) {}
|
|
3068
|
+
}
|
|
3069
|
+
return;
|
|
3070
|
+
}
|
|
3071
|
+
const calloutClose = wcClosest(host, e.target, ".c-callout__close");
|
|
3072
|
+
if (calloutClose) {
|
|
3073
|
+
e.preventDefault();
|
|
3074
|
+
wcEmit(host, "contour:close", {});
|
|
3075
|
+
try { host.remove(); } catch (err) {}
|
|
3076
|
+
return;
|
|
3077
|
+
}
|
|
3078
|
+
});
|
|
3079
|
+
}
|
|
3080
|
+
|
|
3081
|
+
// Modal containment for the light dialog family (BY-46). A native <dialog> in
|
|
3082
|
+
const modalDepth = { n: 0 };
|
|
3083
|
+
let modalSavedOverflow = null;
|
|
3084
|
+
let modalSavedX = 0;
|
|
3085
|
+
let modalSavedY = 0;
|
|
3086
|
+
const modalInerted = new Set();
|
|
3087
|
+
const modalStack = [];
|
|
3088
|
+
let modalTrapWired = false;
|
|
3089
|
+
// R24-15: per-host inert tracking. When modal B opens on top of modal A,
|
|
3090
|
+
const modalInertedBy = new Map(); // host -> Set of inerted siblings
|
|
3091
|
+
|
|
3092
|
+
function modalFocusables(host) {
|
|
3093
|
+
return Array.from(host.querySelectorAll("button, [href], input, select, textarea, [tabindex]:not([tabindex='-1'])"))
|
|
3094
|
+
.filter((el) => !el.hasAttribute("disabled") && el.getAttribute("aria-hidden") !== "true");
|
|
3095
|
+
}
|
|
3096
|
+
|
|
3097
|
+
function modalTrapHandler(e) {
|
|
3098
|
+
if (e.key !== "Tab") return;
|
|
3099
|
+
const host = modalStack[modalStack.length - 1];
|
|
3100
|
+
if (!host) return;
|
|
3101
|
+
const f = modalFocusables(host);
|
|
3102
|
+
if (!f.length) { e.preventDefault(); return; }
|
|
3103
|
+
const first = f[0];
|
|
3104
|
+
const last = f[f.length - 1];
|
|
3105
|
+
const active = document.activeElement;
|
|
3106
|
+
if (e.shiftKey) {
|
|
3107
|
+
if (active === first || !host.contains(active)) { e.preventDefault(); last.focus(); }
|
|
3108
|
+
} else {
|
|
3109
|
+
if (active === last) { e.preventDefault(); first.focus(); }
|
|
3110
|
+
}
|
|
3111
|
+
}
|
|
3112
|
+
|
|
3113
|
+
/** Contain focus within a modal host while open. */
|
|
3114
|
+
export function modalContain(host, open) {
|
|
3115
|
+
if (open) {
|
|
3116
|
+
if (modalDepth.n === 0) {
|
|
3117
|
+
// The lock itself clamps the scroll (overflow:hidden on the scroller),
|
|
3118
|
+
modalSavedX = window.scrollX;
|
|
3119
|
+
modalSavedY = window.scrollY;
|
|
3120
|
+
modalSavedOverflow = document.documentElement.style.overflow;
|
|
3121
|
+
document.documentElement.style.overflow = "hidden";
|
|
3122
|
+
}
|
|
3123
|
+
modalDepth.n += 1;
|
|
3124
|
+
modalStack.push(host);
|
|
3125
|
+
if (modalDepth.n === 1 && !modalTrapWired) {
|
|
3126
|
+
modalTrapWired = true;
|
|
3127
|
+
document.addEventListener("keydown", modalTrapHandler);
|
|
3128
|
+
}
|
|
3129
|
+
// An ancestor cannot be inert (it would inert the whole subtree); the
|
|
3130
|
+
const inerted = new Set();
|
|
3131
|
+
for (let el = host; el && el !== document.body; el = el.parentElement) {
|
|
3132
|
+
for (const sib of el.parentElement.children) {
|
|
3133
|
+
if (sib === el || sib.inert) continue;
|
|
3134
|
+
sib.inert = true;
|
|
3135
|
+
inerted.add(sib);
|
|
3136
|
+
}
|
|
3137
|
+
}
|
|
3138
|
+
modalInertedBy.set(host, inerted);
|
|
3139
|
+
} else {
|
|
3140
|
+
const idx = modalStack.lastIndexOf(host);
|
|
3141
|
+
if (idx >= 0) modalStack.splice(idx, 1);
|
|
3142
|
+
modalDepth.n = Math.max(0, modalDepth.n - 1);
|
|
3143
|
+
// Release only the siblings THIS host inerted (R24-15). A lower modal's
|
|
3144
|
+
// siblings stay inert while it is still open.
|
|
3145
|
+
const inerted = modalInertedBy.get(host);
|
|
3146
|
+
if (inerted) {
|
|
3147
|
+
for (const el of inerted) { el.inert = false; modalInerted.delete(el); }
|
|
3148
|
+
modalInertedBy.delete(host);
|
|
3149
|
+
}
|
|
3150
|
+
if (modalDepth.n === 0) {
|
|
3151
|
+
// Final cleanup: release anything still inerted (should be empty, but
|
|
3152
|
+
// guards against a host removed without a close).
|
|
3153
|
+
for (const el of modalInerted) el.inert = false;
|
|
3154
|
+
modalInerted.clear();
|
|
3155
|
+
document.documentElement.style.overflow = modalSavedOverflow || "";
|
|
3156
|
+
window.scrollTo(modalSavedX, modalSavedY);
|
|
3157
|
+
if (modalTrapWired) {
|
|
3158
|
+
document.removeEventListener("keydown", modalTrapHandler);
|
|
3159
|
+
modalTrapWired = false;
|
|
3160
|
+
}
|
|
3161
|
+
}
|
|
3162
|
+
}
|
|
3163
|
+
}
|
|
3164
|
+
|
|
3165
|
+
/* ============================================================================
|
|
3166
|
+
CONTOUR — data state and remote loading
|
|
3167
|
+
----------------------------------------------------------------------------
|
|
3168
|
+
One implementation of the four data states (`empty`, `loading`, `error`,
|
|
3169
|
+
`skeleton`) and of the remote source (`src`, plus `lazy`, `refresh`,
|
|
3170
|
+
`timeout`).
|
|
3171
|
+
|
|
3172
|
+
Before this file the same forty-line block was written into eight fragments by
|
|
3173
|
+
hand — 6 copies in `content.mjs`, 8 in `data.mjs`, 20 in `map.mjs`, 14 in
|
|
3174
|
+
`navigation.mjs` — and every copy carried the same defects, measured in
|
|
3175
|
+
Chromium against `dist/contour-wc.js` built at 7d75b3d (probe
|
|
3176
|
+
`tmp/wc9/probe.mjs`, 2026-10-27):
|
|
3177
|
+
|
|
3178
|
+
1. a host with `src` painted `"Loading…Loading…"` — two nodes — because the
|
|
3179
|
+
copy re-rendered by calling `attributeChangedCallback` from inside
|
|
3180
|
+
`render()`, which on the connect path is a synchronous nested render;
|
|
3181
|
+
2. a 404 and a malformed body both landed on the EMPTY state
|
|
3182
|
+
(`{"empty":1,"error":0,"text":"No data"}`), so the component claimed it had
|
|
3183
|
+
no data when in fact it had failed to fetch it;
|
|
3184
|
+
3. nothing aborted the request: a host removed mid-flight kept
|
|
3185
|
+
`loadingAfterDetach: 2` stale nodes and was still written to;
|
|
3186
|
+
4. the state was styled by an inline `style.color`, which beat the CSS rule
|
|
3187
|
+
written beside it in the same commit, so the rule was dead — and 33
|
|
3188
|
+
generated `c-*__skeleton` names had no rule anywhere.
|
|
3189
|
+
|
|
3190
|
+
Three rules fall out of that, and they are the whole design here.
|
|
3191
|
+
|
|
3192
|
+
Presentation belongs to the sheet. Nothing in this file writes a `style`
|
|
3193
|
+
attribute; a state node carries the block-scoped element class the system
|
|
3194
|
+
already defines (`c-readout__loading` — 102 of those exist in `src/css/`), so a
|
|
3195
|
+
generated class is never one the system cannot style.
|
|
3196
|
+
|
|
3197
|
+
A state is not a live region. `role="alert"` on a node that is inserted already
|
|
3198
|
+
carrying text is exactly what `tools/audit/contrast-and-aria.mjs` refuses: it
|
|
3199
|
+
scans every `[role="status"],[role="alert"],[aria-live]` whose text is non-empty
|
|
3200
|
+
at load, because such a region has no change left to announce. So the widget
|
|
3201
|
+
says `aria-busy` while it works and nothing at all when it has failed. A
|
|
3202
|
+
consumer that wants the failure spoken routes `contour:error` to the page's own
|
|
3203
|
+
`#toast-host`, which is present and empty for that purpose.
|
|
3204
|
+
|
|
3205
|
+
The loader is shared per URL, not per host: a dashboard that mounts forty
|
|
3206
|
+
chrome widgets against one endpoint should ask it once. That is also why the
|
|
3207
|
+
abort belongs to the last host out, not the first — see `leaveRequest`.
|
|
3208
|
+
========================================================================= */
|
|
3209
|
+
|
|
3210
|
+
// Copy. A component overrides any of these through its own attribute, because a
|
|
3211
|
+
/** Fallback state copy used when remote data is unavailable. */
|
|
3212
|
+
export const STATE_FALLBACK = {
|
|
3213
|
+
empty: "No data",
|
|
3214
|
+
chart: "No data",
|
|
3215
|
+
contour: "No field",
|
|
3216
|
+
dropdown: "No options",
|
|
3217
|
+
loading: "Loading…",
|
|
3218
|
+
error: "Could not load.",
|
|
3219
|
+
};
|
|
3220
|
+
|
|
3221
|
+
/**
|
|
3222
|
+
* Resolve a state label for a host (R18-63). A consumer supplies a `labels`
|
|
3223
|
+
* JSON attribute (e.g. `labels='{"loading":"Chargement…"}'`); it is merged over
|
|
3224
|
+
* the English default, so a partial object localises only the keys it names.
|
|
3225
|
+
* A malformed attribute is ignored rather than thrown — a bad label must not
|
|
3226
|
+
* take the widget down. Returns the default when no override is present.
|
|
3227
|
+
*/
|
|
3228
|
+
export function stateLabel(host, key) {
|
|
3229
|
+
const fallback = STATE_FALLBACK[key] || key;
|
|
3230
|
+
const raw = host && host.getAttribute ? host.getAttribute("labels") : null;
|
|
3231
|
+
if (!raw) return fallback;
|
|
3232
|
+
try {
|
|
3233
|
+
const parsed = JSON.parse(raw);
|
|
3234
|
+
if (parsed && typeof parsed === "object" && typeof parsed[key] === "string" && parsed[key]) return parsed[key];
|
|
3235
|
+
} catch (e) { /* a malformed labels attribute is ignored, not fatal */ }
|
|
3236
|
+
return fallback;
|
|
3237
|
+
}
|
|
3238
|
+
|
|
3239
|
+
// One in-flight request per URL, shared by every host that asked for it.
|
|
3240
|
+
const remoteInflight = new Map();
|
|
3241
|
+
// The last result per URL, so a re-mounted host paints instead of re-asking. A
|
|
3242
|
+
const REMOTE_CACHE_MAX = 64;
|
|
3243
|
+
const remoteCache = new Map();
|
|
3244
|
+
|
|
3245
|
+
function cacheResult(src, data) {
|
|
3246
|
+
if (remoteCache.size >= REMOTE_CACHE_MAX) remoteCache.delete(remoteCache.keys().next().value);
|
|
3247
|
+
remoteCache.set(src, data);
|
|
3248
|
+
}
|
|
3249
|
+
|
|
3250
|
+
function setStatus(host, status) {
|
|
3251
|
+
host._remoteStatus = status;
|
|
3252
|
+
if (status !== "error") host._remoteError = null;
|
|
3253
|
+
// `aria-busy` is the platform's own word for "this region is mid-update", it is
|
|
3254
|
+
if (status === "loading") host.setAttribute("aria-busy", "true");
|
|
3255
|
+
else host.removeAttribute("aria-busy");
|
|
3256
|
+
// The same status drives the `:state(data-loading)` custom state (BY-32): a
|
|
3257
|
+
if (typeof host._setCustomState === "function") host._setCustomState("data-loading", status === "loading");
|
|
3258
|
+
}
|
|
3259
|
+
|
|
3260
|
+
function emitState(host, name, detail) {
|
|
3261
|
+
host.dispatchEvent(new CustomEvent(name, { detail, bubbles: true, composed: true }));
|
|
3262
|
+
}
|
|
3263
|
+
|
|
3264
|
+
function countOf(data) {
|
|
3265
|
+
if (Array.isArray(data)) return data.length;
|
|
3266
|
+
if (data && typeof data === "object") return Object.keys(data).length;
|
|
3267
|
+
return data === null || data === undefined ? 0 : 1;
|
|
3268
|
+
}
|
|
3269
|
+
|
|
3270
|
+
/**
|
|
3271
|
+
* Leave a shared request. The host stops listening, and if it was the last host
|
|
3272
|
+
* that cared, the request itself is cancelled.
|
|
3273
|
+
*
|
|
3274
|
+
* This is why the abort is not simply `onDispose(host, () => controller.abort())`:
|
|
3275
|
+
* with a shared URL, the first widget to be removed from the page would cancel the
|
|
3276
|
+
* request its nine siblings are still waiting on, and the defect would look like a
|
|
3277
|
+
* network failure that only happens on a dashboard.
|
|
3278
|
+
*/
|
|
3279
|
+
function leaveRequest(host) {
|
|
3280
|
+
const entry = host._remoteEntry;
|
|
3281
|
+
host._remoteEntry = null;
|
|
3282
|
+
if (!entry) return;
|
|
3283
|
+
entry.hosts.delete(host);
|
|
3284
|
+
if (entry.hosts.size === 0 && entry.controller) entry.controller.abort();
|
|
3285
|
+
}
|
|
3286
|
+
|
|
3287
|
+
/**
|
|
3288
|
+
* Ask for `src`, and report whether the host is waiting on it.
|
|
3289
|
+
*
|
|
3290
|
+
* `fields` are the attributes the payload may feed, in the order the component
|
|
3291
|
+
* prefers them. Reads nothing and writes nothing the component paints — the
|
|
3292
|
+
* values come back through `remoteData`.
|
|
3293
|
+
*/
|
|
3294
|
+
/** Load remote data for the given fields on a host. */
|
|
3295
|
+
export function loadRemote(host, fields) {
|
|
3296
|
+
const src = host.getAttribute("src");
|
|
3297
|
+
if (!src) {
|
|
3298
|
+
leaveRequest(host);
|
|
3299
|
+
setStatus(host, host._remoteData !== undefined ? "ready" : "idle");
|
|
3300
|
+
return;
|
|
3301
|
+
}
|
|
3302
|
+
remoteRefresh(host);
|
|
3303
|
+
const wanted = typeof fields === "string" ? [fields] : fields;
|
|
3304
|
+
// An authored attribute wins outright: the component must not fetch over the top
|
|
3305
|
+
// of markup the author wrote.
|
|
3306
|
+
if (wanted.every((f) => host.getAttribute(f) !== null)) {
|
|
3307
|
+
leaveRequest(host);
|
|
3308
|
+
setStatus(host, "ready");
|
|
3309
|
+
return;
|
|
3310
|
+
}
|
|
3311
|
+
// A host below the fold must not compete with the forty above it for the same
|
|
3312
|
+
if (!remoteVisible(host)) {
|
|
3313
|
+
setStatus(host, "loading");
|
|
3314
|
+
return;
|
|
3315
|
+
}
|
|
3316
|
+
// The shared cache is keyed by `cache-key` when the author names one,
|
|
3317
|
+
const noCache = host.hasAttribute("no-cache");
|
|
3318
|
+
const cacheKey = host.getAttribute("cache-key") || src;
|
|
3319
|
+
if (noCache) {
|
|
3320
|
+
if (host._remoteSrc === src && host._remoteData !== undefined) {
|
|
3321
|
+
setStatus(host, "ready");
|
|
3322
|
+
return;
|
|
3323
|
+
}
|
|
3324
|
+
} else {
|
|
3325
|
+
const cached = remoteCache.get(cacheKey);
|
|
3326
|
+
if (cached !== undefined) {
|
|
3327
|
+
host._remoteSrc = src;
|
|
3328
|
+
host._remoteData = cached;
|
|
3329
|
+
setStatus(host, "ready");
|
|
3330
|
+
return;
|
|
3331
|
+
}
|
|
3332
|
+
if (host._remoteSrc === src && host._remoteStatus === "ready" && host._remoteData !== undefined) {
|
|
3333
|
+
return;
|
|
3334
|
+
}
|
|
3335
|
+
}
|
|
3336
|
+
// Already asked: a host still waiting, or one whose last ask settled in
|
|
3337
|
+
if (host._remoteSrc === src && (host._remoteStatus === "loading" || host._remoteStatus === "error")) return; // already asked
|
|
3338
|
+
|
|
3339
|
+
leaveRequest(host);
|
|
3340
|
+
host._remoteSrc = src;
|
|
3341
|
+
setStatus(host, "loading");
|
|
3342
|
+
|
|
3343
|
+
let entry = remoteInflight.get(src);
|
|
3344
|
+
if (!entry) {
|
|
3345
|
+
entry = { hosts: new Set(), controller: new AbortController(), cacheKey, cacheKeys: new Set() };
|
|
3346
|
+
remoteInflight.set(src, entry);
|
|
3347
|
+
// All three arguments: `host` carries the timeout attribute and owns the
|
|
3348
|
+
entry.promise = startFetch(host, src, entry).then(
|
|
3349
|
+
(data) => {
|
|
3350
|
+
if (remoteInflight.get(src) === entry) remoteInflight.delete(src);
|
|
3351
|
+
// The entry is keyed by URL, but a host that named a cache-key must be
|
|
3352
|
+
cacheResult(src, data);
|
|
3353
|
+
for (const k of entry.cacheKeys) {
|
|
3354
|
+
if (k && k !== src) cacheResult(k, data);
|
|
3355
|
+
}
|
|
3356
|
+
for (const h of entry.hosts) {
|
|
3357
|
+
h._remoteData = data;
|
|
3358
|
+
h._remoteEntry = null;
|
|
3359
|
+
setStatus(h, "ready");
|
|
3360
|
+
emitState(h, "contour:load", { src, count: countOf(data) });
|
|
3361
|
+
}
|
|
3362
|
+
},
|
|
3363
|
+
(err) => {
|
|
3364
|
+
if (remoteInflight.get(src) === entry) remoteInflight.delete(src);
|
|
3365
|
+
for (const h of entry.hosts) {
|
|
3366
|
+
h._remoteEntry = null;
|
|
3367
|
+
setStatus(h, "error");
|
|
3368
|
+
h._remoteError = err && err.name === "HttpError" ? `Could not load (${err.status})` : STATE_FALLBACK.error;
|
|
3369
|
+
emitState(h, "contour:error", {
|
|
3370
|
+
src,
|
|
3371
|
+
message: h._remoteError,
|
|
3372
|
+
name: err && err.name,
|
|
3373
|
+
status: err && err.status,
|
|
3374
|
+
});
|
|
3375
|
+
}
|
|
3376
|
+
}
|
|
3377
|
+
).finally(() => {
|
|
3378
|
+
for (const h of entry.hosts) if (h.isConnected) h.requestRender();
|
|
3379
|
+
entry.hosts.clear();
|
|
3380
|
+
});
|
|
3381
|
+
}
|
|
3382
|
+
entry.hosts.add(host);
|
|
3383
|
+
if (!noCache && cacheKey) entry.cacheKeys.add(cacheKey);
|
|
3384
|
+
host._remoteEntry = entry;
|
|
3385
|
+
// Leaving the page is not failing the request; the host simply stops caring.
|
|
3386
|
+
if (!host._remoteDisposeRegistered) {
|
|
3387
|
+
host._remoteDisposeRegistered = true;
|
|
3388
|
+
onDispose(host, () => {
|
|
3389
|
+
host._remoteDisposeRegistered = false;
|
|
3390
|
+
leaveRequest(host);
|
|
3391
|
+
});
|
|
3392
|
+
}
|
|
3393
|
+
}
|
|
3394
|
+
|
|
3395
|
+
/**
|
|
3396
|
+
* Drop a URL's cached result so the next host that asks for it re-fetches.
|
|
3397
|
+
* The refresh timer and the retry button already clear the entry themselves;
|
|
3398
|
+
* this is the page-side handle for the same job (an admin action, a
|
|
3399
|
+
* websocket that says the tiles changed) without forcing a remount.
|
|
3400
|
+
* @param {string} srcOrKey the URL — or the cache-key a host asked under
|
|
3401
|
+
*/
|
|
3402
|
+
/** Invalidate cached remote data by source or key. */
|
|
3403
|
+
export function remoteInvalidate(srcOrKey) {
|
|
3404
|
+
remoteCache.delete(srcOrKey);
|
|
3405
|
+
}
|
|
3406
|
+
|
|
3407
|
+
// `AbortSignal.timeout` is the platform's own deadline; where it is missing, the
|
|
3408
|
+
function startFetch(host, src, entry) {
|
|
3409
|
+
const ms = parseInt(host.getAttribute("timeout") || "", 10);
|
|
3410
|
+
let timer = null;
|
|
3411
|
+
let signal = entry.controller.signal;
|
|
3412
|
+
if (Number.isFinite(ms) && ms > 0) {
|
|
3413
|
+
if (typeof AbortSignal !== "undefined" && AbortSignal.timeout) {
|
|
3414
|
+
// `AbortSignal.any` needs no guard: it ships with `AbortSignal.timeout`, and
|
|
3415
|
+
// a host on an engine without the former has no use for the latter either.
|
|
3416
|
+
signal = AbortSignal.any([signal, AbortSignal.timeout(ms)]);
|
|
3417
|
+
} else {
|
|
3418
|
+
timer = setTimeout(() => entry.controller.abort(), ms);
|
|
3419
|
+
}
|
|
3420
|
+
}
|
|
3421
|
+
// The deadline belongs to the request, so the last host out already aborts it;
|
|
3422
|
+
// the timer is cleared on any settle so a cached answer costs nothing later.
|
|
3423
|
+
// One disposer per host, not per request: `refresh` re-issues a request, and
|
|
3424
|
+
// the old shape appended a closure to the host's teardown list on every one,
|
|
3425
|
+
// retaining a timer id that had already fired until the next disconnect.
|
|
3426
|
+
if (timer) {
|
|
3427
|
+
host._remoteDeadline = timer;
|
|
3428
|
+
if (!host._remoteDeadlineWired) {
|
|
3429
|
+
host._remoteDeadlineWired = true;
|
|
3430
|
+
onDispose(host, () => {
|
|
3431
|
+
host._remoteDeadlineWired = false;
|
|
3432
|
+
clearTimeout(host._remoteDeadline);
|
|
3433
|
+
host._remoteDeadline = null;
|
|
3434
|
+
});
|
|
3435
|
+
}
|
|
3436
|
+
}
|
|
3437
|
+
const clearDeadline = () => {
|
|
3438
|
+
if (!timer) return;
|
|
3439
|
+
clearTimeout(timer);
|
|
3440
|
+
if (host._remoteDeadline === timer) host._remoteDeadline = null;
|
|
3441
|
+
};
|
|
3442
|
+
|
|
3443
|
+
return fetch(src, { signal })
|
|
3444
|
+
.then((res) => {
|
|
3445
|
+
clearDeadline();
|
|
3446
|
+
// The status line is the boundary. `fetch` resolves on 404 and on 500, so
|
|
3447
|
+
if (!res.ok) {
|
|
3448
|
+
const e = new Error(`Could not load (${res.status})`);
|
|
3449
|
+
e.name = "HttpError";
|
|
3450
|
+
e.status = res.status;
|
|
3451
|
+
throw e;
|
|
3452
|
+
}
|
|
3453
|
+
return res.text();
|
|
3454
|
+
})
|
|
3455
|
+
.then((text) => {
|
|
3456
|
+
try { return JSON.parse(text); }
|
|
3457
|
+
catch (err) {
|
|
3458
|
+
const e = new Error(STATE_FALLBACK.error);
|
|
3459
|
+
e.name = "ParseError";
|
|
3460
|
+
e.cause = err;
|
|
3461
|
+
throw e;
|
|
3462
|
+
}
|
|
3463
|
+
});
|
|
3464
|
+
}
|
|
3465
|
+
|
|
3466
|
+
/**
|
|
3467
|
+
* The value a component should render for one field: the attribute the author
|
|
3468
|
+
* wrote, else the matching key of the remote payload, else nothing.
|
|
3469
|
+
*
|
|
3470
|
+
* An array payload feeds the field the component asked for, so
|
|
3471
|
+
* `<contour-readout src="/rows.json">` works with a bare list; an object payload
|
|
3472
|
+
* is matched by key, so one endpoint can serve several fields of one component.
|
|
3473
|
+
* The return is always the string the render body already parses, so adopting this
|
|
3474
|
+
* changes no component's parsing.
|
|
3475
|
+
*/
|
|
3476
|
+
/** Read the cached remote data for a field. */
|
|
3477
|
+
export function remoteData(host, field) {
|
|
3478
|
+
const authored = host.getAttribute(field);
|
|
3479
|
+
if (authored !== null) return authored;
|
|
3480
|
+
const data = host._remoteData;
|
|
3481
|
+
if (data === undefined || data === null) return null;
|
|
3482
|
+
if (Array.isArray(data)) return JSON.stringify(data);
|
|
3483
|
+
if (typeof data === "object") {
|
|
3484
|
+
const keys = typeof field === "string" ? [field] : field;
|
|
3485
|
+
for (const k of keys) {
|
|
3486
|
+
if (data[k] === undefined) continue;
|
|
3487
|
+
return typeof data[k] === "string" ? data[k] : JSON.stringify(data[k]);
|
|
3488
|
+
}
|
|
3489
|
+
return null;
|
|
3490
|
+
}
|
|
3491
|
+
return String(data);
|
|
3492
|
+
}
|
|
3493
|
+
|
|
3494
|
+
/**
|
|
3495
|
+
* `refresh="<seconds>"`: revalidate the source on a timer. The loop pauses while
|
|
3496
|
+
* the tab is hidden and stops when the host leaves the page, because a dashboard
|
|
3497
|
+
* left open in a background tab is the common way a design system becomes the
|
|
3498
|
+
* reason a laptop is warm.
|
|
3499
|
+
*
|
|
3500
|
+
* Registered once per mount: `remoteRefresh` is called from `render()`, and a
|
|
3501
|
+
* timer scheduled here fires and clears `_remoteTimer`, so the guard has to be a
|
|
3502
|
+
* flag that survives the tick or every re-render adds another loop.
|
|
3503
|
+
*/
|
|
3504
|
+
/** Refresh remote data for a host. */
|
|
3505
|
+
export function remoteRefresh(host) {
|
|
3506
|
+
const seconds = parseFloat(host.getAttribute("refresh") || "");
|
|
3507
|
+
const want = host.hasAttribute("src") && Number.isFinite(seconds) && seconds > 0;
|
|
3508
|
+
if (!want) {
|
|
3509
|
+
if (host._remoteTimer !== undefined) { clearTimeout(host._remoteTimer); host._remoteTimer = undefined; }
|
|
3510
|
+
host._remoteLoop = false;
|
|
3511
|
+
return;
|
|
3512
|
+
}
|
|
3513
|
+
if (host._remoteLoop) return;
|
|
3514
|
+
host._remoteLoop = true;
|
|
3515
|
+
const tick = () => {
|
|
3516
|
+
host._remoteTimer = undefined;
|
|
3517
|
+
if (!host.isConnected || !host.hasAttribute("refresh")) { host._remoteLoop = false; return; }
|
|
3518
|
+
if (document.hidden) { host._remoteTimer = setTimeout(tick, 1000); return; }
|
|
3519
|
+
const src = host.getAttribute("src");
|
|
3520
|
+
const namedKey = host.getAttribute("cache-key");
|
|
3521
|
+
if (namedKey) remoteCache.delete(namedKey);
|
|
3522
|
+
remoteCache.delete(src);
|
|
3523
|
+
host._remoteSrc = null;
|
|
3524
|
+
host._remoteLoop = false;
|
|
3525
|
+
host.requestRender();
|
|
3526
|
+
};
|
|
3527
|
+
host._remoteTimer = setTimeout(tick, Math.max(1000, seconds * 1000));
|
|
3528
|
+
onDispose(host, () => {
|
|
3529
|
+
clearTimeout(host._remoteTimer);
|
|
3530
|
+
host._remoteTimer = undefined;
|
|
3531
|
+
host._remoteLoop = false;
|
|
3532
|
+
});
|
|
3533
|
+
}
|
|
3534
|
+
|
|
3535
|
+
// `loading="lazy"` belongs to the markup, not to the platform: an element below
|
|
3536
|
+
let _sharedLazyIO = null;
|
|
3537
|
+
const _sharedLazyTargets = new Map();
|
|
3538
|
+
/** Whether remote data is currently visible. */
|
|
3539
|
+
export function remoteVisible(host) {
|
|
3540
|
+
if (!host.hasAttribute("lazy")) return true;
|
|
3541
|
+
if (typeof IntersectionObserver !== "function") return true;
|
|
3542
|
+
if (host._remoteVisible) return true;
|
|
3543
|
+
if (host._lazyRegistered) return false;
|
|
3544
|
+
if (!_sharedLazyIO) {
|
|
3545
|
+
_sharedLazyIO = new IntersectionObserver((records) => {
|
|
3546
|
+
for (const r of records) {
|
|
3547
|
+
const activate = _sharedLazyTargets.get(r.target);
|
|
3548
|
+
if (!activate || !r.isIntersecting) continue;
|
|
3549
|
+
_sharedLazyTargets.delete(r.target);
|
|
3550
|
+
_sharedLazyIO.unobserve(r.target);
|
|
3551
|
+
activate();
|
|
3552
|
+
}
|
|
3553
|
+
}, { rootMargin: "200px" });
|
|
3554
|
+
}
|
|
3555
|
+
const activate = () => {
|
|
3556
|
+
host._remoteVisible = true;
|
|
3557
|
+
host._lazyRegistered = false;
|
|
3558
|
+
host.requestRender();
|
|
3559
|
+
};
|
|
3560
|
+
host._lazyRegistered = true;
|
|
3561
|
+
_sharedLazyTargets.set(host, activate);
|
|
3562
|
+
_sharedLazyIO.observe(host);
|
|
3563
|
+
onDispose(host, () => {
|
|
3564
|
+
_sharedLazyIO.unobserve(host);
|
|
3565
|
+
_sharedLazyTargets.delete(host);
|
|
3566
|
+
host._lazyRegistered = false;
|
|
3567
|
+
});
|
|
3568
|
+
return false;
|
|
3569
|
+
}
|
|
3570
|
+
|
|
3571
|
+
/**
|
|
3572
|
+
* Page-side visibility events (BY-42). The loader's `remoteVisible` is one-shot
|
|
3573
|
+
* and loader-internal: it exists to gate a single fetch. A dashboard that does
|
|
3574
|
+
* its own ink work (a non-loader animation, a slow layout) needs the same
|
|
3575
|
+
* signal exported, with both halves — enter AND leave — because "paused until
|
|
3576
|
+
* it enters" is only useful if the pause lifts. Events are the loader's own
|
|
3577
|
+
* convention: bubbles + composed, on the host.
|
|
3578
|
+
*
|
|
3579
|
+
* The returned disposer stops the observer; it is also wired to onDispose so a
|
|
3580
|
+
* host removed from the DOM stops observing without the caller tracking it.
|
|
3581
|
+
* Where IntersectionObserver is missing the honest fallback is to report the
|
|
3582
|
+
* element as entered once and stop: an unobserved element is not "never seen",
|
|
3583
|
+
* and a dashboard that waits for leave that can never come is a dashboard that
|
|
3584
|
+
* never resumes.
|
|
3585
|
+
*/
|
|
3586
|
+
/** Watch viewport intersection for lazy loading. */
|
|
3587
|
+
export function watchViewport(host) {
|
|
3588
|
+
if (host._contourViewWired) return () => {};
|
|
3589
|
+
host._contourViewWired = true;
|
|
3590
|
+
const emit = (type) => host.dispatchEvent(new CustomEvent(type, { bubbles: true, composed: true }));
|
|
3591
|
+
if (typeof IntersectionObserver !== "function") {
|
|
3592
|
+
emit("contour:view-enter");
|
|
3593
|
+
return () => {};
|
|
3594
|
+
}
|
|
3595
|
+
const io = new IntersectionObserver((records) => {
|
|
3596
|
+
for (const r of records) {
|
|
3597
|
+
if (r.isIntersecting) emit("contour:view-enter");
|
|
3598
|
+
else emit("contour:view-leave");
|
|
3599
|
+
}
|
|
3600
|
+
});
|
|
3601
|
+
io.observe(host);
|
|
3602
|
+
onDispose(host, () => io.disconnect());
|
|
3603
|
+
return () => io.disconnect();
|
|
3604
|
+
}
|
|
3605
|
+
|
|
3606
|
+
// ---------------------------------------------------------------------------
|
|
3607
|
+
|
|
3608
|
+
// A state node carries the block-scoped element class the sheet already defines
|
|
3609
|
+
function stateNode(block, kind, text) {
|
|
3610
|
+
const node = document.createElement("div");
|
|
3611
|
+
node.className = "c-" + block + "__" + kind;
|
|
3612
|
+
node.dataset.contourState = kind;
|
|
3613
|
+
node.textContent = text;
|
|
3614
|
+
return node;
|
|
3615
|
+
}
|
|
3616
|
+
|
|
3617
|
+
function skeletonRow(i, total) {
|
|
3618
|
+
// The system's own skeleton block and its own modifiers: `--title` for the first
|
|
3619
|
+
const node = document.createElement("div");
|
|
3620
|
+
node.className = "c-skeleton " + (i === 0 && total > 1 ? "c-skeleton--title" : "c-skeleton--text");
|
|
3621
|
+
node.dataset.contourState = "skeleton";
|
|
3622
|
+
return node;
|
|
3623
|
+
}
|
|
3624
|
+
|
|
3625
|
+
/**
|
|
3626
|
+
* Paint the host's data state, if it has one. Returns true when a state took over
|
|
3627
|
+
* the render, so the caller returns before building content it would discard.
|
|
3628
|
+
*
|
|
3629
|
+
* The order is deliberate: `loading` (attribute or open request) wins over `error`,
|
|
3630
|
+
* because a retry in flight is not a failure, and either wins over `skeleton`,
|
|
3631
|
+
* which is a placeholder for a state the host may already be in.
|
|
3632
|
+
*/
|
|
3633
|
+
/** Render loading/empty/error states for a block. */
|
|
3634
|
+
export function renderStates(host, block, opts) {
|
|
3635
|
+
const options = opts || {};
|
|
3636
|
+
const loading = host.getAttribute("loading");
|
|
3637
|
+
if (loading !== null || host._remoteStatus === "loading") {
|
|
3638
|
+
host.appendChild(stateNode(block, "loading", loading || stateLabel(host, "loading")));
|
|
3639
|
+
return true;
|
|
3640
|
+
}
|
|
3641
|
+
const error = host.getAttribute("error");
|
|
3642
|
+
if (error !== null || host._remoteStatus === "error") {
|
|
3643
|
+
const message = (error !== null && error !== "") ? error : (host._remoteError || stateLabel(host, "error"));
|
|
3644
|
+
const node = stateNode(block, "error", message);
|
|
3645
|
+
// `retry` is the actionable half of an error. It reuses the button the system
|
|
3646
|
+
if (host.hasAttribute("retry")) {
|
|
3647
|
+
const btn = document.createElement("button");
|
|
3648
|
+
btn.type = "button";
|
|
3649
|
+
btn.className = "c-btn c-btn--ghost c-btn--sm";
|
|
3650
|
+
// R31-145: retry is a primary recovery action — icon+text, never icon-only.
|
|
3651
|
+
setHTML(btn, '<svg aria-hidden="true" viewBox="0 0 24 24"><use href="#i-refresh" /></svg>');
|
|
3652
|
+
btn.appendChild(document.createTextNode(" " + (host.getAttribute("retry") || "Retry")));
|
|
3653
|
+
btn.dataset.action = "retry";
|
|
3654
|
+
node.appendChild(btn);
|
|
3655
|
+
}
|
|
3656
|
+
host.appendChild(node);
|
|
3657
|
+
return true;
|
|
3658
|
+
}
|
|
3659
|
+
if (host.hasAttribute("skeleton")) {
|
|
3660
|
+
const asked = parseInt(host.getAttribute("skeleton") || "3", 10);
|
|
3661
|
+
const count = Math.min(options.max || 6, Math.max(1, Number.isFinite(asked) ? asked : 3));
|
|
3662
|
+
for (let i = 0; i < count; i++) host.appendChild(skeletonRow(i, count));
|
|
3663
|
+
return true;
|
|
3664
|
+
}
|
|
3665
|
+
return false;
|
|
3666
|
+
}
|
|
3667
|
+
|
|
3668
|
+
/** Paint the empty state — for a host with no data and no authored content. */
|
|
3669
|
+
/** Render the empty state for a block. */
|
|
3670
|
+
export function renderEmpty(host, block) {
|
|
3671
|
+
host.appendChild(stateNode(block, "empty", host.getAttribute("empty") || stateLabel(host, "empty")));
|
|
3672
|
+
}
|
|
3673
|
+
|
|
3674
|
+
/**
|
|
3675
|
+
* R24-24: shared JSON array parser. Parses a JSON attribute and returns an
|
|
3676
|
+
* array (empty if not an array or malformed). Warns on malformed JSON so
|
|
3677
|
+
* the error is visible in the console.
|
|
3678
|
+
*/
|
|
3679
|
+
export function parseArrayAttr(host, attr, warn) {
|
|
3680
|
+
const raw = host.getAttribute(attr);
|
|
3681
|
+
if (!raw) return [];
|
|
3682
|
+
try {
|
|
3683
|
+
const parsed = JSON.parse(raw);
|
|
3684
|
+
if (Array.isArray(parsed)) return parsed;
|
|
3685
|
+
if (warn) warn(host, attr, new Error("not an array"));
|
|
3686
|
+
return [];
|
|
3687
|
+
} catch (e) {
|
|
3688
|
+
if (warn) warn(host, attr, e);
|
|
3689
|
+
return [];
|
|
3690
|
+
}
|
|
3691
|
+
}
|
|
3692
|
+
|
|
3693
|
+
// Delegated on the host (AGENTS.md rule 12): the retry button is regenerated on
|
|
3694
|
+
// every render, so a listener bound to the node would be dropped by the next pass.
|
|
3695
|
+
/** Wire state (loading/empty/error) interactions for a host. */
|
|
3696
|
+
export function wireStates(host) {
|
|
3697
|
+
if (host._contourStatesWired) return;
|
|
3698
|
+
host._contourStatesWired = true;
|
|
3699
|
+
host.addEventListener("click", (e) => {
|
|
3700
|
+
const btn = e.target && e.target.closest ? e.target.closest('[data-action="retry"]') : null;
|
|
3701
|
+
if (!btn || !host.contains(btn)) return;
|
|
3702
|
+
e.preventDefault();
|
|
3703
|
+
const src = host.getAttribute("src");
|
|
3704
|
+
const namedKey = host.getAttribute("cache-key");
|
|
3705
|
+
if (namedKey) remoteCache.delete(namedKey);
|
|
3706
|
+
if (src) remoteCache.delete(src);
|
|
3707
|
+
leaveRequest(host);
|
|
3708
|
+
host._remoteSrc = null;
|
|
3709
|
+
host._remoteData = undefined;
|
|
3710
|
+
setStatus(host, "idle");
|
|
3711
|
+
emitState(host, "contour:retry", { src });
|
|
3712
|
+
host.requestRender();
|
|
3713
|
+
});
|
|
3714
|
+
}
|
|
3715
|
+
|
|
3716
|
+
|
|
3717
|
+
if (typeof window !== "undefined") {
|
|
3718
|
+
window.ContourVersion = CONTOUR_VERSION;
|
|
3719
|
+
if (!window.Contour) window.Contour = {
|
|
3720
|
+
format: { value: formatValue, number: (value, format, locale) => formatValue(value, format, locale), time: (value, locale) => { try { return new Intl.DateTimeFormat(locale || undefined).format(new Date(value)); } catch (e) { return String(value); } }, locale: (locale) => locale || (typeof navigator !== "undefined" ? navigator.language : "en") },
|
|
3721
|
+
markers: { shapes: MARKER_SHAPES, styles: markerStyles, assign: assignMarkers },
|
|
3722
|
+
};
|
|
3723
|
+
queueMicrotask(() => { try { window.dispatchEvent(new CustomEvent("contour:ready", { detail: { version: CONTOUR_VERSION, count: REGISTERED.length } })); } catch (e) {} });
|
|
3724
|
+
}
|