ember-attacher 4.2.1 → 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
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,6 +14,213 @@ import { precompileTemplate } from '@ember/template-compilation';
16
14
  import { setComponentTemplate } from '@ember/component';
17
15
  import templateOnly from '@ember/component/template-only';
18
16
 
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
+ }
55
+
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
+
19
224
  /**
20
225
  * DOM and event helpers for attachment boundary and cursor detection.
21
226
  */
@@ -41,53 +246,496 @@ function elementContainsEvent(element, event) {
41
246
  }
42
247
  return Boolean(event?.target && element.contains(event.target));
43
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
+ }
44
264
 
45
265
  /**
46
- * Check if cursor coordinates lie in the geometric gap between the target and floating element.
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.
47
273
  *
48
- * Used for interactive attachments with `isOffset=true` to prevent premature hide
49
- * while the cursor transitions across the gap between target and attachment.
274
+ * Supports both DOM Elements and Floating UI VirtualElements via `getBoundingClientRect()`.
50
275
  *
51
- * @param {MouseEvent} event
276
+ * @param {MouseEvent | { clientX: number, clientY: number }} event
277
+ * @param {{ x: number, y: number } | null | undefined} origin
52
278
  * @param {Element | { getBoundingClientRect: Function } | null | undefined} target
53
- * @param {Element | null | undefined} floatingElement
279
+ * @param {Element | { getBoundingClientRect: Function } | null | undefined} floatingElement
54
280
  * @returns {boolean}
55
281
  */
56
- function isCursorBetween(event, target, floatingElement) {
57
- if (!target || !floatingElement) {
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) {
58
289
  return false;
59
290
  }
60
- const {
61
- clientX,
62
- clientY
63
- } = event;
64
- const attachmentPosition = floatingElement.getBoundingClientRect();
65
- const targetPosition = target.getBoundingClientRect();
66
- const isBetweenLeftAndRight = clientX > Math.min(attachmentPosition.left, targetPosition.left) && clientX < Math.max(attachmentPosition.right, targetPosition.right);
67
- const isBetweenTopAndBottom = clientY > Math.min(attachmentPosition.top, targetPosition.top) && clientY < Math.max(attachmentPosition.bottom, targetPosition.bottom);
68
-
69
- // Check if cursor is between a left-flipped attachment
70
- if (attachmentPosition.right < targetPosition.left && clientX >= attachmentPosition.right && clientX <= targetPosition.left && isBetweenTopAndBottom) {
291
+ const px = event.clientX;
292
+ const py = event.clientY;
293
+ if (isPointInRect(px, py, targetRect) || isPointInRect(px, py, floatingRect)) {
71
294
  return true;
72
295
  }
296
+ const hasRealOrigin = Boolean(origin) && (origin.x !== 0 || origin.y !== 0 || isPointInRect(0, 0, targetRect));
73
297
 
74
- // Check if cursor is between a right-flipped attachment
75
- if (attachmentPosition.left > targetPosition.right && clientX <= attachmentPosition.left && clientX >= targetPosition.right && isBetweenTopAndBottom) {
76
- return true;
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);
77
308
  }
78
309
 
79
- // Check if cursor is between a bottom-flipped attachment
80
- if (attachmentPosition.top > targetPosition.bottom && clientY <= attachmentPosition.top && clientY >= targetPosition.bottom && isBetweenLeftAndRight) {
81
- return true;
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);
82
320
  }
83
321
 
84
- // Check if cursor is between a top-flipped attachment
85
- if (attachmentPosition.bottom < targetPosition.top && clientY >= attachmentPosition.bottom && clientY <= targetPosition.top && isBetweenLeftAndRight) {
86
- return true;
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);
87
344
  }
88
345
  return false;
89
346
  }
90
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
+ }
738
+
91
739
  function consume(positional) {
92
740
  for (let i = 0; i < positional.length; i++) {
93
741
  void positional[i];
@@ -131,129 +779,264 @@ function onUpdate(fn) {
131
779
  });
132
780
  }
133
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
+
134
926
  var MaybeInElement = setComponentTemplate(precompileTemplate("{{~#if @renderInPlace~}}{{yield}}{{~else~}}{{#in-element @destinationElement insertBefore=null}}{{yield}}{{/in-element}}{{~/if~}}", {
135
927
  strictMode: true
136
928
  }), templateOnly());
137
929
 
138
- 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");
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");
139
931
 
140
932
  var _class, _descriptor, _descriptor2, _descriptor3, _descriptor4, _descriptor5, _descriptor6, _descriptor7, _descriptor8;
141
933
  const animationTestWaiter = buildWaiter('basic-attacher');
