ember-attacher 4.2.0 → 4.3.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.
@@ -1,13 +1,11 @@
1
- import { _ as _applyDecoratedDescriptor, a as _defineProperty, b as _initializerDefineProperty, r as resolveAttachmentTarget, g as getListenerTarget, i as isElementTarget } from '../target-resolution-Bz738VeA.js';
2
1
  import { action } from '@ember/object';
3
2
  import Component from '@glimmer/component';
4
- import { later, cancel, schedule, next, debounce, run } from '@ember/runloop';
3
+ import { schedule, cancel, later, next, debounce, run } from '@ember/runloop';
5
4
  import { getOwner } from '@ember/application';
6
5
  import { guidFor } from '@ember/object/internals';
7
- import { htmlSafe, isHTMLSafe } from '@ember/template';
8
- import { warn, assert, runInDebug } from '@ember/debug';
9
- import { isEmpty, typeOf } from '@ember/utils';
10
- import { flip, shift, limitShift, arrow, autoUpdate, computePosition } from '@floating-ui/dom';
6
+ import { isHTMLSafe } from '@ember/template';
7
+ import { runInDebug, warn, assert } from '@ember/debug';
8
+ import { arrow, flip, shift, limitShift, autoUpdate, computePosition } from '@floating-ui/dom';
11
9
  import { buildWaiter } from '@ember/test-waiters';
12
10
  import { tracked } from '@glimmer/tracking';
13
11
  import { modifier } from 'ember-modifier';
@@ -16,21 +14,740 @@ import { precompileTemplate } from '@ember/template-compilation';
16
14
  import { setComponentTemplate } from '@ember/component';
17
15
  import templateOnly from '@ember/component/template-only';
18
16
 
19
- var MaybeInElement = setComponentTemplate(precompileTemplate("{{~#if @renderInPlace~}}{{yield}}{{~else~}}{{#in-element @destinationElement insertBefore=null}}{{yield}}{{/in-element}}{{~/if~}}", {
20
- strictMode: true
21
- }), templateOnly());
17
+ function _applyDecoratedDescriptor(i, e, r, n, l) {
18
+ var a = {};
19
+ return Object.keys(n).forEach(function (i) {
20
+ a[i] = n[i];
21
+ }), a.enumerable = !!a.enumerable, a.configurable = !!a.configurable, ("value" in a || a.initializer) && (a.writable = true), a = r.slice().reverse().reduce(function (r, n) {
22
+ return n(i, e, r) || r;
23
+ }, a), l && void 0 !== a.initializer && (a.value = a.initializer ? a.initializer.call(l) : void 0, a.initializer = void 0), void 0 === a.initializer ? (Object.defineProperty(i, e, a), null) : a;
24
+ }
25
+ function _defineProperty(e, r, t) {
26
+ return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
27
+ value: t,
28
+ enumerable: true,
29
+ configurable: true,
30
+ writable: true
31
+ }) : e[r] = t, e;
32
+ }
33
+ function _initializerDefineProperty(e, i, r, l) {
34
+ r && Object.defineProperty(e, i, {
35
+ enumerable: r.enumerable,
36
+ configurable: r.configurable,
37
+ writable: r.writable,
38
+ value: r.initializer ? r.initializer.call(l) : void 0
39
+ });
40
+ }
41
+ function _toPrimitive(t, e) {
42
+ if ("object" != typeof t || !t) return t;
43
+ var r;
44
+ if ("undefined" != typeof Symbol && void 0 !== (r = t[Symbol.toPrimitive])) {
45
+ var i = r.call(t, e);
46
+ if ("object" != typeof i) return i;
47
+ throw new TypeError("@@toPrimitive must return a primitive value.");
48
+ }
49
+ return ("string" === e ? String : Number)(t);
50
+ }
51
+ function _toPropertyKey(t) {
52
+ var i = _toPrimitive(t, "string");
53
+ return "symbol" == typeof i ? i : i + "";
54
+ }
22
55
 
