@openelement/ui 1.0.0-alpha.15 → 1.0.0-alpha.16

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.
@@ -0,0 +1,253 @@
1
+ import { readInstanceState, writeInstanceState } from "./instance-state.js";
2
+ import { deepActiveElement, nextInstanceId } from "./component-recipes.js";
3
+ //#region src/dropdown-machine.ts
4
+ /**
5
+ * @openelement/ui - open-dropdown activation choreography (module helper).
6
+ *
7
+ * The generated element owns the compiled template (trigger span, native
8
+ * popover content) and the declared `anchorName` property; this module owns
9
+ * the imperative activation the compiled program cannot express: the
10
+ * realm-unique anchor-name assignment and the cross-shadow focus-return
11
+ * restoration (#1226). The platform does the rest — the content is a native
12
+ * `popover` (top layer, built-in light dismiss), placement is CSS anchor
13
+ * positioning, and no behavior machine rides on either.
14
+ *
15
+ * The lifecycle hooks run before the template's nodes exist, so the
16
+ * focus-return listeners wire on the SHADOW ROOT synchronously — the shell
17
+ * attaches the retained root before mounting, but the nodes do not exist
18
+ * yet, and wiring on the content itself would need a frame of deferral that
19
+ * loses the first-open capture to an interaction in the mount frame. The
20
+ * listeners ride the shadow ROOT in capture phase because the popover's
21
+ * `beforetoggle`/`toggle` events neither bubble nor compose: a
22
+ * `composed: false` event's propagation path truncates at the shadow
23
+ * boundary, so the host (or anything light-side) never sees them, while the
24
+ * shadow root — the last node on the truncated path — does, in either phase.
25
+ * The content's `position-anchor` half is applied lazily at `beforetoggle`
26
+ * (the spec fires it before the open flip, so the anchor is in place before
27
+ * the popover can become visible).
28
+ *
29
+ * Functions take the host explicitly — the same host the lifecycle `env`
30
+ * provides — so the unit harness drives them without connecting an element.
31
+ */
32
+ function dropdownContent(host) {
33
+ return host.shadowRoot?.querySelector(".content") ?? null;
34
+ }
35
+ function dropdownTriggerAria(host) {
36
+ return readInstanceState(host, "triggerAria", () => ({
37
+ triggers: /* @__PURE__ */ new Map(),
38
+ generatedIds: /* @__PURE__ */ new Map()
39
+ }));
40
+ }
41
+ function applyAttribute(element, name, value) {
42
+ if (element.getAttribute(name) === value) return;
43
+ if (value === null) element.removeAttribute(name);
44
+ else element.setAttribute(name, value);
45
+ }
46
+ function syncDropdownTriggerAria(host, disconnected = false) {
47
+ const content = dropdownContent(host);
48
+ const aria = dropdownTriggerAria(host);
49
+ const triggers = disconnected ? [] : host.shadowRoot?.querySelector("slot[name=\"trigger\"]")?.assignedElements() ?? [];
50
+ const panels = disconnected || triggers.length === 0 ? [] : content?.querySelector("slot")?.assignedElements() ?? [];
51
+ for (const [trigger, original] of aria.triggers) {
52
+ if (triggers.includes(trigger)) continue;
53
+ applyAttribute(trigger, "aria-expanded", original.expanded);
54
+ applyAttribute(trigger, "aria-controls", original.controls);
55
+ aria.triggers.delete(trigger);
56
+ }
57
+ for (const [panel, id] of aria.generatedIds) {
58
+ if (panels.includes(panel)) continue;
59
+ if (panel.id === id) panel.removeAttribute("id");
60
+ aria.generatedIds.delete(panel);
61
+ }
62
+ const controlIds = panels.map((panel) => {
63
+ if (panel.id !== "") return panel.id;
64
+ const tree = panel.getRootNode();
65
+ let id;
66
+ do
67
+ id = `open-dropdown-content-${nextInstanceId()}`;
68
+ while (tree.getElementById(id));
69
+ panel.id = id;
70
+ aria.generatedIds.set(panel, id);
71
+ return id;
72
+ });
73
+ const expanded = String(content?.matches(":popover-open") ?? false);
74
+ for (const trigger of triggers) {
75
+ if (!aria.triggers.has(trigger)) aria.triggers.set(trigger, {
76
+ expanded: trigger.getAttribute("aria-expanded"),
77
+ controls: trigger.getAttribute("aria-controls")
78
+ });
79
+ applyAttribute(trigger, "aria-expanded", expanded);
80
+ applyAttribute(trigger, "aria-controls", controlIds.length ? controlIds.join(" ") : null);
81
+ }
82
+ }
83
+ function clearDropdownTriggerAria(host) {
84
+ syncDropdownTriggerAria(host, true);
85
+ }
86
+ /**
87
+ * Assign the realm-unique anchor name and apply the HOST half (`anchor-name`).
88
+ * Idempotent: an author-assigned name (a public property write re-entering
89
+ * through the change channel) re-applies the same value, and the
90
+ * instance-assigned name never changes after activation.
91
+ *
92
+ * The CONTENT half (`position-anchor`) is NOT applied here: a reconnect
93
+ * re-claims the retained nodes against the compiled static seeds, and a
94
+ * runtime-written inline style would count as an extra static attribute
95
+ * (`OEIR_LEAF_CLAIM_MISMATCH`). The content half lives only inside the open
96
+ * window instead — applied at `beforetoggle`, removed on close and on
97
+ * dispose — so the closed element's static surface stays exactly the compiled
98
+ * declaration, and the anchor is still in place before any open is
99
+ * observable.
100
+ */
101
+ function syncDropdownAnchor(host) {
102
+ if (host.anchorName === "") host.anchorName = `--open-dropdown-trigger-${nextInstanceId()}`;
103
+ host.style.setProperty("anchor-name", host.anchorName);
104
+ host.style.setProperty("--oe-dropdown-anchor", host.anchorName);
105
+ }
106
+ /**
107
+ * Drop the content's runtime `position-anchor` so the closed element's
108
+ * static surface matches the compiled seeds again (a reconnect re-claims the
109
+ * retained nodes against them). Removing the LAST declaration leaves a
110
+ * residual `style=""` attribute on this engine, and the claim counts
111
+ * attributes, not declarations — an extra `style` member fails the seed
112
+ * compare (`OEIR_LEAF_CLAIM_MISMATCH`). An empty declaration block therefore
113
+ * drops the attribute itself: only an element with no inline declarations
114
+ * left is affected, so an authored style attribute would never be touched.
115
+ */
116
+ function dropContentPositionAnchor(content) {
117
+ if (content.hasAttribute("style")) content.removeAttribute("style");
118
+ }
119
+ function clearDropdownPositionAnchor(host) {
120
+ const content = dropdownContent(host);
121
+ if (content !== null) dropContentPositionAnchor(content);
122
+ }
123
+ /** True when the focus event's composed path runs through this popover's content. */
124
+ function focusTargetsPopover(host, event) {
125
+ const content = dropdownContent(host);
126
+ if (content === null) return false;
127
+ return event.composedPath().includes(content);
128
+ }
129
+ /**
130
+ * Wire the cross-shadow focus-return restoration once per host (reconnects
131
+ * keep the existing listeners). Native popover focus return only works when
132
+ * the previously focused element lives in the same tree as the popover; the
133
+ * trigger is slotted light DOM while the popover sits in this shadow root, so
134
+ * on real pages (the host inside a page's shadow tree) the platform drops
135
+ * focus to <body> on dismiss (#1226). The trigger path records the composed
136
+ * focused element as the popover opens; on close, restore it only when the
137
+ * platform failed to.
138
+ *
139
+ * The wiring is ELEMENT-lifetime, not connection-lifetime: `signal` is the
140
+ * shell's instance-lifetime teardown signal, so it cannot bound a
141
+ * per-connection listener set (a reconnect would find the wiring disposed
142
+ * while the compiled nodes were re-claimed). It is accepted for the intrinsic
143
+ * call contract and deliberately ignored (`void signal`); the listeners live
144
+ * once per host on the retained root and are removed by
145
+ * `disposeDropdownFocusWiring` at activation and at teardown. ADR-0182's
146
+ * 2026-11-20 correction records this reading; the earlier connection-signal
147
+ * wording was wrong.
148
+ */
149
+ function watchDropdownFocusReturn(host, signal) {
150
+ if (readInstanceState(host, "focusWired", () => false)) return;
151
+ const root = host.shadowRoot;
152
+ if (root === null) return;
153
+ const generation = readInstanceState(host, "connectionGeneration", () => 0);
154
+ const onFocusIn = (event) => {
155
+ if (focusTargetsPopover(host, event)) writeInstanceState(host, "popoverHadFocus", true);
156
+ };
157
+ const onBeforeToggle = (event) => {
158
+ const toggle = event;
159
+ const content = event.target;
160
+ if (!(content instanceof HTMLElement) || content !== dropdownContent(host)) return;
161
+ if (toggle.newState === "closed") {
162
+ dropContentPositionAnchor(content);
163
+ return;
164
+ }
165
+ if (toggle.newState !== "open") return;
166
+ writeInstanceState(host, "popoverHadFocus", false);
167
+ writeInstanceState(host, "previouslyFocused", deepActiveElement());
168
+ };
169
+ const onToggle = (event) => {
170
+ const toggle = event;
171
+ const content = event.target;
172
+ if (!(content instanceof HTMLElement) || content !== dropdownContent(host)) return;
173
+ if (readInstanceState(host, "connectionGeneration", () => 0) !== generation) return;
174
+ if (host.isConnected) syncDropdownTriggerAria(host);
175
+ if (toggle.newState !== "closed") return;
176
+ dropContentPositionAnchor(content);
177
+ const hadFocus = readInstanceState(host, "popoverHadFocus", () => false);
178
+ const previous = readInstanceState(host, "previouslyFocused", () => null);
179
+ writeInstanceState(host, "previouslyFocused", null);
180
+ if (!hadFocus || !previous?.isConnected) return;
181
+ queueMicrotask(() => {
182
+ if (!host.isConnected) return;
183
+ if (!previous.isConnected) return;
184
+ const active = deepActiveElement();
185
+ if (active === previous) return;
186
+ const focusInside = active !== null && (host.contains(active) || content.contains(active));
187
+ const dropped = !active || active === document.body || active === document.documentElement;
188
+ if (!focusInside && !dropped) return;
189
+ previous.focus();
190
+ });
191
+ };
192
+ writeInstanceState(host, "focusWired", true);
193
+ const listeners = [
194
+ ["focusin", onFocusIn],
195
+ ["beforetoggle", onBeforeToggle],
196
+ ["toggle", onToggle],
197
+ ["slotchange", () => {
198
+ if (host.isConnected) syncDropdownTriggerAria(host);
199
+ }]
200
+ ];
201
+ for (const [type, listener] of listeners) root.addEventListener(type, listener, true);
202
+ writeInstanceState(host, "focusListeners", listeners);
203
+ }
204
+ function disposeDropdownFocusWiring(host) {
205
+ const listeners = readInstanceState(host, "focusListeners", () => void 0);
206
+ const root = host.shadowRoot;
207
+ if (listeners !== void 0 && root !== null) for (const [type, listener] of listeners) root.removeEventListener(type, listener, true);
208
+ writeInstanceState(host, "focusListeners", void 0);
209
+ writeInstanceState(host, "focusWired", false);
210
+ writeInstanceState(host, "popoverHadFocus", false);
211
+ writeInstanceState(host, "previouslyFocused", null);
212
+ }
213
+ /**
214
+ * Activation = anchor sync + focus-return wiring. The wiring is element-lifetime
215
+ * (idempotent while the same connection stays live); the optional `signal` is
216
+ * accepted for the intrinsic call contract and deliberately ignored — see
217
+ * `watchDropdownFocusReturn`.
218
+ */
219
+ function activateDropdown(host, signal) {
220
+ disposeDropdownFocusWiring(host);
221
+ writeInstanceState(host, "connectionGeneration", readInstanceState(host, "connectionGeneration", () => 0) + 1);
222
+ clearDropdownPositionAnchor(host);
223
+ syncDropdownAnchor(host);
224
+ watchDropdownFocusReturn(host, signal);
225
+ if (host.isConnected) syncDropdownTriggerAria(host);
226
+ }
227
+ /**
228
+ * Trigger pointerdown bookkeeping: a mouse click is preceded by a pointerdown
229
+ * that natively light-dismisses an open popover; the click that follows must
230
+ * not re-open it. Keyboard/programmatic clicks have no pointerdown and toggle
231
+ * normally.
232
+ */
233
+ function recordDropdownPointerDown(host) {
234
+ const content = dropdownContent(host);
235
+ writeInstanceState(host, "openAtPointerDown", content?.matches(":popover-open") ?? false);
236
+ }
237
+ /**
238
+ * Trigger click: the pointerdown light-dismiss guard, then the native
239
+ * `togglePopover()`. The synchronous 'beforetoggle' listener is the single
240
+ * owner of the return-focus capture (#1226); it runs inside togglePopover()
241
+ * before the open flip, so nothing can move focus between this call and the
242
+ * capture.
243
+ */
244
+ function toggleDropdown(host) {
245
+ const wasOpen = readInstanceState(host, "openAtPointerDown", () => false);
246
+ writeInstanceState(host, "openAtPointerDown", false);
247
+ if (wasOpen) return;
248
+ const content = dropdownContent(host);
249
+ if (!content) return;
250
+ content.togglePopover();
251
+ }
252
+ //#endregion
253
+ export { activateDropdown, clearDropdownPositionAnchor, clearDropdownTriggerAria, disposeDropdownFocusWiring, recordDropdownPointerDown, syncDropdownAnchor, toggleDropdown, watchDropdownFocusReturn };