142
934
  let BasicAttacher = (_class = class BasicAttacher extends Component {
143
- /**
144
- * ================== PUBLIC CONFIG OPTIONS ==================
145
- */
935
+ _opt(key) {
936
+ return this.args[key] ?? this._config[key] ?? DEFAULTS[key];
937
+ }
146
938
  get arrow() {
147
- return this.args.arrow ?? this._config.arrow ?? DEFAULTS.arrow;
939
+ return this._opt('arrow');
148
940
  }
149
941
  get autoUpdate() {
150
- return this.args.autoUpdate ?? this._config.autoUpdate ?? DEFAULTS.autoUpdate;
942
+ return this._opt('autoUpdate');
151
943
  }
152
944
  get animation() {
153
945
  return this.args.animation || this._config.animation || DEFAULTS.animation;
154
946
  }
155
947
  get flip() {
156
- return this.args.flip ?? this._config.flip ?? DEFAULTS.flip;
948
+ return this._opt('flip');
157
949
  }
158
950
  get hideDelay() {
159
- return this.args.hideDelay ?? this._config.hideDelay ?? DEFAULTS.hideDelay;
951
+ return this._opt('hideDelay');
160
952
  }
161
953
  get hideDuration() {
162
- return this.args.hideDuration ?? this._config.hideDuration ?? DEFAULTS.hideDuration;
954
+ return this._opt('hideDuration');
163
955
  }
164
956
  get hideOn() {
165
- if (this.args.hideOn === null) {
166
- return null;
167
- }
168
- return this.args.hideOn ?? this._config.hideOn ?? DEFAULTS.hideOn;
957
+ return this.args.hideOn === null ? null : this._opt('hideOn');
169
958
  }
170
959
  get interactive() {
171
- return this.args.interactive ?? this._config.interactive ?? DEFAULTS.interactive;
960
+ return this._opt('interactive');
172
961
  }
173
962
  get isOffset() {
174
- return this.args.isOffset ?? this._config.isOffset ?? DEFAULTS.isOffset;
963
+ return this._opt('isOffset');
175
964
  }
176
965
  get isShown() {
177
- return this.args.isShown ?? this._config.isShown ?? DEFAULTS.isShown;
966
+ return this._opt('isShown');
178
967
  }
179
968
  get lazyRender() {
180
- return this.args.lazyRender ?? this._config.lazyRender ?? DEFAULTS.lazyRender;
969
+ return this._opt('lazyRender');
181
970
  }
182
- get placement() {
183
- return this.args.placement ?? this._config.placement ?? DEFAULTS.placement;
184
- }
185
- get floatingElementContainer() {
186
- return this.args.floatingElementContainer || this._config.floatingElementContainer || DEFAULTS.floatingElementContainer;
187
- }
188
- get class() {
189
- return this.args.class || this._config.class;
971
+ get overflowPadding() {
972
+ return this._opt('overflowPadding');
190
973
  }
191
- get floatingUiOptions() {
192
- return this.args.floatingUiOptions || this._config.floatingUiOptions || DEFAULTS.floatingUiOptions;
974
+ get placement() {
975
+ return this._opt('placement');
193
976
  }
194
977
  get renderInPlace() {
195
- return this.args.renderInPlace ?? this._config.renderInPlace ?? DEFAULTS.renderInPlace;
978
+ return this._opt('renderInPlace');
196
979
  }
197
980
  get showDelay() {
198
- return this.args.showDelay ?? this._config.showDelay ?? DEFAULTS.showDelay;
981
+ return this._opt('showDelay');
199
982
  }
200
983
  get showDuration() {
201
- return this.args.showDuration ?? this._config.showDuration ?? DEFAULTS.showDuration;
984
+ return this._opt('showDuration');
202
985
  }
203
986
  get showOn() {
204
- if (this.args.showOn === null) {
205
- return null;
206
- }
207
- 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');
208
991
  }
209
992
  get style() {
210
- return this.args.style ?? this._config.style ?? DEFAULTS.style;
993
+ return this._opt('style');
211
994
  }
212
995
  get useCapture() {
213
- 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;
214
1006
  }
215
1007
  get configKey() {
216
1008
  return this.args.configKey || 'popover';
217
1009
  }
1010
+ get _isTooltip() {
1011
+ return this.configKey === 'tooltip' || this.args.ariaRole === 'tooltip';
1012
+ }
218
1013
  get isFillAnimation() {
219
1014
  return this.animation === 'fill';
220
1015
  }
221
1016
  get renderFloatingElement() {
222
- return (this.renderInPlace || this._currentTarget) && (!this.lazyRender || this._mustRender);
1017
+ return Boolean(this.renderInPlace || this._currentTarget);
223
1018
  }
224
1019
  get shouldRenderFloatingElement() {
225
- // Always render the floating element unless lazyRender is true and we haven't been triggered yet
226
1020
  return !this.lazyRender || this._mustRender;
227
1021
  }
228
1022
  get id() {
229
1023
  return this.args.id || `${guidFor(this)}-floating`;
230
1024
  }
231
- get overflowPadding() {
232
- return this.args.overflowPadding ?? this._config.overflowPadding ?? DEFAULTS.overflowPadding;
233
- }
234
-
235
- // The circle element needs a special duration that is slightly faster than the floating element's
236
- // transition, this prevents text from appearing outside the circle as it fills the background
237
- get _circleTransitionDuration() {
238
- return htmlSafe(`transition-duration: ${Math.round(this._transitionDuration / 1.25)}ms`);
239
- }
240
1025
  get _class() {
241
1026
  const showOrHideClass = `ember-attacher-${this._isStartingAnimation ? 'show' : 'hide'}`;
242
1027
  const arrowClass = `ember-attacher-${this.arrow ? 'with' : 'without'}-arrow`;
243
- const baseClass = this.class || '';
244
- const additionalClass = this.args.additionalClass || '';
245
- 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(' ');
246
1029
  }
247
1030
  get _style() {
248
1031
  const style = this.style;
249
- const transitionDuration = this._transitionDuration;
250
- 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), {
251
1036
  id: 'ember-attacher-require-html-safe-style'
252
1037
  });
253
- return htmlSafe(`transition-duration: ${transitionDuration}ms; ${style}`);
1038
+ return style;
254
1039
  }
255
-
256
- // This is memoized so it can be used by both attach-popover and attach-tooltip
257
1040
  get _envConfig() {
258
1041
  return getOwner(this).resolveRegistration('config:environment').emberAttacher || {};
259
1042
  }
@@ -264,62 +1047,72 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
264
1047
  };
265
1048
  }