23
- var TEMPLATE = precompileTemplate("{{~#unless this.renderFloatingElement~}}<meta hidden {{this.parentFinder}} {{this.isShownDidUpdate this.isShown}}/>{{~/unless~}}{{~#if this.renderFloatingElement~}}<this.MaybeInElement @destinationElement={{this._floatingElementContainer}} @renderInPlace={{this._renderInPlace}}><div\n class=\"ember-attacher\"\n id={{this.id}}\n role={{@ariaRole}}\n {{this.setupFloatingElement}}\n {{this.isShownDidUpdate this.isShown}}\n {{this.targetDidUpdate this.hideOn this.showOn @explicitTarget}}\n {{this.optionsDidUpdate this.autoUpdate this.animation this.arrow this.useCapture this.placement this._renderInPlace this._middleware}}\n ...attributes\n >\n <div class={{this._class}} style={{this._style}}>\n {{yield (hash hide=this.hide setReference=this.setReference reference=this.reference)}}\n {{#if this.arrow}}\n <div class=\"ember-attacher-arrow\" x-arrow {{this.insertArrow}}></div>\n {{/if}}\n {{#if this.isFillAnimation}}\n <div x-circle style=\"{{this._circleTransitionDuration}}\"></div>\n {{/if}}\n </div>\n </div></this.MaybeInElement>{{~/if~}}\n");
56
+ const KNOWN_HASPOPUP_ROLES = new Set(['dialog', 'menu', 'listbox', 'tree', 'grid', 'true', 'false']);
57
+ function splitTokens(value) {
58
+ return value ? value.trim().split(/\s+/).filter(Boolean) : [];
59
+ }
60
+
61
+ /**
62
+ * Tracks and restores ARIA attributes owned by a single BasicAttacher instance
63
+ * without clobbering pre-existing caller attributes or tokens.
64
+ */
65
+ class AttachmentAriaController {
66
+ constructor() {
67
+ _defineProperty(this, "_boundTarget", null);
68
+ _defineProperty(this, "_isTooltip", false);
69
+ _defineProperty(this, "_attachmentId", null);
70
+ _defineProperty(this, "_ariaRole", undefined);
71
+ _defineProperty(this, "_addedDescribedByToken", false);
72
+ _defineProperty(this, "_ownsHasPopup", false);
73
+ _defineProperty(this, "_ownsControls", false);
74
+ _defineProperty(this, "_ownsExpanded", false);
75
+ }
76
+ /**
77
+ * Bind ARIA metadata to a target Element (no-op when target is null/non-Element).
78
+ *
79
+ * @param {Element | null} target
80
+ * @param {{ isTooltip: boolean, id: string, ariaRole?: string, isOpen: boolean }} options
81
+ */
82
+ bind(target, {
83
+ isTooltip,
84
+ id,
85
+ ariaRole,
86
+ isOpen
87
+ }) {
88
+ if (this._boundTarget && (this._boundTarget !== target || this._attachmentId !== id || this._isTooltip !== isTooltip || this._ariaRole !== ariaRole)) {
89
+ this.unbind();
90
+ }
91
+ if (!target || typeof target.setAttribute !== 'function') {
92
+ return;
93
+ }
94
+ this._boundTarget = target;
95
+ this._isTooltip = isTooltip;
96
+ this._attachmentId = id;
97
+ this._ariaRole = ariaRole;
98
+ if (!isTooltip) {
99
+ if (!target.hasAttribute('aria-haspopup')) {
100
+ const role = ariaRole || 'dialog';
101
+ runInDebug(() => {
102
+ warn(`[ember-attacher] Unrecognized aria-haspopup role "${role}". Expected one of: dialog, menu, listbox, tree, grid.`, KNOWN_HASPOPUP_ROLES.has(role), {
103
+ id: 'ember-attacher.unrecognized-aria-haspopup'
104
+ });
105
+ });
106
+ target.setAttribute('aria-haspopup', role);
107
+ this._ownsHasPopup = true;
108
+ }
109
+ if (!target.hasAttribute('aria-controls')) {
110
+ target.setAttribute('aria-controls', id);
111
+ this._ownsControls = true;
112
+ }
113
+ if (!target.hasAttribute('aria-expanded')) {
114
+ target.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
115
+ this._ownsExpanded = true;
116
+ }
117
+ }
118
+ this.setOpen(isOpen);
119
+ }
120
+
121
+ /**
122
+ * Update open/closed ARIA state on the bound target.
123
+ *
124
+ * @param {boolean} isOpen
125
+ */
126
+ setOpen(isOpen) {
127
+ const target = this._boundTarget;
128
+ if (!target) {
129
+ return;
130
+ }
131
+ if (this._isTooltip) {
132
+ this._setDescribedByOpen(target, isOpen);
133
+ } else if (this._ownsExpanded) {
134
+ target.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
135
+ }
136
+ }
137
+
138
+ /**
139
+ * Remove only the attributes and tokens added by this controller.
140
+ */
141
+ unbind() {
142
+ const target = this._boundTarget;
143
+ if (!target) {
144
+ return;
145
+ }
146
+ if (this._addedDescribedByToken) {
147
+ this._removeDescribedByToken(target, this._attachmentId);
148
+ this._addedDescribedByToken = false;
149
+ }
150
+ if (this._ownsHasPopup) {
151
+ target.removeAttribute('aria-haspopup');
152
+ this._ownsHasPopup = false;
153
+ }
154
+ if (this._ownsControls) {
155
+ target.removeAttribute('aria-controls');
156
+ this._ownsControls = false;
157
+ }
158
+ if (this._ownsExpanded) {
159
+ target.removeAttribute('aria-expanded');
160
+ this._ownsExpanded = false;
161
+ }
162
+ this._boundTarget = null;
163
+ this._attachmentId = null;
164
+ this._isTooltip = false;
165
+ this._ariaRole = undefined;
166
+ }
167
+ _setDescribedByOpen(target, isOpen) {
168
+ const id = this._attachmentId;
169
+ if (!id) {
170
+ return;
171
+ }
172
+ if (isOpen) {
173
+ const tokens = splitTokens(target.getAttribute('aria-describedby'));
174
+ if (!tokens.includes(id)) {
175
+ tokens.push(id);
176
+ target.setAttribute('aria-describedby', tokens.join(' '));
177
+ this._addedDescribedByToken = true;
178
+ }
179
+ } else if (this._addedDescribedByToken) {
180
+ this._removeDescribedByToken(target, id);
181
+ this._addedDescribedByToken = false;
182
+ }
183
+ }
184
+ _removeDescribedByToken(target, token) {
185
+ if (!token) {
186
+ return;
187
+ }
188
+ const remaining = splitTokens(target.getAttribute('aria-describedby')).filter(t => t !== token);
189
+ if (remaining.length > 0) {
190
+ target.setAttribute('aria-describedby', remaining.join(' '));
191
+ } else {
192
+ target.removeAttribute('aria-describedby');
193
+ }
194
+ }
195
+ }
196
+
197
+ /**
198
+ * Restore focus to the Target if focus currently lives inside the floating attachment
199
+ * or on another element outside the Target when dismissed via Escape.
200
+ *
201
+ * @param {Element | null} target
202
+ * @param {Element | null} floatingElement
203
+ */
204
+ function restoreFocusOnEscape(target, floatingElement) {
205
+ if (!target || typeof target.focus !== 'function' || typeof document === 'undefined') {
206
+ return;
207
+ }
208
+ const active = document.activeElement;
209
+ if (active === target) {
210
+ return;
211
+ }
212
+ const focusInsideAttachment = Boolean(floatingElement && active && floatingElement.contains(active));
213
+ if (focusInsideAttachment) {
214
+ try {
215
+ target.focus({
216
+ preventScroll: true
217
+ });
218
+ } catch {
219
+ target.focus();
220
+ }
221
+ }
222
+ }
223
+
224
+ /**
225
+ * DOM and event helpers for attachment boundary and cursor detection.
226
+ */
227
+
228
+ /**
229
+ * Determine whether an event originated from or traversed through a given DOM element.
230
+ *
231
+ * Uses `event.composedPath()` to safely detect clicks on elements that were subsequently
232
+ * removed from the DOM during event handling (e.g. self-disappearing buttons).
233
+ * Falls back to `element.contains(event.target)` when `composedPath` is unavailable.
234
+ *
235
+ * @param {Element | null | undefined} element
236
+ * @param {Event | null | undefined} event
237
+ * @returns {boolean}
238
+ */
239
+ function elementContainsEvent(element, event) {
240
+ if (!element) {
241
+ return false;
242
+ }
243
+ const path = typeof event?.composedPath === 'function' ? event.composedPath() : null;
244
+ if (path && path.length > 0) {
245
+ return path.includes(element);
246
+ }
247
+ return Boolean(event?.target && element.contains(event.target));
248
+ }
249
+ const CORRIDOR_BUFFER = 2;
250
+ function isPointInRect(x, y, rect) {
251
+ return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;
252
+ }
253
+ function pointInTriangle(px, py, ax, ay, bx, by, cx, cy) {
254
+ const d1 = (px - bx) * (ay - by) - (ax - bx) * (py - by);
255
+ const d2 = (px - cx) * (by - cy) - (bx - cx) * (py - cy);
256
+ const d3 = (px - ax) * (cy - ay) - (cx - ax) * (py - ay);
257
+ const hasNeg = d1 < 0 || d2 < 0 || d3 < 0;
258
+ const hasPos = d1 > 0 || d2 > 0 || d3 > 0;
259
+ return !(hasNeg && hasPos);
260
+ }
261
+ function pointInQuad(px, py, x1, y1, x2, y2, x3, y3, x4, y4) {
262
+ return pointInTriangle(px, py, x1, y1, x2, y2, x3, y3) || pointInTriangle(px, py, x1, y1, x3, y3, x4, y4);
263
+ }
264
+
265
+ /**
266
+ * Determine whether the cursor lies inside either rect or the diagonal safe-polygon
267
+ * corridor between the mouseleave exit point on the Target (or the Target's facing edge
268
+ * when synthetic events omit pointer coordinates) and the facing edge of the Attachment.
269
+ *
270
+ * Unlike an 8-corner bounding convex hull, this corridor only spans the gap between
271
+ * the Target's facing edge and the Attachment's facing edge, so exiting laterally
272
+ * into adjacent UI beside the Target never keeps the Attachment stuck open.
273
+ *
274
+ * Supports both DOM Elements and Floating UI VirtualElements via `getBoundingClientRect()`.
275
+ *
276
+ * @param {MouseEvent | { clientX: number, clientY: number }} event
277
+ * @param {{ x: number, y: number } | null | undefined} origin
278
+ * @param {Element | { getBoundingClientRect: Function } | null | undefined} target
279
+ * @param {Element | { getBoundingClientRect: Function } | null | undefined} floatingElement
280
+ * @returns {boolean}
281
+ */
282
+ function isCursorInSafePolygon(event, origin, target, floatingElement) {
283
+ if (!event || !target || !floatingElement || typeof target.getBoundingClientRect !== 'function' || typeof floatingElement.getBoundingClientRect !== 'function') {
284
+ return false;
285
+ }
286
+ const targetRect = target.getBoundingClientRect();
287
+ const floatingRect = floatingElement.getBoundingClientRect();
288
+ if (floatingRect.width === 0 && floatingRect.height === 0) {
289
+ return false;
290
+ }
291
+ const px = event.clientX;
292
+ const py = event.clientY;
293
+ if (isPointInRect(px, py, targetRect) || isPointInRect(px, py, floatingRect)) {
294
+ return true;
295
+ }
296
+ const hasRealOrigin = Boolean(origin) && (origin.x !== 0 || origin.y !== 0 || isPointInRect(0, 0, targetRect));
297
+
298
+ // Attachment is above target: gap is between floatingRect.bottom and targetRect.top
299
+ if (floatingRect.bottom <= targetRect.top + CORRIDOR_BUFFER) {
300
+ const bx = floatingRect.left - CORRIDOR_BUFFER;
301
+ const by = floatingRect.bottom;
302
+ const cx = floatingRect.right + CORRIDOR_BUFFER;
303
+ const cy = floatingRect.bottom;
304
+ if (hasRealOrigin) {
305
+ return pointInTriangle(px, py, origin.x, origin.y + CORRIDOR_BUFFER, bx, by, cx, cy);
306
+ }
307
+ return pointInQuad(px, py, targetRect.left, targetRect.top + CORRIDOR_BUFFER, targetRect.right, targetRect.top + CORRIDOR_BUFFER, cx, cy, bx, by);
308
+ }
309
+
310
+ // Attachment is below target: gap is between targetRect.bottom and floatingRect.top
311
+ if (floatingRect.top >= targetRect.bottom - CORRIDOR_BUFFER) {
312
+ const bx = floatingRect.left - CORRIDOR_BUFFER;
313
+ const by = floatingRect.top;
314
+ const cx = floatingRect.right + CORRIDOR_BUFFER;
315
+ const cy = floatingRect.top;
316
+ if (hasRealOrigin) {
317
+ return pointInTriangle(px, py, origin.x, origin.y - CORRIDOR_BUFFER, bx, by, cx, cy);
318
+ }
319
+ return pointInQuad(px, py, targetRect.left, targetRect.bottom - CORRIDOR_BUFFER, targetRect.right, targetRect.bottom - CORRIDOR_BUFFER, cx, cy, bx, by);
320
+ }
321
+
322
+ // Attachment is to the left of target: gap is between floatingRect.right and targetRect.left
323
+ if (floatingRect.right <= targetRect.left + CORRIDOR_BUFFER) {
324
+ const bx = floatingRect.right;
325
+ const by = floatingRect.top - CORRIDOR_BUFFER;
326
+ const cx = floatingRect.right;
327
+ const cy = floatingRect.bottom + CORRIDOR_BUFFER;
328
+ if (hasRealOrigin) {
329
+ return pointInTriangle(px, py, origin.x + CORRIDOR_BUFFER, origin.y, bx, by, cx, cy);
330
+ }
331
+ return pointInQuad(px, py, targetRect.left + CORRIDOR_BUFFER, targetRect.top, targetRect.left + CORRIDOR_BUFFER, targetRect.bottom, cx, cy, bx, by);
332
+ }
333
+
334
+ // Attachment is to the right of target: gap is between targetRect.right and floatingRect.left
335
+ if (floatingRect.left >= targetRect.right - CORRIDOR_BUFFER) {
336
+ const bx = floatingRect.left;
337
+ const by = floatingRect.top - CORRIDOR_BUFFER;
338
+ const cx = floatingRect.left;
339
+ const cy = floatingRect.bottom + CORRIDOR_BUFFER;
340
+ if (hasRealOrigin) {
341
+ return pointInTriangle(px, py, origin.x - CORRIDOR_BUFFER, origin.y, bx, by, cx, cy);
342
+ }
343
+ return pointInQuad(px, py, targetRect.right - CORRIDOR_BUFFER, targetRect.top, targetRect.right - CORRIDOR_BUFFER, targetRect.bottom, cx, cy, bx, by);
344
+ }
345
+ return false;
346
+ }
347
+
348
+ const activeAttachers = new Set();
349
+ const floatingElementParentMap = new WeakMap();
350
+ const handledEscapeEvents = new WeakSet();
351
+
352
+ /**
353
+ * Register a mounted BasicAttacher instance in the in-process attachment tree.
354
+ *
355
+ * @param {object} attacher
356
+ */
357
+ function registerAttacher(attacher) {
358
+ activeAttachers.add(attacher);
359
+ }
360
+
361
+ /**
362
+ * Unregister a destroyed BasicAttacher instance from the in-process attachment tree.
363
+ *
364
+ * @param {object} attacher
365
+ */
366
+ function unregisterAttacher(attacher) {
367
+ activeAttachers.delete(attacher);
368
+ }
369
+
370
+ /**
371
+ * Resolve the logical parent BasicAttacher whose floating element contains
372
+ * this attacher's target or template parent element.
373
+ *
374
+ * @param {object} child
375
+ * @returns {object | null}
376
+ */
377
+ function getParentAttacher(child) {
378
+ const anchors = [child._listenerTarget, child.parentElement].filter(Boolean);
379
+ for (const anchor of anchors) {
380
+ const start = anchor.classList?.contains('ember-attacher') ? anchor.parentElement : anchor;
381
+ const hostEl = start?.closest?.('.ember-attacher');
382
+ if (hostEl && hostEl !== child._floatingElement) {
383
+ for (const candidate of activeAttachers) {
384
+ if (candidate !== child && candidate._floatingElement === hostEl) {
385
+ if (child._floatingElement) {
386
+ floatingElementParentMap.set(child._floatingElement, candidate);
387
+ }
388
+ return candidate;
389
+ }
390
+ }
391
+ }
392
+ }
393
+ if (child._floatingElement && floatingElementParentMap.has(child._floatingElement)) {
394
+ return floatingElementParentMap.get(child._floatingElement) ?? null;
395
+ }
396
+ return null;
397
+ }
398
+
399
+ /**
400
+ * Cache the parent attachment relationship on the child's floating element so
401
+ * clicks that unmount the child mid-event still trace back to the parent via composedPath.
402
+ *
403
+ * @param {object} attacher
404
+ */
405
+ function syncParentAttachment(attacher) {
406
+ getParentAttacher(attacher);
407
+ }
408
+
409
+ /**
410
+ * Check whether `candidate` is a logical descendant of `ancestor` in the attachment tree.
411
+ *
412
+ * @param {object} candidate
413
+ * @param {object} ancestor
414
+ * @returns {boolean}
415
+ */
416
+ function isDescendantOf(candidate, ancestor) {
417
+ const visited = new Set();
418
+ let current = getParentAttacher(candidate);
419
+ while (current && !visited.has(current)) {
420
+ if (current === ancestor) {
421
+ return true;
422
+ }
423
+ visited.add(current);
424
+ current = getParentAttacher(current);
425
+ }
426
+ return false;
427
+ }
428
+
429
+ /**
430
+ * Determine whether a DOM event originated inside any logical descendant Attachment
431
+ * (or its Target) of `parent`.
432
+ *
433
+ * @param {object} parent
434
+ * @param {Event} event
435
+ * @returns {boolean}
436
+ */
437
+ function descendantAttachmentContainsEvent(parent, event) {
438
+ for (const candidate of activeAttachers) {
439
+ if (candidate !== parent && isDescendantOf(candidate, parent)) {
440
+ if (elementContainsEvent(candidate._floatingElement, event) || elementContainsEvent(candidate._listenerTarget, event)) {
441
+ return true;
442
+ }
443
+ }
444
+ }
445
+ const path = typeof event?.composedPath === 'function' ? event.composedPath() : null;
446
+ if (path) {
447
+ for (const node of path) {
448
+ let currentParent = floatingElementParentMap.get(node);
449
+ const visited = new Set();
450
+ while (currentParent && !visited.has(currentParent)) {
451
+ if (currentParent === parent) {
452
+ return true;
453
+ }
454
+ visited.add(currentParent);
455
+ currentParent = getParentAttacher(currentParent) ?? (currentParent._floatingElement ? floatingElementParentMap.get(currentParent._floatingElement) : null);
456
+ }
457
+ }
458
+ }
459
+ return false;
460
+ }
461
+
462
+ /**
463
+ * Determine whether a DOM node is contained inside any logical descendant Attachment
464
+ * (or its Target) of `parent`.
465
+ *
466
+ * @param {object} parent
467
+ * @param {Node | null | undefined} node
468
+ * @returns {boolean}
469
+ */
470
+ function descendantAttachmentContainsNode(parent, node) {
471
+ if (!node) {
472
+ return false;
473
+ }
474
+ for (const candidate of activeAttachers) {
475
+ if (candidate !== parent && isDescendantOf(candidate, parent)) {
476
+ if (candidate._floatingElement?.contains(node) || candidate._listenerTarget?.contains(node)) {
477
+ return true;
478
+ }
479
+ }
480
+ }
481
+ return false;
482
+ }
483
+
484
+ /**
485
+ * Enforce LIFO Escape dismissal across nested Attachments: only the deepest
486
+ * currently open escapable Attachment handles a given Escape keydown event.
487
+ *
488
+ * @param {object} attacher
489
+ * @param {KeyboardEvent} event
490
+ * @returns {boolean}
491
+ */
492
+ function shouldHandleEscapeKey(attacher, event) {
493
+ if (handledEscapeEvents.has(event)) {
494
+ return false;
495
+ }
496
+ for (const candidate of activeAttachers) {
497
+ if (candidate !== attacher && !candidate.isDestroyed && !candidate.isDestroying && !candidate._isHiding && !candidate._positioningSuspended && Boolean(candidate._hideListenersOnDocumentByEvent?.keydown) && isDescendantOf(candidate, attacher)) {
498
+ return false;
499
+ }
500
+ }
501
+ handledEscapeEvents.add(event);
502
+ return true;
503
+ }
504
+
505
+ /**
506
+ * Target resolution seam for BasicAttacher.
507
+ *
508
+ * Keeps listener target and Floating UI reference selection in one private
509
+ * module so explicit targets (elements, virtual references, and selectors)
510
+ * can be resolved cleanly without cluttering positioning or lifecycle logic.
511
+ */
512
+
513
+ /**
514
+ * Determine whether a target is a DOM Element.
515
+ *
516
+ * @param {unknown} value
517
+ * @returns {boolean}
518
+ */
519
+ function isElementTarget(value) {
520
+ return typeof Element !== 'undefined' && value instanceof Element;
521
+ }
522
+
523
+ /**
524
+ * Floating UI virtual references are plain objects with `getBoundingClientRect`.
525
+ *
526
+ * @param {unknown} value
527
+ * @returns {boolean}
528
+ */
529
+ function isVirtualReference(value) {
530
+ if (value == null || typeof value !== 'object') {
531
+ return false;
532
+ }
533
+ if (isElementTarget(value)) {
534
+ return false;
535
+ }
536
+ return typeof value.getBoundingClientRect === 'function';
537
+ }
538
+
539
+ /**
540
+ * Resolve a public `@explicitTarget` value (Element | selector | virtual ref).
541
+ *
542
+ * Selector strings use `querySelectorAll` and must match exactly one node
543
+ * (same contract as `@floatingElementContainer`).
544
+ *
545
+ * @param {Element | string | { getBoundingClientRect: Function } | null | undefined} value
546
+ * @param {ParentNode | Document | null | undefined} root
547
+ * @returns {Element | { getBoundingClientRect: Function } | null}
548
+ */
549
+ function coerceExplicitTarget(value, root) {
550
+ if (value == null) {
551
+ return null;
552
+ }
553
+ if (isElementTarget(value) || isVirtualReference(value)) {
554
+ return value;
555
+ }
556
+ if (typeof value === 'string') {
557
+ const doc = root ?? (typeof document !== 'undefined' ? document : null);
558
+ assert(`explicitTarget selector "${value}" cannot be resolved without a document`, doc != null);
559
+ const matches = doc.querySelectorAll(value);
560
+ assert(`explicitTarget selector "${value}" found ${matches.length} possible targets when there should be exactly 1`, matches.length === 1);
561
+ return matches[0];
562
+ }
563
+ assert('explicitTarget must be an Element, a CSS selector string, or a Floating UI virtual reference with getBoundingClientRect', false);
564
+ return null;
565
+ }
566
+
567
+ /**
568
+ * Pick the Floating UI reference: explicit arg, then yielded registration, then parent.
569
+ * Supports both options-bag and positional signatures.
570
+ *
571
+ * @param {object | Element | string | { getBoundingClientRect: Function } | null | undefined} optionsOrExplicit
572
+ * @param {Element | { getBoundingClientRect: Function } | null | undefined} [registeredOrParent]
573
+ * @param {Element | null | undefined} [parentElement] Implicit parent from the meta finder.
574
+ * @param {ParentNode | Document | null | undefined} [root]
575
+ * @returns {Element | { getBoundingClientRect: Function } | null}
576
+ */
577
+ function resolveAttachmentTarget(optionsOrExplicit, registeredOrParent, parentElement, root) {
578
+ let explicitTarget;
579
+ let registeredTarget;
580
+ let parent;
581
+ let searchRoot;
582
+ if (optionsOrExplicit != null && typeof optionsOrExplicit === 'object' && !isElementTarget(optionsOrExplicit) && !isVirtualReference(optionsOrExplicit)) {
583
+ ({
584
+ explicitTarget,
585
+ registeredTarget,
586
+ parentElement: parent,
587
+ root: searchRoot
588
+ } = optionsOrExplicit);
589
+ } else {
590
+ explicitTarget = optionsOrExplicit;
591
+ if (arguments.length <= 2) {
592
+ parent = registeredOrParent;
593
+ } else {
594
+ registeredTarget = registeredOrParent;
595
+ parent = parentElement;
596
+ searchRoot = root;
597
+ }
598
+ }
599
+ if (explicitTarget != null) {
600
+ return coerceExplicitTarget(explicitTarget, searchRoot);
601
+ }
602
+ if (registeredTarget != null) {
603
+ return registeredTarget;
604
+ }
605
+ return parent ?? null;
606
+ }
607
+
608
+ /**
609
+ * Extract the DOM Element that should receive event listeners.
610
+ * Real Elements receive events directly. Virtual references may provide a
611
+ * `contextElement`; virtual references without a contextElement attach no listeners.
612
+ *
613
+ * @param {Element | { getBoundingClientRect: Function, contextElement?: Element } | null | undefined} target
614
+ * @returns {Element | null}
615
+ */
616
+ function getListenerTarget(target) {
617
+ if (isElementTarget(target)) {
618
+ return target;
619
+ }
620
+ if (isVirtualReference(target) && isElementTarget(target.contextElement)) {
621
+ return target.contextElement;
622
+ }
623
+ return null;
624
+ }
625
+
626
+ /**
627
+ * Whether the current browser environment supports Top-Layer `[popover="manual"]`.
628
+ *
629
+ * @returns {boolean}
630
+ */
631
+ function supportsPopoverHost() {
632
+ return typeof HTMLElement !== 'undefined' && typeof HTMLElement.prototype.showPopover === 'function';
633
+ }
634
+
635
+ /**
636
+ * Find the nearest open modal `<dialog>` (`dialog:modal`) enclosing a context node,
637
+ * so Top-Layer attachments opened inside `showModal()` stay DOM-inside the modal
638
+ * and do not become inert.
639
+ *
640
+ * @param {Element | null | undefined} contextNode
641
+ * @returns {Element | null}
642
+ */
643
+ function getModalDialogContainer(contextNode) {
644
+ if (!isElementTarget(contextNode) || typeof contextNode.closest !== 'function') {
645
+ return null;
646
+ }
647
+ try {
648
+ return contextNode.closest('dialog:modal');
649
+ } catch {
650
+ return null;
651
+ }
652
+ }
653
+
654
+ /**
655
+ * Resolve the DOM destination element for `MaybeInElement`.
656
+ *
657
+ * @param {{
658
+ * renderInPlace: boolean,
659
+ * parentElement: Element | null,
660
+ * maybeContainer: Element | string | null | undefined,
661
+ * hasCustomContainer: boolean,
662
+ * modalContainer: Element | null,
663
+ * usePopoverHost: boolean,
664
+ * }} options
665
+ * @returns {Element | undefined}
666
+ */
667
+ function resolveHostContainer({
668
+ renderInPlace,
669
+ parentElement,
670
+ maybeContainer,
671
+ hasCustomContainer,
672
+ modalContainer,
673
+ usePopoverHost
674
+ }) {
675
+ if (renderInPlace) {
676
+ return parentElement;
677
+ }
678
+ if (maybeContainer instanceof Element) {
679
+ return maybeContainer;
680
+ }
681
+ if (!hasCustomContainer && modalContainer) {
682
+ return modalContainer;
683
+ }
684
+ if (typeof maybeContainer === 'string') {
685
+ const possibleContainers = document.querySelectorAll(maybeContainer);
686
+
687
+ // DEFAULTS.floatingElementContainer is '.ember-application'; embedded or
688
+ // standalone Top-Layer mounts without .ember-application fall back to body.
689
+ if (possibleContainers.length === 0 && !hasCustomContainer && usePopoverHost) {
690
+ return document.body;
691
+ }
692
+ assert(`floatingElementContainer selector "${maybeContainer}" found ` + `${possibleContainers.length} possible containers when there should be exactly 1`, possibleContainers.length === 1);
693
+ return possibleContainers[0];
694
+ }
695
+ return undefined;
696
+ }
697
+
698
+ /**
699
+ * Promote a `[popover]` host element into the browser Top Layer.
700
+ * If `showPopover()` throws, logs a debug warning and removes `[popover]` so the
701
+ * `{{#in-element}}` portal fallback stays visible instead of matching UA `:not(:popover-open)`.
702
+ *
703
+ * @param {Element | null | undefined} el
704
+ */
705
+ function showPopoverHost(el) {
706
+ if (el && el.isConnected && el.hasAttribute('popover') && typeof el.showPopover === 'function') {
707
+ try {
708
+ if (!el.matches(':popover-open')) {
709
+ el.showPopover();
710
+ }
711
+ } catch (error) {
712
+ warn(`[ember-attacher] Top-layer showPopover failed: ${error?.message ?? error}`, false, {
713
+ id: 'ember-attacher.popover-error'
714
+ });
715
+ el.removeAttribute('popover');
716
+ }
717
+ }
718
+ }
719
+
720
+ /**
721
+ * Remove a `[popover]` host element from the browser Top Layer.
722
+ *
723
+ * @param {Element | null | undefined} el
724
+ */
725
+ function hidePopoverHost(el) {
726
+ if (el && el.isConnected && el.hasAttribute('popover') && typeof el.hidePopover === 'function') {
727
+ try {
728
+ if (el.matches(':popover-open')) {
729
+ el.hidePopover();
730
+ }
731
+ } catch (error) {
732
+ warn(`[ember-attacher] Top-layer hidePopover failed: ${error?.message ?? error}`, false, {
733
+ id: 'ember-attacher.popover-error'
734
+ });
735
+ }
736
+ }
737
+ }
24
738
 