266
1049
  get _hideOn() {
267
- let hideOn = this.hideOn;
268
- if (hideOn === undefined) {
269
- hideOn = DEFAULTS.hideOn;
270
- }
1050
+ const hideOn = this.hideOn === undefined ? DEFAULTS.hideOn : this.hideOn;
271
1051
  return hideOn === null ? [] : hideOn.split(' ');
272
1052
  }
1053
+ get _showOn() {
1054
+ const showOn = this.showOn === undefined ? DEFAULTS.showOn : this.showOn;
1055
+ return showOn === null ? [] : showOn.split(' ');
1056
+ }
273
1057
  get _middleware() {
274
- // Copy the middleware since we might write to the provided array
275
- const middleware = this.args.middleware ? [...this.args.middleware] : [];
276
- const flipString = this.flip;
277
- if (flipString) {
278
- const flipOptions = {
279
- fallbackPlacements: flipString.split(' ')
280
- };
281
- const flipMiddleware = middleware.find(name => name === 'flip');
282
- if (!flipMiddleware) {
283
- middleware.push(flip(flipOptions));
284
- } else if (!flipMiddleware.fallbackPlacements) {
285
- 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;
286
1092
  }
287
- } else if (this.overflowPadding !== false) {
288
- middleware.push(flip());
1093
+ return false;
289
1094
  }
290
- if (this.overflowPadding !== false && !middleware.find(name => name === 'shift')) {
291
- middleware.push(shift({
292
- limiter: limitShift(),
293
- padding: this.overflowPadding
294
- }));
295
- }
296
- if (this.arrow && this._arrowElement && !middleware.find(name => name === 'arrow')) {
297
- middleware.push(arrow({
298
- element: this._arrowElement
299
- }));
1095
+ const modalDialog = getModalDialogContainer(this._listenerTarget || this.parentElement);
1096
+ if (this._modalContainer !== modalDialog) {
1097
+ this._modalContainer = modalDialog;
1098
+ return true;
300
1099
  }
301
- return middleware;
302
- }
303
- get _floatingElementContainer() {
304
- const maybeContainer = this.floatingElementContainer;
305
- const renderInPlace = this._renderInPlace;
306
- let floatingElementContainer;
307
- if (renderInPlace) {
308
- floatingElementContainer = this.parentElement;
309
- } else if (maybeContainer instanceof Element) {
310
- floatingElementContainer = maybeContainer;
311
- } else if (typeof maybeContainer === 'string') {
312
- const selector = maybeContainer;
313
- const possibleContainers = document.querySelectorAll(selector);
314
- assert(`floatingElementContainer selector "${selector}" found ` + `${possibleContainers.length} possible containers when there should be exactly 1`, possibleContainers.length === 1);
315
- floatingElementContainer = possibleContainers[0];
316
- }
317
- return floatingElementContainer;
1100
+ return false;
318
1101
  }
319
- get _renderInPlace() {
320
- // document is undefined in Fastboot, so we have to render in
321
- // place for the floating element to show up at all.
322
- 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);
323
1116
  }
324
1117
  _setIsVisibleAfterDelay(isVisible, delay) {
325
1118
  if (!this._floatingElement) {
@@ -328,87 +1121,38 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
328
1121
  });
329
1122
  return;
330
1123
  }
331
- const onChange = this.args.onChange;
332
1124
  if (delay) {
333
1125
  this._delayedVisibilityToggle = later(this, () => {
334
1126
  this._animationTimeout = requestAnimationFrame(() => {
335
1127
  animationTestWaiter.endAsync(this._animationTimeout);
336
1128
  if (!this.isDestroyed && !this.isDestroying) {
337
- if (!isVisible) {
338
- this._cleanup?.();
339
- this._cleanup = null;
340
- }
341
- this._floatingElement.style.display = isVisible ? 'block' : 'none';
342
-
343
- // Prevent jank by making the attachment invisible until positioned.
344
- // The visibility style will be toggled by this._startShowAnimation()
345
- this._floatingElement.style.visibility = isVisible ? 'hidden' : '';
346
- if (onChange) {
347
- onChange(isVisible);
348
- }
1129
+ this._applyVisibility(isVisible);
349
1130
  }
350
1131
  });
351
1132
  animationTestWaiter.beginAsync(this._animationTimeout);
352
1133
  }, delay);
353
1134
  } else {
354
- if (!isVisible) {
355
- this._cleanup?.();
356
- this._cleanup = null;
357
- }
358
- this._floatingElement.style.display = isVisible ? 'block' : 'none';
359
- // Prevent jank by making the attachment invisible until positioned.
360
- // The visibility style will be toggled by this._startShowAnimation()
361
- this._floatingElement.style.visibility = isVisible ? 'hidden' : '';
362
- if (onChange) {
363
- onChange(isVisible);
364
- }
365
- }
366
- }
367
- get _showOn() {
368
- let showOn = this.showOn;
369
- if (showOn === undefined) {
370
- showOn = DEFAULTS.showOn;
1135
+ this._applyVisibility(isVisible);
371
1136
  }
372
- return showOn === null ? [] : showOn.split(' ');
373
1137
  }