25
- var _class, _descriptor, _descriptor2, _descriptor3, _descriptor4, _descriptor5, _descriptor6, _descriptor7, _descriptor8;
26
- const animationTestWaiter = buildWaiter('basic-attacher');
27
739
  function consume(positional) {
28
740
  for (let i = 0; i < positional.length; i++) {
29
741
  void positional[i];
30
742
  }
31
743
  }
32
744
 
33
- // Run once per element, after render, so tracked writes do not hit the modifier's tracking frame.
745
+ /**
746
+ * Run once per element, after render, so tracked writes do not hit the modifier's tracking frame.
747
+ *
748
+ * @param {Function} fn
749
+ * @returns {import('ember-modifier').ModifierFunction}
750
+ */
34
751
  function onInsert(fn) {
35
752
  const seen = new WeakSet();
36
753
  return modifier(element => {
@@ -43,8 +760,13 @@ function onInsert(fn) {
43
760
  });
44
761
  }
45
762
 
46
- // Skip install ({{did-update}} semantics). Each factory has its own WeakSet so two
47
- // onUpdate modifiers on the same node do not steal each other's first run.
763
+ /**
764
+ * Skip install ({{did-update}} semantics). Each factory has its own WeakSet so two
765
+ * onUpdate modifiers on the same node do not steal each other's first run.
766
+ *
767
+ * @param {Function} fn
768
+ * @returns {import('ember-modifier').ModifierFunction}
769
+ */
48
770
  function onUpdate(fn) {
49
771
  const seen = new WeakSet();
50
772
  return modifier((element, positional) => {
@@ -56,121 +778,265 @@ function onUpdate(fn) {
56
778
  fn();
57
779
  });
58
780
  }
781
+
782
+ /**
783
+ * Check whether an attachment target (DOM Element or VirtualElement) is still connected.
784
+ *
785
+ * @param {Element | { contextElement?: Element } | null | undefined} target
786
+ * @returns {boolean}
787
+ */
788
+ function isTargetConnected(target) {
789
+ if (!target) {
790
+ return false;
791
+ }
792
+ if (isElementTarget(target)) {
793
+ return target.isConnected;
794
+ }
795
+ if (target.contextElement instanceof Element) {
796
+ return target.contextElement.isConnected;
797
+ }
798
+ return true;
799
+ }
800
+
801
+ /**
802
+ * Normalize and deduplicate the Floating UI middleware array without mutating
803
+ * caller-supplied middleware objects.
804
+ *
805
+ * @param {{
806
+ * rawMiddleware: Array<any> | null | undefined,
807
+ * arrowElement: Element | null,
808
+ * flipOption: string | null | undefined,
809
+ * overflowPadding: number | boolean | undefined,
810
+ * arrowEnabled: boolean,
811
+ * }} options
812
+ * @returns {Array<any>}
813
+ */
814
+ function buildMiddleware({
815
+ rawMiddleware,
816
+ arrowElement,
817
+ flipOption,
818
+ overflowPadding,
819
+ arrowEnabled
820
+ }) {
821
+ const middleware = (rawMiddleware || []).map(m => {
822
+ if (m?.name === 'arrow' && arrowElement) {
823
+ if (typeof m.options === 'function') {
824
+ return arrow(state => {
825
+ const resolved = m.options(state) || {};
826
+ return resolved.element ? resolved : {
827
+ ...resolved,
828
+ element: arrowElement
829
+ };
830
+ });
831
+ }
832
+ if (!m.options?.element) {
833
+ return arrow({
834
+ ...m.options,
835
+ element: arrowElement
836
+ });
837
+ }
838
+ }
839
+ return m;
840
+ });
841
+ if (!middleware.some(m => m?.name === 'flip')) {
842
+ if (flipOption) {
843
+ middleware.push(flip({
844
+ fallbackPlacements: flipOption.split(' ')
845
+ }));
846
+ } else if (overflowPadding !== false) {
847
+ middleware.push(flip());
848
+ }
849
+ }
850
+ if (overflowPadding !== false && !middleware.some(m => m?.name === 'shift')) {
851
+ middleware.push(shift({
852
+ limiter: limitShift(),
853
+ padding: overflowPadding
854
+ }));
855
+ }
856
+ if (arrowEnabled && arrowElement && !middleware.some(m => m?.name === 'arrow')) {
857
+ middleware.push(arrow({
858
+ element: arrowElement
859
+ }));
860
+ }
861
+ return middleware;
862
+ }
863
+
864
+ /**
865
+ * Apply the resolved `computePosition` coordinates, arrow offset, `middlewareData.hide`
866
+ * attributes, and `x-placement` to the floating and arrow elements.
867
+ *
868
+ * @param {Element} floatingElement
869
+ * @param {Element | null} arrowElement
870
+ * @param {{
871
+ * x: number,
872
+ * y: number,
873
+ * placement: string,
874
+ * strategy: string,
875
+ * middlewareData: Record<string, any>,
876
+ * isHidden: boolean,
877
+ * }} result
878
+ */
879
+ function applyPositionResult(floatingElement, arrowElement, {
880
+ x,
881
+ y,
882
+ placement,
883
+ strategy,
884
+ middlewareData,
885
+ isHidden
886
+ }) {
887
+ Object.assign(floatingElement.style, {
888
+ position: strategy,
889
+ left: `${x}px`,
890
+ top: `${y}px`
891
+ });
892
+ if (middlewareData.arrow && arrowElement) {
893
+ const {
894
+ x: arrowX,
895
+ y: arrowY
896
+ } = middlewareData.arrow;
897
+ Object.assign(arrowElement.style, {
898
+ left: arrowX != null ? `${arrowX}px` : '',
899
+ top: arrowY != null ? `${arrowY}px` : ''
900
+ });
901
+ }
902
+ if (middlewareData.hide) {
903
+ const {
904
+ referenceHidden,
905
+ escaped
906
+ } = middlewareData.hide;
907
+ if (referenceHidden) {
908
+ floatingElement.setAttribute('data-reference-hidden', '');
909
+ } else {
910
+ floatingElement.removeAttribute('data-reference-hidden');
911
+ }
912
+ if (escaped) {
913
+ floatingElement.setAttribute('data-escaped', '');
914
+ } else {
915
+ floatingElement.removeAttribute('data-escaped');
916
+ }
917
+ if (referenceHidden || escaped) {
918
+ floatingElement.style.visibility = 'hidden';
919
+ } else if (!isHidden) {
920
+ floatingElement.style.visibility = '';
921
+ }
922
+ }
923
+ floatingElement.setAttribute('x-placement', placement);
924
+ }
925
+
926
+ var MaybeInElement = setComponentTemplate(precompileTemplate("{{~#if @renderInPlace~}}{{yield}}{{~else~}}{{#in-element @destinationElement insertBefore=null}}{{yield}}{{/in-element}}{{~/if~}}", {
927
+ strictMode: true
928
+ }), templateOnly());
929
+
930
+ var TEMPLATE = precompileTemplate("{{~#unless this.renderFloatingElement~}}<meta hidden {{this.parentFinder}} {{this.targetDidUpdate this.hideOn this.showOn @explicitTarget}} {{this.isShownDidUpdate this.isShown}}/>{{~/unless~}}{{~#if this.renderFloatingElement~}}<this.MaybeInElement @destinationElement={{this._floatingElementContainer}} @renderInPlace={{this._renderInPlace}}><div\n class=\"ember-attacher\"\n id={{this.id}}\n popover={{this._popoverAttr}}\n role={{@ariaRole}}\n {{this.setupFloatingElement}}\n {{this.targetDidUpdate this.hideOn this.showOn @explicitTarget}}\n {{this.isShownDidUpdate this.isShown}}\n {{this.optionsDidUpdate this.autoUpdate this.animation this.arrow this.useCapture this.placement this.strategy this._renderInPlace this._middleware this.id @ariaRole}}\n ...attributes\n >\n {{#if this.shouldRenderFloatingElement}}\n <div class={{this._class}} style={{this._style}}>\n {{yield (hash hide=this.hide setReference=this.setReference reference=this.reference)}}\n {{#if this.arrow}}\n <div class=\"ember-attacher-arrow\" x-arrow {{this.insertArrow}}></div>\n {{/if}}\n {{#if this.isFillAnimation}}\n <div x-circle></div>\n {{/if}}\n </div>\n {{/if}}\n </div></this.MaybeInElement>{{~/if~}}\n");
931
+
932
+ var _class, _descriptor, _descriptor2, _descriptor3, _descriptor4, _descriptor5, _descriptor6, _descriptor7, _descriptor8;
933
+ const animationTestWaiter = buildWaiter('basic-attacher');
59
934
  let BasicAttacher = (_class = class BasicAttacher extends Component {
60
- /**
61
- * ================== PUBLIC CONFIG OPTIONS ==================
62
- */
935
+ _opt(key) {
936
+ return this.args[key] ?? this._config[key] ?? DEFAULTS[key];
937
+ }
63
938
  get arrow() {
64
- return this.args.arrow ?? this._config.arrow ?? DEFAULTS.arrow;
939
+ return this._opt('arrow');
65
940
  }
66
941
  get autoUpdate() {
67
- return this.args.autoUpdate ?? this._config.autoUpdate ?? DEFAULTS.autoUpdate;
942
+ return this._opt('autoUpdate');
68
943
  }
69
944
  get animation() {
70
945
  return this.args.animation || this._config.animation || DEFAULTS.animation;
71
946
  }
72
947
  get flip() {
73
- return this.args.flip ?? this._config.flip ?? DEFAULTS.flip;
948
+ return this._opt('flip');
74
949
  }
75
950
  get hideDelay() {
76
- return this.args.hideDelay ?? this._config.hideDelay ?? DEFAULTS.hideDelay;
951
+ return this._opt('hideDelay');
77
952
  }
78
953
  get hideDuration() {
79
- return this.args.hideDuration ?? this._config.hideDuration ?? DEFAULTS.hideDuration;
954
+ return this._opt('hideDuration');
80
955
  }
81
956
  get hideOn() {
82
- if (this.args.hideOn === null) {
83
- return null;
84
- }
85
- return this.args.hideOn ?? this._config.hideOn ?? DEFAULTS.hideOn;
957
+ return this.args.hideOn === null ? null : this._opt('hideOn');
86
958
  }
87
959
  get interactive() {
88
- return this.args.interactive ?? this._config.interactive ?? DEFAULTS.interactive;
960
+ return this._opt('interactive');
89
961
  }
90
962
  get isOffset() {
91
- return this.args.isOffset ?? this._config.isOffset ?? DEFAULTS.isOffset;
963
+ return this._opt('isOffset');
92
964
  }
93
965
  get isShown() {
94
- return this.args.isShown ?? this._config.isShown ?? DEFAULTS.isShown;
966
+ return this._opt('isShown');
95
967
  }
96
968
  get lazyRender() {
97
- return this.args.lazyRender ?? this._config.lazyRender ?? DEFAULTS.lazyRender;
969
+ return this._opt('lazyRender');
98
970
  }
99
- get placement() {
100
- return this.args.placement ?? this._config.placement ?? DEFAULTS.placement;
101
- }
102
- get floatingElementContainer() {
103
- return this.args.floatingElementContainer || this._config.floatingElementContainer || DEFAULTS.floatingElementContainer;
104
- }
105
- get class() {
106
- return this.args.class || this._config.class;
971
+ get overflowPadding() {
972
+ return this._opt('overflowPadding');
107
973
  }
108
- get floatingUiOptions() {
109
- return this.args.floatingUiOptions || this._config.floatingUiOptions || DEFAULTS.floatingUiOptions;
974
+ get placement() {
975
+ return this._opt('placement');
110
976
  }
111
977
  get renderInPlace() {
112
- return this.args.renderInPlace ?? this._config.renderInPlace ?? DEFAULTS.renderInPlace;
978
+ return this._opt('renderInPlace');
113
979
  }
114
980
  get showDelay() {
115
- return this.args.showDelay ?? this._config.showDelay ?? DEFAULTS.showDelay;
981
+ return this._opt('showDelay');
116
982
  }
117
983
  get showDuration() {
118
- return this.args.showDuration ?? this._config.showDuration ?? DEFAULTS.showDuration;
984
+ return this._opt('showDuration');
119
985
  }
120
986
  get showOn() {
121
- if (this.args.showOn === null) {
122
- return null;
123
- }
124
- return this.args.showOn ?? this._config.showOn ?? DEFAULTS.showOn;
987
+ return this.args.showOn === null ? null : this._opt('showOn');
988
+ }
989
+ get strategy() {
990
+ return this._opt('strategy');
125
991
  }
126
992
  get style() {
127
- return this.args.style ?? this._config.style ?? DEFAULTS.style;
993
+ return this._opt('style');
128
994
  }
129
995
  get useCapture() {
130
- return this.args.useCapture ?? this._config.useCapture ?? DEFAULTS.useCapture;
996
+ return this._opt('useCapture');
997
+ }
998
+ get class() {
999
+ return this.args.class || this._config.class;
1000
+ }
1001
+ get floatingElementContainer() {
1002
+ return this.args.floatingElementContainer || this._config.floatingElementContainer || DEFAULTS.floatingElementContainer;
1003
+ }
1004
+ get floatingUiOptions() {
1005
+ return this.args.floatingUiOptions || this._config.floatingUiOptions || DEFAULTS.floatingUiOptions;
131
1006
  }
132
1007
  get configKey() {
133
1008
  return this.args.configKey || 'popover';
134
1009
  }
1010
+ get _isTooltip() {
1011
+ return this.configKey === 'tooltip' || this.args.ariaRole === 'tooltip';
1012
+ }
135
1013
  get isFillAnimation() {
136
1014
  return this.animation === 'fill';
137
1015
  }
138
1016
  get renderFloatingElement() {
139
- return (this.renderInPlace || this._currentTarget) && (!this.lazyRender || this._mustRender);
1017
+ return Boolean(this.renderInPlace || this._currentTarget);
140
1018
  }
141
1019
  get shouldRenderFloatingElement() {
142
- // Always render the floating element unless lazyRender is true and we haven't been triggered yet
143
1020
  return !this.lazyRender || this._mustRender;
144
1021
  }
145
1022
  get id() {
146
1023
  return this.args.id || `${guidFor(this)}-floating`;
147
1024
  }
148
- get overflowPadding() {
149
- return this.args.overflowPadding ?? this._config.overflowPadding ?? DEFAULTS.overflowPadding;
150
- }
151
-
152
- // The circle element needs a special duration that is slightly faster than the floating element's
153
- // transition, this prevents text from appearing outside the circle as it fills the background
154
- get _circleTransitionDuration() {
155
- return htmlSafe(`transition-duration: ${Math.round(this._transitionDuration / 1.25)}ms`);
156
- }
157
1025
  get _class() {
158
1026
  const showOrHideClass = `ember-attacher-${this._isStartingAnimation ? 'show' : 'hide'}`;
159
1027
  const arrowClass = `ember-attacher-${this.arrow ? 'with' : 'without'}-arrow`;
160
- const baseClass = this.class || '';
161
- const additionalClass = this.args.additionalClass || '';
162
- return [`ember-attacher-${this.animation}`, baseClass, additionalClass, showOrHideClass, arrowClass].filter(Boolean).join(' ');
1028
+ return [`ember-attacher-${this.animation}`, this.class || '', this.args.additionalClass || '', showOrHideClass, arrowClass].filter(Boolean).join(' ');
163
1029
  }
164
1030
  get _style() {
165
1031
  const style = this.style;
166
- const transitionDuration = this._transitionDuration;
167
- warn('@ember/string/htmlSafe must be used for any `style` passed to ember-attacher', isEmpty(style) || isHTMLSafe(style), {
1032
+ if (!style) {
1033
+ return undefined;
1034
+ }
1035
+ warn('@ember/string/htmlSafe must be used for any `style` passed to ember-attacher', isHTMLSafe(style), {
168
1036
  id: 'ember-attacher-require-html-safe-style'
169
1037
  });
170
- return htmlSafe(`transition-duration: ${transitionDuration}ms; ${style}`);
1038
+ return style;
171
1039
  }
172
-
173
- // This is memoized so it can be used by both attach-popover and attach-tooltip
174
1040
  get _envConfig() {
175
1041
  return getOwner(this).resolveRegistration('config:environment').emberAttacher || {};
176
1042
  }
@@ -181,62 +1047,72 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
181
1047
  };
182
1048
  }
183
1049
  get _hideOn() {
184
- let hideOn = this.hideOn;
185
- if (hideOn === undefined) {
186
- hideOn = DEFAULTS.hideOn;
187
- }
1050
+ const hideOn = this.hideOn === undefined ? DEFAULTS.hideOn : this.hideOn;
188
1051
  return hideOn === null ? [] : hideOn.split(' ');
189
1052
  }
1053
+ get _showOn() {
1054
+ const showOn = this.showOn === undefined ? DEFAULTS.showOn : this.showOn;
1055
+ return showOn === null ? [] : showOn.split(' ');
1056
+ }
190
1057
  get _middleware() {
191
- // Copy the middleware since we might write to the provided array
192
- const middleware = this.args.middleware ? [...this.args.middleware] : [];
193
- const flipString = this.flip;
194
- if (flipString) {
195
- const flipOptions = {
196
- fallbackPlacements: flipString.split(' ')
197
- };
198
- const flipMiddleware = middleware.find(name => name === 'flip');
199
- if (!flipMiddleware) {
200
- middleware.push(flip(flipOptions));
201
- } else if (!flipMiddleware.fallbackPlacements) {
202
- Object.assign({}, flipMiddleware, flipOptions);
1058
+ return buildMiddleware({
1059
+ rawMiddleware: this._opt('middleware'),
1060
+ arrowElement: this._arrowElement,
1061
+ flipOption: this.flip,
1062
+ overflowPadding: this.overflowPadding,
1063
+ arrowEnabled: Boolean(this.arrow)
1064
+ });
1065
+ }
1066
+ get _hasCustomFloatingElementContainer() {
1067
+ return Boolean(this.args.floatingElementContainer || this._config.floatingElementContainer);
1068
+ }
1069
+ get _usePopoverHost() {
1070
+ return supportsPopoverHost() && !this._renderInPlace && !this._hasCustomFloatingElementContainer;
1071
+ }
1072
+ get _popoverAttr() {
1073
+ return this._usePopoverHost ? 'manual' : undefined;
1074
+ }
1075
+ get _renderInPlace() {
1076
+ return typeof document !== 'undefined' ? Boolean(this.renderInPlace) : true;
1077
+ }
1078
+ get _floatingElementContainer() {
1079
+ return resolveHostContainer({
1080
+ renderInPlace: this._renderInPlace,
1081
+ parentElement: this.parentElement,
1082
+ maybeContainer: this.floatingElementContainer,
1083
+ hasCustomContainer: this._hasCustomFloatingElementContainer,
1084
+ modalContainer: this._modalContainer,
1085
+ usePopoverHost: this._usePopoverHost
1086
+ });
1087
+ }
1088
+ _syncModalContainer() {
1089
+ if (this._renderInPlace || this._hasCustomFloatingElementContainer) {
1090
+ if (this._modalContainer !== null) {
1091
+ this._modalContainer = null;
203
1092
  }
204
- } else if (this.overflowPadding !== false) {
205
- middleware.push(flip());
206
- }
207
- if (this.overflowPadding !== false && !middleware.find(name => name === 'shift')) {
208
- middleware.push(shift({
209
- limiter: limitShift(),
210
- padding: this.overflowPadding
211
- }));
1093
+ return false;
212
1094
  }
213
- if (this.arrow && this._arrowElement && !middleware.find(name => name === 'arrow')) {
214
- middleware.push(arrow({
215
- element: this._arrowElement
216
- }));
1095
+ const modalDialog = getModalDialogContainer(this._listenerTarget || this.parentElement);
1096
+ if (this._modalContainer !== modalDialog) {
1097
+ this._modalContainer = modalDialog;
1098
+ return true;
217
1099
  }
218
- return middleware;
219
- }
220
- get _floatingElementContainer() {
221
- const maybeContainer = this.floatingElementContainer;
222
- const renderInPlace = this._renderInPlace;
223
- let floatingElementContainer;
224
- if (renderInPlace) {
225
- floatingElementContainer = this.parentElement;
226
- } else if (maybeContainer instanceof Element) {
227
- floatingElementContainer = maybeContainer;
228
- } else if (typeof maybeContainer === 'string') {
229
- const selector = maybeContainer;
230
- const possibleContainers = document.querySelectorAll(selector);
231
- assert(`floatingElementContainer selector "${selector}" found ` + `${possibleContainers.length} possible containers when there should be exactly 1`, possibleContainers.length === 1);
232
- floatingElementContainer = possibleContainers[0];
233
- }
234
- return floatingElementContainer;
1100
+ return false;
235
1101
  }
236
- get _renderInPlace() {
237
- // document is undefined in Fastboot, so we have to render in
238
- // place for the floating element to show up at all.
239
- return typeof document !== 'undefined' ? !!this.renderInPlace : true;
1102
+ _applyVisibility(isVisible) {
1103
+ if (!isVisible) {
1104
+ this._cleanup?.();
1105
+ this._cleanup = null;
1106
+ }
1107
+ this._floatingElement.style.display = isVisible ? 'block' : 'none';
1108
+ // Prevent jank by keeping the attachment invisible until positioned by _startShowAnimation().
1109
+ this._floatingElement.style.visibility = isVisible ? 'hidden' : '';
1110
+ if (isVisible) {
1111
+ showPopoverHost(this._floatingElement);
1112
+ } else {
1113
+ hidePopoverHost(this._floatingElement);
1114
+ }
1115
+ this.args.onChange?.(isVisible);
240
1116
  }
241
1117
  _setIsVisibleAfterDelay(isVisible, delay) {
242
1118
  if (!this._floatingElement) {
@@ -245,87 +1121,38 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
245
1121
  });
246
1122
  return;
247
1123
  }
248
- const onChange = this.args.onChange;
249
1124
  if (delay) {
250
1125
  this._delayedVisibilityToggle = later(this, () => {
251
1126
  this._animationTimeout = requestAnimationFrame(() => {
252
1127
  animationTestWaiter.endAsync(this._animationTimeout);
253
1128
  if (!this.isDestroyed && !this.isDestroying) {
254
- if (!isVisible) {
255
- this._cleanup?.();
256
- this._cleanup = null;
257
- }
258
- this._floatingElement.style.display = isVisible ? 'block' : 'none';
259
-
260
- // Prevent jank by making the attachment invisible until positioned.
261
- // The visibility style will be toggled by this._startShowAnimation()
262
- this._floatingElement.style.visibility = isVisible ? 'hidden' : '';
263
- if (onChange) {
264
- onChange(isVisible);
265
- }
1129
+ this._applyVisibility(isVisible);
266
1130
  }
267
1131
  });
268
1132
  animationTestWaiter.beginAsync(this._animationTimeout);
269
1133
  }, delay);
270
1134
  } else {
271
- if (!isVisible) {
272
- this._cleanup?.();
273
- this._cleanup = null;
274
- }
275
- this._floatingElement.style.display = isVisible ? 'block' : 'none';
276
- // Prevent jank by making the attachment invisible until positioned.
277
- // The visibility style will be toggled by this._startShowAnimation()
278
- this._floatingElement.style.visibility = isVisible ? 'hidden' : '';
279
- if (onChange) {
280
- onChange(isVisible);
281
- }
282
- }
283
- }
284
- get _showOn() {
285
- let showOn = this.showOn;
286
- if (showOn === undefined) {
287
- showOn = DEFAULTS.showOn;
1135
+ this._applyVisibility(isVisible);
288
1136
  }
289
- return showOn === null ? [] : showOn.split(' ');
290
1137
  }
291
-
292
- // Exposed via the named yield to enable custom hide events
293
1138
  hide() {
294
1139
  this._hide();
295
1140
  }
296
-
297
- /**
298
- * Register an explicit attachment target (Element or Floating UI virtual ref).
299
- * Yielded for composition into other modifiers.
300
- * Pass `null` to clear and fall back to `@explicitTarget` / parent.
301
- *
302
- * Calls `_initializeAttacher` directly so registration that happens during the
303
- * floating element's first render takes effect before the next user event.
304
- *
305
- * @param {Element | { getBoundingClientRect: Function } | null | undefined} target
306
- */
307
1141
  setReference(target) {
308
1142
  cancel(this._setReferenceTimer);
309
-
310
- // Defer: callers often invoke this from another modifier's
311
- // `modify()` (composition). Tracked writes + re-init must not run in
312
- // that tracking frame.
313
1143
  this._setReferenceTimer = schedule('actions', () => {
314
1144
  this._setReferenceTimer = null;
315
1145
  if (this.isDestroyed || this.isDestroying) {
316
1146
  return;
317
1147
  }
318
- const next = target ?? null;
319
- if (this._registeredTarget === next) {
1148
+ const nextTarget = target ?? null;
1149
+ if (this._registeredTarget === nextTarget) {
320
1150
  return;
321
1151
  }
322
- this._registeredTarget = next;
1152
+ this._registeredTarget = nextTarget;
323
1153
  this._initializeAttacher();
324
1154
  });
325
1155
  }
326
-
327
- // Always defined on first render so the modifier binding is present immediately.
328
-
329
1156
  _ensureArgumentsAreValid() {
330
1157
  runInDebug(() => {
331
1158
  if (this.arrow && this.isFillAnimation) {
@@ -342,37 +1169,31 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
342
1169
  }
343
1170
  constructor() {
344
1171
  super(...arguments);
345
-
346
- // The debounced _hide() and _show() are stored here so they can be cancelled when necessary
347
1172
  _defineProperty(this, "MaybeInElement", MaybeInElement);
348
1173
  _initializerDefineProperty(this, "parentNotFound", _descriptor, this);
349
1174
  _initializerDefineProperty(this, "parentElement", _descriptor2, this);
350
1175
  _initializerDefineProperty(this, "_isStartingAnimation", _descriptor3, this);
351
1176
  _initializerDefineProperty(this, "_arrowElement", _descriptor4, this);
352
1177
  _initializerDefineProperty(this, "_currentTarget", _descriptor5, this);
353
- // Yielded `setReference` / `reference` registration. Prefer
354
- // `@explicitTarget` when that arg is set; otherwise this beats parent.
355
1178
  _initializerDefineProperty(this, "_registeredTarget", _descriptor6, this);
1179
+ _initializerDefineProperty(this, "_mustRender", _descriptor7, this);
1180
+ _initializerDefineProperty(this, "_modalContainer", _descriptor8, this);
356
1181
  _defineProperty(this, "_setReferenceTimer", null);
357
- // Untracked copy of the node listeners are on. `_removeEventListeners` must
358
- // not read `_currentTarget` in the same computation that writes it
359
- // (`targetDidUpdate` → `_initializeAttacher` when `@explicitTarget` changes).
1182
+ // Untracked copy of the node listeners are on so `_removeEventListeners` does
1183
+ // not read `_currentTarget` in the same frame that writes it (`targetDidUpdate`).
360
1184
  _defineProperty(this, "_listenerTarget", null);
361
- // This is set to true when the popover is shown in order to override lazyRender=false
362
- _initializerDefineProperty(this, "_mustRender", _descriptor7, this);
363
- _initializerDefineProperty(this, "_transitionDuration", _descriptor8, this);
364
1185
  _defineProperty(this, "_floatingElement", null);
365
1186
  _defineProperty(this, "parentFinder", onInsert(element => {
366
- if (this.isDestroyed || this.isDestroying) {
367
- return;
1187
+ if (!this.isDestroyed && !this.isDestroying) {
1188
+ this.parentElement = element.parentElement;
1189
+ this._initializeAttacher();
368
1190
  }
369
- this.parentElement = element.parentElement;
370
- this._initializeAttacher();
371
1191
  }));
372
- // Insert + autoUpdate teardown. Must not read tracked state in the modifier
373
- // callback (the scheduled fn is fine); a tracked read would re-run this and
374
- // fire the destructor before updates.
1192
+ // Insert + autoUpdate teardown. Must not read tracked state synchronously in
1193
+ // the modifier callback (the scheduled fn is fine) or tracked updates will re-fire teardown.
375
1194
  _defineProperty(this, "setupFloatingElement", modifier(element => {
1195
+ this._floatingElement = element;
1196
+ registerAttacher(this);
376
1197
  const timer = schedule('actions', () => {
377
1198
  if (this.isDestroyed || this.isDestroying) {
378
1199
  return;
@@ -381,55 +1202,52 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
381
1202
  if (this.renderInPlace) {
382
1203
  this.parentElement = element.parentElement;
383
1204
  this._initializeAttacher();
1205
+ } else {
1206
+ syncParentAttachment(this);
384
1207
  }
385
1208
  });
386
1209
  return () => {
387
1210
  cancel(timer);
1211
+ if (this._floatingElement === element) {
1212
+ this._floatingElement = null;
1213
+ }
388
1214
  this._cleanup?.();
389
1215
  };
390
1216
  }));
391
1217
  _defineProperty(this, "insertArrow", onInsert(element => {
392
- if (this.isDestroyed || this.isDestroying) {
393
- return;
1218
+ if (!this.isDestroyed && !this.isDestroying) {
1219
+ this._arrowElement = element;
394
1220
  }
395
- this._arrowElement = element;
396
1221
  }));
397
1222
  _defineProperty(this, "isShownDidUpdate", onUpdate(() => this._syncIsShown()));
398
1223
  _defineProperty(this, "targetDidUpdate", onUpdate(() => this._initializeAttacher()));
399
1224
  _defineProperty(this, "optionsDidUpdate", onUpdate(() => {
400
1225
  this._ensureArgumentsAreValid();
1226
+ this._syncAria();
401
1227
  this._update();
402
1228
  }));
403
1229
  _defineProperty(this, "reference", modifier(element => {
404
1230
  this.setReference(element);
405
1231
  return () => {
406
- if (this.isDestroyed || this.isDestroying) {
407
- return;
408
- }
409
- if (this._registeredTarget === element) {
1232
+ if (!this.isDestroyed && !this.isDestroying && this._registeredTarget === element) {
410
1233
  this.setReference(null);
411
1234
  }
412
1235
  };
413
1236
  }));
1237
+ registerAttacher(this);
414
1238
  this._delayedVisibilityToggle = null;
415
-
416
- // The final source of truth on whether or not all _hide() or _show() actions have completed
417
1239
  this._isHidden = true;
418
-
419
- // Blocks _update from (re)starting autoUpdate after hide until the next show.
1240
+ this._isHiding = false;
420
1241
  this._positioningSuspended = false;
421
-
422
- // Holds a delayed function to toggle the visibility of the attachment.
423
- // Used to make sure animations can complete before the attachment is hidden.
424
1242
  this._animationTimeout = null;
425
-
426
- // Used to store event listeners so they can be removed when necessary.
427
1243
  this._hideListenersOnDocumentByEvent = {};
428
1244
  this._hideListenersOnTargetByEvent = {};
429
1245
  this._showListenersOnTargetByEvent = {};
430
-
431
- // Hacks to make sure event listeners have the right context and are still removable
432
- this._debouncedHideIfMouseOutsideTargetOrAttachment = this._debouncedHideIfMouseOutsideTargetOrAttachment.bind(this);
1246
+ this._aria = new AttachmentAriaController();
1247
+ this._ariaOpen = false;
1248
+ this._mouseLeaveOrigin = null;
1249
+ this._restoreFocusOnHide = false;
1250
+ this._suppressFocusShow = false;
433
1251
  this._hide = this._hide.bind(this);
434
1252
  this._hideAfterDelay = this._hideAfterDelay.bind(this);
435
1253
  this._hideIfMouseOutsideTargetOrAttachment = this._hideIfMouseOutsideTargetOrAttachment.bind(this);
@@ -441,6 +1259,14 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
441
1259
  this._showAfterDelay = this._showAfterDelay.bind(this);
442
1260
  this._lastUseCaptureArgumentValue = this.useCapture;
443
1261
  }
1262
+ _syncAria() {
1263
+ this._aria.bind(this._listenerTarget, {
1264
+ isTooltip: this._isTooltip,
1265
+ id: this.id,
1266
+ ariaRole: this.args.ariaRole,
1267
+ isOpen: this._ariaOpen
1268
+ });
1269
+ }
444
1270
  _initializeAttacher() {
445
1271
  this._removeEventListeners();
446
1272
  const target = resolveAttachmentTarget({
@@ -450,16 +1276,18 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
450
1276
  });
451
1277
  this._listenerTarget = getListenerTarget(target);
452
1278
  this._currentTarget = target;
1279
+ this._syncModalContainer();
1280
+ syncParentAttachment(this);
453
1281
  this._addListenersForShowEvents();
454
1282
  if (!this._isHidden || this.isShown) {
1283
+ this._ariaOpen = true;
1284
+ this._syncAria();
455
1285
  this._addListenersForHideEvents();
456
-
457
- // Even if the attachment is already shown, we still want to
458
- // call this._show() to make sure its position is updated for a potentially new target.
459
1286
  this._show();
1287
+ } else {
1288
+ this._ariaOpen = false;
1289
+ this._syncAria();
460
1290
  }
461
-
462
- // Call hook for subclasses to add their own initialization logic
463
1291
  this.args.onInitializeAttacher?.(this._currentTarget, this.id);
464
1292
  }
465
1293
  _addListenersForShowEvents() {
@@ -474,17 +1302,18 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
474
1302
  }
475
1303
  willDestroy() {
476
1304
  super.willDestroy(...arguments);
1305
+ unregisterAttacher(this);
477
1306
  this._cleanup?.();
478
1307
  this._cleanup = null;
479
1308
  cancel(this._setReferenceTimer);
480
1309
  this._cancelAnimation();
481
1310
  cancel(this._delayedVisibilityToggle);
1311
+ this._aria.unbind();
482
1312
  this._removeEventListeners();
483
-
484
- // Call hook for cleanup
485
1313
  this.args.onWillDestroy?.(this._currentTarget, this.id);
486
1314
  }
487
1315
  _removeEventListeners() {
1316
+ this._mouseLeaveOrigin = null;
488
1317
  Object.keys(this._hideListenersOnDocumentByEvent).forEach(eventType => {
489
1318
  document.removeEventListener(eventType, this._hideListenersOnDocumentByEvent[eventType], this.useCapture);
490
1319
  delete this._hideListenersOnDocumentByEvent[eventType];
@@ -503,22 +1332,19 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
503
1332
  const isShown = this.isShown;
504
1333
  if (isShown === true && this._isHidden) {
505
1334
  this._show();
506
-
507
- // Add the hide listeners in the next run loop to avoid conflicts
508
- // where clicking triggers both an isShown toggle and a clickout.
509
1335
  next(this, () => this._addListenersForHideEvents());
510
1336
  } else if (isShown === false && !this._isHidden) {
511
1337
  this._hide();
512
1338
  }
513
1339
  }
514
-
515
- /**
516
- * ================== SHOW ATTACHMENT LOGIC ==================
517
- */
518
-
519
- _showAfterDelay() {
1340
+ _showAfterDelay(event) {
1341
+ if (this._suppressFocusShow && (event?.type === 'focus' || event?.type === 'focusin')) {
1342
+ return;
1343
+ }
520
1344
  cancel(this._delayedVisibilityToggle);
1345
+ this._isHiding = false;
521
1346
  this._mustRender = true;
1347
+ syncParentAttachment(this);
522
1348
  this._addListenersForHideEvents();
523
1349
  const showDelay = parseInt(this.showDelay);
524
1350
  this._delayedVisibilityToggle = debounce(this, this._show, showDelay, !showDelay);
@@ -528,35 +1354,38 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
528
1354
  if (!this._currentTarget) {
529
1355
  return;
530
1356
  }
1357
+ this._restoreFocusOnHide = false;
1358
+ this._isHiding = false;
531
1359
  this._positioningSuspended = false;
532
1360
  this._mustRender = true;
533
-
534
- // Make the attachment visible immediately so transition animations can take place
1361
+ this._ariaOpen = true;
1362
+ this._aria.setOpen(true);
1363
+ const modalContainerChanged = this._syncModalContainer();
1364
+ syncParentAttachment(this);
1365
+ if (modalContainerChanged) {
1366
+ next(this, () => {
1367
+ if (!this.isDestroyed && !this.isDestroying && !this._isHiding && this._currentTarget) {
1368
+ this._setIsVisibleAfterDelay(true, 0);
1369
+ this._startShowAnimation();
1370
+ }
1371
+ });
1372
+ return;
1373
+ }
535
1374
  this._setIsVisibleAfterDelay(true, 0);
536
1375
  this._startShowAnimation();
537
1376
  }
538
1377
  _startShowAnimation() {
539
- // Start the show animation on the next cycle so CSS transitions can have an effect.
540
- // If we start the animation immediately, the transition won't work because
541
- // `display: none` => `display: ''` is not transition-able.
542
- // All included animations set opaque: 0, so the attachment is still effectively hidden until
543
- // the final RAF occurs.
544
1378
  this._animationTimeout = requestAnimationFrame(() => {
545
1379
  animationTestWaiter.endAsync(this._animationTimeout);
546
1380
  if (this.isDestroyed || this.isDestroying || !this._currentTarget) {
547
1381
  return;
548
1382
  }
549
1383
  const floatingElement = this._floatingElement;
550
-
551
- // Wait until the element is visible before continuing
552
1384
  if (!floatingElement || floatingElement.style.display === 'none') {
553
1385
  this._startShowAnimation();
554
1386
  return;
555
1387
  }
556
1388
  this._update();
557
-
558
- // Wait for the above positioning to take effect before starting the show animation,
559
- // else the positioning itself will be animated, causing animation glitches.
560
1389
  this._animationTimeout = requestAnimationFrame(() => {
561
1390
  animationTestWaiter.endAsync(this._animationTimeout);
562
1391
  if (this.isDestroyed || this.isDestroying || !this._currentTarget) {
@@ -566,9 +1395,11 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
566
1395
  if (this.isDestroyed || this.isDestroying || !this._currentTarget) {
567
1396
  return;
568
1397
  }
569
- // Make the floating element visible now that it has been positioned
570
- floatingElement.style.visibility = '';
571
- this._transitionDuration = parseInt(this.showDuration);
1398
+ if (!floatingElement.hasAttribute('data-reference-hidden') && !floatingElement.hasAttribute('data-escaped')) {
1399
+ floatingElement.style.visibility = '';
1400
+ }
1401
+ const showDuration = parseInt(this.showDuration);
1402
+ floatingElement.style.setProperty('--ember-attacher-transition-duration', `${showDuration}ms`);
572
1403
  this._isStartingAnimation = true;
573
1404
  floatingElement.setAttribute('aria-hidden', 'false');
574
1405
  });
@@ -578,18 +1409,17 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
578
1409
  });
579
1410
  animationTestWaiter.beginAsync(this._animationTimeout);
580
1411
  }
581
-
582
- /**
583
- * ================== HIDE ATTACHMENT LOGIC ==================
584
- */
585
-
586
1412
  _hideAfterDelay() {
587
1413
  cancel(this._delayedVisibilityToggle);
1414
+ this._isHiding = true;
588
1415
  const hideDelay = parseInt(this.hideDelay);
589
1416
  this._delayedVisibilityToggle = debounce(this, this._hide, hideDelay, !hideDelay);
590
1417
  }
591
1418
  _hide() {
1419
+ this._isHiding = true;
592
1420
  this._positioningSuspended = true;
1421
+ this._ariaOpen = false;
1422
+ this._mouseLeaveOrigin = null;
593
1423
  this._cleanup?.();
594
1424
  this._cleanup = null;
595
1425
  if (!this._floatingElement) {
@@ -604,7 +1434,6 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
604
1434
  this._removeListenersForHideEvents();
605
1435
  this._animationTimeout = requestAnimationFrame(() => {
606
1436
  animationTestWaiter.endAsync(this._animationTimeout);
607
- // Avoid a race condition where we attempt to hide after the component is being destroyed.
608
1437
  if (this.isDestroyed || this.isDestroying) {
609
1438
  return;
610
1439
  }
@@ -613,30 +1442,32 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
613
1442
  if (this.isDestroyed || this.isDestroying) {
614
1443
  return;
615
1444
  }
616
- this._transitionDuration = hideDuration;
1445
+ if (this._restoreFocusOnHide) {
1446
+ this._restoreFocusOnHide = false;
1447
+ this._suppressFocusShow = true;
1448
+ try {
1449
+ restoreFocusOnEscape(this._listenerTarget, this._floatingElement);
1450
+ } finally {
1451
+ this._suppressFocusShow = false;
1452
+ }
1453
+ }
1454
+ this._floatingElement.style.setProperty('--ember-attacher-transition-duration', `${hideDuration}ms`);
617
1455
  this._isStartingAnimation = false;
618
1456
  this._floatingElement.setAttribute('aria-hidden', 'true');
619
- // Wait for any animations to complete before hiding the attachment
1457
+ this._aria.setOpen(false);
620
1458
  this._setIsVisibleAfterDelay(false, hideDuration);
621
1459
  });
622
1460
  this._isHidden = true;
623
1461
  });
624
1462
  animationTestWaiter.beginAsync(this._animationTimeout);
625
1463
  }
626
-
627
- /**
628
- * ================== HIDE LISTENERS ==================
629
- */
630
-
631
1464
  _addListenersForHideEvents() {
632
1465
  const hideOn = this._hideOn;
633
1466
  const target = this._listenerTarget;
634
-
635
- // Target or component was destroyed (virtual refs without contextElement skip listeners)
636
- if (!target || this.isDestroyed || this.isDestroying) {
1467
+ if (!this._currentTarget || this.isDestroyed || this.isDestroying) {
637
1468
  return;
638
1469
  }
639
- if (hideOn.includes('click')) {
1470
+ if (target && hideOn.includes('click')) {
640
1471
  const showOnClickListener = this._showListenersOnTargetByEvent.click;
641
1472
  if (showOnClickListener) {
642
1473
  target.removeEventListener('click', showOnClickListener, this.useCapture);
@@ -654,29 +1485,25 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
654
1485
  this._hideListenersOnDocumentByEvent.keydown = this._hideOnEscapeKey;
655
1486
  document.addEventListener('keydown', this._hideOnEscapeKey, this.useCapture);
656
1487
  }
657
-
658
- // Hides the attachment when the mouse leaves the target
659
- // (or leaves both target and attachment for interactive attachments)
660
- if (hideOn.includes('mouseleave')) {
1488
+ if (target && hideOn.includes('mouseleave')) {
661
1489
  this._hideListenersOnTargetByEvent.mouseleave = this._hideOnMouseLeaveTarget;
662
1490
  target.addEventListener('mouseleave', this._hideOnMouseLeaveTarget, this.useCapture);
663
1491
  }
664
-
665
- // Hides the attachment when focus is lost on the target
666
- ['blur', 'focusout'].forEach(eventType => {
667
- if (hideOn.includes(eventType)) {
668
- this._hideListenersOnTargetByEvent[eventType] = this._hideOnLostFocus;
669
- target.addEventListener(eventType, this._hideOnLostFocus, this.useCapture);
670
- }
671
- });
1492
+ if (target) {
1493
+ ['blur', 'focusout'].forEach(eventType => {
1494
+ if (hideOn.includes(eventType)) {
1495
+ this._hideListenersOnTargetByEvent[eventType] = this._hideOnLostFocus;
1496
+ target.addEventListener(eventType, this._hideOnLostFocus, this.useCapture);
1497
+ }
1498
+ });
1499
+ }
672
1500
  }
673
- _hideOnMouseLeaveTarget() {
1501
+ _hideOnMouseLeaveTarget(event) {
674
1502
  if (this.interactive) {
675
- // TODO(kjb) Should debounce this, but hiding appears sluggish if you debounce.
676
- // - If you debounce with immediate fire, you get a bug where you can move out of the
677
- // attachment and not trigger the hide because the hide check was debounced
678
- // - Ideally we would debounce with an immediate run, then instead of debouncing, we would
679
- // queue another fire at the end of the debounce period
1503
+ this._mouseLeaveOrigin = event ? {
1504
+ x: event.clientX,
1505
+ y: event.clientY
1506
+ } : null;
680
1507
  if (!this._hideListenersOnDocumentByEvent.mousemove) {
681
1508
  this._hideListenersOnDocumentByEvent.mousemove = this._hideIfMouseOutsideTargetOrAttachment;
682
1509
  document.addEventListener('mousemove', this._hideIfMouseOutsideTargetOrAttachment, this.useCapture);
@@ -685,87 +1512,46 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
685
1512
  this._hideAfterDelay();
686
1513
  }
687
1514
  }
688
- _debouncedHideIfMouseOutsideTargetOrAttachment(event) {
689
- debounce(this, this._hideIfMouseOutsideTargetOrAttachment, event, 10);
690
- }
691
1515
  _hideIfMouseOutsideTargetOrAttachment(event) {
692
1516
  const target = this._listenerTarget;
693
1517
  if (!target) {
694
1518
  return;
695
1519
  }
696
-
697
- // If cursor is not on the attachment or target, hide the floating element
698
- if (!target.contains(event.target) && !(this.isOffset && this._isCursorBetweenTargetAndAttachment(event)) && this._floatingElement && !this._floatingElement.contains(event.target)) {
699
- // Remove this listener before hiding the attachment
1520
+ if (!target.contains(event.target) && !descendantAttachmentContainsEvent(this, event) && !isCursorInSafePolygon(event, this._mouseLeaveOrigin, this._currentTarget, this._floatingElement) && this._floatingElement && !this._floatingElement.contains(event.target)) {
1521
+ this._mouseLeaveOrigin = null;
700
1522
  delete this._hideListenersOnDocumentByEvent.mousemove;
701
1523
  document.removeEventListener('mousemove', this._hideIfMouseOutsideTargetOrAttachment, this.useCapture);
702
1524
  this._hideAfterDelay();
703
1525
  }
704
1526
  }
705
- _isCursorBetweenTargetAndAttachment(event) {
706
- if (!this._currentTarget || !this._floatingElement) {
707
- return false;
708
- }
709
- const {
710
- clientX,
711
- clientY
712
- } = event;
713
- const attachmentPosition = this._floatingElement.getBoundingClientRect();
714
- const targetPosition = this._currentTarget.getBoundingClientRect();
715
- const isBetweenLeftAndRight = clientX > Math.min(attachmentPosition.left, targetPosition.left) && clientX < Math.max(attachmentPosition.right, targetPosition.right);
716
- const isBetweenTopAndBottom = clientY > Math.min(attachmentPosition.top, targetPosition.top) && clientY < Math.max(attachmentPosition.bottom, targetPosition.bottom);
717
-
718
- // Check if cursor is between a left-flipped attachment
719
- if (attachmentPosition.right < targetPosition.left && clientX >= attachmentPosition.right && clientX <= targetPosition.left && isBetweenTopAndBottom) {
720
- return true;
721
- }
722
-
723
- // Check if cursor is between a right-flipped attachment
724
- if (attachmentPosition.left > targetPosition.right && clientX <= attachmentPosition.left && clientX >= targetPosition.right && isBetweenTopAndBottom) {
725
- return true;
726
- }
727
-
728
- // Check if cursor is between a bottom-flipped attachment
729
- if (attachmentPosition.top > targetPosition.bottom && clientY <= attachmentPosition.top && clientY >= targetPosition.bottom && isBetweenLeftAndRight) {
730
- return true;
731
- }
732
-
733
- // Check if cursor is between a top-flipped attachment
734
- if (attachmentPosition.bottom < targetPosition.top && clientY >= attachmentPosition.bottom && clientY <= targetPosition.top && isBetweenLeftAndRight) {
735
- return true;
736
- }
737
- return false;
738
- }
739
1527
  _hideOnClickOut(event) {
740
1528
  const target = this._listenerTarget;
741
- const targetReceivedClick = target ? target.contains(event.target) : false;
742
- if (this.interactive) {
743
- if (!targetReceivedClick && !this._floatingElement.contains(event.target)) {
744
- this._hideAfterDelay();
745
- }
746
- } else if (!targetReceivedClick) {
1529
+ if (elementContainsEvent(target, event) || descendantAttachmentContainsEvent(this, event)) {
1530
+ return;
1531
+ }
1532
+ if (!this.interactive || !elementContainsEvent(this._floatingElement, event)) {
747
1533
  this._hideAfterDelay();
748
1534
  }
749
1535
  }
750
1536
  _hideOnEscapeKey(event) {
751
- if (event.keyCode === 27) {
1537
+ if ((event.key === 'Escape' || event.keyCode === 27) && shouldHandleEscapeKey(this, event)) {
1538
+ this._restoreFocusOnHide = !this._isTooltip;
752
1539
  return this._hideAfterDelay();
753
1540
  }
754
1541
  }
755
1542
  _hideOnLostFocus(event) {
756
1543
  if (event.relatedTarget === null) {
757
1544
  this._hideAfterDelay();
1545
+ return;
758
1546
  }
759
1547
  const target = this._listenerTarget;
760
1548
  if (!target) {
761
1549
  return;
762
1550
  }
763
- const targetContainsFocus = target.contains(event.relatedTarget);
764
- if (this.interactive) {
765
- if (!targetContainsFocus && !this._floatingElement.contains(event.relatedTarget)) {
766
- this._hideAfterDelay();
767
- }
768
- } else if (!targetContainsFocus) {
1551
+ if (target.contains(event.relatedTarget) || descendantAttachmentContainsNode(this, event.relatedTarget)) {
1552
+ return;
1553
+ }
1554
+ if (!this.interactive || !this._floatingElement?.contains(event.relatedTarget)) {
769
1555
  this._hideAfterDelay();
770
1556
  }
771
1557
  }
@@ -774,16 +1560,11 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
774
1560
  document.removeEventListener(eventType, this._hideListenersOnDocumentByEvent[eventType], this.useCapture);
775
1561
  delete this._hideListenersOnDocumentByEvent[eventType];
776
1562
  });
777
- const showOn = this._showOn;
778
1563
  const target = this._listenerTarget;
779
-
780
- // The target was destroyed, nothing to remove listeners from
781
1564
  if (!target) {
782
1565
  return;
783
1566
  }
784
-
785
- // Switch clicking back to a show event
786
- if (showOn.includes('click')) {
1567
+ if (this._showOn.includes('click')) {
787
1568
  const hideOnClickListener = this._hideListenersOnTargetByEvent.click;
788
1569
  if (hideOnClickListener) {
789
1570
  target.removeEventListener('click', hideOnClickListener, this.useCapture);
@@ -803,21 +1584,11 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
803
1584
  _update() {
804
1585
  this._cleanup?.();
805
1586
  this._cleanup = null;
806
-
807
- // Suspended after _hide until the next _show. Hide writes tracked state that
808
- // re-renders and can re-fire optionsDidUpdate → _update; without this flag
809
- // that path restarts autoUpdate (especially with hideDuration: 0). Do not
810
- // use _isHidden here — it stays true until late in _startShowAnimation,
811
- // after _update must already run.
812
- if (this.isDestroyed || this.isDestroying || this._positioningSuspended || !this._currentTarget || !this._floatingElement) {
813
- return;
814
- }
815
- const isTargetConnected = isElementTarget(this._currentTarget) ? this._currentTarget.isConnected : true;
816
- if (!isTargetConnected || !this._floatingElement.isConnected) {
1587
+ if (this.isDestroyed || this.isDestroying || this._positioningSuspended || !this._currentTarget || !this._floatingElement || !isTargetConnected(this._currentTarget) || !this._floatingElement.isConnected) {
817
1588
  return;
818
1589
  }
819
1590
  if (this.autoUpdate) {
820
- this._cleanup = autoUpdate(this._currentTarget, this._floatingElement, this._updatePosition, typeOf(this.autoUpdate) === 'object' ? this.autoUpdate : undefined);
1591
+ this._cleanup = autoUpdate(this._currentTarget, this._floatingElement, this._updatePosition, typeof this.autoUpdate === 'object' && this.autoUpdate !== null ? this.autoUpdate : undefined);
821
1592
  } else {
822
1593
  this._updatePosition();
823
1594
  }
@@ -826,43 +1597,37 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
826
1597
  if (this.isDestroyed || this.isDestroying || !this._currentTarget || !this._floatingElement) {
827
1598
  return;
828
1599
  }
829
- const isTargetConnected = isElementTarget(this._currentTarget) ? this._currentTarget.isConnected : true;
830
- if (!isTargetConnected || !this._floatingElement.isConnected) {
831
- // Stop lingering observers if a node detached mid-update.
1600
+ if (!isTargetConnected(this._currentTarget) || !this._floatingElement.isConnected) {
832
1601
  this._cleanup?.();
833
1602
  this._cleanup = null;
834
1603
  return;
835
1604
  }
1605
+ const strategy = this.strategy;
836
1606
  const computePositionToken = animationTestWaiter.beginAsync();
837
1607
  computePosition(this._currentTarget, this._floatingElement, {
838
1608
  ...this.floatingUiOptions,
839
1609
  middleware: this._middleware,
840
- placement: this.placement
1610
+ placement: this.placement,
1611
+ strategy
841
1612
  }).then(({
842
1613
  x,
843
1614
  y,
844
1615
  placement,
1616
+ strategy: computedStrategy,
845
1617
  middlewareData
846
1618
  }) => {
847
1619
  animationTestWaiter.endAsync(computePositionToken);
848
1620
  if (this.isDestroyed || this.isDestroying || !this._floatingElement || !this._floatingElement.isConnected) {
849
1621
  return;
850
1622
  }
851
- Object.assign(this._floatingElement.style, {
852
- left: `${x}px`,
853
- top: `${y}px`
1623
+ applyPositionResult(this._floatingElement, this._arrowElement, {
1624
+ x,
1625
+ y,
1626
+ placement,
1627
+ strategy: computedStrategy || strategy,
1628
+ middlewareData,
1629
+ isHidden: this._isHidden
854
1630
  });
855
- if (middlewareData.arrow && this._arrowElement) {
856
- const {
857
- x: arrowX,
858
- y: arrowY
859
- } = middlewareData.arrow;
860
- Object.assign(this._arrowElement.style, {
861
- left: arrowX != null ? `${arrowX}px` : '',
862
- top: arrowY != null ? `${arrowY}px` : ''
863
- });
864
- }
865
- this._floatingElement.setAttribute('x-placement', placement);
866
1631
  }).catch(error => {
867
1632
  animationTestWaiter.endAsync(computePositionToken);
868
1633
  if (!this.isDestroyed && !this.isDestroying) {
@@ -932,12 +1697,12 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
932
1697
  initializer: function () {
933
1698
  return false;
934
1699
  }
935
- }), _descriptor8 = _applyDecoratedDescriptor(_class.prototype, "_transitionDuration", [tracked], {
1700
+ }), _descriptor8 = _applyDecoratedDescriptor(_class.prototype, "_modalContainer", [tracked], {
936
1701
  configurable: true,
937
1702
  enumerable: true,
938
1703
  writable: true,
939
1704
  initializer: function () {
940
- return 0;
1705
+ return null;
941
1706
  }
942
1707
  }), _applyDecoratedDescriptor(_class.prototype, "hide", [action], Object.getOwnPropertyDescriptor(_class.prototype, "hide"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "setReference", [action], Object.getOwnPropertyDescriptor(_class.prototype, "setReference"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "_updatePosition", [action], Object.getOwnPropertyDescriptor(_class.prototype, "_updatePosition"), _class.prototype), _class);
943
1708
  setComponentTemplate(TEMPLATE, BasicAttacher);