374
-
375
- // Exposed via the named yield to enable custom hide events
376
1138
  hide() {
377
1139
  this._hide();
378
1140
  }
379
-
380
- /**
381
- * Register an explicit attachment target (Element or Floating UI virtual ref).
382
- * Yielded for composition into other modifiers.
383
- * Pass `null` to clear and fall back to `@explicitTarget` / parent.
384
- *
385
- * Calls `_initializeAttacher` directly so registration that happens during the
386
- * floating element's first render takes effect before the next user event.
387
- *
388
- * @param {Element | { getBoundingClientRect: Function } | null | undefined} target
389
- */
390
1141
  setReference(target) {
391
1142
  cancel(this._setReferenceTimer);
392
-
393
- // Defer: callers often invoke this from another modifier's
394
- // `modify()` (composition). Tracked writes + re-init must not run in
395
- // that tracking frame.
396
1143
  this._setReferenceTimer = schedule('actions', () => {
397
1144
  this._setReferenceTimer = null;
398
1145
  if (this.isDestroyed || this.isDestroying) {
399
1146
  return;
400
1147
  }
401
- const next = target ?? null;
402
- if (this._registeredTarget === next) {
1148
+ const nextTarget = target ?? null;
1149
+ if (this._registeredTarget === nextTarget) {
403
1150
  return;
404
1151
  }
405
- this._registeredTarget = next;
1152
+ this._registeredTarget = nextTarget;
406
1153
  this._initializeAttacher();
407
1154
  });
408
1155
  }
409
-
410
- // Always defined on first render so the modifier binding is present immediately.
411
-
412
1156
  _ensureArgumentsAreValid() {
413
1157
  runInDebug(() => {
414
1158
  if (this.arrow && this.isFillAnimation) {
@@ -425,37 +1169,31 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
425
1169
  }
426
1170
  constructor() {
427
1171
  super(...arguments);
428
-
429
- // The debounced _hide() and _show() are stored here so they can be cancelled when necessary
430
1172
  _defineProperty(this, "MaybeInElement", MaybeInElement);
431
1173
  _initializerDefineProperty(this, "parentNotFound", _descriptor, this);
432
1174
  _initializerDefineProperty(this, "parentElement", _descriptor2, this);
433
1175
  _initializerDefineProperty(this, "_isStartingAnimation", _descriptor3, this);
434
1176
  _initializerDefineProperty(this, "_arrowElement", _descriptor4, this);
435
1177
  _initializerDefineProperty(this, "_currentTarget", _descriptor5, this);
436
- // Yielded `setReference` / `reference` registration. Prefer
437
- // `@explicitTarget` when that arg is set; otherwise this beats parent.
438
1178
  _initializerDefineProperty(this, "_registeredTarget", _descriptor6, this);
1179
+ _initializerDefineProperty(this, "_mustRender", _descriptor7, this);
1180
+ _initializerDefineProperty(this, "_modalContainer", _descriptor8, this);
439
1181
  _defineProperty(this, "_setReferenceTimer", null);
440
- // Untracked copy of the node listeners are on. `_removeEventListeners` must
441
- // not read `_currentTarget` in the same computation that writes it
442
- // (`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`).
443
1184
  _defineProperty(this, "_listenerTarget", null);
444
- // This is set to true when the popover is shown in order to override lazyRender=false
445
- _initializerDefineProperty(this, "_mustRender", _descriptor7, this);
446
- _initializerDefineProperty(this, "_transitionDuration", _descriptor8, this);
447
1185
  _defineProperty(this, "_floatingElement", null);
448
1186
  _defineProperty(this, "parentFinder", onInsert(element => {
449
- if (this.isDestroyed || this.isDestroying) {
450
- return;
1187
+ if (!this.isDestroyed && !this.isDestroying) {
1188
+ this.parentElement = element.parentElement;
1189
+ this._initializeAttacher();
451
1190
  }
452
- this.parentElement = element.parentElement;
453
- this._initializeAttacher();
454
1191
  }));
455
- // Insert + autoUpdate teardown. Must not read tracked state in the modifier
456
- // callback (the scheduled fn is fine); a tracked read would re-run this and
457
- // 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.
458
1194
  _defineProperty(this, "setupFloatingElement", modifier(element => {
1195
+ this._floatingElement = element;
1196
+ registerAttacher(this);
459
1197
  const timer = schedule('actions', () => {
460
1198
  if (this.isDestroyed || this.isDestroying) {
461
1199
  return;
@@ -464,55 +1202,52 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
464
1202
  if (this.renderInPlace) {
465
1203
  this.parentElement = element.parentElement;
466
1204
  this._initializeAttacher();
1205
+ } else {
1206
+ syncParentAttachment(this);
467
1207
  }
468
1208
  });
469
1209
  return () => {
470
1210
  cancel(timer);
1211
+ if (this._floatingElement === element) {
1212
+ this._floatingElement = null;
1213
+ }
471
1214
  this._cleanup?.();
472
1215
  };
473
1216
  }));
474
1217
  _defineProperty(this, "insertArrow", onInsert(element => {
475
- if (this.isDestroyed || this.isDestroying) {
476
- return;
1218
+ if (!this.isDestroyed && !this.isDestroying) {
1219
+ this._arrowElement = element;
477
1220
  }
478
- this._arrowElement = element;
479
1221
  }));
480
1222
  _defineProperty(this, "isShownDidUpdate", onUpdate(() => this._syncIsShown()));
481
1223
  _defineProperty(this, "targetDidUpdate", onUpdate(() => this._initializeAttacher()));
482
1224
  _defineProperty(this, "optionsDidUpdate", onUpdate(() => {
483
1225
  this._ensureArgumentsAreValid();
1226
+ this._syncAria();
484
1227
  this._update();
485
1228
  }));
486
1229
  _defineProperty(this, "reference", modifier(element => {
487
1230
  this.setReference(element);
488
1231
  return () => {
489
- if (this.isDestroyed || this.isDestroying) {
490
- return;
491
- }
492
- if (this._registeredTarget === element) {
1232
+ if (!this.isDestroyed && !this.isDestroying && this._registeredTarget === element) {
493
1233
  this.setReference(null);
494
1234
  }
495
1235
  };
496
1236
  }));
1237
+ registerAttacher(this);
497
1238
  this._delayedVisibilityToggle = null;
498
-
499
- // The final source of truth on whether or not all _hide() or _show() actions have completed
500
1239
  this._isHidden = true;
501
-
502
- // Blocks _update from (re)starting autoUpdate after hide until the next show.
1240
+ this._isHiding = false;
503
1241
  this._positioningSuspended = false;
504
-
505
- // Holds a delayed function to toggle the visibility of the attachment.
506
- // Used to make sure animations can complete before the attachment is hidden.
507
1242
  this._animationTimeout = null;
508
-
509
- // Used to store event listeners so they can be removed when necessary.
510
1243
  this._hideListenersOnDocumentByEvent = {};
511
1244
  this._hideListenersOnTargetByEvent = {};
512
1245
  this._showListenersOnTargetByEvent = {};
513
-
514
- // Hacks to make sure event listeners have the right context and are still removable
515
- 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;
516
1251
  this._hide = this._hide.bind(this);
517
1252
  this._hideAfterDelay = this._hideAfterDelay.bind(this);
518
1253
  this._hideIfMouseOutsideTargetOrAttachment = this._hideIfMouseOutsideTargetOrAttachment.bind(this);
@@ -524,6 +1259,14 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
524
1259
  this._showAfterDelay = this._showAfterDelay.bind(this);
525
1260
  this._lastUseCaptureArgumentValue = this.useCapture;
526
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
+ }
527
1270
  _initializeAttacher() {
528
1271
  this._removeEventListeners();
529
1272
  const target = resolveAttachmentTarget({
@@ -533,16 +1276,18 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
533
1276
  });
534
1277
  this._listenerTarget = getListenerTarget(target);
535
1278
  this._currentTarget = target;
1279
+ this._syncModalContainer();
1280
+ syncParentAttachment(this);
536
1281
  this._addListenersForShowEvents();
537
1282
  if (!this._isHidden || this.isShown) {
1283
+ this._ariaOpen = true;
1284
+ this._syncAria();
538
1285
  this._addListenersForHideEvents();
539
-
540
- // Even if the attachment is already shown, we still want to
541
- // call this._show() to make sure its position is updated for a potentially new target.
542
1286
  this._show();
1287
+ } else {
1288
+ this._ariaOpen = false;
1289
+ this._syncAria();
543
1290
  }
544
-
545
- // Call hook for subclasses to add their own initialization logic
546
1291
  this.args.onInitializeAttacher?.(this._currentTarget, this.id);
547
1292
  }
548
1293
  _addListenersForShowEvents() {
@@ -557,17 +1302,18 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
557
1302
  }
558
1303
  willDestroy() {
559
1304
  super.willDestroy(...arguments);
1305
+ unregisterAttacher(this);
560
1306
  this._cleanup?.();
561
1307
  this._cleanup = null;
562
1308
  cancel(this._setReferenceTimer);
563
1309
  this._cancelAnimation();
564
1310
  cancel(this._delayedVisibilityToggle);
1311
+ this._aria.unbind();
565
1312
  this._removeEventListeners();
566
-
567
- // Call hook for cleanup
568
1313
  this.args.onWillDestroy?.(this._currentTarget, this.id);
569
1314
  }
570
1315
  _removeEventListeners() {
1316
+ this._mouseLeaveOrigin = null;
571
1317
  Object.keys(this._hideListenersOnDocumentByEvent).forEach(eventType => {
572
1318
  document.removeEventListener(eventType, this._hideListenersOnDocumentByEvent[eventType], this.useCapture);
573
1319
  delete this._hideListenersOnDocumentByEvent[eventType];
@@ -586,22 +1332,19 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
586
1332
  const isShown = this.isShown;
587
1333
  if (isShown === true && this._isHidden) {
588
1334
  this._show();
589
-
590
- // Add the hide listeners in the next run loop to avoid conflicts
591
- // where clicking triggers both an isShown toggle and a clickout.
592
1335
  next(this, () => this._addListenersForHideEvents());
593
1336
  } else if (isShown === false && !this._isHidden) {
594
1337
  this._hide();
595
1338
  }
596
1339
  }
597
-
598
- /**
599
- * ================== SHOW ATTACHMENT LOGIC ==================
600
- */
601
-
602
- _showAfterDelay() {
1340
+ _showAfterDelay(event) {
1341
+ if (this._suppressFocusShow && (event?.type === 'focus' || event?.type === 'focusin')) {
1342
+ return;
1343
+ }
603
1344
  cancel(this._delayedVisibilityToggle);
1345
+ this._isHiding = false;
604
1346
  this._mustRender = true;
1347
+ syncParentAttachment(this);
605
1348
  this._addListenersForHideEvents();
606
1349
  const showDelay = parseInt(this.showDelay);
607
1350
  this._delayedVisibilityToggle = debounce(this, this._show, showDelay, !showDelay);
@@ -611,35 +1354,38 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
611
1354
  if (!this._currentTarget) {
612
1355
  return;
613
1356
  }
1357
+ this._restoreFocusOnHide = false;
1358
+ this._isHiding = false;
614
1359
  this._positioningSuspended = false;
615
1360
  this._mustRender = true;
616
-
617
- // 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
+ }
618
1374
  this._setIsVisibleAfterDelay(true, 0);
619
1375
  this._startShowAnimation();
620
1376
  }
621
1377
  _startShowAnimation() {
622
- // Start the show animation on the next cycle so CSS transitions can have an effect.
623
- // If we start the animation immediately, the transition won't work because
624
- // `display: none` => `display: ''` is not transition-able.
625
- // All included animations set opaque: 0, so the attachment is still effectively hidden until
626
- // the final RAF occurs.
627
1378
  this._animationTimeout = requestAnimationFrame(() => {
628
1379
  animationTestWaiter.endAsync(this._animationTimeout);
629
1380
  if (this.isDestroyed || this.isDestroying || !this._currentTarget) {
630
1381
  return;
631
1382
  }
632
1383
  const floatingElement = this._floatingElement;
633
-
634
- // Wait until the element is visible before continuing
635
1384
  if (!floatingElement || floatingElement.style.display === 'none') {
636
1385
  this._startShowAnimation();
637
1386
  return;
638
1387
  }
639
1388
  this._update();
640
-
641
- // Wait for the above positioning to take effect before starting the show animation,
642
- // else the positioning itself will be animated, causing animation glitches.
643
1389
  this._animationTimeout = requestAnimationFrame(() => {
644
1390
  animationTestWaiter.endAsync(this._animationTimeout);
645
1391
  if (this.isDestroyed || this.isDestroying || !this._currentTarget) {
@@ -649,9 +1395,11 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
649
1395
  if (this.isDestroyed || this.isDestroying || !this._currentTarget) {
650
1396
  return;
651
1397
  }
652
- // Make the floating element visible now that it has been positioned
653
- floatingElement.style.visibility = '';
654
- 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`);
655
1403
  this._isStartingAnimation = true;
656
1404
  floatingElement.setAttribute('aria-hidden', 'false');
657
1405
  });
@@ -661,18 +1409,17 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
661
1409
  });
662
1410
  animationTestWaiter.beginAsync(this._animationTimeout);
663
1411
  }
664
-
665
- /**
666
- * ================== HIDE ATTACHMENT LOGIC ==================
667
- */
668
-
669
1412
  _hideAfterDelay() {
670
1413
  cancel(this._delayedVisibilityToggle);
1414
+ this._isHiding = true;
671
1415
  const hideDelay = parseInt(this.hideDelay);
672
1416
  this._delayedVisibilityToggle = debounce(this, this._hide, hideDelay, !hideDelay);
673
1417
  }
674
1418
  _hide() {
1419
+ this._isHiding = true;
675
1420
  this._positioningSuspended = true;
1421
+ this._ariaOpen = false;
1422
+ this._mouseLeaveOrigin = null;
676
1423
  this._cleanup?.();
677
1424
  this._cleanup = null;
678
1425
  if (!this._floatingElement) {
@@ -687,7 +1434,6 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
687
1434
  this._removeListenersForHideEvents();
688
1435
  this._animationTimeout = requestAnimationFrame(() => {
689
1436
  animationTestWaiter.endAsync(this._animationTimeout);
690
- // Avoid a race condition where we attempt to hide after the component is being destroyed.
691
1437
  if (this.isDestroyed || this.isDestroying) {
692
1438
  return;
693
1439
  }
@@ -696,30 +1442,32 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
696
1442
  if (this.isDestroyed || this.isDestroying) {
697
1443
  return;
698
1444
  }
699
- 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`);
700
1455
  this._isStartingAnimation = false;
701
1456
  this._floatingElement.setAttribute('aria-hidden', 'true');
702
- // Wait for any animations to complete before hiding the attachment
1457
+ this._aria.setOpen(false);
703
1458
  this._setIsVisibleAfterDelay(false, hideDuration);
704
1459
  });
705
1460
  this._isHidden = true;
706
1461
  });
707
1462
  animationTestWaiter.beginAsync(this._animationTimeout);
708
1463
  }
709
-
710
- /**
711
- * ================== HIDE LISTENERS ==================
712
- */
713
-
714
1464
  _addListenersForHideEvents() {
715
1465
  const hideOn = this._hideOn;
716
1466
  const target = this._listenerTarget;
717
-
718
- // Target or component was destroyed (virtual refs without contextElement skip listeners)
719
- if (!target || this.isDestroyed || this.isDestroying) {
1467
+ if (!this._currentTarget || this.isDestroyed || this.isDestroying) {
720
1468
  return;
721
1469
  }
722
- if (hideOn.includes('click')) {
1470
+ if (target && hideOn.includes('click')) {
723
1471
  const showOnClickListener = this._showListenersOnTargetByEvent.click;
724
1472
  if (showOnClickListener) {
725
1473
  target.removeEventListener('click', showOnClickListener, this.useCapture);
@@ -737,29 +1485,25 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
737
1485
  this._hideListenersOnDocumentByEvent.keydown = this._hideOnEscapeKey;
738
1486
  document.addEventListener('keydown', this._hideOnEscapeKey, this.useCapture);
739
1487
  }
740
-
741
- // Hides the attachment when the mouse leaves the target
742
- // (or leaves both target and attachment for interactive attachments)
743
- if (hideOn.includes('mouseleave')) {
1488
+ if (target && hideOn.includes('mouseleave')) {
744
1489
  this._hideListenersOnTargetByEvent.mouseleave = this._hideOnMouseLeaveTarget;
745
1490
  target.addEventListener('mouseleave', this._hideOnMouseLeaveTarget, this.useCapture);
746
1491
  }
747
-
748
- // Hides the attachment when focus is lost on the target
749
- ['blur', 'focusout'].forEach(eventType => {
750
- if (hideOn.includes(eventType)) {
751
- this._hideListenersOnTargetByEvent[eventType] = this._hideOnLostFocus;
752
- target.addEventListener(eventType, this._hideOnLostFocus, this.useCapture);
753
- }
754
- });
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
+ }
755
1500
  }
756
- _hideOnMouseLeaveTarget() {
1501
+ _hideOnMouseLeaveTarget(event) {
757
1502
  if (this.interactive) {
758
- // TODO(kjb) Should debounce this, but hiding appears sluggish if you debounce.
759
- // - If you debounce with immediate fire, you get a bug where you can move out of the
760
- // attachment and not trigger the hide because the hide check was debounced
761
- // - Ideally we would debounce with an immediate run, then instead of debouncing, we would
762
- // queue another fire at the end of the debounce period
1503
+ this._mouseLeaveOrigin = event ? {
1504
+ x: event.clientX,
1505
+ y: event.clientY
1506
+ } : null;
763
1507
  if (!this._hideListenersOnDocumentByEvent.mousemove) {
764
1508
  this._hideListenersOnDocumentByEvent.mousemove = this._hideIfMouseOutsideTargetOrAttachment;
765
1509
  document.addEventListener('mousemove', this._hideIfMouseOutsideTargetOrAttachment, this.useCapture);
@@ -768,18 +1512,13 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
768
1512
  this._hideAfterDelay();
769
1513
  }
770
1514
  }
771
- _debouncedHideIfMouseOutsideTargetOrAttachment(event) {
772
- debounce(this, this._hideIfMouseOutsideTargetOrAttachment, event, 10);
773
- }
774
1515
  _hideIfMouseOutsideTargetOrAttachment(event) {
775
1516
  const target = this._listenerTarget;
776
1517
  if (!target) {
777
1518
  return;
778
1519
  }
779
-
780
- // If cursor is not on the attachment or target, hide the floating element
781
- if (!target.contains(event.target) && !(this.isOffset && isCursorBetween(event, this._currentTarget, this._floatingElement)) && this._floatingElement && !this._floatingElement.contains(event.target)) {
782
- // 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;
783
1522
  delete this._hideListenersOnDocumentByEvent.mousemove;
784
1523
  document.removeEventListener('mousemove', this._hideIfMouseOutsideTargetOrAttachment, this.useCapture);
785
1524
  this._hideAfterDelay();
@@ -787,34 +1526,32 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
787
1526
  }
788
1527
  _hideOnClickOut(event) {
789
1528
  const target = this._listenerTarget;
790
- const targetReceivedClick = elementContainsEvent(target, event);
791
- if (this.interactive) {
792
- if (!targetReceivedClick && !elementContainsEvent(this._floatingElement, event)) {
793
- this._hideAfterDelay();
794
- }
795
- } else if (!targetReceivedClick) {
1529
+ if (elementContainsEvent(target, event) || descendantAttachmentContainsEvent(this, event)) {
1530
+ return;
1531
+ }
1532
+ if (!this.interactive || !elementContainsEvent(this._floatingElement, event)) {
796
1533
  this._hideAfterDelay();
797
1534
  }
798
1535
  }
799
1536
  _hideOnEscapeKey(event) {
800
- if (event.keyCode === 27) {
1537
+ if ((event.key === 'Escape' || event.keyCode === 27) && shouldHandleEscapeKey(this, event)) {
1538
+ this._restoreFocusOnHide = !this._isTooltip;
801
1539
  return this._hideAfterDelay();
802
1540
  }
803
1541
  }
804
1542
  _hideOnLostFocus(event) {
805
1543
  if (event.relatedTarget === null) {
806
1544
  this._hideAfterDelay();
1545
+ return;
807
1546
  }
808
1547
  const target = this._listenerTarget;
809
1548
  if (!target) {
810
1549
  return;
811
1550
  }
812
- const targetContainsFocus = target.contains(event.relatedTarget);
813
- if (this.interactive) {
814
- if (!targetContainsFocus && !this._floatingElement.contains(event.relatedTarget)) {
815
- this._hideAfterDelay();
816
- }
817
- } 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)) {
818
1555
  this._hideAfterDelay();
819
1556
  }
820
1557
  }
@@ -823,16 +1560,11 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
823
1560
  document.removeEventListener(eventType, this._hideListenersOnDocumentByEvent[eventType], this.useCapture);
824
1561
  delete this._hideListenersOnDocumentByEvent[eventType];
825
1562
  });
826
- const showOn = this._showOn;
827
1563
  const target = this._listenerTarget;
828
-
829
- // The target was destroyed, nothing to remove listeners from
830
1564
  if (!target) {
831
1565
  return;
832
1566
  }
833
-
834
- // Switch clicking back to a show event
835
- if (showOn.includes('click')) {
1567
+ if (this._showOn.includes('click')) {
836
1568
  const hideOnClickListener = this._hideListenersOnTargetByEvent.click;
837
1569
  if (hideOnClickListener) {
838
1570
  target.removeEventListener('click', hideOnClickListener, this.useCapture);
@@ -852,21 +1584,11 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
852
1584
  _update() {
853
1585
  this._cleanup?.();
854
1586
  this._cleanup = null;
855
-
856
- // Suspended after _hide until the next _show. Hide writes tracked state that
857
- // re-renders and can re-fire optionsDidUpdate → _update; without this flag
858
- // that path restarts autoUpdate (especially with hideDuration: 0). Do not
859
- // use _isHidden here — it stays true until late in _startShowAnimation,
860
- // after _update must already run.
861
- if (this.isDestroyed || this.isDestroying || this._positioningSuspended || !this._currentTarget || !this._floatingElement) {
862
- return;
863
- }
864
- const isTargetConnected = isElementTarget(this._currentTarget) ? this._currentTarget.isConnected : this._currentTarget?.contextElement instanceof Element ? this._currentTarget.contextElement.isConnected : true;
865
- if (!isTargetConnected || !this._floatingElement.isConnected) {
1587
+ if (this.isDestroyed || this.isDestroying || this._positioningSuspended || !this._currentTarget || !this._floatingElement || !isTargetConnected(this._currentTarget) || !this._floatingElement.isConnected) {
866
1588
  return;
867
1589
  }
868
1590
  if (this.autoUpdate) {
869
- 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);
870
1592
  } else {
871
1593
  this._updatePosition();
872
1594
  }
@@ -875,43 +1597,37 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
875
1597
  if (this.isDestroyed || this.isDestroying || !this._currentTarget || !this._floatingElement) {
876
1598
  return;
877
1599
  }
878
- const isTargetConnected = isElementTarget(this._currentTarget) ? this._currentTarget.isConnected : this._currentTarget?.contextElement instanceof Element ? this._currentTarget.contextElement.isConnected : true;
879
- if (!isTargetConnected || !this._floatingElement.isConnected) {
880
- // Stop lingering observers if a node detached mid-update.
1600
+ if (!isTargetConnected(this._currentTarget) || !this._floatingElement.isConnected) {
881
1601
  this._cleanup?.();
882
1602
  this._cleanup = null;
883
1603
  return;
884
1604
  }
1605
+ const strategy = this.strategy;
885
1606
  const computePositionToken = animationTestWaiter.beginAsync();
886
1607
  computePosition(this._currentTarget, this._floatingElement, {
887
1608
  ...this.floatingUiOptions,
888
1609
  middleware: this._middleware,
889
- placement: this.placement
1610
+ placement: this.placement,
1611
+ strategy
890
1612
  }).then(({
891
1613
  x,
892
1614
  y,
893
1615
  placement,
1616
+ strategy: computedStrategy,
894
1617
  middlewareData
895
1618
  }) => {
896
1619
  animationTestWaiter.endAsync(computePositionToken);
897
1620
  if (this.isDestroyed || this.isDestroying || !this._floatingElement || !this._floatingElement.isConnected) {
898
1621
  return;
899
1622
  }
900
- Object.assign(this._floatingElement.style, {
901
- left: `${x}px`,
902
- 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
903
1630
  });
904
- if (middlewareData.arrow && this._arrowElement) {
905
- const {
906
- x: arrowX,
907
- y: arrowY
908
- } = middlewareData.arrow;
909
- Object.assign(this._arrowElement.style, {
910
- left: arrowX != null ? `${arrowX}px` : '',
911
- top: arrowY != null ? `${arrowY}px` : ''
912
- });
913
- }
914
- this._floatingElement.setAttribute('x-placement', placement);
915
1631
  }).catch(error => {
916
1632
  animationTestWaiter.endAsync(computePositionToken);
917
1633
  if (!this.isDestroyed && !this.isDestroying) {
@@ -981,12 +1697,12 @@ let BasicAttacher = (_class = class BasicAttacher extends Component {
981
1697
  initializer: function () {
982
1698
  return false;
983
1699
  }
984
- }), _descriptor8 = _applyDecoratedDescriptor(_class.prototype, "_transitionDuration", [tracked], {
1700
+ }), _descriptor8 = _applyDecoratedDescriptor(_class.prototype, "_modalContainer", [tracked], {
985
1701
  configurable: true,
986
1702
  enumerable: true,
987
1703
  writable: true,
988
1704
  initializer: function () {
989
- return 0;
1705
+ return null;
990
1706
  }
991
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);
992
1708
  setComponentTemplate(TEMPLATE, BasicAttacher);