@yoopta/ui 6.0.0-beta.13 → 6.0.0-beta.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/action-menu-list.js +1 -1
  2. package/dist/action-menu-list.js.map +1 -0
  3. package/dist/block-dnd.js.map +1 -0
  4. package/dist/block-options.js +1 -1
  5. package/dist/block-options.js.map +1 -0
  6. package/dist/chunks/_tslib-8f8de673.js +36 -0
  7. package/dist/chunks/_tslib-8f8de673.js.map +1 -0
  8. package/dist/chunks/floating-ui.react-b048728e.js +5 -0
  9. package/dist/chunks/floating-ui.react-d2303b03.js +4506 -0
  10. package/dist/chunks/floating-ui.react-d2303b03.js.map +1 -0
  11. package/dist/chunks/floating-ui.react-feaab622.js +4506 -0
  12. package/dist/chunks/floating-ui.react-feaab622.js.map +1 -0
  13. package/dist/chunks/highlight-color-picker-027fa4b4.js +93 -0
  14. package/dist/chunks/highlight-color-picker-027fa4b4.js.map +1 -0
  15. package/dist/chunks/highlight-color-picker-a1a292a9.js +1 -0
  16. package/dist/chunks/highlight-color-picker-a979e7a3.js +93 -0
  17. package/dist/chunks/highlight-color-picker-a979e7a3.js.map +1 -0
  18. package/dist/chunks/index-bfd2e7c4.js +6 -0
  19. package/dist/chunks/index-bfd2e7c4.js.map +1 -0
  20. package/dist/chunks/style-inject.es-746bb8ed.js +29 -0
  21. package/dist/chunks/style-inject.es-746bb8ed.js.map +1 -0
  22. package/dist/chunks/throttle-278836f4.js +45 -0
  23. package/dist/chunks/throttle-278836f4.js.map +1 -0
  24. package/dist/element-options.js +1 -1
  25. package/dist/element-options.js.map +1 -0
  26. package/dist/floating-block-actions.js.map +1 -0
  27. package/dist/floating-toolbar/floating-toolbar.d.ts.map +1 -1
  28. package/dist/floating-toolbar.js +1 -1
  29. package/dist/floating-toolbar.js.map +1 -0
  30. package/dist/highlight-color-picker.js +1 -1
  31. package/dist/highlight-color-picker.js.map +1 -0
  32. package/dist/index.js +1 -1
  33. package/dist/index.js.map +1 -0
  34. package/dist/overlay.js +1 -1
  35. package/dist/overlay.js.map +1 -0
  36. package/dist/portal/Portal.d.ts.map +1 -1
  37. package/dist/portal.js +1 -1
  38. package/dist/portal.js.map +1 -0
  39. package/dist/selection-box.js.map +1 -0
  40. package/dist/slash-command-menu.js +1 -1
  41. package/dist/slash-command-menu.js.map +1 -0
  42. package/package.json +2 -2
@@ -0,0 +1,4506 @@
1
+ import * as React from 'react';
2
+ import { useLayoutEffect, useEffect, useRef } from 'react';
3
+ import * as ReactDOM from 'react-dom';
4
+
5
+ function hasWindow() {
6
+ return typeof window !== 'undefined';
7
+ }
8
+ function getNodeName(node) {
9
+ if (isNode(node)) {
10
+ return (node.nodeName || '').toLowerCase();
11
+ }
12
+ // Mocked nodes in testing environments may not be instances of Node. By
13
+ // returning `#document` an infinite loop won't occur.
14
+ // https://github.com/floating-ui/floating-ui/issues/2317
15
+ return '#document';
16
+ }
17
+ function getWindow(node) {
18
+ var _node$ownerDocument;
19
+ return (node == null || (_node$ownerDocument = node.ownerDocument) == null ? void 0 : _node$ownerDocument.defaultView) || window;
20
+ }
21
+ function getDocumentElement(node) {
22
+ var _ref;
23
+ return (_ref = (isNode(node) ? node.ownerDocument : node.document) || window.document) == null ? void 0 : _ref.documentElement;
24
+ }
25
+ function isNode(value) {
26
+ if (!hasWindow()) {
27
+ return false;
28
+ }
29
+ return value instanceof Node || value instanceof getWindow(value).Node;
30
+ }
31
+ function isElement(value) {
32
+ if (!hasWindow()) {
33
+ return false;
34
+ }
35
+ return value instanceof Element || value instanceof getWindow(value).Element;
36
+ }
37
+ function isHTMLElement(value) {
38
+ if (!hasWindow()) {
39
+ return false;
40
+ }
41
+ return value instanceof HTMLElement || value instanceof getWindow(value).HTMLElement;
42
+ }
43
+ function isShadowRoot(value) {
44
+ if (!hasWindow() || typeof ShadowRoot === 'undefined') {
45
+ return false;
46
+ }
47
+ return value instanceof ShadowRoot || value instanceof getWindow(value).ShadowRoot;
48
+ }
49
+ const invalidOverflowDisplayValues = /*#__PURE__*/new Set(['inline', 'contents']);
50
+ function isOverflowElement(element) {
51
+ const {
52
+ overflow,
53
+ overflowX,
54
+ overflowY,
55
+ display
56
+ } = getComputedStyle$1(element);
57
+ return /auto|scroll|overlay|hidden|clip/.test(overflow + overflowY + overflowX) && !invalidOverflowDisplayValues.has(display);
58
+ }
59
+ const tableElements = /*#__PURE__*/new Set(['table', 'td', 'th']);
60
+ function isTableElement(element) {
61
+ return tableElements.has(getNodeName(element));
62
+ }
63
+ const topLayerSelectors = [':popover-open', ':modal'];
64
+ function isTopLayer(element) {
65
+ return topLayerSelectors.some(selector => {
66
+ try {
67
+ return element.matches(selector);
68
+ } catch (_e) {
69
+ return false;
70
+ }
71
+ });
72
+ }
73
+ const transformProperties = ['transform', 'translate', 'scale', 'rotate', 'perspective'];
74
+ const willChangeValues = ['transform', 'translate', 'scale', 'rotate', 'perspective', 'filter'];
75
+ const containValues = ['paint', 'layout', 'strict', 'content'];
76
+ function isContainingBlock(elementOrCss) {
77
+ const webkit = isWebKit();
78
+ const css = isElement(elementOrCss) ? getComputedStyle$1(elementOrCss) : elementOrCss;
79
+
80
+ // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block
81
+ // https://drafts.csswg.org/css-transforms-2/#individual-transforms
82
+ return transformProperties.some(value => css[value] ? css[value] !== 'none' : false) || (css.containerType ? css.containerType !== 'normal' : false) || !webkit && (css.backdropFilter ? css.backdropFilter !== 'none' : false) || !webkit && (css.filter ? css.filter !== 'none' : false) || willChangeValues.some(value => (css.willChange || '').includes(value)) || containValues.some(value => (css.contain || '').includes(value));
83
+ }
84
+ function getContainingBlock(element) {
85
+ let currentNode = getParentNode(element);
86
+ while (isHTMLElement(currentNode) && !isLastTraversableNode(currentNode)) {
87
+ if (isContainingBlock(currentNode)) {
88
+ return currentNode;
89
+ } else if (isTopLayer(currentNode)) {
90
+ return null;
91
+ }
92
+ currentNode = getParentNode(currentNode);
93
+ }
94
+ return null;
95
+ }
96
+ function isWebKit() {
97
+ if (typeof CSS === 'undefined' || !CSS.supports) return false;
98
+ return CSS.supports('-webkit-backdrop-filter', 'none');
99
+ }
100
+ const lastTraversableNodeNames = /*#__PURE__*/new Set(['html', 'body', '#document']);
101
+ function isLastTraversableNode(node) {
102
+ return lastTraversableNodeNames.has(getNodeName(node));
103
+ }
104
+ function getComputedStyle$1(element) {
105
+ return getWindow(element).getComputedStyle(element);
106
+ }
107
+ function getNodeScroll(element) {
108
+ if (isElement(element)) {
109
+ return {
110
+ scrollLeft: element.scrollLeft,
111
+ scrollTop: element.scrollTop
112
+ };
113
+ }
114
+ return {
115
+ scrollLeft: element.scrollX,
116
+ scrollTop: element.scrollY
117
+ };
118
+ }
119
+ function getParentNode(node) {
120
+ if (getNodeName(node) === 'html') {
121
+ return node;
122
+ }
123
+ const result =
124
+ // Step into the shadow DOM of the parent of a slotted node.
125
+ node.assignedSlot ||
126
+ // DOM Element detected.
127
+ node.parentNode ||
128
+ // ShadowRoot detected.
129
+ isShadowRoot(node) && node.host ||
130
+ // Fallback.
131
+ getDocumentElement(node);
132
+ return isShadowRoot(result) ? result.host : result;
133
+ }
134
+ function getNearestOverflowAncestor(node) {
135
+ const parentNode = getParentNode(node);
136
+ if (isLastTraversableNode(parentNode)) {
137
+ return node.ownerDocument ? node.ownerDocument.body : node.body;
138
+ }
139
+ if (isHTMLElement(parentNode) && isOverflowElement(parentNode)) {
140
+ return parentNode;
141
+ }
142
+ return getNearestOverflowAncestor(parentNode);
143
+ }
144
+ function getOverflowAncestors(node, list, traverseIframes) {
145
+ var _node$ownerDocument2;
146
+ if (list === void 0) {
147
+ list = [];
148
+ }
149
+ if (traverseIframes === void 0) {
150
+ traverseIframes = true;
151
+ }
152
+ const scrollableAncestor = getNearestOverflowAncestor(node);
153
+ const isBody = scrollableAncestor === ((_node$ownerDocument2 = node.ownerDocument) == null ? void 0 : _node$ownerDocument2.body);
154
+ const win = getWindow(scrollableAncestor);
155
+ if (isBody) {
156
+ const frameElement = getFrameElement(win);
157
+ return list.concat(win, win.visualViewport || [], isOverflowElement(scrollableAncestor) ? scrollableAncestor : [], frameElement && traverseIframes ? getOverflowAncestors(frameElement) : []);
158
+ }
159
+ return list.concat(scrollableAncestor, getOverflowAncestors(scrollableAncestor, [], traverseIframes));
160
+ }
161
+ function getFrameElement(win) {
162
+ return win.parent && Object.getPrototypeOf(win.parent) ? win.frameElement : null;
163
+ }
164
+
165
+ function activeElement(doc) {
166
+ let activeElement = doc.activeElement;
167
+ while (((_activeElement = activeElement) == null || (_activeElement = _activeElement.shadowRoot) == null ? void 0 : _activeElement.activeElement) != null) {
168
+ var _activeElement;
169
+ activeElement = activeElement.shadowRoot.activeElement;
170
+ }
171
+ return activeElement;
172
+ }
173
+ function contains(parent, child) {
174
+ if (!parent || !child) {
175
+ return false;
176
+ }
177
+ const rootNode = child.getRootNode == null ? void 0 : child.getRootNode();
178
+
179
+ // First, attempt with faster native method
180
+ if (parent.contains(child)) {
181
+ return true;
182
+ }
183
+
184
+ // then fallback to custom implementation with Shadow DOM support
185
+ if (rootNode && isShadowRoot(rootNode)) {
186
+ let next = child;
187
+ while (next) {
188
+ if (parent === next) {
189
+ return true;
190
+ }
191
+ // @ts-ignore
192
+ next = next.parentNode || next.host;
193
+ }
194
+ }
195
+
196
+ // Give up, the result is false
197
+ return false;
198
+ }
199
+ // Avoid Chrome DevTools blue warning.
200
+ function getPlatform() {
201
+ const uaData = navigator.userAgentData;
202
+ if (uaData != null && uaData.platform) {
203
+ return uaData.platform;
204
+ }
205
+ return navigator.platform;
206
+ }
207
+ function getUserAgent() {
208
+ const uaData = navigator.userAgentData;
209
+ if (uaData && Array.isArray(uaData.brands)) {
210
+ return uaData.brands.map(_ref => {
211
+ let {
212
+ brand,
213
+ version
214
+ } = _ref;
215
+ return brand + "/" + version;
216
+ }).join(' ');
217
+ }
218
+ return navigator.userAgent;
219
+ }
220
+
221
+ // License: https://github.com/adobe/react-spectrum/blob/b35d5c02fe900badccd0cf1a8f23bb593419f238/packages/@react-aria/utils/src/isVirtualEvent.ts
222
+ function isVirtualClick(event) {
223
+ // FIXME: Firefox is now emitting a deprecation warning for `mozInputSource`.
224
+ // Try to find a workaround for this. `react-aria` source still has the check.
225
+ if (event.mozInputSource === 0 && event.isTrusted) {
226
+ return true;
227
+ }
228
+ if (isAndroid() && event.pointerType) {
229
+ return event.type === 'click' && event.buttons === 1;
230
+ }
231
+ return event.detail === 0 && !event.pointerType;
232
+ }
233
+ function isVirtualPointerEvent(event) {
234
+ if (isJSDOM()) return false;
235
+ return !isAndroid() && event.width === 0 && event.height === 0 || isAndroid() && event.width === 1 && event.height === 1 && event.pressure === 0 && event.detail === 0 && event.pointerType === 'mouse' ||
236
+ // iOS VoiceOver returns 0.333• for width/height.
237
+ event.width < 1 && event.height < 1 && event.pressure === 0 && event.detail === 0 && event.pointerType === 'touch';
238
+ }
239
+ function isSafari() {
240
+ // Chrome DevTools does not complain about navigator.vendor
241
+ return /apple/i.test(navigator.vendor);
242
+ }
243
+ function isAndroid() {
244
+ const re = /android/i;
245
+ return re.test(getPlatform()) || re.test(getUserAgent());
246
+ }
247
+ function isJSDOM() {
248
+ return getUserAgent().includes('jsdom/');
249
+ }
250
+ function isReactEvent(event) {
251
+ return 'nativeEvent' in event;
252
+ }
253
+ function isRootElement(element) {
254
+ return element.matches('html,body');
255
+ }
256
+ function getDocument(node) {
257
+ return (node == null ? void 0 : node.ownerDocument) || document;
258
+ }
259
+ function isEventTargetWithin(event, node) {
260
+ if (node == null) {
261
+ return false;
262
+ }
263
+ if ('composedPath' in event) {
264
+ return event.composedPath().includes(node);
265
+ }
266
+
267
+ // TS thinks `event` is of type never as it assumes all browsers support composedPath, but browsers without shadow dom don't
268
+ const e = event;
269
+ return e.target != null && node.contains(e.target);
270
+ }
271
+ function getTarget(event) {
272
+ if ('composedPath' in event) {
273
+ return event.composedPath()[0];
274
+ }
275
+
276
+ // TS thinks `event` is of type never as it assumes all browsers support
277
+ // `composedPath()`, but browsers without shadow DOM don't.
278
+ return event.target;
279
+ }
280
+ const TYPEABLE_SELECTOR = "input:not([type='hidden']):not([disabled])," + "[contenteditable]:not([contenteditable='false']),textarea:not([disabled])";
281
+ function isTypeableElement(element) {
282
+ return isHTMLElement(element) && element.matches(TYPEABLE_SELECTOR);
283
+ }
284
+ function stopEvent(event) {
285
+ event.preventDefault();
286
+ event.stopPropagation();
287
+ }
288
+ function isTypeableCombobox(element) {
289
+ if (!element) return false;
290
+ return element.getAttribute('role') === 'combobox' && isTypeableElement(element);
291
+ }
292
+
293
+ /**
294
+ * Custom positioning reference element.
295
+ * @see https://floating-ui.com/docs/virtual-elements
296
+ */
297
+
298
+ const min = Math.min;
299
+ const max = Math.max;
300
+ const round = Math.round;
301
+ const floor = Math.floor;
302
+ const createCoords = v => ({
303
+ x: v,
304
+ y: v
305
+ });
306
+ const oppositeSideMap = {
307
+ left: 'right',
308
+ right: 'left',
309
+ bottom: 'top',
310
+ top: 'bottom'
311
+ };
312
+ const oppositeAlignmentMap = {
313
+ start: 'end',
314
+ end: 'start'
315
+ };
316
+ function clamp(start, value, end) {
317
+ return max(start, min(value, end));
318
+ }
319
+ function evaluate(value, param) {
320
+ return typeof value === 'function' ? value(param) : value;
321
+ }
322
+ function getSide(placement) {
323
+ return placement.split('-')[0];
324
+ }
325
+ function getAlignment(placement) {
326
+ return placement.split('-')[1];
327
+ }
328
+ function getOppositeAxis(axis) {
329
+ return axis === 'x' ? 'y' : 'x';
330
+ }
331
+ function getAxisLength(axis) {
332
+ return axis === 'y' ? 'height' : 'width';
333
+ }
334
+ const yAxisSides = /*#__PURE__*/new Set(['top', 'bottom']);
335
+ function getSideAxis(placement) {
336
+ return yAxisSides.has(getSide(placement)) ? 'y' : 'x';
337
+ }
338
+ function getAlignmentAxis(placement) {
339
+ return getOppositeAxis(getSideAxis(placement));
340
+ }
341
+ function getAlignmentSides(placement, rects, rtl) {
342
+ if (rtl === void 0) {
343
+ rtl = false;
344
+ }
345
+ const alignment = getAlignment(placement);
346
+ const alignmentAxis = getAlignmentAxis(placement);
347
+ const length = getAxisLength(alignmentAxis);
348
+ let mainAlignmentSide = alignmentAxis === 'x' ? alignment === (rtl ? 'end' : 'start') ? 'right' : 'left' : alignment === 'start' ? 'bottom' : 'top';
349
+ if (rects.reference[length] > rects.floating[length]) {
350
+ mainAlignmentSide = getOppositePlacement(mainAlignmentSide);
351
+ }
352
+ return [mainAlignmentSide, getOppositePlacement(mainAlignmentSide)];
353
+ }
354
+ function getExpandedPlacements(placement) {
355
+ const oppositePlacement = getOppositePlacement(placement);
356
+ return [getOppositeAlignmentPlacement(placement), oppositePlacement, getOppositeAlignmentPlacement(oppositePlacement)];
357
+ }
358
+ function getOppositeAlignmentPlacement(placement) {
359
+ return placement.replace(/start|end/g, alignment => oppositeAlignmentMap[alignment]);
360
+ }
361
+ const lrPlacement = ['left', 'right'];
362
+ const rlPlacement = ['right', 'left'];
363
+ const tbPlacement = ['top', 'bottom'];
364
+ const btPlacement = ['bottom', 'top'];
365
+ function getSideList(side, isStart, rtl) {
366
+ switch (side) {
367
+ case 'top':
368
+ case 'bottom':
369
+ if (rtl) return isStart ? rlPlacement : lrPlacement;
370
+ return isStart ? lrPlacement : rlPlacement;
371
+ case 'left':
372
+ case 'right':
373
+ return isStart ? tbPlacement : btPlacement;
374
+ default:
375
+ return [];
376
+ }
377
+ }
378
+ function getOppositeAxisPlacements(placement, flipAlignment, direction, rtl) {
379
+ const alignment = getAlignment(placement);
380
+ let list = getSideList(getSide(placement), direction === 'start', rtl);
381
+ if (alignment) {
382
+ list = list.map(side => side + "-" + alignment);
383
+ if (flipAlignment) {
384
+ list = list.concat(list.map(getOppositeAlignmentPlacement));
385
+ }
386
+ }
387
+ return list;
388
+ }
389
+ function getOppositePlacement(placement) {
390
+ return placement.replace(/left|right|bottom|top/g, side => oppositeSideMap[side]);
391
+ }
392
+ function expandPaddingObject(padding) {
393
+ return {
394
+ top: 0,
395
+ right: 0,
396
+ bottom: 0,
397
+ left: 0,
398
+ ...padding
399
+ };
400
+ }
401
+ function getPaddingObject(padding) {
402
+ return typeof padding !== 'number' ? expandPaddingObject(padding) : {
403
+ top: padding,
404
+ right: padding,
405
+ bottom: padding,
406
+ left: padding
407
+ };
408
+ }
409
+ function rectToClientRect(rect) {
410
+ const {
411
+ x,
412
+ y,
413
+ width,
414
+ height
415
+ } = rect;
416
+ return {
417
+ width,
418
+ height,
419
+ top: y,
420
+ left: x,
421
+ right: x + width,
422
+ bottom: y + height,
423
+ x,
424
+ y
425
+ };
426
+ }
427
+
428
+ /*!
429
+ * tabbable 6.4.0
430
+ * @license MIT, https://github.com/focus-trap/tabbable/blob/master/LICENSE
431
+ */
432
+ // NOTE: separate `:not()` selectors has broader browser support than the newer
433
+ // `:not([inert], [inert] *)` (Feb 2023)
434
+ var candidateSelectors = ['input:not([inert]):not([inert] *)', 'select:not([inert]):not([inert] *)', 'textarea:not([inert]):not([inert] *)', 'a[href]:not([inert]):not([inert] *)', 'button:not([inert]):not([inert] *)', '[tabindex]:not(slot):not([inert]):not([inert] *)', 'audio[controls]:not([inert]):not([inert] *)', 'video[controls]:not([inert]):not([inert] *)', '[contenteditable]:not([contenteditable="false"]):not([inert]):not([inert] *)', 'details>summary:first-of-type:not([inert]):not([inert] *)', 'details:not([inert]):not([inert] *)'];
435
+ var candidateSelector = /* #__PURE__ */candidateSelectors.join(',');
436
+ var NoElement = typeof Element === 'undefined';
437
+ var matches = NoElement ? function () {} : Element.prototype.matches || Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;
438
+ var getRootNode = !NoElement && Element.prototype.getRootNode ? function (element) {
439
+ var _element$getRootNode;
440
+ return element === null || element === void 0 ? void 0 : (_element$getRootNode = element.getRootNode) === null || _element$getRootNode === void 0 ? void 0 : _element$getRootNode.call(element);
441
+ } : function (element) {
442
+ return element === null || element === void 0 ? void 0 : element.ownerDocument;
443
+ };
444
+
445
+ /**
446
+ * Determines if a node is inert or in an inert ancestor.
447
+ * @param {Node} [node]
448
+ * @param {boolean} [lookUp] If true and `node` is not inert, looks up at ancestors to
449
+ * see if any of them are inert. If false, only `node` itself is considered.
450
+ * @returns {boolean} True if inert itself or by way of being in an inert ancestor.
451
+ * False if `node` is falsy.
452
+ */
453
+ var _isInert = function isInert(node, lookUp) {
454
+ var _node$getAttribute;
455
+ if (lookUp === void 0) {
456
+ lookUp = true;
457
+ }
458
+ // CAREFUL: JSDom does not support inert at all, so we can't use the `HTMLElement.inert`
459
+ // JS API property; we have to check the attribute, which can either be empty or 'true';
460
+ // if it's `null` (not specified) or 'false', it's an active element
461
+ var inertAtt = node === null || node === void 0 ? void 0 : (_node$getAttribute = node.getAttribute) === null || _node$getAttribute === void 0 ? void 0 : _node$getAttribute.call(node, 'inert');
462
+ var inert = inertAtt === '' || inertAtt === 'true';
463
+
464
+ // NOTE: this could also be handled with `node.matches('[inert], :is([inert] *)')`
465
+ // if it weren't for `matches()` not being a function on shadow roots; the following
466
+ // code works for any kind of node
467
+ var result = inert || lookUp && node && (
468
+ // closest does not exist on shadow roots, so we fall back to a manual
469
+ // lookup upward, in case it is not defined.
470
+ typeof node.closest === 'function' ? node.closest('[inert]') : _isInert(node.parentNode));
471
+ return result;
472
+ };
473
+
474
+ /**
475
+ * Determines if a node's content is editable.
476
+ * @param {Element} [node]
477
+ * @returns True if it's content-editable; false if it's not or `node` is falsy.
478
+ */
479
+ var isContentEditable = function isContentEditable(node) {
480
+ var _node$getAttribute2;
481
+ // CAREFUL: JSDom does not support the `HTMLElement.isContentEditable` API so we have
482
+ // to use the attribute directly to check for this, which can either be empty or 'true';
483
+ // if it's `null` (not specified) or 'false', it's a non-editable element
484
+ var attValue = node === null || node === void 0 ? void 0 : (_node$getAttribute2 = node.getAttribute) === null || _node$getAttribute2 === void 0 ? void 0 : _node$getAttribute2.call(node, 'contenteditable');
485
+ return attValue === '' || attValue === 'true';
486
+ };
487
+
488
+ /**
489
+ * @param {Element} el container to check in
490
+ * @param {boolean} includeContainer add container to check
491
+ * @param {(node: Element) => boolean} filter filter candidates
492
+ * @returns {Element[]}
493
+ */
494
+ var getCandidates = function getCandidates(el, includeContainer, filter) {
495
+ // even if `includeContainer=false`, we still have to check it for inertness because
496
+ // if it's inert (either by itself or via its parent), then all its children are inert
497
+ if (_isInert(el)) {
498
+ return [];
499
+ }
500
+ var candidates = Array.prototype.slice.apply(el.querySelectorAll(candidateSelector));
501
+ if (includeContainer && matches.call(el, candidateSelector)) {
502
+ candidates.unshift(el);
503
+ }
504
+ candidates = candidates.filter(filter);
505
+ return candidates;
506
+ };
507
+
508
+ /**
509
+ * @callback GetShadowRoot
510
+ * @param {Element} element to check for shadow root
511
+ * @returns {ShadowRoot|boolean} ShadowRoot if available or boolean indicating if a shadowRoot is attached but not available.
512
+ */
513
+
514
+ /**
515
+ * @callback ShadowRootFilter
516
+ * @param {Element} shadowHostNode the element which contains shadow content
517
+ * @returns {boolean} true if a shadow root could potentially contain valid candidates.
518
+ */
519
+
520
+ /**
521
+ * @typedef {Object} CandidateScope
522
+ * @property {Element} scopeParent contains inner candidates
523
+ * @property {Element[]} candidates list of candidates found in the scope parent
524
+ */
525
+
526
+ /**
527
+ * @typedef {Object} IterativeOptions
528
+ * @property {GetShadowRoot|boolean} getShadowRoot true if shadow support is enabled; falsy if not;
529
+ * if a function, implies shadow support is enabled and either returns the shadow root of an element
530
+ * or a boolean stating if it has an undisclosed shadow root
531
+ * @property {(node: Element) => boolean} filter filter candidates
532
+ * @property {boolean} flatten if true then result will flatten any CandidateScope into the returned list
533
+ * @property {ShadowRootFilter} shadowRootFilter filter shadow roots;
534
+ */
535
+
536
+ /**
537
+ * @param {Element[]} elements list of element containers to match candidates from
538
+ * @param {boolean} includeContainer add container list to check
539
+ * @param {IterativeOptions} options
540
+ * @returns {Array.<Element|CandidateScope>}
541
+ */
542
+ var _getCandidatesIteratively = function getCandidatesIteratively(elements, includeContainer, options) {
543
+ var candidates = [];
544
+ var elementsToCheck = Array.from(elements);
545
+ while (elementsToCheck.length) {
546
+ var element = elementsToCheck.shift();
547
+ if (_isInert(element, false)) {
548
+ // no need to look up since we're drilling down
549
+ // anything inside this container will also be inert
550
+ continue;
551
+ }
552
+ if (element.tagName === 'SLOT') {
553
+ // add shadow dom slot scope (slot itself cannot be focusable)
554
+ var assigned = element.assignedElements();
555
+ var content = assigned.length ? assigned : element.children;
556
+ var nestedCandidates = _getCandidatesIteratively(content, true, options);
557
+ if (options.flatten) {
558
+ candidates.push.apply(candidates, nestedCandidates);
559
+ } else {
560
+ candidates.push({
561
+ scopeParent: element,
562
+ candidates: nestedCandidates
563
+ });
564
+ }
565
+ } else {
566
+ // check candidate element
567
+ var validCandidate = matches.call(element, candidateSelector);
568
+ if (validCandidate && options.filter(element) && (includeContainer || !elements.includes(element))) {
569
+ candidates.push(element);
570
+ }
571
+
572
+ // iterate over shadow content if possible
573
+ var shadowRoot = element.shadowRoot ||
574
+ // check for an undisclosed shadow
575
+ typeof options.getShadowRoot === 'function' && options.getShadowRoot(element);
576
+
577
+ // no inert look up because we're already drilling down and checking for inertness
578
+ // on the way down, so all containers to this root node should have already been
579
+ // vetted as non-inert
580
+ var validShadowRoot = !_isInert(shadowRoot, false) && (!options.shadowRootFilter || options.shadowRootFilter(element));
581
+ if (shadowRoot && validShadowRoot) {
582
+ // add shadow dom scope IIF a shadow root node was given; otherwise, an undisclosed
583
+ // shadow exists, so look at light dom children as fallback BUT create a scope for any
584
+ // child candidates found because they're likely slotted elements (elements that are
585
+ // children of the web component element (which has the shadow), in the light dom, but
586
+ // slotted somewhere _inside_ the undisclosed shadow) -- the scope is created below,
587
+ // _after_ we return from this recursive call
588
+ var _nestedCandidates = _getCandidatesIteratively(shadowRoot === true ? element.children : shadowRoot.children, true, options);
589
+ if (options.flatten) {
590
+ candidates.push.apply(candidates, _nestedCandidates);
591
+ } else {
592
+ candidates.push({
593
+ scopeParent: element,
594
+ candidates: _nestedCandidates
595
+ });
596
+ }
597
+ } else {
598
+ // there's not shadow so just dig into the element's (light dom) children
599
+ // __without__ giving the element special scope treatment
600
+ elementsToCheck.unshift.apply(elementsToCheck, element.children);
601
+ }
602
+ }
603
+ }
604
+ return candidates;
605
+ };
606
+
607
+ /**
608
+ * @private
609
+ * Determines if the node has an explicitly specified `tabindex` attribute.
610
+ * @param {HTMLElement} node
611
+ * @returns {boolean} True if so; false if not.
612
+ */
613
+ var hasTabIndex = function hasTabIndex(node) {
614
+ return !isNaN(parseInt(node.getAttribute('tabindex'), 10));
615
+ };
616
+
617
+ /**
618
+ * Determine the tab index of a given node.
619
+ * @param {HTMLElement} node
620
+ * @returns {number} Tab order (negative, 0, or positive number).
621
+ * @throws {Error} If `node` is falsy.
622
+ */
623
+ var getTabIndex = function getTabIndex(node) {
624
+ if (!node) {
625
+ throw new Error('No node provided');
626
+ }
627
+ if (node.tabIndex < 0) {
628
+ // in Chrome, <details/>, <audio controls/> and <video controls/> elements get a default
629
+ // `tabIndex` of -1 when the 'tabindex' attribute isn't specified in the DOM,
630
+ // yet they are still part of the regular tab order; in FF, they get a default
631
+ // `tabIndex` of 0; since Chrome still puts those elements in the regular tab
632
+ // order, consider their tab index to be 0.
633
+ // Also browsers do not return `tabIndex` correctly for contentEditable nodes;
634
+ // so if they don't have a tabindex attribute specifically set, assume it's 0.
635
+ if ((/^(AUDIO|VIDEO|DETAILS)$/.test(node.tagName) || isContentEditable(node)) && !hasTabIndex(node)) {
636
+ return 0;
637
+ }
638
+ }
639
+ return node.tabIndex;
640
+ };
641
+
642
+ /**
643
+ * Determine the tab index of a given node __for sort order purposes__.
644
+ * @param {HTMLElement} node
645
+ * @param {boolean} [isScope] True for a custom element with shadow root or slot that, by default,
646
+ * has tabIndex -1, but needs to be sorted by document order in order for its content to be
647
+ * inserted into the correct sort position.
648
+ * @returns {number} Tab order (negative, 0, or positive number).
649
+ */
650
+ var getSortOrderTabIndex = function getSortOrderTabIndex(node, isScope) {
651
+ var tabIndex = getTabIndex(node);
652
+ if (tabIndex < 0 && isScope && !hasTabIndex(node)) {
653
+ return 0;
654
+ }
655
+ return tabIndex;
656
+ };
657
+ var sortOrderedTabbables = function sortOrderedTabbables(a, b) {
658
+ return a.tabIndex === b.tabIndex ? a.documentOrder - b.documentOrder : a.tabIndex - b.tabIndex;
659
+ };
660
+ var isInput = function isInput(node) {
661
+ return node.tagName === 'INPUT';
662
+ };
663
+ var isHiddenInput = function isHiddenInput(node) {
664
+ return isInput(node) && node.type === 'hidden';
665
+ };
666
+ var isDetailsWithSummary = function isDetailsWithSummary(node) {
667
+ var r = node.tagName === 'DETAILS' && Array.prototype.slice.apply(node.children).some(function (child) {
668
+ return child.tagName === 'SUMMARY';
669
+ });
670
+ return r;
671
+ };
672
+ var getCheckedRadio = function getCheckedRadio(nodes, form) {
673
+ for (var i = 0; i < nodes.length; i++) {
674
+ if (nodes[i].checked && nodes[i].form === form) {
675
+ return nodes[i];
676
+ }
677
+ }
678
+ };
679
+ var isTabbableRadio = function isTabbableRadio(node) {
680
+ if (!node.name) {
681
+ return true;
682
+ }
683
+ var radioScope = node.form || getRootNode(node);
684
+ var queryRadios = function queryRadios(name) {
685
+ return radioScope.querySelectorAll('input[type="radio"][name="' + name + '"]');
686
+ };
687
+ var radioSet;
688
+ if (typeof window !== 'undefined' && typeof window.CSS !== 'undefined' && typeof window.CSS.escape === 'function') {
689
+ radioSet = queryRadios(window.CSS.escape(node.name));
690
+ } else {
691
+ try {
692
+ radioSet = queryRadios(node.name);
693
+ } catch (err) {
694
+ // eslint-disable-next-line no-console
695
+ console.error('Looks like you have a radio button with a name attribute containing invalid CSS selector characters and need the CSS.escape polyfill: %s', err.message);
696
+ return false;
697
+ }
698
+ }
699
+ var checked = getCheckedRadio(radioSet, node.form);
700
+ return !checked || checked === node;
701
+ };
702
+ var isRadio = function isRadio(node) {
703
+ return isInput(node) && node.type === 'radio';
704
+ };
705
+ var isNonTabbableRadio = function isNonTabbableRadio(node) {
706
+ return isRadio(node) && !isTabbableRadio(node);
707
+ };
708
+
709
+ // determines if a node is ultimately attached to the window's document
710
+ var isNodeAttached = function isNodeAttached(node) {
711
+ var _nodeRoot;
712
+ // The root node is the shadow root if the node is in a shadow DOM; some document otherwise
713
+ // (but NOT _the_ document; see second 'If' comment below for more).
714
+ // If rootNode is shadow root, it'll have a host, which is the element to which the shadow
715
+ // is attached, and the one we need to check if it's in the document or not (because the
716
+ // shadow, and all nodes it contains, is never considered in the document since shadows
717
+ // behave like self-contained DOMs; but if the shadow's HOST, which is part of the document,
718
+ // is hidden, or is not in the document itself but is detached, it will affect the shadow's
719
+ // visibility, including all the nodes it contains). The host could be any normal node,
720
+ // or a custom element (i.e. web component). Either way, that's the one that is considered
721
+ // part of the document, not the shadow root, nor any of its children (i.e. the node being
722
+ // tested).
723
+ // To further complicate things, we have to look all the way up until we find a shadow HOST
724
+ // that is attached (or find none) because the node might be in nested shadows...
725
+ // If rootNode is not a shadow root, it won't have a host, and so rootNode should be the
726
+ // document (per the docs) and while it's a Document-type object, that document does not
727
+ // appear to be the same as the node's `ownerDocument` for some reason, so it's safer
728
+ // to ignore the rootNode at this point, and use `node.ownerDocument`. Otherwise,
729
+ // using `rootNode.contains(node)` will _always_ be true we'll get false-positives when
730
+ // node is actually detached.
731
+ // NOTE: If `nodeRootHost` or `node` happens to be the `document` itself (which is possible
732
+ // if a tabbable/focusable node was quickly added to the DOM, focused, and then removed
733
+ // from the DOM as in https://github.com/focus-trap/focus-trap-react/issues/905), then
734
+ // `ownerDocument` will be `null`, hence the optional chaining on it.
735
+ var nodeRoot = node && getRootNode(node);
736
+ var nodeRootHost = (_nodeRoot = nodeRoot) === null || _nodeRoot === void 0 ? void 0 : _nodeRoot.host;
737
+
738
+ // in some cases, a detached node will return itself as the root instead of a document or
739
+ // shadow root object, in which case, we shouldn't try to look further up the host chain
740
+ var attached = false;
741
+ if (nodeRoot && nodeRoot !== node) {
742
+ var _nodeRootHost, _nodeRootHost$ownerDo, _node$ownerDocument;
743
+ attached = !!((_nodeRootHost = nodeRootHost) !== null && _nodeRootHost !== void 0 && (_nodeRootHost$ownerDo = _nodeRootHost.ownerDocument) !== null && _nodeRootHost$ownerDo !== void 0 && _nodeRootHost$ownerDo.contains(nodeRootHost) || node !== null && node !== void 0 && (_node$ownerDocument = node.ownerDocument) !== null && _node$ownerDocument !== void 0 && _node$ownerDocument.contains(node));
744
+ while (!attached && nodeRootHost) {
745
+ var _nodeRoot2, _nodeRootHost2, _nodeRootHost2$ownerD;
746
+ // since it's not attached and we have a root host, the node MUST be in a nested shadow DOM,
747
+ // which means we need to get the host's host and check if that parent host is contained
748
+ // in (i.e. attached to) the document
749
+ nodeRoot = getRootNode(nodeRootHost);
750
+ nodeRootHost = (_nodeRoot2 = nodeRoot) === null || _nodeRoot2 === void 0 ? void 0 : _nodeRoot2.host;
751
+ attached = !!((_nodeRootHost2 = nodeRootHost) !== null && _nodeRootHost2 !== void 0 && (_nodeRootHost2$ownerD = _nodeRootHost2.ownerDocument) !== null && _nodeRootHost2$ownerD !== void 0 && _nodeRootHost2$ownerD.contains(nodeRootHost));
752
+ }
753
+ }
754
+ return attached;
755
+ };
756
+ var isZeroArea = function isZeroArea(node) {
757
+ var _node$getBoundingClie = node.getBoundingClientRect(),
758
+ width = _node$getBoundingClie.width,
759
+ height = _node$getBoundingClie.height;
760
+ return width === 0 && height === 0;
761
+ };
762
+ var isHidden = function isHidden(node, _ref) {
763
+ var displayCheck = _ref.displayCheck,
764
+ getShadowRoot = _ref.getShadowRoot;
765
+ if (displayCheck === 'full-native') {
766
+ if ('checkVisibility' in node) {
767
+ // Chrome >= 105, Edge >= 105, Firefox >= 106, Safari >= 17.4
768
+ // @see https://developer.mozilla.org/en-US/docs/Web/API/Element/checkVisibility#browser_compatibility
769
+ var visible = node.checkVisibility({
770
+ // Checking opacity might be desirable for some use cases, but natively,
771
+ // opacity zero elements _are_ focusable and tabbable.
772
+ checkOpacity: false,
773
+ opacityProperty: false,
774
+ contentVisibilityAuto: true,
775
+ visibilityProperty: true,
776
+ // This is an alias for `visibilityProperty`. Contemporary browsers
777
+ // support both. However, this alias has wider browser support (Chrome
778
+ // >= 105 and Firefox >= 106, vs. Chrome >= 121 and Firefox >= 122), so
779
+ // we include it anyway.
780
+ checkVisibilityCSS: true
781
+ });
782
+ return !visible;
783
+ }
784
+ // Fall through to manual visibility checks
785
+ }
786
+
787
+ // NOTE: visibility will be `undefined` if node is detached from the document
788
+ // (see notes about this further down), which means we will consider it visible
789
+ // (this is legacy behavior from a very long way back)
790
+ // NOTE: we check this regardless of `displayCheck="none"` because this is a
791
+ // _visibility_ check, not a _display_ check
792
+ if (getComputedStyle(node).visibility === 'hidden') {
793
+ return true;
794
+ }
795
+ var isDirectSummary = matches.call(node, 'details>summary:first-of-type');
796
+ var nodeUnderDetails = isDirectSummary ? node.parentElement : node;
797
+ if (matches.call(nodeUnderDetails, 'details:not([open]) *')) {
798
+ return true;
799
+ }
800
+ if (!displayCheck || displayCheck === 'full' ||
801
+ // full-native can run this branch when it falls through in case
802
+ // Element#checkVisibility is unsupported
803
+ displayCheck === 'full-native' || displayCheck === 'legacy-full') {
804
+ if (typeof getShadowRoot === 'function') {
805
+ // figure out if we should consider the node to be in an undisclosed shadow and use the
806
+ // 'non-zero-area' fallback
807
+ var originalNode = node;
808
+ while (node) {
809
+ var parentElement = node.parentElement;
810
+ var rootNode = getRootNode(node);
811
+ if (parentElement && !parentElement.shadowRoot && getShadowRoot(parentElement) === true // check if there's an undisclosed shadow
812
+ ) {
813
+ // node has an undisclosed shadow which means we can only treat it as a black box, so we
814
+ // fall back to a non-zero-area test
815
+ return isZeroArea(node);
816
+ } else if (node.assignedSlot) {
817
+ // iterate up slot
818
+ node = node.assignedSlot;
819
+ } else if (!parentElement && rootNode !== node.ownerDocument) {
820
+ // cross shadow boundary
821
+ node = rootNode.host;
822
+ } else {
823
+ // iterate up normal dom
824
+ node = parentElement;
825
+ }
826
+ }
827
+ node = originalNode;
828
+ }
829
+ // else, `getShadowRoot` might be true, but all that does is enable shadow DOM support
830
+ // (i.e. it does not also presume that all nodes might have undisclosed shadows); or
831
+ // it might be a falsy value, which means shadow DOM support is disabled
832
+
833
+ // Since we didn't find it sitting in an undisclosed shadow (or shadows are disabled)
834
+ // now we can just test to see if it would normally be visible or not, provided it's
835
+ // attached to the main document.
836
+ // NOTE: We must consider case where node is inside a shadow DOM and given directly to
837
+ // `isTabbable()` or `isFocusable()` -- regardless of `getShadowRoot` option setting.
838
+
839
+ if (isNodeAttached(node)) {
840
+ // this works wherever the node is: if there's at least one client rect, it's
841
+ // somehow displayed; it also covers the CSS 'display: contents' case where the
842
+ // node itself is hidden in place of its contents; and there's no need to search
843
+ // up the hierarchy either
844
+ return !node.getClientRects().length;
845
+ }
846
+
847
+ // Else, the node isn't attached to the document, which means the `getClientRects()`
848
+ // API will __always__ return zero rects (this can happen, for example, if React
849
+ // is used to render nodes onto a detached tree, as confirmed in this thread:
850
+ // https://github.com/facebook/react/issues/9117#issuecomment-284228870)
851
+ //
852
+ // It also means that even window.getComputedStyle(node).display will return `undefined`
853
+ // because styles are only computed for nodes that are in the document.
854
+ //
855
+ // NOTE: THIS HAS BEEN THE CASE FOR YEARS. It is not new, nor is it caused by tabbable
856
+ // somehow. Though it was never stated officially, anyone who has ever used tabbable
857
+ // APIs on nodes in detached containers has actually implicitly used tabbable in what
858
+ // was later (as of v5.2.0 on Apr 9, 2021) called `displayCheck="none"` mode -- essentially
859
+ // considering __everything__ to be visible because of the innability to determine styles.
860
+ //
861
+ // v6.0.0: As of this major release, the default 'full' option __no longer treats detached
862
+ // nodes as visible with the 'none' fallback.__
863
+ if (displayCheck !== 'legacy-full') {
864
+ return true; // hidden
865
+ }
866
+ // else, fallback to 'none' mode and consider the node visible
867
+ } else if (displayCheck === 'non-zero-area') {
868
+ // NOTE: Even though this tests that the node's client rect is non-zero to determine
869
+ // whether it's displayed, and that a detached node will __always__ have a zero-area
870
+ // client rect, we don't special-case for whether the node is attached or not. In
871
+ // this mode, we do want to consider nodes that have a zero area to be hidden at all
872
+ // times, and that includes attached or not.
873
+ return isZeroArea(node);
874
+ }
875
+
876
+ // visible, as far as we can tell, or per current `displayCheck=none` mode, we assume
877
+ // it's visible
878
+ return false;
879
+ };
880
+
881
+ // form fields (nested) inside a disabled fieldset are not focusable/tabbable
882
+ // unless they are in the _first_ <legend> element of the top-most disabled
883
+ // fieldset
884
+ var isDisabledFromFieldset = function isDisabledFromFieldset(node) {
885
+ if (/^(INPUT|BUTTON|SELECT|TEXTAREA)$/.test(node.tagName)) {
886
+ var parentNode = node.parentElement;
887
+ // check if `node` is contained in a disabled <fieldset>
888
+ while (parentNode) {
889
+ if (parentNode.tagName === 'FIELDSET' && parentNode.disabled) {
890
+ // look for the first <legend> among the children of the disabled <fieldset>
891
+ for (var i = 0; i < parentNode.children.length; i++) {
892
+ var child = parentNode.children.item(i);
893
+ // when the first <legend> (in document order) is found
894
+ if (child.tagName === 'LEGEND') {
895
+ // if its parent <fieldset> is not nested in another disabled <fieldset>,
896
+ // return whether `node` is a descendant of its first <legend>
897
+ return matches.call(parentNode, 'fieldset[disabled] *') ? true : !child.contains(node);
898
+ }
899
+ }
900
+ // the disabled <fieldset> containing `node` has no <legend>
901
+ return true;
902
+ }
903
+ parentNode = parentNode.parentElement;
904
+ }
905
+ }
906
+
907
+ // else, node's tabbable/focusable state should not be affected by a fieldset's
908
+ // enabled/disabled state
909
+ return false;
910
+ };
911
+ var isNodeMatchingSelectorFocusable = function isNodeMatchingSelectorFocusable(options, node) {
912
+ if (node.disabled || isHiddenInput(node) || isHidden(node, options) ||
913
+ // For a details element with a summary, the summary element gets the focus
914
+ isDetailsWithSummary(node) || isDisabledFromFieldset(node)) {
915
+ return false;
916
+ }
917
+ return true;
918
+ };
919
+ var isNodeMatchingSelectorTabbable = function isNodeMatchingSelectorTabbable(options, node) {
920
+ if (isNonTabbableRadio(node) || getTabIndex(node) < 0 || !isNodeMatchingSelectorFocusable(options, node)) {
921
+ return false;
922
+ }
923
+ return true;
924
+ };
925
+ var isShadowRootTabbable = function isShadowRootTabbable(shadowHostNode) {
926
+ var tabIndex = parseInt(shadowHostNode.getAttribute('tabindex'), 10);
927
+ if (isNaN(tabIndex) || tabIndex >= 0) {
928
+ return true;
929
+ }
930
+ // If a custom element has an explicit negative tabindex,
931
+ // browsers will not allow tab targeting said element's children.
932
+ return false;
933
+ };
934
+
935
+ /**
936
+ * @param {Array.<Element|CandidateScope>} candidates
937
+ * @returns Element[]
938
+ */
939
+ var _sortByOrder = function sortByOrder(candidates) {
940
+ var regularTabbables = [];
941
+ var orderedTabbables = [];
942
+ candidates.forEach(function (item, i) {
943
+ var isScope = !!item.scopeParent;
944
+ var element = isScope ? item.scopeParent : item;
945
+ var candidateTabindex = getSortOrderTabIndex(element, isScope);
946
+ var elements = isScope ? _sortByOrder(item.candidates) : element;
947
+ if (candidateTabindex === 0) {
948
+ isScope ? regularTabbables.push.apply(regularTabbables, elements) : regularTabbables.push(element);
949
+ } else {
950
+ orderedTabbables.push({
951
+ documentOrder: i,
952
+ tabIndex: candidateTabindex,
953
+ item: item,
954
+ isScope: isScope,
955
+ content: elements
956
+ });
957
+ }
958
+ });
959
+ return orderedTabbables.sort(sortOrderedTabbables).reduce(function (acc, sortable) {
960
+ sortable.isScope ? acc.push.apply(acc, sortable.content) : acc.push(sortable.content);
961
+ return acc;
962
+ }, []).concat(regularTabbables);
963
+ };
964
+ var tabbable = function tabbable(container, options) {
965
+ options = options || {};
966
+ var candidates;
967
+ if (options.getShadowRoot) {
968
+ candidates = _getCandidatesIteratively([container], options.includeContainer, {
969
+ filter: isNodeMatchingSelectorTabbable.bind(null, options),
970
+ flatten: false,
971
+ getShadowRoot: options.getShadowRoot,
972
+ shadowRootFilter: isShadowRootTabbable
973
+ });
974
+ } else {
975
+ candidates = getCandidates(container, options.includeContainer, isNodeMatchingSelectorTabbable.bind(null, options));
976
+ }
977
+ return _sortByOrder(candidates);
978
+ };
979
+ var isTabbable = function isTabbable(node, options) {
980
+ options = options || {};
981
+ if (!node) {
982
+ throw new Error('No node provided');
983
+ }
984
+ if (matches.call(node, candidateSelector) === false) {
985
+ return false;
986
+ }
987
+ return isNodeMatchingSelectorTabbable(options, node);
988
+ };
989
+
990
+ function computeCoordsFromPlacement(_ref, placement, rtl) {
991
+ let {
992
+ reference,
993
+ floating
994
+ } = _ref;
995
+ const sideAxis = getSideAxis(placement);
996
+ const alignmentAxis = getAlignmentAxis(placement);
997
+ const alignLength = getAxisLength(alignmentAxis);
998
+ const side = getSide(placement);
999
+ const isVertical = sideAxis === 'y';
1000
+ const commonX = reference.x + reference.width / 2 - floating.width / 2;
1001
+ const commonY = reference.y + reference.height / 2 - floating.height / 2;
1002
+ const commonAlign = reference[alignLength] / 2 - floating[alignLength] / 2;
1003
+ let coords;
1004
+ switch (side) {
1005
+ case 'top':
1006
+ coords = {
1007
+ x: commonX,
1008
+ y: reference.y - floating.height
1009
+ };
1010
+ break;
1011
+ case 'bottom':
1012
+ coords = {
1013
+ x: commonX,
1014
+ y: reference.y + reference.height
1015
+ };
1016
+ break;
1017
+ case 'right':
1018
+ coords = {
1019
+ x: reference.x + reference.width,
1020
+ y: commonY
1021
+ };
1022
+ break;
1023
+ case 'left':
1024
+ coords = {
1025
+ x: reference.x - floating.width,
1026
+ y: commonY
1027
+ };
1028
+ break;
1029
+ default:
1030
+ coords = {
1031
+ x: reference.x,
1032
+ y: reference.y
1033
+ };
1034
+ }
1035
+ switch (getAlignment(placement)) {
1036
+ case 'start':
1037
+ coords[alignmentAxis] -= commonAlign * (rtl && isVertical ? -1 : 1);
1038
+ break;
1039
+ case 'end':
1040
+ coords[alignmentAxis] += commonAlign * (rtl && isVertical ? -1 : 1);
1041
+ break;
1042
+ }
1043
+ return coords;
1044
+ }
1045
+
1046
+ /**
1047
+ * Computes the `x` and `y` coordinates that will place the floating element
1048
+ * next to a given reference element.
1049
+ *
1050
+ * This export does not have any `platform` interface logic. You will need to
1051
+ * write one for the platform you are using Floating UI with.
1052
+ */
1053
+ const computePosition$1 = async (reference, floating, config) => {
1054
+ const {
1055
+ placement = 'bottom',
1056
+ strategy = 'absolute',
1057
+ middleware = [],
1058
+ platform
1059
+ } = config;
1060
+ const validMiddleware = middleware.filter(Boolean);
1061
+ const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(floating));
1062
+ let rects = await platform.getElementRects({
1063
+ reference,
1064
+ floating,
1065
+ strategy
1066
+ });
1067
+ let {
1068
+ x,
1069
+ y
1070
+ } = computeCoordsFromPlacement(rects, placement, rtl);
1071
+ let statefulPlacement = placement;
1072
+ let middlewareData = {};
1073
+ let resetCount = 0;
1074
+ for (let i = 0; i < validMiddleware.length; i++) {
1075
+ const {
1076
+ name,
1077
+ fn
1078
+ } = validMiddleware[i];
1079
+ const {
1080
+ x: nextX,
1081
+ y: nextY,
1082
+ data,
1083
+ reset
1084
+ } = await fn({
1085
+ x,
1086
+ y,
1087
+ initialPlacement: placement,
1088
+ placement: statefulPlacement,
1089
+ strategy,
1090
+ middlewareData,
1091
+ rects,
1092
+ platform,
1093
+ elements: {
1094
+ reference,
1095
+ floating
1096
+ }
1097
+ });
1098
+ x = nextX != null ? nextX : x;
1099
+ y = nextY != null ? nextY : y;
1100
+ middlewareData = {
1101
+ ...middlewareData,
1102
+ [name]: {
1103
+ ...middlewareData[name],
1104
+ ...data
1105
+ }
1106
+ };
1107
+ if (reset && resetCount <= 50) {
1108
+ resetCount++;
1109
+ if (typeof reset === 'object') {
1110
+ if (reset.placement) {
1111
+ statefulPlacement = reset.placement;
1112
+ }
1113
+ if (reset.rects) {
1114
+ rects = reset.rects === true ? await platform.getElementRects({
1115
+ reference,
1116
+ floating,
1117
+ strategy
1118
+ }) : reset.rects;
1119
+ }
1120
+ ({
1121
+ x,
1122
+ y
1123
+ } = computeCoordsFromPlacement(rects, statefulPlacement, rtl));
1124
+ }
1125
+ i = -1;
1126
+ }
1127
+ }
1128
+ return {
1129
+ x,
1130
+ y,
1131
+ placement: statefulPlacement,
1132
+ strategy,
1133
+ middlewareData
1134
+ };
1135
+ };
1136
+
1137
+ /**
1138
+ * Resolves with an object of overflow side offsets that determine how much the
1139
+ * element is overflowing a given clipping boundary on each side.
1140
+ * - positive = overflowing the boundary by that number of pixels
1141
+ * - negative = how many pixels left before it will overflow
1142
+ * - 0 = lies flush with the boundary
1143
+ * @see https://floating-ui.com/docs/detectOverflow
1144
+ */
1145
+ async function detectOverflow(state, options) {
1146
+ var _await$platform$isEle;
1147
+ if (options === void 0) {
1148
+ options = {};
1149
+ }
1150
+ const {
1151
+ x,
1152
+ y,
1153
+ platform,
1154
+ rects,
1155
+ elements,
1156
+ strategy
1157
+ } = state;
1158
+ const {
1159
+ boundary = 'clippingAncestors',
1160
+ rootBoundary = 'viewport',
1161
+ elementContext = 'floating',
1162
+ altBoundary = false,
1163
+ padding = 0
1164
+ } = evaluate(options, state);
1165
+ const paddingObject = getPaddingObject(padding);
1166
+ const altContext = elementContext === 'floating' ? 'reference' : 'floating';
1167
+ const element = elements[altBoundary ? altContext : elementContext];
1168
+ const clippingClientRect = rectToClientRect(await platform.getClippingRect({
1169
+ element: ((_await$platform$isEle = await (platform.isElement == null ? void 0 : platform.isElement(element))) != null ? _await$platform$isEle : true) ? element : element.contextElement || (await (platform.getDocumentElement == null ? void 0 : platform.getDocumentElement(elements.floating))),
1170
+ boundary,
1171
+ rootBoundary,
1172
+ strategy
1173
+ }));
1174
+ const rect = elementContext === 'floating' ? {
1175
+ x,
1176
+ y,
1177
+ width: rects.floating.width,
1178
+ height: rects.floating.height
1179
+ } : rects.reference;
1180
+ const offsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(elements.floating));
1181
+ const offsetScale = (await (platform.isElement == null ? void 0 : platform.isElement(offsetParent))) ? (await (platform.getScale == null ? void 0 : platform.getScale(offsetParent))) || {
1182
+ x: 1,
1183
+ y: 1
1184
+ } : {
1185
+ x: 1,
1186
+ y: 1
1187
+ };
1188
+ const elementClientRect = rectToClientRect(platform.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform.convertOffsetParentRelativeRectToViewportRelativeRect({
1189
+ elements,
1190
+ rect,
1191
+ offsetParent,
1192
+ strategy
1193
+ }) : rect);
1194
+ return {
1195
+ top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y,
1196
+ bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y,
1197
+ left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x,
1198
+ right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x
1199
+ };
1200
+ }
1201
+
1202
+ /**
1203
+ * Optimizes the visibility of the floating element by flipping the `placement`
1204
+ * in order to keep it in view when the preferred placement(s) will overflow the
1205
+ * clipping boundary. Alternative to `autoPlacement`.
1206
+ * @see https://floating-ui.com/docs/flip
1207
+ */
1208
+ const flip$2 = function (options) {
1209
+ if (options === void 0) {
1210
+ options = {};
1211
+ }
1212
+ return {
1213
+ name: 'flip',
1214
+ options,
1215
+ async fn(state) {
1216
+ var _middlewareData$arrow, _middlewareData$flip;
1217
+ const {
1218
+ placement,
1219
+ middlewareData,
1220
+ rects,
1221
+ initialPlacement,
1222
+ platform,
1223
+ elements
1224
+ } = state;
1225
+ const {
1226
+ mainAxis: checkMainAxis = true,
1227
+ crossAxis: checkCrossAxis = true,
1228
+ fallbackPlacements: specifiedFallbackPlacements,
1229
+ fallbackStrategy = 'bestFit',
1230
+ fallbackAxisSideDirection = 'none',
1231
+ flipAlignment = true,
1232
+ ...detectOverflowOptions
1233
+ } = evaluate(options, state);
1234
+
1235
+ // If a reset by the arrow was caused due to an alignment offset being
1236
+ // added, we should skip any logic now since `flip()` has already done its
1237
+ // work.
1238
+ // https://github.com/floating-ui/floating-ui/issues/2549#issuecomment-1719601643
1239
+ if ((_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {
1240
+ return {};
1241
+ }
1242
+ const side = getSide(placement);
1243
+ const initialSideAxis = getSideAxis(initialPlacement);
1244
+ const isBasePlacement = getSide(initialPlacement) === initialPlacement;
1245
+ const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating));
1246
+ const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipAlignment ? [getOppositePlacement(initialPlacement)] : getExpandedPlacements(initialPlacement));
1247
+ const hasFallbackAxisSideDirection = fallbackAxisSideDirection !== 'none';
1248
+ if (!specifiedFallbackPlacements && hasFallbackAxisSideDirection) {
1249
+ fallbackPlacements.push(...getOppositeAxisPlacements(initialPlacement, flipAlignment, fallbackAxisSideDirection, rtl));
1250
+ }
1251
+ const placements = [initialPlacement, ...fallbackPlacements];
1252
+ const overflow = await detectOverflow(state, detectOverflowOptions);
1253
+ const overflows = [];
1254
+ let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || [];
1255
+ if (checkMainAxis) {
1256
+ overflows.push(overflow[side]);
1257
+ }
1258
+ if (checkCrossAxis) {
1259
+ const sides = getAlignmentSides(placement, rects, rtl);
1260
+ overflows.push(overflow[sides[0]], overflow[sides[1]]);
1261
+ }
1262
+ overflowsData = [...overflowsData, {
1263
+ placement,
1264
+ overflows
1265
+ }];
1266
+
1267
+ // One or more sides is overflowing.
1268
+ if (!overflows.every(side => side <= 0)) {
1269
+ var _middlewareData$flip2, _overflowsData$filter;
1270
+ const nextIndex = (((_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) || 0) + 1;
1271
+ const nextPlacement = placements[nextIndex];
1272
+ if (nextPlacement) {
1273
+ const ignoreCrossAxisOverflow = checkCrossAxis === 'alignment' ? initialSideAxis !== getSideAxis(nextPlacement) : false;
1274
+ if (!ignoreCrossAxisOverflow ||
1275
+ // We leave the current main axis only if every placement on that axis
1276
+ // overflows the main axis.
1277
+ overflowsData.every(d => getSideAxis(d.placement) === initialSideAxis ? d.overflows[0] > 0 : true)) {
1278
+ // Try next placement and re-run the lifecycle.
1279
+ return {
1280
+ data: {
1281
+ index: nextIndex,
1282
+ overflows: overflowsData
1283
+ },
1284
+ reset: {
1285
+ placement: nextPlacement
1286
+ }
1287
+ };
1288
+ }
1289
+ }
1290
+
1291
+ // First, find the candidates that fit on the mainAxis side of overflow,
1292
+ // then find the placement that fits the best on the main crossAxis side.
1293
+ let resetPlacement = (_overflowsData$filter = overflowsData.filter(d => d.overflows[0] <= 0).sort((a, b) => a.overflows[1] - b.overflows[1])[0]) == null ? void 0 : _overflowsData$filter.placement;
1294
+
1295
+ // Otherwise fallback.
1296
+ if (!resetPlacement) {
1297
+ switch (fallbackStrategy) {
1298
+ case 'bestFit':
1299
+ {
1300
+ var _overflowsData$filter2;
1301
+ const placement = (_overflowsData$filter2 = overflowsData.filter(d => {
1302
+ if (hasFallbackAxisSideDirection) {
1303
+ const currentSideAxis = getSideAxis(d.placement);
1304
+ return currentSideAxis === initialSideAxis ||
1305
+ // Create a bias to the `y` side axis due to horizontal
1306
+ // reading directions favoring greater width.
1307
+ currentSideAxis === 'y';
1308
+ }
1309
+ return true;
1310
+ }).map(d => [d.placement, d.overflows.filter(overflow => overflow > 0).reduce((acc, overflow) => acc + overflow, 0)]).sort((a, b) => a[1] - b[1])[0]) == null ? void 0 : _overflowsData$filter2[0];
1311
+ if (placement) {
1312
+ resetPlacement = placement;
1313
+ }
1314
+ break;
1315
+ }
1316
+ case 'initialPlacement':
1317
+ resetPlacement = initialPlacement;
1318
+ break;
1319
+ }
1320
+ }
1321
+ if (placement !== resetPlacement) {
1322
+ return {
1323
+ reset: {
1324
+ placement: resetPlacement
1325
+ }
1326
+ };
1327
+ }
1328
+ }
1329
+ return {};
1330
+ }
1331
+ };
1332
+ };
1333
+
1334
+ function getBoundingRect(rects) {
1335
+ const minX = min(...rects.map(rect => rect.left));
1336
+ const minY = min(...rects.map(rect => rect.top));
1337
+ const maxX = max(...rects.map(rect => rect.right));
1338
+ const maxY = max(...rects.map(rect => rect.bottom));
1339
+ return {
1340
+ x: minX,
1341
+ y: minY,
1342
+ width: maxX - minX,
1343
+ height: maxY - minY
1344
+ };
1345
+ }
1346
+ function getRectsByLine(rects) {
1347
+ const sortedRects = rects.slice().sort((a, b) => a.y - b.y);
1348
+ const groups = [];
1349
+ let prevRect = null;
1350
+ for (let i = 0; i < sortedRects.length; i++) {
1351
+ const rect = sortedRects[i];
1352
+ if (!prevRect || rect.y - prevRect.y > prevRect.height / 2) {
1353
+ groups.push([rect]);
1354
+ } else {
1355
+ groups[groups.length - 1].push(rect);
1356
+ }
1357
+ prevRect = rect;
1358
+ }
1359
+ return groups.map(rect => rectToClientRect(getBoundingRect(rect)));
1360
+ }
1361
+ /**
1362
+ * Provides improved positioning for inline reference elements that can span
1363
+ * over multiple lines, such as hyperlinks or range selections.
1364
+ * @see https://floating-ui.com/docs/inline
1365
+ */
1366
+ const inline$2 = function (options) {
1367
+ if (options === void 0) {
1368
+ options = {};
1369
+ }
1370
+ return {
1371
+ name: 'inline',
1372
+ options,
1373
+ async fn(state) {
1374
+ const {
1375
+ placement,
1376
+ elements,
1377
+ rects,
1378
+ platform,
1379
+ strategy
1380
+ } = state;
1381
+ // A MouseEvent's client{X,Y} coords can be up to 2 pixels off a
1382
+ // ClientRect's bounds, despite the event listener being triggered. A
1383
+ // padding of 2 seems to handle this issue.
1384
+ const {
1385
+ padding = 2,
1386
+ x,
1387
+ y
1388
+ } = evaluate(options, state);
1389
+ const nativeClientRects = Array.from((await (platform.getClientRects == null ? void 0 : platform.getClientRects(elements.reference))) || []);
1390
+ const clientRects = getRectsByLine(nativeClientRects);
1391
+ const fallback = rectToClientRect(getBoundingRect(nativeClientRects));
1392
+ const paddingObject = getPaddingObject(padding);
1393
+ function getBoundingClientRect() {
1394
+ // There are two rects and they are disjoined.
1395
+ if (clientRects.length === 2 && clientRects[0].left > clientRects[1].right && x != null && y != null) {
1396
+ // Find the first rect in which the point is fully inside.
1397
+ return clientRects.find(rect => x > rect.left - paddingObject.left && x < rect.right + paddingObject.right && y > rect.top - paddingObject.top && y < rect.bottom + paddingObject.bottom) || fallback;
1398
+ }
1399
+
1400
+ // There are 2 or more connected rects.
1401
+ if (clientRects.length >= 2) {
1402
+ if (getSideAxis(placement) === 'y') {
1403
+ const firstRect = clientRects[0];
1404
+ const lastRect = clientRects[clientRects.length - 1];
1405
+ const isTop = getSide(placement) === 'top';
1406
+ const top = firstRect.top;
1407
+ const bottom = lastRect.bottom;
1408
+ const left = isTop ? firstRect.left : lastRect.left;
1409
+ const right = isTop ? firstRect.right : lastRect.right;
1410
+ const width = right - left;
1411
+ const height = bottom - top;
1412
+ return {
1413
+ top,
1414
+ bottom,
1415
+ left,
1416
+ right,
1417
+ width,
1418
+ height,
1419
+ x: left,
1420
+ y: top
1421
+ };
1422
+ }
1423
+ const isLeftSide = getSide(placement) === 'left';
1424
+ const maxRight = max(...clientRects.map(rect => rect.right));
1425
+ const minLeft = min(...clientRects.map(rect => rect.left));
1426
+ const measureRects = clientRects.filter(rect => isLeftSide ? rect.left === minLeft : rect.right === maxRight);
1427
+ const top = measureRects[0].top;
1428
+ const bottom = measureRects[measureRects.length - 1].bottom;
1429
+ const left = minLeft;
1430
+ const right = maxRight;
1431
+ const width = right - left;
1432
+ const height = bottom - top;
1433
+ return {
1434
+ top,
1435
+ bottom,
1436
+ left,
1437
+ right,
1438
+ width,
1439
+ height,
1440
+ x: left,
1441
+ y: top
1442
+ };
1443
+ }
1444
+ return fallback;
1445
+ }
1446
+ const resetRects = await platform.getElementRects({
1447
+ reference: {
1448
+ getBoundingClientRect
1449
+ },
1450
+ floating: elements.floating,
1451
+ strategy
1452
+ });
1453
+ if (rects.reference.x !== resetRects.reference.x || rects.reference.y !== resetRects.reference.y || rects.reference.width !== resetRects.reference.width || rects.reference.height !== resetRects.reference.height) {
1454
+ return {
1455
+ reset: {
1456
+ rects: resetRects
1457
+ }
1458
+ };
1459
+ }
1460
+ return {};
1461
+ }
1462
+ };
1463
+ };
1464
+
1465
+ const originSides = /*#__PURE__*/new Set(['left', 'top']);
1466
+
1467
+ // For type backwards-compatibility, the `OffsetOptions` type was also
1468
+ // Derivable.
1469
+
1470
+ async function convertValueToCoords(state, options) {
1471
+ const {
1472
+ placement,
1473
+ platform,
1474
+ elements
1475
+ } = state;
1476
+ const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating));
1477
+ const side = getSide(placement);
1478
+ const alignment = getAlignment(placement);
1479
+ const isVertical = getSideAxis(placement) === 'y';
1480
+ const mainAxisMulti = originSides.has(side) ? -1 : 1;
1481
+ const crossAxisMulti = rtl && isVertical ? -1 : 1;
1482
+ const rawValue = evaluate(options, state);
1483
+
1484
+ // eslint-disable-next-line prefer-const
1485
+ let {
1486
+ mainAxis,
1487
+ crossAxis,
1488
+ alignmentAxis
1489
+ } = typeof rawValue === 'number' ? {
1490
+ mainAxis: rawValue,
1491
+ crossAxis: 0,
1492
+ alignmentAxis: null
1493
+ } : {
1494
+ mainAxis: rawValue.mainAxis || 0,
1495
+ crossAxis: rawValue.crossAxis || 0,
1496
+ alignmentAxis: rawValue.alignmentAxis
1497
+ };
1498
+ if (alignment && typeof alignmentAxis === 'number') {
1499
+ crossAxis = alignment === 'end' ? alignmentAxis * -1 : alignmentAxis;
1500
+ }
1501
+ return isVertical ? {
1502
+ x: crossAxis * crossAxisMulti,
1503
+ y: mainAxis * mainAxisMulti
1504
+ } : {
1505
+ x: mainAxis * mainAxisMulti,
1506
+ y: crossAxis * crossAxisMulti
1507
+ };
1508
+ }
1509
+
1510
+ /**
1511
+ * Modifies the placement by translating the floating element along the
1512
+ * specified axes.
1513
+ * A number (shorthand for `mainAxis` or distance), or an axes configuration
1514
+ * object may be passed.
1515
+ * @see https://floating-ui.com/docs/offset
1516
+ */
1517
+ const offset$2 = function (options) {
1518
+ if (options === void 0) {
1519
+ options = 0;
1520
+ }
1521
+ return {
1522
+ name: 'offset',
1523
+ options,
1524
+ async fn(state) {
1525
+ var _middlewareData$offse, _middlewareData$arrow;
1526
+ const {
1527
+ x,
1528
+ y,
1529
+ placement,
1530
+ middlewareData
1531
+ } = state;
1532
+ const diffCoords = await convertValueToCoords(state, options);
1533
+
1534
+ // If the placement is the same and the arrow caused an alignment offset
1535
+ // then we don't need to change the positioning coordinates.
1536
+ if (placement === ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse.placement) && (_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {
1537
+ return {};
1538
+ }
1539
+ return {
1540
+ x: x + diffCoords.x,
1541
+ y: y + diffCoords.y,
1542
+ data: {
1543
+ ...diffCoords,
1544
+ placement
1545
+ }
1546
+ };
1547
+ }
1548
+ };
1549
+ };
1550
+
1551
+ /**
1552
+ * Optimizes the visibility of the floating element by shifting it in order to
1553
+ * keep it in view when it will overflow the clipping boundary.
1554
+ * @see https://floating-ui.com/docs/shift
1555
+ */
1556
+ const shift$2 = function (options) {
1557
+ if (options === void 0) {
1558
+ options = {};
1559
+ }
1560
+ return {
1561
+ name: 'shift',
1562
+ options,
1563
+ async fn(state) {
1564
+ const {
1565
+ x,
1566
+ y,
1567
+ placement
1568
+ } = state;
1569
+ const {
1570
+ mainAxis: checkMainAxis = true,
1571
+ crossAxis: checkCrossAxis = false,
1572
+ limiter = {
1573
+ fn: _ref => {
1574
+ let {
1575
+ x,
1576
+ y
1577
+ } = _ref;
1578
+ return {
1579
+ x,
1580
+ y
1581
+ };
1582
+ }
1583
+ },
1584
+ ...detectOverflowOptions
1585
+ } = evaluate(options, state);
1586
+ const coords = {
1587
+ x,
1588
+ y
1589
+ };
1590
+ const overflow = await detectOverflow(state, detectOverflowOptions);
1591
+ const crossAxis = getSideAxis(getSide(placement));
1592
+ const mainAxis = getOppositeAxis(crossAxis);
1593
+ let mainAxisCoord = coords[mainAxis];
1594
+ let crossAxisCoord = coords[crossAxis];
1595
+ if (checkMainAxis) {
1596
+ const minSide = mainAxis === 'y' ? 'top' : 'left';
1597
+ const maxSide = mainAxis === 'y' ? 'bottom' : 'right';
1598
+ const min = mainAxisCoord + overflow[minSide];
1599
+ const max = mainAxisCoord - overflow[maxSide];
1600
+ mainAxisCoord = clamp(min, mainAxisCoord, max);
1601
+ }
1602
+ if (checkCrossAxis) {
1603
+ const minSide = crossAxis === 'y' ? 'top' : 'left';
1604
+ const maxSide = crossAxis === 'y' ? 'bottom' : 'right';
1605
+ const min = crossAxisCoord + overflow[minSide];
1606
+ const max = crossAxisCoord - overflow[maxSide];
1607
+ crossAxisCoord = clamp(min, crossAxisCoord, max);
1608
+ }
1609
+ const limitedCoords = limiter.fn({
1610
+ ...state,
1611
+ [mainAxis]: mainAxisCoord,
1612
+ [crossAxis]: crossAxisCoord
1613
+ });
1614
+ return {
1615
+ ...limitedCoords,
1616
+ data: {
1617
+ x: limitedCoords.x - x,
1618
+ y: limitedCoords.y - y,
1619
+ enabled: {
1620
+ [mainAxis]: checkMainAxis,
1621
+ [crossAxis]: checkCrossAxis
1622
+ }
1623
+ }
1624
+ };
1625
+ }
1626
+ };
1627
+ };
1628
+
1629
+ /**
1630
+ * Provides data that allows you to change the size of the floating element —
1631
+ * for instance, prevent it from overflowing the clipping boundary or match the
1632
+ * width of the reference element.
1633
+ * @see https://floating-ui.com/docs/size
1634
+ */
1635
+ const size$2 = function (options) {
1636
+ if (options === void 0) {
1637
+ options = {};
1638
+ }
1639
+ return {
1640
+ name: 'size',
1641
+ options,
1642
+ async fn(state) {
1643
+ var _state$middlewareData, _state$middlewareData2;
1644
+ const {
1645
+ placement,
1646
+ rects,
1647
+ platform,
1648
+ elements
1649
+ } = state;
1650
+ const {
1651
+ apply = () => {},
1652
+ ...detectOverflowOptions
1653
+ } = evaluate(options, state);
1654
+ const overflow = await detectOverflow(state, detectOverflowOptions);
1655
+ const side = getSide(placement);
1656
+ const alignment = getAlignment(placement);
1657
+ const isYAxis = getSideAxis(placement) === 'y';
1658
+ const {
1659
+ width,
1660
+ height
1661
+ } = rects.floating;
1662
+ let heightSide;
1663
+ let widthSide;
1664
+ if (side === 'top' || side === 'bottom') {
1665
+ heightSide = side;
1666
+ widthSide = alignment === ((await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating))) ? 'start' : 'end') ? 'left' : 'right';
1667
+ } else {
1668
+ widthSide = side;
1669
+ heightSide = alignment === 'end' ? 'top' : 'bottom';
1670
+ }
1671
+ const maximumClippingHeight = height - overflow.top - overflow.bottom;
1672
+ const maximumClippingWidth = width - overflow.left - overflow.right;
1673
+ const overflowAvailableHeight = min(height - overflow[heightSide], maximumClippingHeight);
1674
+ const overflowAvailableWidth = min(width - overflow[widthSide], maximumClippingWidth);
1675
+ const noShift = !state.middlewareData.shift;
1676
+ let availableHeight = overflowAvailableHeight;
1677
+ let availableWidth = overflowAvailableWidth;
1678
+ if ((_state$middlewareData = state.middlewareData.shift) != null && _state$middlewareData.enabled.x) {
1679
+ availableWidth = maximumClippingWidth;
1680
+ }
1681
+ if ((_state$middlewareData2 = state.middlewareData.shift) != null && _state$middlewareData2.enabled.y) {
1682
+ availableHeight = maximumClippingHeight;
1683
+ }
1684
+ if (noShift && !alignment) {
1685
+ const xMin = max(overflow.left, 0);
1686
+ const xMax = max(overflow.right, 0);
1687
+ const yMin = max(overflow.top, 0);
1688
+ const yMax = max(overflow.bottom, 0);
1689
+ if (isYAxis) {
1690
+ availableWidth = width - 2 * (xMin !== 0 || xMax !== 0 ? xMin + xMax : max(overflow.left, overflow.right));
1691
+ } else {
1692
+ availableHeight = height - 2 * (yMin !== 0 || yMax !== 0 ? yMin + yMax : max(overflow.top, overflow.bottom));
1693
+ }
1694
+ }
1695
+ await apply({
1696
+ ...state,
1697
+ availableWidth,
1698
+ availableHeight
1699
+ });
1700
+ const nextDimensions = await platform.getDimensions(elements.floating);
1701
+ if (width !== nextDimensions.width || height !== nextDimensions.height) {
1702
+ return {
1703
+ reset: {
1704
+ rects: true
1705
+ }
1706
+ };
1707
+ }
1708
+ return {};
1709
+ }
1710
+ };
1711
+ };
1712
+
1713
+ function getCssDimensions(element) {
1714
+ const css = getComputedStyle$1(element);
1715
+ // In testing environments, the `width` and `height` properties are empty
1716
+ // strings for SVG elements, returning NaN. Fallback to `0` in this case.
1717
+ let width = parseFloat(css.width) || 0;
1718
+ let height = parseFloat(css.height) || 0;
1719
+ const hasOffset = isHTMLElement(element);
1720
+ const offsetWidth = hasOffset ? element.offsetWidth : width;
1721
+ const offsetHeight = hasOffset ? element.offsetHeight : height;
1722
+ const shouldFallback = round(width) !== offsetWidth || round(height) !== offsetHeight;
1723
+ if (shouldFallback) {
1724
+ width = offsetWidth;
1725
+ height = offsetHeight;
1726
+ }
1727
+ return {
1728
+ width,
1729
+ height,
1730
+ $: shouldFallback
1731
+ };
1732
+ }
1733
+
1734
+ function unwrapElement(element) {
1735
+ return !isElement(element) ? element.contextElement : element;
1736
+ }
1737
+
1738
+ function getScale(element) {
1739
+ const domElement = unwrapElement(element);
1740
+ if (!isHTMLElement(domElement)) {
1741
+ return createCoords(1);
1742
+ }
1743
+ const rect = domElement.getBoundingClientRect();
1744
+ const {
1745
+ width,
1746
+ height,
1747
+ $
1748
+ } = getCssDimensions(domElement);
1749
+ let x = ($ ? round(rect.width) : rect.width) / width;
1750
+ let y = ($ ? round(rect.height) : rect.height) / height;
1751
+
1752
+ // 0, NaN, or Infinity should always fallback to 1.
1753
+
1754
+ if (!x || !Number.isFinite(x)) {
1755
+ x = 1;
1756
+ }
1757
+ if (!y || !Number.isFinite(y)) {
1758
+ y = 1;
1759
+ }
1760
+ return {
1761
+ x,
1762
+ y
1763
+ };
1764
+ }
1765
+
1766
+ const noOffsets = /*#__PURE__*/createCoords(0);
1767
+ function getVisualOffsets(element) {
1768
+ const win = getWindow(element);
1769
+ if (!isWebKit() || !win.visualViewport) {
1770
+ return noOffsets;
1771
+ }
1772
+ return {
1773
+ x: win.visualViewport.offsetLeft,
1774
+ y: win.visualViewport.offsetTop
1775
+ };
1776
+ }
1777
+ function shouldAddVisualOffsets(element, isFixed, floatingOffsetParent) {
1778
+ if (isFixed === void 0) {
1779
+ isFixed = false;
1780
+ }
1781
+ if (!floatingOffsetParent || isFixed && floatingOffsetParent !== getWindow(element)) {
1782
+ return false;
1783
+ }
1784
+ return isFixed;
1785
+ }
1786
+
1787
+ function getBoundingClientRect(element, includeScale, isFixedStrategy, offsetParent) {
1788
+ if (includeScale === void 0) {
1789
+ includeScale = false;
1790
+ }
1791
+ if (isFixedStrategy === void 0) {
1792
+ isFixedStrategy = false;
1793
+ }
1794
+ const clientRect = element.getBoundingClientRect();
1795
+ const domElement = unwrapElement(element);
1796
+ let scale = createCoords(1);
1797
+ if (includeScale) {
1798
+ if (offsetParent) {
1799
+ if (isElement(offsetParent)) {
1800
+ scale = getScale(offsetParent);
1801
+ }
1802
+ } else {
1803
+ scale = getScale(element);
1804
+ }
1805
+ }
1806
+ const visualOffsets = shouldAddVisualOffsets(domElement, isFixedStrategy, offsetParent) ? getVisualOffsets(domElement) : createCoords(0);
1807
+ let x = (clientRect.left + visualOffsets.x) / scale.x;
1808
+ let y = (clientRect.top + visualOffsets.y) / scale.y;
1809
+ let width = clientRect.width / scale.x;
1810
+ let height = clientRect.height / scale.y;
1811
+ if (domElement) {
1812
+ const win = getWindow(domElement);
1813
+ const offsetWin = offsetParent && isElement(offsetParent) ? getWindow(offsetParent) : offsetParent;
1814
+ let currentWin = win;
1815
+ let currentIFrame = getFrameElement(currentWin);
1816
+ while (currentIFrame && offsetParent && offsetWin !== currentWin) {
1817
+ const iframeScale = getScale(currentIFrame);
1818
+ const iframeRect = currentIFrame.getBoundingClientRect();
1819
+ const css = getComputedStyle$1(currentIFrame);
1820
+ const left = iframeRect.left + (currentIFrame.clientLeft + parseFloat(css.paddingLeft)) * iframeScale.x;
1821
+ const top = iframeRect.top + (currentIFrame.clientTop + parseFloat(css.paddingTop)) * iframeScale.y;
1822
+ x *= iframeScale.x;
1823
+ y *= iframeScale.y;
1824
+ width *= iframeScale.x;
1825
+ height *= iframeScale.y;
1826
+ x += left;
1827
+ y += top;
1828
+ currentWin = getWindow(currentIFrame);
1829
+ currentIFrame = getFrameElement(currentWin);
1830
+ }
1831
+ }
1832
+ return rectToClientRect({
1833
+ width,
1834
+ height,
1835
+ x,
1836
+ y
1837
+ });
1838
+ }
1839
+
1840
+ // If <html> has a CSS width greater than the viewport, then this will be
1841
+ // incorrect for RTL.
1842
+ function getWindowScrollBarX(element, rect) {
1843
+ const leftScroll = getNodeScroll(element).scrollLeft;
1844
+ if (!rect) {
1845
+ return getBoundingClientRect(getDocumentElement(element)).left + leftScroll;
1846
+ }
1847
+ return rect.left + leftScroll;
1848
+ }
1849
+
1850
+ function getHTMLOffset(documentElement, scroll) {
1851
+ const htmlRect = documentElement.getBoundingClientRect();
1852
+ const x = htmlRect.left + scroll.scrollLeft - getWindowScrollBarX(documentElement, htmlRect);
1853
+ const y = htmlRect.top + scroll.scrollTop;
1854
+ return {
1855
+ x,
1856
+ y
1857
+ };
1858
+ }
1859
+
1860
+ function convertOffsetParentRelativeRectToViewportRelativeRect(_ref) {
1861
+ let {
1862
+ elements,
1863
+ rect,
1864
+ offsetParent,
1865
+ strategy
1866
+ } = _ref;
1867
+ const isFixed = strategy === 'fixed';
1868
+ const documentElement = getDocumentElement(offsetParent);
1869
+ const topLayer = elements ? isTopLayer(elements.floating) : false;
1870
+ if (offsetParent === documentElement || topLayer && isFixed) {
1871
+ return rect;
1872
+ }
1873
+ let scroll = {
1874
+ scrollLeft: 0,
1875
+ scrollTop: 0
1876
+ };
1877
+ let scale = createCoords(1);
1878
+ const offsets = createCoords(0);
1879
+ const isOffsetParentAnElement = isHTMLElement(offsetParent);
1880
+ if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
1881
+ if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) {
1882
+ scroll = getNodeScroll(offsetParent);
1883
+ }
1884
+ if (isHTMLElement(offsetParent)) {
1885
+ const offsetRect = getBoundingClientRect(offsetParent);
1886
+ scale = getScale(offsetParent);
1887
+ offsets.x = offsetRect.x + offsetParent.clientLeft;
1888
+ offsets.y = offsetRect.y + offsetParent.clientTop;
1889
+ }
1890
+ }
1891
+ const htmlOffset = documentElement && !isOffsetParentAnElement && !isFixed ? getHTMLOffset(documentElement, scroll) : createCoords(0);
1892
+ return {
1893
+ width: rect.width * scale.x,
1894
+ height: rect.height * scale.y,
1895
+ x: rect.x * scale.x - scroll.scrollLeft * scale.x + offsets.x + htmlOffset.x,
1896
+ y: rect.y * scale.y - scroll.scrollTop * scale.y + offsets.y + htmlOffset.y
1897
+ };
1898
+ }
1899
+
1900
+ function getClientRects(element) {
1901
+ return Array.from(element.getClientRects());
1902
+ }
1903
+
1904
+ // Gets the entire size of the scrollable document area, even extending outside
1905
+ // of the `<html>` and `<body>` rect bounds if horizontally scrollable.
1906
+ function getDocumentRect(element) {
1907
+ const html = getDocumentElement(element);
1908
+ const scroll = getNodeScroll(element);
1909
+ const body = element.ownerDocument.body;
1910
+ const width = max(html.scrollWidth, html.clientWidth, body.scrollWidth, body.clientWidth);
1911
+ const height = max(html.scrollHeight, html.clientHeight, body.scrollHeight, body.clientHeight);
1912
+ let x = -scroll.scrollLeft + getWindowScrollBarX(element);
1913
+ const y = -scroll.scrollTop;
1914
+ if (getComputedStyle$1(body).direction === 'rtl') {
1915
+ x += max(html.clientWidth, body.clientWidth) - width;
1916
+ }
1917
+ return {
1918
+ width,
1919
+ height,
1920
+ x,
1921
+ y
1922
+ };
1923
+ }
1924
+
1925
+ // Safety check: ensure the scrollbar space is reasonable in case this
1926
+ // calculation is affected by unusual styles.
1927
+ // Most scrollbars leave 15-18px of space.
1928
+ const SCROLLBAR_MAX = 25;
1929
+ function getViewportRect(element, strategy) {
1930
+ const win = getWindow(element);
1931
+ const html = getDocumentElement(element);
1932
+ const visualViewport = win.visualViewport;
1933
+ let width = html.clientWidth;
1934
+ let height = html.clientHeight;
1935
+ let x = 0;
1936
+ let y = 0;
1937
+ if (visualViewport) {
1938
+ width = visualViewport.width;
1939
+ height = visualViewport.height;
1940
+ const visualViewportBased = isWebKit();
1941
+ if (!visualViewportBased || visualViewportBased && strategy === 'fixed') {
1942
+ x = visualViewport.offsetLeft;
1943
+ y = visualViewport.offsetTop;
1944
+ }
1945
+ }
1946
+ const windowScrollbarX = getWindowScrollBarX(html);
1947
+ // <html> `overflow: hidden` + `scrollbar-gutter: stable` reduces the
1948
+ // visual width of the <html> but this is not considered in the size
1949
+ // of `html.clientWidth`.
1950
+ if (windowScrollbarX <= 0) {
1951
+ const doc = html.ownerDocument;
1952
+ const body = doc.body;
1953
+ const bodyStyles = getComputedStyle(body);
1954
+ const bodyMarginInline = doc.compatMode === 'CSS1Compat' ? parseFloat(bodyStyles.marginLeft) + parseFloat(bodyStyles.marginRight) || 0 : 0;
1955
+ const clippingStableScrollbarWidth = Math.abs(html.clientWidth - body.clientWidth - bodyMarginInline);
1956
+ if (clippingStableScrollbarWidth <= SCROLLBAR_MAX) {
1957
+ width -= clippingStableScrollbarWidth;
1958
+ }
1959
+ } else if (windowScrollbarX <= SCROLLBAR_MAX) {
1960
+ // If the <body> scrollbar is on the left, the width needs to be extended
1961
+ // by the scrollbar amount so there isn't extra space on the right.
1962
+ width += windowScrollbarX;
1963
+ }
1964
+ return {
1965
+ width,
1966
+ height,
1967
+ x,
1968
+ y
1969
+ };
1970
+ }
1971
+
1972
+ const absoluteOrFixed = /*#__PURE__*/new Set(['absolute', 'fixed']);
1973
+ // Returns the inner client rect, subtracting scrollbars if present.
1974
+ function getInnerBoundingClientRect(element, strategy) {
1975
+ const clientRect = getBoundingClientRect(element, true, strategy === 'fixed');
1976
+ const top = clientRect.top + element.clientTop;
1977
+ const left = clientRect.left + element.clientLeft;
1978
+ const scale = isHTMLElement(element) ? getScale(element) : createCoords(1);
1979
+ const width = element.clientWidth * scale.x;
1980
+ const height = element.clientHeight * scale.y;
1981
+ const x = left * scale.x;
1982
+ const y = top * scale.y;
1983
+ return {
1984
+ width,
1985
+ height,
1986
+ x,
1987
+ y
1988
+ };
1989
+ }
1990
+ function getClientRectFromClippingAncestor(element, clippingAncestor, strategy) {
1991
+ let rect;
1992
+ if (clippingAncestor === 'viewport') {
1993
+ rect = getViewportRect(element, strategy);
1994
+ } else if (clippingAncestor === 'document') {
1995
+ rect = getDocumentRect(getDocumentElement(element));
1996
+ } else if (isElement(clippingAncestor)) {
1997
+ rect = getInnerBoundingClientRect(clippingAncestor, strategy);
1998
+ } else {
1999
+ const visualOffsets = getVisualOffsets(element);
2000
+ rect = {
2001
+ x: clippingAncestor.x - visualOffsets.x,
2002
+ y: clippingAncestor.y - visualOffsets.y,
2003
+ width: clippingAncestor.width,
2004
+ height: clippingAncestor.height
2005
+ };
2006
+ }
2007
+ return rectToClientRect(rect);
2008
+ }
2009
+ function hasFixedPositionAncestor(element, stopNode) {
2010
+ const parentNode = getParentNode(element);
2011
+ if (parentNode === stopNode || !isElement(parentNode) || isLastTraversableNode(parentNode)) {
2012
+ return false;
2013
+ }
2014
+ return getComputedStyle$1(parentNode).position === 'fixed' || hasFixedPositionAncestor(parentNode, stopNode);
2015
+ }
2016
+
2017
+ // A "clipping ancestor" is an `overflow` element with the characteristic of
2018
+ // clipping (or hiding) child elements. This returns all clipping ancestors
2019
+ // of the given element up the tree.
2020
+ function getClippingElementAncestors(element, cache) {
2021
+ const cachedResult = cache.get(element);
2022
+ if (cachedResult) {
2023
+ return cachedResult;
2024
+ }
2025
+ let result = getOverflowAncestors(element, [], false).filter(el => isElement(el) && getNodeName(el) !== 'body');
2026
+ let currentContainingBlockComputedStyle = null;
2027
+ const elementIsFixed = getComputedStyle$1(element).position === 'fixed';
2028
+ let currentNode = elementIsFixed ? getParentNode(element) : element;
2029
+
2030
+ // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block
2031
+ while (isElement(currentNode) && !isLastTraversableNode(currentNode)) {
2032
+ const computedStyle = getComputedStyle$1(currentNode);
2033
+ const currentNodeIsContaining = isContainingBlock(currentNode);
2034
+ if (!currentNodeIsContaining && computedStyle.position === 'fixed') {
2035
+ currentContainingBlockComputedStyle = null;
2036
+ }
2037
+ const shouldDropCurrentNode = elementIsFixed ? !currentNodeIsContaining && !currentContainingBlockComputedStyle : !currentNodeIsContaining && computedStyle.position === 'static' && !!currentContainingBlockComputedStyle && absoluteOrFixed.has(currentContainingBlockComputedStyle.position) || isOverflowElement(currentNode) && !currentNodeIsContaining && hasFixedPositionAncestor(element, currentNode);
2038
+ if (shouldDropCurrentNode) {
2039
+ // Drop non-containing blocks.
2040
+ result = result.filter(ancestor => ancestor !== currentNode);
2041
+ } else {
2042
+ // Record last containing block for next iteration.
2043
+ currentContainingBlockComputedStyle = computedStyle;
2044
+ }
2045
+ currentNode = getParentNode(currentNode);
2046
+ }
2047
+ cache.set(element, result);
2048
+ return result;
2049
+ }
2050
+
2051
+ // Gets the maximum area that the element is visible in due to any number of
2052
+ // clipping ancestors.
2053
+ function getClippingRect(_ref) {
2054
+ let {
2055
+ element,
2056
+ boundary,
2057
+ rootBoundary,
2058
+ strategy
2059
+ } = _ref;
2060
+ const elementClippingAncestors = boundary === 'clippingAncestors' ? isTopLayer(element) ? [] : getClippingElementAncestors(element, this._c) : [].concat(boundary);
2061
+ const clippingAncestors = [...elementClippingAncestors, rootBoundary];
2062
+ const firstClippingAncestor = clippingAncestors[0];
2063
+ const clippingRect = clippingAncestors.reduce((accRect, clippingAncestor) => {
2064
+ const rect = getClientRectFromClippingAncestor(element, clippingAncestor, strategy);
2065
+ accRect.top = max(rect.top, accRect.top);
2066
+ accRect.right = min(rect.right, accRect.right);
2067
+ accRect.bottom = min(rect.bottom, accRect.bottom);
2068
+ accRect.left = max(rect.left, accRect.left);
2069
+ return accRect;
2070
+ }, getClientRectFromClippingAncestor(element, firstClippingAncestor, strategy));
2071
+ return {
2072
+ width: clippingRect.right - clippingRect.left,
2073
+ height: clippingRect.bottom - clippingRect.top,
2074
+ x: clippingRect.left,
2075
+ y: clippingRect.top
2076
+ };
2077
+ }
2078
+
2079
+ function getDimensions(element) {
2080
+ const {
2081
+ width,
2082
+ height
2083
+ } = getCssDimensions(element);
2084
+ return {
2085
+ width,
2086
+ height
2087
+ };
2088
+ }
2089
+
2090
+ function getRectRelativeToOffsetParent(element, offsetParent, strategy) {
2091
+ const isOffsetParentAnElement = isHTMLElement(offsetParent);
2092
+ const documentElement = getDocumentElement(offsetParent);
2093
+ const isFixed = strategy === 'fixed';
2094
+ const rect = getBoundingClientRect(element, true, isFixed, offsetParent);
2095
+ let scroll = {
2096
+ scrollLeft: 0,
2097
+ scrollTop: 0
2098
+ };
2099
+ const offsets = createCoords(0);
2100
+
2101
+ // If the <body> scrollbar appears on the left (e.g. RTL systems). Use
2102
+ // Firefox with layout.scrollbar.side = 3 in about:config to test this.
2103
+ function setLeftRTLScrollbarOffset() {
2104
+ offsets.x = getWindowScrollBarX(documentElement);
2105
+ }
2106
+ if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
2107
+ if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) {
2108
+ scroll = getNodeScroll(offsetParent);
2109
+ }
2110
+ if (isOffsetParentAnElement) {
2111
+ const offsetRect = getBoundingClientRect(offsetParent, true, isFixed, offsetParent);
2112
+ offsets.x = offsetRect.x + offsetParent.clientLeft;
2113
+ offsets.y = offsetRect.y + offsetParent.clientTop;
2114
+ } else if (documentElement) {
2115
+ setLeftRTLScrollbarOffset();
2116
+ }
2117
+ }
2118
+ if (isFixed && !isOffsetParentAnElement && documentElement) {
2119
+ setLeftRTLScrollbarOffset();
2120
+ }
2121
+ const htmlOffset = documentElement && !isOffsetParentAnElement && !isFixed ? getHTMLOffset(documentElement, scroll) : createCoords(0);
2122
+ const x = rect.left + scroll.scrollLeft - offsets.x - htmlOffset.x;
2123
+ const y = rect.top + scroll.scrollTop - offsets.y - htmlOffset.y;
2124
+ return {
2125
+ x,
2126
+ y,
2127
+ width: rect.width,
2128
+ height: rect.height
2129
+ };
2130
+ }
2131
+
2132
+ function isStaticPositioned(element) {
2133
+ return getComputedStyle$1(element).position === 'static';
2134
+ }
2135
+
2136
+ function getTrueOffsetParent(element, polyfill) {
2137
+ if (!isHTMLElement(element) || getComputedStyle$1(element).position === 'fixed') {
2138
+ return null;
2139
+ }
2140
+ if (polyfill) {
2141
+ return polyfill(element);
2142
+ }
2143
+ let rawOffsetParent = element.offsetParent;
2144
+
2145
+ // Firefox returns the <html> element as the offsetParent if it's non-static,
2146
+ // while Chrome and Safari return the <body> element. The <body> element must
2147
+ // be used to perform the correct calculations even if the <html> element is
2148
+ // non-static.
2149
+ if (getDocumentElement(element) === rawOffsetParent) {
2150
+ rawOffsetParent = rawOffsetParent.ownerDocument.body;
2151
+ }
2152
+ return rawOffsetParent;
2153
+ }
2154
+
2155
+ // Gets the closest ancestor positioned element. Handles some edge cases,
2156
+ // such as table ancestors and cross browser bugs.
2157
+ function getOffsetParent(element, polyfill) {
2158
+ const win = getWindow(element);
2159
+ if (isTopLayer(element)) {
2160
+ return win;
2161
+ }
2162
+ if (!isHTMLElement(element)) {
2163
+ let svgOffsetParent = getParentNode(element);
2164
+ while (svgOffsetParent && !isLastTraversableNode(svgOffsetParent)) {
2165
+ if (isElement(svgOffsetParent) && !isStaticPositioned(svgOffsetParent)) {
2166
+ return svgOffsetParent;
2167
+ }
2168
+ svgOffsetParent = getParentNode(svgOffsetParent);
2169
+ }
2170
+ return win;
2171
+ }
2172
+ let offsetParent = getTrueOffsetParent(element, polyfill);
2173
+ while (offsetParent && isTableElement(offsetParent) && isStaticPositioned(offsetParent)) {
2174
+ offsetParent = getTrueOffsetParent(offsetParent, polyfill);
2175
+ }
2176
+ if (offsetParent && isLastTraversableNode(offsetParent) && isStaticPositioned(offsetParent) && !isContainingBlock(offsetParent)) {
2177
+ return win;
2178
+ }
2179
+ return offsetParent || getContainingBlock(element) || win;
2180
+ }
2181
+
2182
+ const getElementRects = async function (data) {
2183
+ const getOffsetParentFn = this.getOffsetParent || getOffsetParent;
2184
+ const getDimensionsFn = this.getDimensions;
2185
+ const floatingDimensions = await getDimensionsFn(data.floating);
2186
+ return {
2187
+ reference: getRectRelativeToOffsetParent(data.reference, await getOffsetParentFn(data.floating), data.strategy),
2188
+ floating: {
2189
+ x: 0,
2190
+ y: 0,
2191
+ width: floatingDimensions.width,
2192
+ height: floatingDimensions.height
2193
+ }
2194
+ };
2195
+ };
2196
+
2197
+ function isRTL(element) {
2198
+ return getComputedStyle$1(element).direction === 'rtl';
2199
+ }
2200
+
2201
+ const platform = {
2202
+ convertOffsetParentRelativeRectToViewportRelativeRect,
2203
+ getDocumentElement,
2204
+ getClippingRect,
2205
+ getOffsetParent,
2206
+ getElementRects,
2207
+ getClientRects,
2208
+ getDimensions,
2209
+ getScale,
2210
+ isElement,
2211
+ isRTL
2212
+ };
2213
+
2214
+ function rectsAreEqual(a, b) {
2215
+ return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;
2216
+ }
2217
+
2218
+ // https://samthor.au/2021/observing-dom/
2219
+ function observeMove(element, onMove) {
2220
+ let io = null;
2221
+ let timeoutId;
2222
+ const root = getDocumentElement(element);
2223
+ function cleanup() {
2224
+ var _io;
2225
+ clearTimeout(timeoutId);
2226
+ (_io = io) == null || _io.disconnect();
2227
+ io = null;
2228
+ }
2229
+ function refresh(skip, threshold) {
2230
+ if (skip === void 0) {
2231
+ skip = false;
2232
+ }
2233
+ if (threshold === void 0) {
2234
+ threshold = 1;
2235
+ }
2236
+ cleanup();
2237
+ const elementRectForRootMargin = element.getBoundingClientRect();
2238
+ const {
2239
+ left,
2240
+ top,
2241
+ width,
2242
+ height
2243
+ } = elementRectForRootMargin;
2244
+ if (!skip) {
2245
+ onMove();
2246
+ }
2247
+ if (!width || !height) {
2248
+ return;
2249
+ }
2250
+ const insetTop = floor(top);
2251
+ const insetRight = floor(root.clientWidth - (left + width));
2252
+ const insetBottom = floor(root.clientHeight - (top + height));
2253
+ const insetLeft = floor(left);
2254
+ const rootMargin = -insetTop + "px " + -insetRight + "px " + -insetBottom + "px " + -insetLeft + "px";
2255
+ const options = {
2256
+ rootMargin,
2257
+ threshold: max(0, min(1, threshold)) || 1
2258
+ };
2259
+ let isFirstUpdate = true;
2260
+ function handleObserve(entries) {
2261
+ const ratio = entries[0].intersectionRatio;
2262
+ if (ratio !== threshold) {
2263
+ if (!isFirstUpdate) {
2264
+ return refresh();
2265
+ }
2266
+ if (!ratio) {
2267
+ // If the reference is clipped, the ratio is 0. Throttle the refresh
2268
+ // to prevent an infinite loop of updates.
2269
+ timeoutId = setTimeout(() => {
2270
+ refresh(false, 1e-7);
2271
+ }, 1000);
2272
+ } else {
2273
+ refresh(false, ratio);
2274
+ }
2275
+ }
2276
+ if (ratio === 1 && !rectsAreEqual(elementRectForRootMargin, element.getBoundingClientRect())) {
2277
+ // It's possible that even though the ratio is reported as 1, the
2278
+ // element is not actually fully within the IntersectionObserver's root
2279
+ // area anymore. This can happen under performance constraints. This may
2280
+ // be a bug in the browser's IntersectionObserver implementation. To
2281
+ // work around this, we compare the element's bounding rect now with
2282
+ // what it was at the time we created the IntersectionObserver. If they
2283
+ // are not equal then the element moved, so we refresh.
2284
+ refresh();
2285
+ }
2286
+ isFirstUpdate = false;
2287
+ }
2288
+
2289
+ // Older browsers don't support a `document` as the root and will throw an
2290
+ // error.
2291
+ try {
2292
+ io = new IntersectionObserver(handleObserve, {
2293
+ ...options,
2294
+ // Handle <iframe>s
2295
+ root: root.ownerDocument
2296
+ });
2297
+ } catch (_e) {
2298
+ io = new IntersectionObserver(handleObserve, options);
2299
+ }
2300
+ io.observe(element);
2301
+ }
2302
+ refresh(true);
2303
+ return cleanup;
2304
+ }
2305
+
2306
+ /**
2307
+ * Automatically updates the position of the floating element when necessary.
2308
+ * Should only be called when the floating element is mounted on the DOM or
2309
+ * visible on the screen.
2310
+ * @returns cleanup function that should be invoked when the floating element is
2311
+ * removed from the DOM or hidden from the screen.
2312
+ * @see https://floating-ui.com/docs/autoUpdate
2313
+ */
2314
+ function autoUpdate(reference, floating, update, options) {
2315
+ if (options === void 0) {
2316
+ options = {};
2317
+ }
2318
+ const {
2319
+ ancestorScroll = true,
2320
+ ancestorResize = true,
2321
+ elementResize = typeof ResizeObserver === 'function',
2322
+ layoutShift = typeof IntersectionObserver === 'function',
2323
+ animationFrame = false
2324
+ } = options;
2325
+ const referenceEl = unwrapElement(reference);
2326
+ const ancestors = ancestorScroll || ancestorResize ? [...(referenceEl ? getOverflowAncestors(referenceEl) : []), ...getOverflowAncestors(floating)] : [];
2327
+ ancestors.forEach(ancestor => {
2328
+ ancestorScroll && ancestor.addEventListener('scroll', update, {
2329
+ passive: true
2330
+ });
2331
+ ancestorResize && ancestor.addEventListener('resize', update);
2332
+ });
2333
+ const cleanupIo = referenceEl && layoutShift ? observeMove(referenceEl, update) : null;
2334
+ let reobserveFrame = -1;
2335
+ let resizeObserver = null;
2336
+ if (elementResize) {
2337
+ resizeObserver = new ResizeObserver(_ref => {
2338
+ let [firstEntry] = _ref;
2339
+ if (firstEntry && firstEntry.target === referenceEl && resizeObserver) {
2340
+ // Prevent update loops when using the `size` middleware.
2341
+ // https://github.com/floating-ui/floating-ui/issues/1740
2342
+ resizeObserver.unobserve(floating);
2343
+ cancelAnimationFrame(reobserveFrame);
2344
+ reobserveFrame = requestAnimationFrame(() => {
2345
+ var _resizeObserver;
2346
+ (_resizeObserver = resizeObserver) == null || _resizeObserver.observe(floating);
2347
+ });
2348
+ }
2349
+ update();
2350
+ });
2351
+ if (referenceEl && !animationFrame) {
2352
+ resizeObserver.observe(referenceEl);
2353
+ }
2354
+ resizeObserver.observe(floating);
2355
+ }
2356
+ let frameId;
2357
+ let prevRefRect = animationFrame ? getBoundingClientRect(reference) : null;
2358
+ if (animationFrame) {
2359
+ frameLoop();
2360
+ }
2361
+ function frameLoop() {
2362
+ const nextRefRect = getBoundingClientRect(reference);
2363
+ if (prevRefRect && !rectsAreEqual(prevRefRect, nextRefRect)) {
2364
+ update();
2365
+ }
2366
+ prevRefRect = nextRefRect;
2367
+ frameId = requestAnimationFrame(frameLoop);
2368
+ }
2369
+ update();
2370
+ return () => {
2371
+ var _resizeObserver2;
2372
+ ancestors.forEach(ancestor => {
2373
+ ancestorScroll && ancestor.removeEventListener('scroll', update);
2374
+ ancestorResize && ancestor.removeEventListener('resize', update);
2375
+ });
2376
+ cleanupIo == null || cleanupIo();
2377
+ (_resizeObserver2 = resizeObserver) == null || _resizeObserver2.disconnect();
2378
+ resizeObserver = null;
2379
+ if (animationFrame) {
2380
+ cancelAnimationFrame(frameId);
2381
+ }
2382
+ };
2383
+ }
2384
+
2385
+ /**
2386
+ * Modifies the placement by translating the floating element along the
2387
+ * specified axes.
2388
+ * A number (shorthand for `mainAxis` or distance), or an axes configuration
2389
+ * object may be passed.
2390
+ * @see https://floating-ui.com/docs/offset
2391
+ */
2392
+ const offset$1 = offset$2;
2393
+
2394
+ /**
2395
+ * Optimizes the visibility of the floating element by shifting it in order to
2396
+ * keep it in view when it will overflow the clipping boundary.
2397
+ * @see https://floating-ui.com/docs/shift
2398
+ */
2399
+ const shift$1 = shift$2;
2400
+
2401
+ /**
2402
+ * Optimizes the visibility of the floating element by flipping the `placement`
2403
+ * in order to keep it in view when the preferred placement(s) will overflow the
2404
+ * clipping boundary. Alternative to `autoPlacement`.
2405
+ * @see https://floating-ui.com/docs/flip
2406
+ */
2407
+ const flip$1 = flip$2;
2408
+
2409
+ /**
2410
+ * Provides data that allows you to change the size of the floating element —
2411
+ * for instance, prevent it from overflowing the clipping boundary or match the
2412
+ * width of the reference element.
2413
+ * @see https://floating-ui.com/docs/size
2414
+ */
2415
+ const size$1 = size$2;
2416
+
2417
+ /**
2418
+ * Provides improved positioning for inline reference elements that can span
2419
+ * over multiple lines, such as hyperlinks or range selections.
2420
+ * @see https://floating-ui.com/docs/inline
2421
+ */
2422
+ const inline$1 = inline$2;
2423
+
2424
+ /**
2425
+ * Computes the `x` and `y` coordinates that will place the floating element
2426
+ * next to a given reference element.
2427
+ */
2428
+ const computePosition = (reference, floating, options) => {
2429
+ // This caches the expensive `getClippingElementAncestors` function so that
2430
+ // multiple lifecycle resets re-use the same result. It only lives for a
2431
+ // single call. If other functions become expensive, we can add them as well.
2432
+ const cache = new Map();
2433
+ const mergedOptions = {
2434
+ platform,
2435
+ ...options
2436
+ };
2437
+ const platformWithCache = {
2438
+ ...mergedOptions.platform,
2439
+ _c: cache
2440
+ };
2441
+ return computePosition$1(reference, floating, {
2442
+ ...mergedOptions,
2443
+ platform: platformWithCache
2444
+ });
2445
+ };
2446
+
2447
+ var isClient = typeof document !== 'undefined';
2448
+
2449
+ var noop = function noop() {};
2450
+ var index$1 = isClient ? useLayoutEffect : noop;
2451
+
2452
+ // Fork of `fast-deep-equal` that only does the comparisons we need and compares
2453
+ // functions
2454
+ function deepEqual(a, b) {
2455
+ if (a === b) {
2456
+ return true;
2457
+ }
2458
+ if (typeof a !== typeof b) {
2459
+ return false;
2460
+ }
2461
+ if (typeof a === 'function' && a.toString() === b.toString()) {
2462
+ return true;
2463
+ }
2464
+ let length;
2465
+ let i;
2466
+ let keys;
2467
+ if (a && b && typeof a === 'object') {
2468
+ if (Array.isArray(a)) {
2469
+ length = a.length;
2470
+ if (length !== b.length) return false;
2471
+ for (i = length; i-- !== 0;) {
2472
+ if (!deepEqual(a[i], b[i])) {
2473
+ return false;
2474
+ }
2475
+ }
2476
+ return true;
2477
+ }
2478
+ keys = Object.keys(a);
2479
+ length = keys.length;
2480
+ if (length !== Object.keys(b).length) {
2481
+ return false;
2482
+ }
2483
+ for (i = length; i-- !== 0;) {
2484
+ if (!{}.hasOwnProperty.call(b, keys[i])) {
2485
+ return false;
2486
+ }
2487
+ }
2488
+ for (i = length; i-- !== 0;) {
2489
+ const key = keys[i];
2490
+ if (key === '_owner' && a.$$typeof) {
2491
+ continue;
2492
+ }
2493
+ if (!deepEqual(a[key], b[key])) {
2494
+ return false;
2495
+ }
2496
+ }
2497
+ return true;
2498
+ }
2499
+ return a !== a && b !== b;
2500
+ }
2501
+
2502
+ function getDPR(element) {
2503
+ if (typeof window === 'undefined') {
2504
+ return 1;
2505
+ }
2506
+ const win = element.ownerDocument.defaultView || window;
2507
+ return win.devicePixelRatio || 1;
2508
+ }
2509
+
2510
+ function roundByDPR(element, value) {
2511
+ const dpr = getDPR(element);
2512
+ return Math.round(value * dpr) / dpr;
2513
+ }
2514
+
2515
+ function useLatestRef$1(value) {
2516
+ const ref = React.useRef(value);
2517
+ index$1(() => {
2518
+ ref.current = value;
2519
+ });
2520
+ return ref;
2521
+ }
2522
+
2523
+ /**
2524
+ * Provides data to position a floating element.
2525
+ * @see https://floating-ui.com/docs/useFloating
2526
+ */
2527
+ function useFloating$1(options) {
2528
+ if (options === void 0) {
2529
+ options = {};
2530
+ }
2531
+ const {
2532
+ placement = 'bottom',
2533
+ strategy = 'absolute',
2534
+ middleware = [],
2535
+ platform,
2536
+ elements: {
2537
+ reference: externalReference,
2538
+ floating: externalFloating
2539
+ } = {},
2540
+ transform = true,
2541
+ whileElementsMounted,
2542
+ open
2543
+ } = options;
2544
+ const [data, setData] = React.useState({
2545
+ x: 0,
2546
+ y: 0,
2547
+ strategy,
2548
+ placement,
2549
+ middlewareData: {},
2550
+ isPositioned: false
2551
+ });
2552
+ const [latestMiddleware, setLatestMiddleware] = React.useState(middleware);
2553
+ if (!deepEqual(latestMiddleware, middleware)) {
2554
+ setLatestMiddleware(middleware);
2555
+ }
2556
+ const [_reference, _setReference] = React.useState(null);
2557
+ const [_floating, _setFloating] = React.useState(null);
2558
+ const setReference = React.useCallback(node => {
2559
+ if (node !== referenceRef.current) {
2560
+ referenceRef.current = node;
2561
+ _setReference(node);
2562
+ }
2563
+ }, []);
2564
+ const setFloating = React.useCallback(node => {
2565
+ if (node !== floatingRef.current) {
2566
+ floatingRef.current = node;
2567
+ _setFloating(node);
2568
+ }
2569
+ }, []);
2570
+ const referenceEl = externalReference || _reference;
2571
+ const floatingEl = externalFloating || _floating;
2572
+ const referenceRef = React.useRef(null);
2573
+ const floatingRef = React.useRef(null);
2574
+ const dataRef = React.useRef(data);
2575
+ const hasWhileElementsMounted = whileElementsMounted != null;
2576
+ const whileElementsMountedRef = useLatestRef$1(whileElementsMounted);
2577
+ const platformRef = useLatestRef$1(platform);
2578
+ const openRef = useLatestRef$1(open);
2579
+ const update = React.useCallback(() => {
2580
+ if (!referenceRef.current || !floatingRef.current) {
2581
+ return;
2582
+ }
2583
+ const config = {
2584
+ placement,
2585
+ strategy,
2586
+ middleware: latestMiddleware
2587
+ };
2588
+ if (platformRef.current) {
2589
+ config.platform = platformRef.current;
2590
+ }
2591
+ computePosition(referenceRef.current, floatingRef.current, config).then(data => {
2592
+ const fullData = {
2593
+ ...data,
2594
+ // The floating element's position may be recomputed while it's closed
2595
+ // but still mounted (such as when transitioning out). To ensure
2596
+ // `isPositioned` will be `false` initially on the next open, avoid
2597
+ // setting it to `true` when `open === false` (must be specified).
2598
+ isPositioned: openRef.current !== false
2599
+ };
2600
+ if (isMountedRef.current && !deepEqual(dataRef.current, fullData)) {
2601
+ dataRef.current = fullData;
2602
+ ReactDOM.flushSync(() => {
2603
+ setData(fullData);
2604
+ });
2605
+ }
2606
+ });
2607
+ }, [latestMiddleware, placement, strategy, platformRef, openRef]);
2608
+ index$1(() => {
2609
+ if (open === false && dataRef.current.isPositioned) {
2610
+ dataRef.current.isPositioned = false;
2611
+ setData(data => ({
2612
+ ...data,
2613
+ isPositioned: false
2614
+ }));
2615
+ }
2616
+ }, [open]);
2617
+ const isMountedRef = React.useRef(false);
2618
+ index$1(() => {
2619
+ isMountedRef.current = true;
2620
+ return () => {
2621
+ isMountedRef.current = false;
2622
+ };
2623
+ }, []);
2624
+ index$1(() => {
2625
+ if (referenceEl) referenceRef.current = referenceEl;
2626
+ if (floatingEl) floatingRef.current = floatingEl;
2627
+ if (referenceEl && floatingEl) {
2628
+ if (whileElementsMountedRef.current) {
2629
+ return whileElementsMountedRef.current(referenceEl, floatingEl, update);
2630
+ }
2631
+ update();
2632
+ }
2633
+ }, [referenceEl, floatingEl, update, whileElementsMountedRef, hasWhileElementsMounted]);
2634
+ const refs = React.useMemo(() => ({
2635
+ reference: referenceRef,
2636
+ floating: floatingRef,
2637
+ setReference,
2638
+ setFloating
2639
+ }), [setReference, setFloating]);
2640
+ const elements = React.useMemo(() => ({
2641
+ reference: referenceEl,
2642
+ floating: floatingEl
2643
+ }), [referenceEl, floatingEl]);
2644
+ const floatingStyles = React.useMemo(() => {
2645
+ const initialStyles = {
2646
+ position: strategy,
2647
+ left: 0,
2648
+ top: 0
2649
+ };
2650
+ if (!elements.floating) {
2651
+ return initialStyles;
2652
+ }
2653
+ const x = roundByDPR(elements.floating, data.x);
2654
+ const y = roundByDPR(elements.floating, data.y);
2655
+ if (transform) {
2656
+ return {
2657
+ ...initialStyles,
2658
+ transform: "translate(" + x + "px, " + y + "px)",
2659
+ ...(getDPR(elements.floating) >= 1.5 && {
2660
+ willChange: 'transform'
2661
+ })
2662
+ };
2663
+ }
2664
+ return {
2665
+ position: strategy,
2666
+ left: x,
2667
+ top: y
2668
+ };
2669
+ }, [strategy, transform, elements.floating, data.x, data.y]);
2670
+ return React.useMemo(() => ({
2671
+ ...data,
2672
+ update,
2673
+ refs,
2674
+ elements,
2675
+ floatingStyles
2676
+ }), [data, update, refs, elements, floatingStyles]);
2677
+ }
2678
+
2679
+ /**
2680
+ * Modifies the placement by translating the floating element along the
2681
+ * specified axes.
2682
+ * A number (shorthand for `mainAxis` or distance), or an axes configuration
2683
+ * object may be passed.
2684
+ * @see https://floating-ui.com/docs/offset
2685
+ */
2686
+ const offset = (options, deps) => ({
2687
+ ...offset$1(options),
2688
+ options: [options, deps]
2689
+ });
2690
+
2691
+ /**
2692
+ * Optimizes the visibility of the floating element by shifting it in order to
2693
+ * keep it in view when it will overflow the clipping boundary.
2694
+ * @see https://floating-ui.com/docs/shift
2695
+ */
2696
+ const shift = (options, deps) => ({
2697
+ ...shift$1(options),
2698
+ options: [options, deps]
2699
+ });
2700
+
2701
+ /**
2702
+ * Optimizes the visibility of the floating element by flipping the `placement`
2703
+ * in order to keep it in view when the preferred placement(s) will overflow the
2704
+ * clipping boundary. Alternative to `autoPlacement`.
2705
+ * @see https://floating-ui.com/docs/flip
2706
+ */
2707
+ const flip = (options, deps) => ({
2708
+ ...flip$1(options),
2709
+ options: [options, deps]
2710
+ });
2711
+
2712
+ /**
2713
+ * Provides data that allows you to change the size of the floating element —
2714
+ * for instance, prevent it from overflowing the clipping boundary or match the
2715
+ * width of the reference element.
2716
+ * @see https://floating-ui.com/docs/size
2717
+ */
2718
+ const size = (options, deps) => ({
2719
+ ...size$1(options),
2720
+ options: [options, deps]
2721
+ });
2722
+
2723
+ /**
2724
+ * Provides improved positioning for inline reference elements that can span
2725
+ * over multiple lines, such as hyperlinks or range selections.
2726
+ * @see https://floating-ui.com/docs/inline
2727
+ */
2728
+ const inline = (options, deps) => ({
2729
+ ...inline$1(options),
2730
+ options: [options, deps]
2731
+ });
2732
+
2733
+ /**
2734
+ * Merges an array of refs into a single memoized callback ref or `null`.
2735
+ * @see https://floating-ui.com/docs/react-utils#usemergerefs
2736
+ */
2737
+ function useMergeRefs(refs) {
2738
+ return React.useMemo(() => {
2739
+ if (refs.every(ref => ref == null)) {
2740
+ return null;
2741
+ }
2742
+ return value => {
2743
+ refs.forEach(ref => {
2744
+ if (typeof ref === 'function') {
2745
+ ref(value);
2746
+ } else if (ref != null) {
2747
+ ref.current = value;
2748
+ }
2749
+ });
2750
+ };
2751
+ // eslint-disable-next-line react-hooks/exhaustive-deps
2752
+ }, refs);
2753
+ }
2754
+
2755
+ // https://github.com/mui/material-ui/issues/41190#issuecomment-2040873379
2756
+ const SafeReact = {
2757
+ ...React
2758
+ };
2759
+
2760
+ const useInsertionEffect = SafeReact.useInsertionEffect;
2761
+ const useSafeInsertionEffect = useInsertionEffect || (fn => fn());
2762
+ function useEffectEvent(callback) {
2763
+ const ref = React.useRef(() => {
2764
+ {
2765
+ throw new Error('Cannot call an event handler while rendering.');
2766
+ }
2767
+ });
2768
+ useSafeInsertionEffect(() => {
2769
+ ref.current = callback;
2770
+ });
2771
+ return React.useCallback(function () {
2772
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
2773
+ args[_key] = arguments[_key];
2774
+ }
2775
+ return ref.current == null ? void 0 : ref.current(...args);
2776
+ }, []);
2777
+ }
2778
+
2779
+ var index = typeof document !== 'undefined' ? useLayoutEffect : useEffect;
2780
+
2781
+ function _extends() {
2782
+ _extends = Object.assign ? Object.assign.bind() : function (target) {
2783
+ for (var i = 1; i < arguments.length; i++) {
2784
+ var source = arguments[i];
2785
+ for (var key in source) {
2786
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
2787
+ target[key] = source[key];
2788
+ }
2789
+ }
2790
+ }
2791
+ return target;
2792
+ };
2793
+ return _extends.apply(this, arguments);
2794
+ }
2795
+
2796
+ let serverHandoffComplete = false;
2797
+ let count = 0;
2798
+ const genId = () => // Ensure the id is unique with multiple independent versions of Floating UI
2799
+ // on <React 18
2800
+ "floating-ui-" + Math.random().toString(36).slice(2, 6) + count++;
2801
+ function useFloatingId() {
2802
+ const [id, setId] = React.useState(() => serverHandoffComplete ? genId() : undefined);
2803
+ index(() => {
2804
+ if (id == null) {
2805
+ setId(genId());
2806
+ }
2807
+ // eslint-disable-next-line react-hooks/exhaustive-deps
2808
+ }, []);
2809
+ React.useEffect(() => {
2810
+ serverHandoffComplete = true;
2811
+ }, []);
2812
+ return id;
2813
+ }
2814
+ const useReactId = SafeReact.useId;
2815
+
2816
+ /**
2817
+ * Uses React 18's built-in `useId()` when available, or falls back to a
2818
+ * slightly less performant (requiring a double render) implementation for
2819
+ * earlier React versions.
2820
+ * @see https://floating-ui.com/docs/react-utils#useid
2821
+ */
2822
+ const useId = useReactId || useFloatingId;
2823
+
2824
+ let devMessageSet;
2825
+ {
2826
+ devMessageSet = /*#__PURE__*/new Set();
2827
+ }
2828
+ function error() {
2829
+ var _devMessageSet3;
2830
+ for (var _len2 = arguments.length, messages = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
2831
+ messages[_key2] = arguments[_key2];
2832
+ }
2833
+ const message = "Floating UI: " + messages.join(' ');
2834
+ if (!((_devMessageSet3 = devMessageSet) != null && _devMessageSet3.has(message))) {
2835
+ var _devMessageSet4;
2836
+ (_devMessageSet4 = devMessageSet) == null || _devMessageSet4.add(message);
2837
+ console.error(message);
2838
+ }
2839
+ }
2840
+
2841
+ function createPubSub() {
2842
+ const map = new Map();
2843
+ return {
2844
+ emit(event, data) {
2845
+ var _map$get;
2846
+ (_map$get = map.get(event)) == null || _map$get.forEach(handler => handler(data));
2847
+ },
2848
+ on(event, listener) {
2849
+ map.set(event, [...(map.get(event) || []), listener]);
2850
+ },
2851
+ off(event, listener) {
2852
+ var _map$get2;
2853
+ map.set(event, ((_map$get2 = map.get(event)) == null ? void 0 : _map$get2.filter(l => l !== listener)) || []);
2854
+ }
2855
+ };
2856
+ }
2857
+
2858
+ const FloatingNodeContext = /*#__PURE__*/React.createContext(null);
2859
+ const FloatingTreeContext = /*#__PURE__*/React.createContext(null);
2860
+
2861
+ /**
2862
+ * Returns the parent node id for nested floating elements, if available.
2863
+ * Returns `null` for top-level floating elements.
2864
+ */
2865
+ const useFloatingParentNodeId = () => {
2866
+ var _React$useContext;
2867
+ return ((_React$useContext = React.useContext(FloatingNodeContext)) == null ? void 0 : _React$useContext.id) || null;
2868
+ };
2869
+
2870
+ /**
2871
+ * Returns the nearest floating tree context, if available.
2872
+ */
2873
+ const useFloatingTree = () => React.useContext(FloatingTreeContext);
2874
+
2875
+ function createAttribute(name) {
2876
+ return "data-floating-ui-" + name;
2877
+ }
2878
+
2879
+ function useLatestRef(value) {
2880
+ const ref = useRef(value);
2881
+ index(() => {
2882
+ ref.current = value;
2883
+ });
2884
+ return ref;
2885
+ }
2886
+
2887
+ let rafId = 0;
2888
+ function enqueueFocus(el, options) {
2889
+ if (options === void 0) {
2890
+ options = {};
2891
+ }
2892
+ const {
2893
+ preventScroll = false,
2894
+ cancelPrevious = true,
2895
+ sync = false
2896
+ } = options;
2897
+ cancelPrevious && cancelAnimationFrame(rafId);
2898
+ const exec = () => el == null ? void 0 : el.focus({
2899
+ preventScroll
2900
+ });
2901
+ if (sync) {
2902
+ exec();
2903
+ } else {
2904
+ rafId = requestAnimationFrame(exec);
2905
+ }
2906
+ }
2907
+
2908
+ function getAncestors(nodes, id) {
2909
+ var _nodes$find;
2910
+ let allAncestors = [];
2911
+ let currentParentId = (_nodes$find = nodes.find(node => node.id === id)) == null ? void 0 : _nodes$find.parentId;
2912
+ while (currentParentId) {
2913
+ const currentNode = nodes.find(node => node.id === currentParentId);
2914
+ currentParentId = currentNode == null ? void 0 : currentNode.parentId;
2915
+ if (currentNode) {
2916
+ allAncestors = allAncestors.concat(currentNode);
2917
+ }
2918
+ }
2919
+ return allAncestors;
2920
+ }
2921
+
2922
+ function getChildren(nodes, id) {
2923
+ let allChildren = nodes.filter(node => {
2924
+ var _node$context;
2925
+ return node.parentId === id && ((_node$context = node.context) == null ? void 0 : _node$context.open);
2926
+ });
2927
+ let currentChildren = allChildren;
2928
+ while (currentChildren.length) {
2929
+ currentChildren = nodes.filter(node => {
2930
+ var _currentChildren;
2931
+ return (_currentChildren = currentChildren) == null ? void 0 : _currentChildren.some(n => {
2932
+ var _node$context2;
2933
+ return node.parentId === n.id && ((_node$context2 = node.context) == null ? void 0 : _node$context2.open);
2934
+ });
2935
+ });
2936
+ allChildren = allChildren.concat(currentChildren);
2937
+ }
2938
+ return allChildren;
2939
+ }
2940
+
2941
+ // Modified to add conditional `aria-hidden` support:
2942
+ // https://github.com/theKashey/aria-hidden/blob/9220c8f4a4fd35f63bee5510a9f41a37264382d4/src/index.ts
2943
+ let counterMap = /*#__PURE__*/new WeakMap();
2944
+ let uncontrolledElementsSet = /*#__PURE__*/new WeakSet();
2945
+ let markerMap = {};
2946
+ let lockCount$1 = 0;
2947
+ const supportsInert = () => typeof HTMLElement !== 'undefined' && 'inert' in HTMLElement.prototype;
2948
+ const unwrapHost = node => node && (node.host || unwrapHost(node.parentNode));
2949
+ const correctElements = (parent, targets) => targets.map(target => {
2950
+ if (parent.contains(target)) {
2951
+ return target;
2952
+ }
2953
+ const correctedTarget = unwrapHost(target);
2954
+ if (parent.contains(correctedTarget)) {
2955
+ return correctedTarget;
2956
+ }
2957
+ return null;
2958
+ }).filter(x => x != null);
2959
+ function applyAttributeToOthers(uncorrectedAvoidElements, body, ariaHidden, inert) {
2960
+ const markerName = 'data-floating-ui-inert';
2961
+ const controlAttribute = inert ? 'inert' : ariaHidden ? 'aria-hidden' : null;
2962
+ const avoidElements = correctElements(body, uncorrectedAvoidElements);
2963
+ const elementsToKeep = new Set();
2964
+ const elementsToStop = new Set(avoidElements);
2965
+ const hiddenElements = [];
2966
+ if (!markerMap[markerName]) {
2967
+ markerMap[markerName] = new WeakMap();
2968
+ }
2969
+ const markerCounter = markerMap[markerName];
2970
+ avoidElements.forEach(keep);
2971
+ deep(body);
2972
+ elementsToKeep.clear();
2973
+ function keep(el) {
2974
+ if (!el || elementsToKeep.has(el)) {
2975
+ return;
2976
+ }
2977
+ elementsToKeep.add(el);
2978
+ el.parentNode && keep(el.parentNode);
2979
+ }
2980
+ function deep(parent) {
2981
+ if (!parent || elementsToStop.has(parent)) {
2982
+ return;
2983
+ }
2984
+ [].forEach.call(parent.children, node => {
2985
+ if (getNodeName(node) === 'script') return;
2986
+ if (elementsToKeep.has(node)) {
2987
+ deep(node);
2988
+ } else {
2989
+ const attr = controlAttribute ? node.getAttribute(controlAttribute) : null;
2990
+ const alreadyHidden = attr !== null && attr !== 'false';
2991
+ const counterValue = (counterMap.get(node) || 0) + 1;
2992
+ const markerValue = (markerCounter.get(node) || 0) + 1;
2993
+ counterMap.set(node, counterValue);
2994
+ markerCounter.set(node, markerValue);
2995
+ hiddenElements.push(node);
2996
+ if (counterValue === 1 && alreadyHidden) {
2997
+ uncontrolledElementsSet.add(node);
2998
+ }
2999
+ if (markerValue === 1) {
3000
+ node.setAttribute(markerName, '');
3001
+ }
3002
+ if (!alreadyHidden && controlAttribute) {
3003
+ node.setAttribute(controlAttribute, 'true');
3004
+ }
3005
+ }
3006
+ });
3007
+ }
3008
+ lockCount$1++;
3009
+ return () => {
3010
+ hiddenElements.forEach(element => {
3011
+ const counterValue = (counterMap.get(element) || 0) - 1;
3012
+ const markerValue = (markerCounter.get(element) || 0) - 1;
3013
+ counterMap.set(element, counterValue);
3014
+ markerCounter.set(element, markerValue);
3015
+ if (!counterValue) {
3016
+ if (!uncontrolledElementsSet.has(element) && controlAttribute) {
3017
+ element.removeAttribute(controlAttribute);
3018
+ }
3019
+ uncontrolledElementsSet.delete(element);
3020
+ }
3021
+ if (!markerValue) {
3022
+ element.removeAttribute(markerName);
3023
+ }
3024
+ });
3025
+ lockCount$1--;
3026
+ if (!lockCount$1) {
3027
+ counterMap = new WeakMap();
3028
+ counterMap = new WeakMap();
3029
+ uncontrolledElementsSet = new WeakSet();
3030
+ markerMap = {};
3031
+ }
3032
+ };
3033
+ }
3034
+ function markOthers(avoidElements, ariaHidden, inert) {
3035
+ if (ariaHidden === void 0) {
3036
+ ariaHidden = false;
3037
+ }
3038
+ if (inert === void 0) {
3039
+ inert = false;
3040
+ }
3041
+ const body = getDocument(avoidElements[0]).body;
3042
+ return applyAttributeToOthers(avoidElements.concat(Array.from(body.querySelectorAll('[aria-live]'))), body, ariaHidden, inert);
3043
+ }
3044
+
3045
+ const getTabbableOptions = () => ({
3046
+ getShadowRoot: true,
3047
+ displayCheck:
3048
+ // JSDOM does not support the `tabbable` library. To solve this we can
3049
+ // check if `ResizeObserver` is a real function (not polyfilled), which
3050
+ // determines if the current environment is JSDOM-like.
3051
+ typeof ResizeObserver === 'function' && ResizeObserver.toString().includes('[native code]') ? 'full' : 'none'
3052
+ });
3053
+ function getTabbableIn(container, direction) {
3054
+ const allTabbable = tabbable(container, getTabbableOptions());
3055
+ if (direction === 'prev') {
3056
+ allTabbable.reverse();
3057
+ }
3058
+ const activeIndex = allTabbable.indexOf(activeElement(getDocument(container)));
3059
+ const nextTabbableElements = allTabbable.slice(activeIndex + 1);
3060
+ return nextTabbableElements[0];
3061
+ }
3062
+ function getNextTabbable() {
3063
+ return getTabbableIn(document.body, 'next');
3064
+ }
3065
+ function getPreviousTabbable() {
3066
+ return getTabbableIn(document.body, 'prev');
3067
+ }
3068
+ function isOutsideEvent(event, container) {
3069
+ const containerElement = container || event.currentTarget;
3070
+ const relatedTarget = event.relatedTarget;
3071
+ return !relatedTarget || !contains(containerElement, relatedTarget);
3072
+ }
3073
+ function disableFocusInside(container) {
3074
+ const tabbableElements = tabbable(container, getTabbableOptions());
3075
+ tabbableElements.forEach(element => {
3076
+ element.dataset.tabindex = element.getAttribute('tabindex') || '';
3077
+ element.setAttribute('tabindex', '-1');
3078
+ });
3079
+ }
3080
+ function enableFocusInside(container) {
3081
+ const elements = container.querySelectorAll('[data-tabindex]');
3082
+ elements.forEach(element => {
3083
+ const tabindex = element.dataset.tabindex;
3084
+ delete element.dataset.tabindex;
3085
+ if (tabindex) {
3086
+ element.setAttribute('tabindex', tabindex);
3087
+ } else {
3088
+ element.removeAttribute('tabindex');
3089
+ }
3090
+ });
3091
+ }
3092
+
3093
+ // See Diego Haz's Sandbox for making this logic work well on Safari/iOS:
3094
+ // https://codesandbox.io/s/tabbable-portal-f4tng?file=/src/FocusTrap.tsx
3095
+
3096
+ const HIDDEN_STYLES = {
3097
+ border: 0,
3098
+ clip: 'rect(0 0 0 0)',
3099
+ height: '1px',
3100
+ margin: '-1px',
3101
+ overflow: 'hidden',
3102
+ padding: 0,
3103
+ position: 'fixed',
3104
+ whiteSpace: 'nowrap',
3105
+ width: '1px',
3106
+ top: 0,
3107
+ left: 0
3108
+ };
3109
+ let timeoutId;
3110
+ function setActiveElementOnTab(event) {
3111
+ if (event.key === 'Tab') {
3112
+ event.target;
3113
+ clearTimeout(timeoutId);
3114
+ }
3115
+ }
3116
+ const FocusGuard = /*#__PURE__*/React.forwardRef(function FocusGuard(props, ref) {
3117
+ const [role, setRole] = React.useState();
3118
+ index(() => {
3119
+ if (isSafari()) {
3120
+ // Unlike other screen readers such as NVDA and JAWS, the virtual cursor
3121
+ // on VoiceOver does trigger the onFocus event, so we can use the focus
3122
+ // trap element. On Safari, only buttons trigger the onFocus event.
3123
+ // NB: "group" role in the Sandbox no longer appears to work, must be a
3124
+ // button role.
3125
+ setRole('button');
3126
+ }
3127
+ document.addEventListener('keydown', setActiveElementOnTab);
3128
+ return () => {
3129
+ document.removeEventListener('keydown', setActiveElementOnTab);
3130
+ };
3131
+ }, []);
3132
+ const restProps = {
3133
+ ref,
3134
+ tabIndex: 0,
3135
+ // Role is only for VoiceOver
3136
+ role,
3137
+ 'aria-hidden': role ? undefined : true,
3138
+ [createAttribute('focus-guard')]: '',
3139
+ style: HIDDEN_STYLES
3140
+ };
3141
+ return /*#__PURE__*/React.createElement("span", _extends({}, props, restProps));
3142
+ });
3143
+
3144
+ const PortalContext = /*#__PURE__*/React.createContext(null);
3145
+ const attr = /*#__PURE__*/createAttribute('portal');
3146
+ /**
3147
+ * @see https://floating-ui.com/docs/FloatingPortal#usefloatingportalnode
3148
+ */
3149
+ function useFloatingPortalNode(props) {
3150
+ if (props === void 0) {
3151
+ props = {};
3152
+ }
3153
+ const {
3154
+ id,
3155
+ root
3156
+ } = props;
3157
+ const uniqueId = useId();
3158
+ const portalContext = usePortalContext();
3159
+ const [portalNode, setPortalNode] = React.useState(null);
3160
+ const portalNodeRef = React.useRef(null);
3161
+ index(() => {
3162
+ return () => {
3163
+ portalNode == null || portalNode.remove();
3164
+ // Allow the subsequent layout effects to create a new node on updates.
3165
+ // The portal node will still be cleaned up on unmount.
3166
+ // https://github.com/floating-ui/floating-ui/issues/2454
3167
+ queueMicrotask(() => {
3168
+ portalNodeRef.current = null;
3169
+ });
3170
+ };
3171
+ }, [portalNode]);
3172
+ index(() => {
3173
+ // Wait for the uniqueId to be generated before creating the portal node in
3174
+ // React <18 (using `useFloatingId` instead of the native `useId`).
3175
+ // https://github.com/floating-ui/floating-ui/issues/2778
3176
+ if (!uniqueId) return;
3177
+ if (portalNodeRef.current) return;
3178
+ const existingIdRoot = id ? document.getElementById(id) : null;
3179
+ if (!existingIdRoot) return;
3180
+ const subRoot = document.createElement('div');
3181
+ subRoot.id = uniqueId;
3182
+ subRoot.setAttribute(attr, '');
3183
+ existingIdRoot.appendChild(subRoot);
3184
+ portalNodeRef.current = subRoot;
3185
+ setPortalNode(subRoot);
3186
+ }, [id, uniqueId]);
3187
+ index(() => {
3188
+ // Wait for the root to exist before creating the portal node. The root must
3189
+ // be stored in state, not a ref, for this to work reactively.
3190
+ if (root === null) return;
3191
+ if (!uniqueId) return;
3192
+ if (portalNodeRef.current) return;
3193
+ let container = root || (portalContext == null ? void 0 : portalContext.portalNode);
3194
+ if (container && !isElement(container)) container = container.current;
3195
+ container = container || document.body;
3196
+ let idWrapper = null;
3197
+ if (id) {
3198
+ idWrapper = document.createElement('div');
3199
+ idWrapper.id = id;
3200
+ container.appendChild(idWrapper);
3201
+ }
3202
+ const subRoot = document.createElement('div');
3203
+ subRoot.id = uniqueId;
3204
+ subRoot.setAttribute(attr, '');
3205
+ container = idWrapper || container;
3206
+ container.appendChild(subRoot);
3207
+ portalNodeRef.current = subRoot;
3208
+ setPortalNode(subRoot);
3209
+ }, [id, root, uniqueId, portalContext]);
3210
+ return portalNode;
3211
+ }
3212
+ /**
3213
+ * Portals the floating element into a given container element — by default,
3214
+ * outside of the app root and into the body.
3215
+ * This is necessary to ensure the floating element can appear outside any
3216
+ * potential parent containers that cause clipping (such as `overflow: hidden`),
3217
+ * while retaining its location in the React tree.
3218
+ * @see https://floating-ui.com/docs/FloatingPortal
3219
+ */
3220
+ function FloatingPortal(props) {
3221
+ const {
3222
+ children,
3223
+ id,
3224
+ root,
3225
+ preserveTabOrder = true
3226
+ } = props;
3227
+ const portalNode = useFloatingPortalNode({
3228
+ id,
3229
+ root
3230
+ });
3231
+ const [focusManagerState, setFocusManagerState] = React.useState(null);
3232
+ const beforeOutsideRef = React.useRef(null);
3233
+ const afterOutsideRef = React.useRef(null);
3234
+ const beforeInsideRef = React.useRef(null);
3235
+ const afterInsideRef = React.useRef(null);
3236
+ const modal = focusManagerState == null ? void 0 : focusManagerState.modal;
3237
+ const open = focusManagerState == null ? void 0 : focusManagerState.open;
3238
+ const shouldRenderGuards =
3239
+ // The FocusManager and therefore floating element are currently open/
3240
+ // rendered.
3241
+ !!focusManagerState &&
3242
+ // Guards are only for non-modal focus management.
3243
+ !focusManagerState.modal &&
3244
+ // Don't render if unmount is transitioning.
3245
+ focusManagerState.open && preserveTabOrder && !!(root || portalNode);
3246
+
3247
+ // https://codesandbox.io/s/tabbable-portal-f4tng?file=/src/TabbablePortal.tsx
3248
+ React.useEffect(() => {
3249
+ if (!portalNode || !preserveTabOrder || modal) {
3250
+ return;
3251
+ }
3252
+
3253
+ // Make sure elements inside the portal element are tabbable only when the
3254
+ // portal has already been focused, either by tabbing into a focus trap
3255
+ // element outside or using the mouse.
3256
+ function onFocus(event) {
3257
+ if (portalNode && isOutsideEvent(event)) {
3258
+ const focusing = event.type === 'focusin';
3259
+ const manageFocus = focusing ? enableFocusInside : disableFocusInside;
3260
+ manageFocus(portalNode);
3261
+ }
3262
+ }
3263
+ // Listen to the event on the capture phase so they run before the focus
3264
+ // trap elements onFocus prop is called.
3265
+ portalNode.addEventListener('focusin', onFocus, true);
3266
+ portalNode.addEventListener('focusout', onFocus, true);
3267
+ return () => {
3268
+ portalNode.removeEventListener('focusin', onFocus, true);
3269
+ portalNode.removeEventListener('focusout', onFocus, true);
3270
+ };
3271
+ }, [portalNode, preserveTabOrder, modal]);
3272
+ React.useEffect(() => {
3273
+ if (!portalNode) return;
3274
+ if (open) return;
3275
+ enableFocusInside(portalNode);
3276
+ }, [open, portalNode]);
3277
+ return /*#__PURE__*/React.createElement(PortalContext.Provider, {
3278
+ value: React.useMemo(() => ({
3279
+ preserveTabOrder,
3280
+ beforeOutsideRef,
3281
+ afterOutsideRef,
3282
+ beforeInsideRef,
3283
+ afterInsideRef,
3284
+ portalNode,
3285
+ setFocusManagerState
3286
+ }), [preserveTabOrder, portalNode])
3287
+ }, shouldRenderGuards && portalNode && /*#__PURE__*/React.createElement(FocusGuard, {
3288
+ "data-type": "outside",
3289
+ ref: beforeOutsideRef,
3290
+ onFocus: event => {
3291
+ if (isOutsideEvent(event, portalNode)) {
3292
+ var _beforeInsideRef$curr;
3293
+ (_beforeInsideRef$curr = beforeInsideRef.current) == null || _beforeInsideRef$curr.focus();
3294
+ } else {
3295
+ const prevTabbable = getPreviousTabbable() || (focusManagerState == null ? void 0 : focusManagerState.refs.domReference.current);
3296
+ prevTabbable == null || prevTabbable.focus();
3297
+ }
3298
+ }
3299
+ }), shouldRenderGuards && portalNode && /*#__PURE__*/React.createElement("span", {
3300
+ "aria-owns": portalNode.id,
3301
+ style: HIDDEN_STYLES
3302
+ }), portalNode && /*#__PURE__*/ReactDOM.createPortal(children, portalNode), shouldRenderGuards && portalNode && /*#__PURE__*/React.createElement(FocusGuard, {
3303
+ "data-type": "outside",
3304
+ ref: afterOutsideRef,
3305
+ onFocus: event => {
3306
+ if (isOutsideEvent(event, portalNode)) {
3307
+ var _afterInsideRef$curre;
3308
+ (_afterInsideRef$curre = afterInsideRef.current) == null || _afterInsideRef$curre.focus();
3309
+ } else {
3310
+ const nextTabbable = getNextTabbable() || (focusManagerState == null ? void 0 : focusManagerState.refs.domReference.current);
3311
+ nextTabbable == null || nextTabbable.focus();
3312
+ (focusManagerState == null ? void 0 : focusManagerState.closeOnFocusOut) && (focusManagerState == null ? void 0 : focusManagerState.onOpenChange(false, event.nativeEvent, 'focus-out'));
3313
+ }
3314
+ }
3315
+ }));
3316
+ }
3317
+ const usePortalContext = () => React.useContext(PortalContext);
3318
+
3319
+ const FOCUSABLE_ATTRIBUTE = 'data-floating-ui-focusable';
3320
+ function getFloatingFocusElement(floatingElement) {
3321
+ if (!floatingElement) {
3322
+ return null;
3323
+ }
3324
+ // Try to find the element that has `{...getFloatingProps()}` spread on it.
3325
+ // This indicates the floating element is acting as a positioning wrapper, and
3326
+ // so focus should be managed on the child element with the event handlers and
3327
+ // aria props.
3328
+ return floatingElement.hasAttribute(FOCUSABLE_ATTRIBUTE) ? floatingElement : floatingElement.querySelector("[" + FOCUSABLE_ATTRIBUTE + "]") || floatingElement;
3329
+ }
3330
+
3331
+ const LIST_LIMIT = 20;
3332
+ let previouslyFocusedElements = [];
3333
+ function addPreviouslyFocusedElement(element) {
3334
+ previouslyFocusedElements = previouslyFocusedElements.filter(el => el.isConnected);
3335
+ let tabbableEl = element;
3336
+ if (!tabbableEl || getNodeName(tabbableEl) === 'body') return;
3337
+ if (!isTabbable(tabbableEl, getTabbableOptions())) {
3338
+ const tabbableChild = tabbable(tabbableEl, getTabbableOptions())[0];
3339
+ if (tabbableChild) {
3340
+ tabbableEl = tabbableChild;
3341
+ }
3342
+ }
3343
+ previouslyFocusedElements.push(tabbableEl);
3344
+ if (previouslyFocusedElements.length > LIST_LIMIT) {
3345
+ previouslyFocusedElements = previouslyFocusedElements.slice(-LIST_LIMIT);
3346
+ }
3347
+ }
3348
+ function getPreviouslyFocusedElement() {
3349
+ return previouslyFocusedElements.slice().reverse().find(el => el.isConnected);
3350
+ }
3351
+ const VisuallyHiddenDismiss = /*#__PURE__*/React.forwardRef(function VisuallyHiddenDismiss(props, ref) {
3352
+ return /*#__PURE__*/React.createElement("button", _extends({}, props, {
3353
+ type: "button",
3354
+ ref: ref,
3355
+ tabIndex: -1,
3356
+ style: HIDDEN_STYLES
3357
+ }));
3358
+ });
3359
+ /**
3360
+ * Provides focus management for the floating element.
3361
+ * @see https://floating-ui.com/docs/FloatingFocusManager
3362
+ */
3363
+ function FloatingFocusManager(props) {
3364
+ const {
3365
+ context,
3366
+ children,
3367
+ disabled = false,
3368
+ order = ['content'],
3369
+ guards: _guards = true,
3370
+ initialFocus = 0,
3371
+ returnFocus = true,
3372
+ restoreFocus = false,
3373
+ modal = true,
3374
+ visuallyHiddenDismiss = false,
3375
+ closeOnFocusOut = true
3376
+ } = props;
3377
+ const {
3378
+ open,
3379
+ refs,
3380
+ nodeId,
3381
+ onOpenChange,
3382
+ events,
3383
+ dataRef,
3384
+ floatingId,
3385
+ elements: {
3386
+ domReference,
3387
+ floating
3388
+ }
3389
+ } = context;
3390
+ const ignoreInitialFocus = typeof initialFocus === 'number' && initialFocus < 0;
3391
+ // If the reference is a combobox and is typeable (e.g. input/textarea),
3392
+ // there are different focus semantics. The guards should not be rendered, but
3393
+ // aria-hidden should be applied to all nodes still. Further, the visually
3394
+ // hidden dismiss button should only appear at the end of the list, not the
3395
+ // start.
3396
+ const isUntrappedTypeableCombobox = isTypeableCombobox(domReference) && ignoreInitialFocus;
3397
+
3398
+ // Force the guards to be rendered if the `inert` attribute is not supported.
3399
+ const guards = supportsInert() ? _guards : true;
3400
+ const orderRef = useLatestRef(order);
3401
+ const initialFocusRef = useLatestRef(initialFocus);
3402
+ const returnFocusRef = useLatestRef(returnFocus);
3403
+ const tree = useFloatingTree();
3404
+ const portalContext = usePortalContext();
3405
+ const startDismissButtonRef = React.useRef(null);
3406
+ const endDismissButtonRef = React.useRef(null);
3407
+ const preventReturnFocusRef = React.useRef(false);
3408
+ const isPointerDownRef = React.useRef(false);
3409
+ const tabbableIndexRef = React.useRef(-1);
3410
+ const isInsidePortal = portalContext != null;
3411
+ const floatingFocusElement = getFloatingFocusElement(floating);
3412
+ const getTabbableContent = useEffectEvent(function (container) {
3413
+ if (container === void 0) {
3414
+ container = floatingFocusElement;
3415
+ }
3416
+ return container ? tabbable(container, getTabbableOptions()) : [];
3417
+ });
3418
+ const getTabbableElements = useEffectEvent(container => {
3419
+ const content = getTabbableContent(container);
3420
+ return orderRef.current.map(type => {
3421
+ if (domReference && type === 'reference') {
3422
+ return domReference;
3423
+ }
3424
+ if (floatingFocusElement && type === 'floating') {
3425
+ return floatingFocusElement;
3426
+ }
3427
+ return content;
3428
+ }).filter(Boolean).flat();
3429
+ });
3430
+ React.useEffect(() => {
3431
+ if (disabled) return;
3432
+ if (!modal) return;
3433
+ function onKeyDown(event) {
3434
+ if (event.key === 'Tab') {
3435
+ // The focus guards have nothing to focus, so we need to stop the event.
3436
+ if (contains(floatingFocusElement, activeElement(getDocument(floatingFocusElement))) && getTabbableContent().length === 0 && !isUntrappedTypeableCombobox) {
3437
+ stopEvent(event);
3438
+ }
3439
+ const els = getTabbableElements();
3440
+ const target = getTarget(event);
3441
+ if (orderRef.current[0] === 'reference' && target === domReference) {
3442
+ stopEvent(event);
3443
+ if (event.shiftKey) {
3444
+ enqueueFocus(els[els.length - 1]);
3445
+ } else {
3446
+ enqueueFocus(els[1]);
3447
+ }
3448
+ }
3449
+ if (orderRef.current[1] === 'floating' && target === floatingFocusElement && event.shiftKey) {
3450
+ stopEvent(event);
3451
+ enqueueFocus(els[0]);
3452
+ }
3453
+ }
3454
+ }
3455
+ const doc = getDocument(floatingFocusElement);
3456
+ doc.addEventListener('keydown', onKeyDown);
3457
+ return () => {
3458
+ doc.removeEventListener('keydown', onKeyDown);
3459
+ };
3460
+ }, [disabled, domReference, floatingFocusElement, modal, orderRef, isUntrappedTypeableCombobox, getTabbableContent, getTabbableElements]);
3461
+ React.useEffect(() => {
3462
+ if (disabled) return;
3463
+ if (!floating) return;
3464
+ function handleFocusIn(event) {
3465
+ const target = getTarget(event);
3466
+ const tabbableContent = getTabbableContent();
3467
+ const tabbableIndex = tabbableContent.indexOf(target);
3468
+ if (tabbableIndex !== -1) {
3469
+ tabbableIndexRef.current = tabbableIndex;
3470
+ }
3471
+ }
3472
+ floating.addEventListener('focusin', handleFocusIn);
3473
+ return () => {
3474
+ floating.removeEventListener('focusin', handleFocusIn);
3475
+ };
3476
+ }, [disabled, floating, getTabbableContent]);
3477
+ React.useEffect(() => {
3478
+ if (disabled) return;
3479
+ if (!closeOnFocusOut) return;
3480
+
3481
+ // In Safari, buttons lose focus when pressing them.
3482
+ function handlePointerDown() {
3483
+ isPointerDownRef.current = true;
3484
+ setTimeout(() => {
3485
+ isPointerDownRef.current = false;
3486
+ });
3487
+ }
3488
+ function handleFocusOutside(event) {
3489
+ const relatedTarget = event.relatedTarget;
3490
+ queueMicrotask(() => {
3491
+ const movedToUnrelatedNode = !(contains(domReference, relatedTarget) || contains(floating, relatedTarget) || contains(relatedTarget, floating) || contains(portalContext == null ? void 0 : portalContext.portalNode, relatedTarget) || relatedTarget != null && relatedTarget.hasAttribute(createAttribute('focus-guard')) || tree && (getChildren(tree.nodesRef.current, nodeId).find(node => {
3492
+ var _node$context, _node$context2;
3493
+ return contains((_node$context = node.context) == null ? void 0 : _node$context.elements.floating, relatedTarget) || contains((_node$context2 = node.context) == null ? void 0 : _node$context2.elements.domReference, relatedTarget);
3494
+ }) || getAncestors(tree.nodesRef.current, nodeId).find(node => {
3495
+ var _node$context3, _node$context4;
3496
+ return ((_node$context3 = node.context) == null ? void 0 : _node$context3.elements.floating) === relatedTarget || ((_node$context4 = node.context) == null ? void 0 : _node$context4.elements.domReference) === relatedTarget;
3497
+ })));
3498
+
3499
+ // Restore focus to the previous tabbable element index to prevent
3500
+ // focus from being lost outside the floating tree.
3501
+ if (restoreFocus && movedToUnrelatedNode && activeElement(getDocument(floatingFocusElement)) === getDocument(floatingFocusElement).body) {
3502
+ // Let `FloatingPortal` effect knows that focus is still inside the
3503
+ // floating tree.
3504
+ if (isHTMLElement(floatingFocusElement)) {
3505
+ floatingFocusElement.focus();
3506
+ }
3507
+ const prevTabbableIndex = tabbableIndexRef.current;
3508
+ const tabbableContent = getTabbableContent();
3509
+ const nodeToFocus = tabbableContent[prevTabbableIndex] || tabbableContent[tabbableContent.length - 1] || floatingFocusElement;
3510
+ if (isHTMLElement(nodeToFocus)) {
3511
+ nodeToFocus.focus();
3512
+ }
3513
+ }
3514
+
3515
+ // Focus did not move inside the floating tree, and there are no tabbable
3516
+ // portal guards to handle closing.
3517
+ if ((isUntrappedTypeableCombobox ? true : !modal) && relatedTarget && movedToUnrelatedNode && !isPointerDownRef.current &&
3518
+ // Fix React 18 Strict Mode returnFocus due to double rendering.
3519
+ relatedTarget !== getPreviouslyFocusedElement()) {
3520
+ preventReturnFocusRef.current = true;
3521
+ onOpenChange(false, event, 'focus-out');
3522
+ }
3523
+ });
3524
+ }
3525
+ if (floating && isHTMLElement(domReference)) {
3526
+ domReference.addEventListener('focusout', handleFocusOutside);
3527
+ domReference.addEventListener('pointerdown', handlePointerDown);
3528
+ floating.addEventListener('focusout', handleFocusOutside);
3529
+ return () => {
3530
+ domReference.removeEventListener('focusout', handleFocusOutside);
3531
+ domReference.removeEventListener('pointerdown', handlePointerDown);
3532
+ floating.removeEventListener('focusout', handleFocusOutside);
3533
+ };
3534
+ }
3535
+ }, [disabled, domReference, floating, floatingFocusElement, modal, nodeId, tree, portalContext, onOpenChange, closeOnFocusOut, restoreFocus, getTabbableContent, isUntrappedTypeableCombobox]);
3536
+ React.useEffect(() => {
3537
+ var _portalContext$portal;
3538
+ if (disabled) return;
3539
+
3540
+ // Don't hide portals nested within the parent portal.
3541
+ const portalNodes = Array.from((portalContext == null || (_portalContext$portal = portalContext.portalNode) == null ? void 0 : _portalContext$portal.querySelectorAll("[" + createAttribute('portal') + "]")) || []);
3542
+ if (floating) {
3543
+ const insideElements = [floating, ...portalNodes, startDismissButtonRef.current, endDismissButtonRef.current, orderRef.current.includes('reference') || isUntrappedTypeableCombobox ? domReference : null].filter(x => x != null);
3544
+ const cleanup = modal || isUntrappedTypeableCombobox ? markOthers(insideElements, guards, !guards) : markOthers(insideElements);
3545
+ return () => {
3546
+ cleanup();
3547
+ };
3548
+ }
3549
+ }, [disabled, domReference, floating, modal, orderRef, portalContext, isUntrappedTypeableCombobox, guards]);
3550
+ index(() => {
3551
+ if (disabled || !isHTMLElement(floatingFocusElement)) return;
3552
+ const doc = getDocument(floatingFocusElement);
3553
+ const previouslyFocusedElement = activeElement(doc);
3554
+
3555
+ // Wait for any layout effect state setters to execute to set `tabIndex`.
3556
+ queueMicrotask(() => {
3557
+ const focusableElements = getTabbableElements(floatingFocusElement);
3558
+ const initialFocusValue = initialFocusRef.current;
3559
+ const elToFocus = (typeof initialFocusValue === 'number' ? focusableElements[initialFocusValue] : initialFocusValue.current) || floatingFocusElement;
3560
+ const focusAlreadyInsideFloatingEl = contains(floatingFocusElement, previouslyFocusedElement);
3561
+ if (!ignoreInitialFocus && !focusAlreadyInsideFloatingEl && open) {
3562
+ enqueueFocus(elToFocus, {
3563
+ preventScroll: elToFocus === floatingFocusElement
3564
+ });
3565
+ }
3566
+ });
3567
+ }, [disabled, open, floatingFocusElement, ignoreInitialFocus, getTabbableElements, initialFocusRef]);
3568
+ index(() => {
3569
+ if (disabled || !floatingFocusElement) return;
3570
+ let preventReturnFocusScroll = false;
3571
+ const doc = getDocument(floatingFocusElement);
3572
+ const previouslyFocusedElement = activeElement(doc);
3573
+ const contextData = dataRef.current;
3574
+ let openEvent = contextData.openEvent;
3575
+ addPreviouslyFocusedElement(previouslyFocusedElement);
3576
+
3577
+ // Dismissing via outside press should always ignore `returnFocus` to
3578
+ // prevent unwanted scrolling.
3579
+ function onOpenChange(_ref) {
3580
+ let {
3581
+ open,
3582
+ reason,
3583
+ event,
3584
+ nested
3585
+ } = _ref;
3586
+ if (open) {
3587
+ openEvent = event;
3588
+ }
3589
+ if (reason === 'escape-key' && refs.domReference.current) {
3590
+ addPreviouslyFocusedElement(refs.domReference.current);
3591
+ }
3592
+ if (reason === 'hover' && event.type === 'mouseleave') {
3593
+ preventReturnFocusRef.current = true;
3594
+ }
3595
+ if (reason !== 'outside-press') return;
3596
+ if (nested) {
3597
+ preventReturnFocusRef.current = false;
3598
+ preventReturnFocusScroll = true;
3599
+ } else {
3600
+ preventReturnFocusRef.current = !(isVirtualClick(event) || isVirtualPointerEvent(event));
3601
+ }
3602
+ }
3603
+ events.on('openchange', onOpenChange);
3604
+ const fallbackEl = doc.createElement('span');
3605
+ fallbackEl.setAttribute('tabindex', '-1');
3606
+ fallbackEl.setAttribute('aria-hidden', 'true');
3607
+ Object.assign(fallbackEl.style, HIDDEN_STYLES);
3608
+ if (isInsidePortal && domReference) {
3609
+ domReference.insertAdjacentElement('afterend', fallbackEl);
3610
+ }
3611
+ function getReturnElement() {
3612
+ if (typeof returnFocusRef.current === 'boolean') {
3613
+ return getPreviouslyFocusedElement() || fallbackEl;
3614
+ }
3615
+ return returnFocusRef.current.current || fallbackEl;
3616
+ }
3617
+ return () => {
3618
+ events.off('openchange', onOpenChange);
3619
+ const activeEl = activeElement(doc);
3620
+ const isFocusInsideFloatingTree = contains(floating, activeEl) || tree && getChildren(tree.nodesRef.current, nodeId).some(node => {
3621
+ var _node$context5;
3622
+ return contains((_node$context5 = node.context) == null ? void 0 : _node$context5.elements.floating, activeEl);
3623
+ });
3624
+ const shouldFocusReference = isFocusInsideFloatingTree || openEvent && ['click', 'mousedown'].includes(openEvent.type);
3625
+ if (shouldFocusReference && refs.domReference.current) {
3626
+ addPreviouslyFocusedElement(refs.domReference.current);
3627
+ }
3628
+ const returnElement = getReturnElement();
3629
+ queueMicrotask(() => {
3630
+ if (
3631
+ // eslint-disable-next-line react-hooks/exhaustive-deps
3632
+ returnFocusRef.current && !preventReturnFocusRef.current && isHTMLElement(returnElement) && (
3633
+ // If the focus moved somewhere else after mount, avoid returning focus
3634
+ // since it likely entered a different element which should be
3635
+ // respected: https://github.com/floating-ui/floating-ui/issues/2607
3636
+ returnElement !== activeEl && activeEl !== doc.body ? isFocusInsideFloatingTree : true)) {
3637
+ returnElement.focus({
3638
+ preventScroll: preventReturnFocusScroll
3639
+ });
3640
+ }
3641
+ fallbackEl.remove();
3642
+ });
3643
+ };
3644
+ }, [disabled, floating, floatingFocusElement, returnFocusRef, dataRef, refs, events, tree, nodeId, isInsidePortal, domReference]);
3645
+ React.useEffect(() => {
3646
+ // The `returnFocus` cleanup behavior is inside a microtask; ensure we
3647
+ // wait for it to complete before resetting the flag.
3648
+ queueMicrotask(() => {
3649
+ preventReturnFocusRef.current = false;
3650
+ });
3651
+ }, [disabled]);
3652
+
3653
+ // Synchronize the `context` & `modal` value to the FloatingPortal context.
3654
+ // It will decide whether or not it needs to render its own guards.
3655
+ index(() => {
3656
+ if (disabled) return;
3657
+ if (!portalContext) return;
3658
+ portalContext.setFocusManagerState({
3659
+ modal,
3660
+ closeOnFocusOut,
3661
+ open,
3662
+ onOpenChange,
3663
+ refs
3664
+ });
3665
+ return () => {
3666
+ portalContext.setFocusManagerState(null);
3667
+ };
3668
+ }, [disabled, portalContext, modal, open, onOpenChange, refs, closeOnFocusOut]);
3669
+ index(() => {
3670
+ if (disabled) return;
3671
+ if (!floatingFocusElement) return;
3672
+ if (typeof MutationObserver !== 'function') return;
3673
+ if (ignoreInitialFocus) return;
3674
+ const handleMutation = () => {
3675
+ const tabIndex = floatingFocusElement.getAttribute('tabindex');
3676
+ const tabbableContent = getTabbableContent();
3677
+ const activeEl = activeElement(getDocument(floating));
3678
+ const tabbableIndex = tabbableContent.indexOf(activeEl);
3679
+ if (tabbableIndex !== -1) {
3680
+ tabbableIndexRef.current = tabbableIndex;
3681
+ }
3682
+ if (orderRef.current.includes('floating') || activeEl !== refs.domReference.current && tabbableContent.length === 0) {
3683
+ if (tabIndex !== '0') {
3684
+ floatingFocusElement.setAttribute('tabindex', '0');
3685
+ }
3686
+ } else if (tabIndex !== '-1') {
3687
+ floatingFocusElement.setAttribute('tabindex', '-1');
3688
+ }
3689
+ };
3690
+ handleMutation();
3691
+ const observer = new MutationObserver(handleMutation);
3692
+ observer.observe(floatingFocusElement, {
3693
+ childList: true,
3694
+ subtree: true,
3695
+ attributes: true
3696
+ });
3697
+ return () => {
3698
+ observer.disconnect();
3699
+ };
3700
+ }, [disabled, floating, floatingFocusElement, refs, orderRef, getTabbableContent, ignoreInitialFocus]);
3701
+ function renderDismissButton(location) {
3702
+ if (disabled || !visuallyHiddenDismiss || !modal) {
3703
+ return null;
3704
+ }
3705
+ return /*#__PURE__*/React.createElement(VisuallyHiddenDismiss, {
3706
+ ref: location === 'start' ? startDismissButtonRef : endDismissButtonRef,
3707
+ onClick: event => onOpenChange(false, event.nativeEvent)
3708
+ }, typeof visuallyHiddenDismiss === 'string' ? visuallyHiddenDismiss : 'Dismiss');
3709
+ }
3710
+ const shouldRenderGuards = !disabled && guards && (modal ? !isUntrappedTypeableCombobox : true) && (isInsidePortal || modal);
3711
+ return /*#__PURE__*/React.createElement(React.Fragment, null, shouldRenderGuards && /*#__PURE__*/React.createElement(FocusGuard, {
3712
+ "data-type": "inside",
3713
+ ref: portalContext == null ? void 0 : portalContext.beforeInsideRef,
3714
+ onFocus: event => {
3715
+ if (modal) {
3716
+ const els = getTabbableElements();
3717
+ enqueueFocus(order[0] === 'reference' ? els[0] : els[els.length - 1]);
3718
+ } else if (portalContext != null && portalContext.preserveTabOrder && portalContext.portalNode) {
3719
+ preventReturnFocusRef.current = false;
3720
+ if (isOutsideEvent(event, portalContext.portalNode)) {
3721
+ const nextTabbable = getNextTabbable() || domReference;
3722
+ nextTabbable == null || nextTabbable.focus();
3723
+ } else {
3724
+ var _portalContext$before;
3725
+ (_portalContext$before = portalContext.beforeOutsideRef.current) == null || _portalContext$before.focus();
3726
+ }
3727
+ }
3728
+ }
3729
+ }), !isUntrappedTypeableCombobox && renderDismissButton('start'), children, renderDismissButton('end'), shouldRenderGuards && /*#__PURE__*/React.createElement(FocusGuard, {
3730
+ "data-type": "inside",
3731
+ ref: portalContext == null ? void 0 : portalContext.afterInsideRef,
3732
+ onFocus: event => {
3733
+ if (modal) {
3734
+ enqueueFocus(getTabbableElements()[0]);
3735
+ } else if (portalContext != null && portalContext.preserveTabOrder && portalContext.portalNode) {
3736
+ if (closeOnFocusOut) {
3737
+ preventReturnFocusRef.current = true;
3738
+ }
3739
+ if (isOutsideEvent(event, portalContext.portalNode)) {
3740
+ const prevTabbable = getPreviousTabbable() || domReference;
3741
+ prevTabbable == null || prevTabbable.focus();
3742
+ } else {
3743
+ var _portalContext$afterO;
3744
+ (_portalContext$afterO = portalContext.afterOutsideRef.current) == null || _portalContext$afterO.focus();
3745
+ }
3746
+ }
3747
+ }
3748
+ }));
3749
+ }
3750
+
3751
+ let lockCount = 0;
3752
+ function enableScrollLock() {
3753
+ const isIOS = /iP(hone|ad|od)|iOS/.test(getPlatform());
3754
+ const bodyStyle = document.body.style;
3755
+ // RTL <body> scrollbar
3756
+ const scrollbarX = Math.round(document.documentElement.getBoundingClientRect().left) + document.documentElement.scrollLeft;
3757
+ const paddingProp = scrollbarX ? 'paddingLeft' : 'paddingRight';
3758
+ const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
3759
+ const scrollX = bodyStyle.left ? parseFloat(bodyStyle.left) : window.scrollX;
3760
+ const scrollY = bodyStyle.top ? parseFloat(bodyStyle.top) : window.scrollY;
3761
+ bodyStyle.overflow = 'hidden';
3762
+ if (scrollbarWidth) {
3763
+ bodyStyle[paddingProp] = scrollbarWidth + "px";
3764
+ }
3765
+
3766
+ // Only iOS doesn't respect `overflow: hidden` on document.body, and this
3767
+ // technique has fewer side effects.
3768
+ if (isIOS) {
3769
+ var _window$visualViewpor, _window$visualViewpor2;
3770
+ // iOS 12 does not support `visualViewport`.
3771
+ const offsetLeft = ((_window$visualViewpor = window.visualViewport) == null ? void 0 : _window$visualViewpor.offsetLeft) || 0;
3772
+ const offsetTop = ((_window$visualViewpor2 = window.visualViewport) == null ? void 0 : _window$visualViewpor2.offsetTop) || 0;
3773
+ Object.assign(bodyStyle, {
3774
+ position: 'fixed',
3775
+ top: -(scrollY - Math.floor(offsetTop)) + "px",
3776
+ left: -(scrollX - Math.floor(offsetLeft)) + "px",
3777
+ right: '0'
3778
+ });
3779
+ }
3780
+ return () => {
3781
+ Object.assign(bodyStyle, {
3782
+ overflow: '',
3783
+ [paddingProp]: ''
3784
+ });
3785
+ if (isIOS) {
3786
+ Object.assign(bodyStyle, {
3787
+ position: '',
3788
+ top: '',
3789
+ left: '',
3790
+ right: ''
3791
+ });
3792
+ window.scrollTo(scrollX, scrollY);
3793
+ }
3794
+ };
3795
+ }
3796
+ let cleanup = () => {};
3797
+
3798
+ /**
3799
+ * Provides base styling for a fixed overlay element to dim content or block
3800
+ * pointer events behind a floating element.
3801
+ * It's a regular `<div>`, so it can be styled via any CSS solution you prefer.
3802
+ * @see https://floating-ui.com/docs/FloatingOverlay
3803
+ */
3804
+ const FloatingOverlay = /*#__PURE__*/React.forwardRef(function FloatingOverlay(props, ref) {
3805
+ const {
3806
+ lockScroll = false,
3807
+ ...rest
3808
+ } = props;
3809
+ index(() => {
3810
+ if (!lockScroll) return;
3811
+ lockCount++;
3812
+ if (lockCount === 1) {
3813
+ cleanup = enableScrollLock();
3814
+ }
3815
+ return () => {
3816
+ lockCount--;
3817
+ if (lockCount === 0) {
3818
+ cleanup();
3819
+ }
3820
+ };
3821
+ }, [lockScroll]);
3822
+ return /*#__PURE__*/React.createElement("div", _extends({
3823
+ ref: ref
3824
+ }, rest, {
3825
+ style: {
3826
+ position: 'fixed',
3827
+ overflow: 'auto',
3828
+ top: 0,
3829
+ right: 0,
3830
+ bottom: 0,
3831
+ left: 0,
3832
+ ...rest.style
3833
+ }
3834
+ }));
3835
+ });
3836
+
3837
+ const bubbleHandlerKeys = {
3838
+ pointerdown: 'onPointerDown',
3839
+ mousedown: 'onMouseDown',
3840
+ click: 'onClick'
3841
+ };
3842
+ const captureHandlerKeys = {
3843
+ pointerdown: 'onPointerDownCapture',
3844
+ mousedown: 'onMouseDownCapture',
3845
+ click: 'onClickCapture'
3846
+ };
3847
+ const normalizeProp = normalizable => {
3848
+ var _normalizable$escapeK, _normalizable$outside;
3849
+ return {
3850
+ escapeKey: typeof normalizable === 'boolean' ? normalizable : (_normalizable$escapeK = normalizable == null ? void 0 : normalizable.escapeKey) != null ? _normalizable$escapeK : false,
3851
+ outsidePress: typeof normalizable === 'boolean' ? normalizable : (_normalizable$outside = normalizable == null ? void 0 : normalizable.outsidePress) != null ? _normalizable$outside : true
3852
+ };
3853
+ };
3854
+ /**
3855
+ * Closes the floating element when a dismissal is requested — by default, when
3856
+ * the user presses the `escape` key or outside of the floating element.
3857
+ * @see https://floating-ui.com/docs/useDismiss
3858
+ */
3859
+ function useDismiss(context, props) {
3860
+ if (props === void 0) {
3861
+ props = {};
3862
+ }
3863
+ const {
3864
+ open,
3865
+ onOpenChange,
3866
+ elements,
3867
+ dataRef
3868
+ } = context;
3869
+ const {
3870
+ enabled = true,
3871
+ escapeKey = true,
3872
+ outsidePress: unstable_outsidePress = true,
3873
+ outsidePressEvent = 'pointerdown',
3874
+ referencePress = false,
3875
+ referencePressEvent = 'pointerdown',
3876
+ ancestorScroll = false,
3877
+ bubbles,
3878
+ capture
3879
+ } = props;
3880
+ const tree = useFloatingTree();
3881
+ const outsidePressFn = useEffectEvent(typeof unstable_outsidePress === 'function' ? unstable_outsidePress : () => false);
3882
+ const outsidePress = typeof unstable_outsidePress === 'function' ? outsidePressFn : unstable_outsidePress;
3883
+ const insideReactTreeRef = React.useRef(false);
3884
+ const endedOrStartedInsideRef = React.useRef(false);
3885
+ const {
3886
+ escapeKey: escapeKeyBubbles,
3887
+ outsidePress: outsidePressBubbles
3888
+ } = normalizeProp(bubbles);
3889
+ const {
3890
+ escapeKey: escapeKeyCapture,
3891
+ outsidePress: outsidePressCapture
3892
+ } = normalizeProp(capture);
3893
+ const isComposingRef = React.useRef(false);
3894
+ const closeOnEscapeKeyDown = useEffectEvent(event => {
3895
+ var _dataRef$current$floa;
3896
+ if (!open || !enabled || !escapeKey || event.key !== 'Escape') {
3897
+ return;
3898
+ }
3899
+
3900
+ // Wait until IME is settled. Pressing `Escape` while composing should
3901
+ // close the compose menu, but not the floating element.
3902
+ if (isComposingRef.current) {
3903
+ return;
3904
+ }
3905
+ const nodeId = (_dataRef$current$floa = dataRef.current.floatingContext) == null ? void 0 : _dataRef$current$floa.nodeId;
3906
+ const children = tree ? getChildren(tree.nodesRef.current, nodeId) : [];
3907
+ if (!escapeKeyBubbles) {
3908
+ event.stopPropagation();
3909
+ if (children.length > 0) {
3910
+ let shouldDismiss = true;
3911
+ children.forEach(child => {
3912
+ var _child$context;
3913
+ if ((_child$context = child.context) != null && _child$context.open && !child.context.dataRef.current.__escapeKeyBubbles) {
3914
+ shouldDismiss = false;
3915
+ return;
3916
+ }
3917
+ });
3918
+ if (!shouldDismiss) {
3919
+ return;
3920
+ }
3921
+ }
3922
+ }
3923
+ onOpenChange(false, isReactEvent(event) ? event.nativeEvent : event, 'escape-key');
3924
+ });
3925
+ const closeOnEscapeKeyDownCapture = useEffectEvent(event => {
3926
+ var _getTarget2;
3927
+ const callback = () => {
3928
+ var _getTarget;
3929
+ closeOnEscapeKeyDown(event);
3930
+ (_getTarget = getTarget(event)) == null || _getTarget.removeEventListener('keydown', callback);
3931
+ };
3932
+ (_getTarget2 = getTarget(event)) == null || _getTarget2.addEventListener('keydown', callback);
3933
+ });
3934
+ const closeOnPressOutside = useEffectEvent(event => {
3935
+ var _dataRef$current$floa2;
3936
+ // Given developers can stop the propagation of the synthetic event,
3937
+ // we can only be confident with a positive value.
3938
+ const insideReactTree = insideReactTreeRef.current;
3939
+ insideReactTreeRef.current = false;
3940
+
3941
+ // When click outside is lazy (`click` event), handle dragging.
3942
+ // Don't close if:
3943
+ // - The click started inside the floating element.
3944
+ // - The click ended inside the floating element.
3945
+ const endedOrStartedInside = endedOrStartedInsideRef.current;
3946
+ endedOrStartedInsideRef.current = false;
3947
+ if (outsidePressEvent === 'click' && endedOrStartedInside) {
3948
+ return;
3949
+ }
3950
+ if (insideReactTree) {
3951
+ return;
3952
+ }
3953
+ if (typeof outsidePress === 'function' && !outsidePress(event)) {
3954
+ return;
3955
+ }
3956
+ const target = getTarget(event);
3957
+ const inertSelector = "[" + createAttribute('inert') + "]";
3958
+ const markers = getDocument(elements.floating).querySelectorAll(inertSelector);
3959
+ let targetRootAncestor = isElement(target) ? target : null;
3960
+ while (targetRootAncestor && !isLastTraversableNode(targetRootAncestor)) {
3961
+ const nextParent = getParentNode(targetRootAncestor);
3962
+ if (isLastTraversableNode(nextParent) || !isElement(nextParent)) {
3963
+ break;
3964
+ }
3965
+ targetRootAncestor = nextParent;
3966
+ }
3967
+
3968
+ // Check if the click occurred on a third-party element injected after the
3969
+ // floating element rendered.
3970
+ if (markers.length && isElement(target) && !isRootElement(target) &&
3971
+ // Clicked on a direct ancestor (e.g. FloatingOverlay).
3972
+ !contains(target, elements.floating) &&
3973
+ // If the target root element contains none of the markers, then the
3974
+ // element was injected after the floating element rendered.
3975
+ Array.from(markers).every(marker => !contains(targetRootAncestor, marker))) {
3976
+ return;
3977
+ }
3978
+
3979
+ // Check if the click occurred on the scrollbar
3980
+ if (isHTMLElement(target) && floating) {
3981
+ // In Firefox, `target.scrollWidth > target.clientWidth` for inline
3982
+ // elements.
3983
+ const canScrollX = target.clientWidth > 0 && target.scrollWidth > target.clientWidth;
3984
+ const canScrollY = target.clientHeight > 0 && target.scrollHeight > target.clientHeight;
3985
+ let xCond = canScrollY && event.offsetX > target.clientWidth;
3986
+
3987
+ // In some browsers it is possible to change the <body> (or window)
3988
+ // scrollbar to the left side, but is very rare and is difficult to
3989
+ // check for. Plus, for modal dialogs with backdrops, it is more
3990
+ // important that the backdrop is checked but not so much the window.
3991
+ if (canScrollY) {
3992
+ const isRTL = getComputedStyle$1(target).direction === 'rtl';
3993
+ if (isRTL) {
3994
+ xCond = event.offsetX <= target.offsetWidth - target.clientWidth;
3995
+ }
3996
+ }
3997
+ if (xCond || canScrollX && event.offsetY > target.clientHeight) {
3998
+ return;
3999
+ }
4000
+ }
4001
+ const nodeId = (_dataRef$current$floa2 = dataRef.current.floatingContext) == null ? void 0 : _dataRef$current$floa2.nodeId;
4002
+ const targetIsInsideChildren = tree && getChildren(tree.nodesRef.current, nodeId).some(node => {
4003
+ var _node$context;
4004
+ return isEventTargetWithin(event, (_node$context = node.context) == null ? void 0 : _node$context.elements.floating);
4005
+ });
4006
+ if (isEventTargetWithin(event, elements.floating) || isEventTargetWithin(event, elements.domReference) || targetIsInsideChildren) {
4007
+ return;
4008
+ }
4009
+ const children = tree ? getChildren(tree.nodesRef.current, nodeId) : [];
4010
+ if (children.length > 0) {
4011
+ let shouldDismiss = true;
4012
+ children.forEach(child => {
4013
+ var _child$context2;
4014
+ if ((_child$context2 = child.context) != null && _child$context2.open && !child.context.dataRef.current.__outsidePressBubbles) {
4015
+ shouldDismiss = false;
4016
+ return;
4017
+ }
4018
+ });
4019
+ if (!shouldDismiss) {
4020
+ return;
4021
+ }
4022
+ }
4023
+ onOpenChange(false, event, 'outside-press');
4024
+ });
4025
+ const closeOnPressOutsideCapture = useEffectEvent(event => {
4026
+ var _getTarget4;
4027
+ const callback = () => {
4028
+ var _getTarget3;
4029
+ closeOnPressOutside(event);
4030
+ (_getTarget3 = getTarget(event)) == null || _getTarget3.removeEventListener(outsidePressEvent, callback);
4031
+ };
4032
+ (_getTarget4 = getTarget(event)) == null || _getTarget4.addEventListener(outsidePressEvent, callback);
4033
+ });
4034
+ React.useEffect(() => {
4035
+ if (!open || !enabled) {
4036
+ return;
4037
+ }
4038
+ dataRef.current.__escapeKeyBubbles = escapeKeyBubbles;
4039
+ dataRef.current.__outsidePressBubbles = outsidePressBubbles;
4040
+ let compositionTimeout = -1;
4041
+ function onScroll(event) {
4042
+ onOpenChange(false, event, 'ancestor-scroll');
4043
+ }
4044
+ function handleCompositionStart() {
4045
+ window.clearTimeout(compositionTimeout);
4046
+ isComposingRef.current = true;
4047
+ }
4048
+ function handleCompositionEnd() {
4049
+ // Safari fires `compositionend` before `keydown`, so we need to wait
4050
+ // until the next tick to set `isComposing` to `false`.
4051
+ // https://bugs.webkit.org/show_bug.cgi?id=165004
4052
+ compositionTimeout = window.setTimeout(() => {
4053
+ isComposingRef.current = false;
4054
+ },
4055
+ // 0ms or 1ms don't work in Safari. 5ms appears to consistently work.
4056
+ // Only apply to WebKit for the test to remain 0ms.
4057
+ isWebKit() ? 5 : 0);
4058
+ }
4059
+ const doc = getDocument(elements.floating);
4060
+ if (escapeKey) {
4061
+ doc.addEventListener('keydown', escapeKeyCapture ? closeOnEscapeKeyDownCapture : closeOnEscapeKeyDown, escapeKeyCapture);
4062
+ doc.addEventListener('compositionstart', handleCompositionStart);
4063
+ doc.addEventListener('compositionend', handleCompositionEnd);
4064
+ }
4065
+ outsidePress && doc.addEventListener(outsidePressEvent, outsidePressCapture ? closeOnPressOutsideCapture : closeOnPressOutside, outsidePressCapture);
4066
+ let ancestors = [];
4067
+ if (ancestorScroll) {
4068
+ if (isElement(elements.domReference)) {
4069
+ ancestors = getOverflowAncestors(elements.domReference);
4070
+ }
4071
+ if (isElement(elements.floating)) {
4072
+ ancestors = ancestors.concat(getOverflowAncestors(elements.floating));
4073
+ }
4074
+ if (!isElement(elements.reference) && elements.reference && elements.reference.contextElement) {
4075
+ ancestors = ancestors.concat(getOverflowAncestors(elements.reference.contextElement));
4076
+ }
4077
+ }
4078
+
4079
+ // Ignore the visual viewport for scrolling dismissal (allow pinch-zoom)
4080
+ ancestors = ancestors.filter(ancestor => {
4081
+ var _doc$defaultView;
4082
+ return ancestor !== ((_doc$defaultView = doc.defaultView) == null ? void 0 : _doc$defaultView.visualViewport);
4083
+ });
4084
+ ancestors.forEach(ancestor => {
4085
+ ancestor.addEventListener('scroll', onScroll, {
4086
+ passive: true
4087
+ });
4088
+ });
4089
+ return () => {
4090
+ if (escapeKey) {
4091
+ doc.removeEventListener('keydown', escapeKeyCapture ? closeOnEscapeKeyDownCapture : closeOnEscapeKeyDown, escapeKeyCapture);
4092
+ doc.removeEventListener('compositionstart', handleCompositionStart);
4093
+ doc.removeEventListener('compositionend', handleCompositionEnd);
4094
+ }
4095
+ outsidePress && doc.removeEventListener(outsidePressEvent, outsidePressCapture ? closeOnPressOutsideCapture : closeOnPressOutside, outsidePressCapture);
4096
+ ancestors.forEach(ancestor => {
4097
+ ancestor.removeEventListener('scroll', onScroll);
4098
+ });
4099
+ window.clearTimeout(compositionTimeout);
4100
+ };
4101
+ }, [dataRef, elements, escapeKey, outsidePress, outsidePressEvent, open, onOpenChange, ancestorScroll, enabled, escapeKeyBubbles, outsidePressBubbles, closeOnEscapeKeyDown, escapeKeyCapture, closeOnEscapeKeyDownCapture, closeOnPressOutside, outsidePressCapture, closeOnPressOutsideCapture]);
4102
+ React.useEffect(() => {
4103
+ insideReactTreeRef.current = false;
4104
+ }, [outsidePress, outsidePressEvent]);
4105
+ const reference = React.useMemo(() => ({
4106
+ onKeyDown: closeOnEscapeKeyDown,
4107
+ [bubbleHandlerKeys[referencePressEvent]]: event => {
4108
+ if (referencePress) {
4109
+ onOpenChange(false, event.nativeEvent, 'reference-press');
4110
+ }
4111
+ }
4112
+ }), [closeOnEscapeKeyDown, onOpenChange, referencePress, referencePressEvent]);
4113
+ const floating = React.useMemo(() => ({
4114
+ onKeyDown: closeOnEscapeKeyDown,
4115
+ onMouseDown() {
4116
+ endedOrStartedInsideRef.current = true;
4117
+ },
4118
+ onMouseUp() {
4119
+ endedOrStartedInsideRef.current = true;
4120
+ },
4121
+ [captureHandlerKeys[outsidePressEvent]]: () => {
4122
+ insideReactTreeRef.current = true;
4123
+ }
4124
+ }), [closeOnEscapeKeyDown, outsidePressEvent]);
4125
+ return React.useMemo(() => enabled ? {
4126
+ reference,
4127
+ floating
4128
+ } : {}, [enabled, reference, floating]);
4129
+ }
4130
+
4131
+ function useFloatingRootContext(options) {
4132
+ const {
4133
+ open = false,
4134
+ onOpenChange: onOpenChangeProp,
4135
+ elements: elementsProp
4136
+ } = options;
4137
+ const floatingId = useId();
4138
+ const dataRef = React.useRef({});
4139
+ const [events] = React.useState(() => createPubSub());
4140
+ const nested = useFloatingParentNodeId() != null;
4141
+ {
4142
+ const optionDomReference = elementsProp.reference;
4143
+ if (optionDomReference && !isElement(optionDomReference)) {
4144
+ error('Cannot pass a virtual element to the `elements.reference` option,', 'as it must be a real DOM element. Use `refs.setPositionReference()`', 'instead.');
4145
+ }
4146
+ }
4147
+ const [positionReference, setPositionReference] = React.useState(elementsProp.reference);
4148
+ const onOpenChange = useEffectEvent((open, event, reason) => {
4149
+ dataRef.current.openEvent = open ? event : undefined;
4150
+ events.emit('openchange', {
4151
+ open,
4152
+ event,
4153
+ reason,
4154
+ nested
4155
+ });
4156
+ onOpenChangeProp == null || onOpenChangeProp(open, event, reason);
4157
+ });
4158
+ const refs = React.useMemo(() => ({
4159
+ setPositionReference
4160
+ }), []);
4161
+ const elements = React.useMemo(() => ({
4162
+ reference: positionReference || elementsProp.reference || null,
4163
+ floating: elementsProp.floating || null,
4164
+ domReference: elementsProp.reference
4165
+ }), [positionReference, elementsProp.reference, elementsProp.floating]);
4166
+ return React.useMemo(() => ({
4167
+ dataRef,
4168
+ open,
4169
+ onOpenChange,
4170
+ elements,
4171
+ events,
4172
+ floatingId,
4173
+ refs
4174
+ }), [open, onOpenChange, elements, events, floatingId, refs]);
4175
+ }
4176
+
4177
+ /**
4178
+ * Provides data to position a floating element and context to add interactions.
4179
+ * @see https://floating-ui.com/docs/useFloating
4180
+ */
4181
+ function useFloating(options) {
4182
+ if (options === void 0) {
4183
+ options = {};
4184
+ }
4185
+ const {
4186
+ nodeId
4187
+ } = options;
4188
+ const internalRootContext = useFloatingRootContext({
4189
+ ...options,
4190
+ elements: {
4191
+ reference: null,
4192
+ floating: null,
4193
+ ...options.elements
4194
+ }
4195
+ });
4196
+ const rootContext = options.rootContext || internalRootContext;
4197
+ const computedElements = rootContext.elements;
4198
+ const [_domReference, setDomReference] = React.useState(null);
4199
+ const [positionReference, _setPositionReference] = React.useState(null);
4200
+ const optionDomReference = computedElements == null ? void 0 : computedElements.domReference;
4201
+ const domReference = optionDomReference || _domReference;
4202
+ const domReferenceRef = React.useRef(null);
4203
+ const tree = useFloatingTree();
4204
+ index(() => {
4205
+ if (domReference) {
4206
+ domReferenceRef.current = domReference;
4207
+ }
4208
+ }, [domReference]);
4209
+ const position = useFloating$1({
4210
+ ...options,
4211
+ elements: {
4212
+ ...computedElements,
4213
+ ...(positionReference && {
4214
+ reference: positionReference
4215
+ })
4216
+ }
4217
+ });
4218
+ const setPositionReference = React.useCallback(node => {
4219
+ const computedPositionReference = isElement(node) ? {
4220
+ getBoundingClientRect: () => node.getBoundingClientRect(),
4221
+ contextElement: node
4222
+ } : node;
4223
+ // Store the positionReference in state if the DOM reference is specified externally via the
4224
+ // `elements.reference` option. This ensures that it won't be overridden on future renders.
4225
+ _setPositionReference(computedPositionReference);
4226
+ position.refs.setReference(computedPositionReference);
4227
+ }, [position.refs]);
4228
+ const setReference = React.useCallback(node => {
4229
+ if (isElement(node) || node === null) {
4230
+ domReferenceRef.current = node;
4231
+ setDomReference(node);
4232
+ }
4233
+
4234
+ // Backwards-compatibility for passing a virtual element to `reference`
4235
+ // after it has set the DOM reference.
4236
+ if (isElement(position.refs.reference.current) || position.refs.reference.current === null ||
4237
+ // Don't allow setting virtual elements using the old technique back to
4238
+ // `null` to support `positionReference` + an unstable `reference`
4239
+ // callback ref.
4240
+ node !== null && !isElement(node)) {
4241
+ position.refs.setReference(node);
4242
+ }
4243
+ }, [position.refs]);
4244
+ const refs = React.useMemo(() => ({
4245
+ ...position.refs,
4246
+ setReference,
4247
+ setPositionReference,
4248
+ domReference: domReferenceRef
4249
+ }), [position.refs, setReference, setPositionReference]);
4250
+ const elements = React.useMemo(() => ({
4251
+ ...position.elements,
4252
+ domReference: domReference
4253
+ }), [position.elements, domReference]);
4254
+ const context = React.useMemo(() => ({
4255
+ ...position,
4256
+ ...rootContext,
4257
+ refs,
4258
+ elements,
4259
+ nodeId
4260
+ }), [position, refs, elements, nodeId, rootContext]);
4261
+ index(() => {
4262
+ rootContext.dataRef.current.floatingContext = context;
4263
+ const node = tree == null ? void 0 : tree.nodesRef.current.find(node => node.id === nodeId);
4264
+ if (node) {
4265
+ node.context = context;
4266
+ }
4267
+ });
4268
+ return React.useMemo(() => ({
4269
+ ...position,
4270
+ context,
4271
+ refs,
4272
+ elements
4273
+ }), [position, refs, elements, context]);
4274
+ }
4275
+
4276
+ const ACTIVE_KEY = 'active';
4277
+ const SELECTED_KEY = 'selected';
4278
+ function mergeProps(userProps, propsList, elementKey) {
4279
+ const map = new Map();
4280
+ const isItem = elementKey === 'item';
4281
+ let domUserProps = userProps;
4282
+ if (isItem && userProps) {
4283
+ const {
4284
+ [ACTIVE_KEY]: _,
4285
+ [SELECTED_KEY]: __,
4286
+ ...validProps
4287
+ } = userProps;
4288
+ domUserProps = validProps;
4289
+ }
4290
+ return {
4291
+ ...(elementKey === 'floating' && {
4292
+ tabIndex: -1,
4293
+ [FOCUSABLE_ATTRIBUTE]: ''
4294
+ }),
4295
+ ...domUserProps,
4296
+ ...propsList.map(value => {
4297
+ const propsOrGetProps = value ? value[elementKey] : null;
4298
+ if (typeof propsOrGetProps === 'function') {
4299
+ return userProps ? propsOrGetProps(userProps) : null;
4300
+ }
4301
+ return propsOrGetProps;
4302
+ }).concat(userProps).reduce((acc, props) => {
4303
+ if (!props) {
4304
+ return acc;
4305
+ }
4306
+ Object.entries(props).forEach(_ref => {
4307
+ let [key, value] = _ref;
4308
+ if (isItem && [ACTIVE_KEY, SELECTED_KEY].includes(key)) {
4309
+ return;
4310
+ }
4311
+ if (key.indexOf('on') === 0) {
4312
+ if (!map.has(key)) {
4313
+ map.set(key, []);
4314
+ }
4315
+ if (typeof value === 'function') {
4316
+ var _map$get;
4317
+ (_map$get = map.get(key)) == null || _map$get.push(value);
4318
+ acc[key] = function () {
4319
+ var _map$get2;
4320
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
4321
+ args[_key] = arguments[_key];
4322
+ }
4323
+ return (_map$get2 = map.get(key)) == null ? void 0 : _map$get2.map(fn => fn(...args)).find(val => val !== undefined);
4324
+ };
4325
+ }
4326
+ } else {
4327
+ acc[key] = value;
4328
+ }
4329
+ });
4330
+ return acc;
4331
+ }, {})
4332
+ };
4333
+ }
4334
+ /**
4335
+ * Merges an array of interaction hooks' props into prop getters, allowing
4336
+ * event handler functions to be composed together without overwriting one
4337
+ * another.
4338
+ * @see https://floating-ui.com/docs/useInteractions
4339
+ */
4340
+ function useInteractions(propsList) {
4341
+ if (propsList === void 0) {
4342
+ propsList = [];
4343
+ }
4344
+ const referenceDeps = propsList.map(key => key == null ? void 0 : key.reference);
4345
+ const floatingDeps = propsList.map(key => key == null ? void 0 : key.floating);
4346
+ const itemDeps = propsList.map(key => key == null ? void 0 : key.item);
4347
+ const getReferenceProps = React.useCallback(userProps => mergeProps(userProps, propsList, 'reference'),
4348
+ // eslint-disable-next-line react-hooks/exhaustive-deps
4349
+ referenceDeps);
4350
+ const getFloatingProps = React.useCallback(userProps => mergeProps(userProps, propsList, 'floating'),
4351
+ // eslint-disable-next-line react-hooks/exhaustive-deps
4352
+ floatingDeps);
4353
+ const getItemProps = React.useCallback(userProps => mergeProps(userProps, propsList, 'item'),
4354
+ // eslint-disable-next-line react-hooks/exhaustive-deps
4355
+ itemDeps);
4356
+ return React.useMemo(() => ({
4357
+ getReferenceProps,
4358
+ getFloatingProps,
4359
+ getItemProps
4360
+ }), [getReferenceProps, getFloatingProps, getItemProps]);
4361
+ }
4362
+
4363
+ // Converts a JS style key like `backgroundColor` to a CSS transition-property
4364
+ // like `background-color`.
4365
+ const camelCaseToKebabCase = str => str.replace(/[A-Z]+(?![a-z])|[A-Z]/g, ($, ofs) => (ofs ? '-' : '') + $.toLowerCase());
4366
+ function execWithArgsOrReturn(valueOrFn, args) {
4367
+ return typeof valueOrFn === 'function' ? valueOrFn(args) : valueOrFn;
4368
+ }
4369
+ function useDelayUnmount(open, durationMs) {
4370
+ const [isMounted, setIsMounted] = React.useState(open);
4371
+ if (open && !isMounted) {
4372
+ setIsMounted(true);
4373
+ }
4374
+ React.useEffect(() => {
4375
+ if (!open && isMounted) {
4376
+ const timeout = setTimeout(() => setIsMounted(false), durationMs);
4377
+ return () => clearTimeout(timeout);
4378
+ }
4379
+ }, [open, isMounted, durationMs]);
4380
+ return isMounted;
4381
+ }
4382
+ /**
4383
+ * Provides a status string to apply CSS transitions to a floating element,
4384
+ * correctly handling placement-aware transitions.
4385
+ * @see https://floating-ui.com/docs/useTransition#usetransitionstatus
4386
+ */
4387
+ function useTransitionStatus(context, props) {
4388
+ if (props === void 0) {
4389
+ props = {};
4390
+ }
4391
+ const {
4392
+ open,
4393
+ elements: {
4394
+ floating
4395
+ }
4396
+ } = context;
4397
+ const {
4398
+ duration = 250
4399
+ } = props;
4400
+ const isNumberDuration = typeof duration === 'number';
4401
+ const closeDuration = (isNumberDuration ? duration : duration.close) || 0;
4402
+ const [status, setStatus] = React.useState('unmounted');
4403
+ const isMounted = useDelayUnmount(open, closeDuration);
4404
+ if (!isMounted && status === 'close') {
4405
+ setStatus('unmounted');
4406
+ }
4407
+ index(() => {
4408
+ if (!floating) return;
4409
+ if (open) {
4410
+ setStatus('initial');
4411
+ const frame = requestAnimationFrame(() => {
4412
+ setStatus('open');
4413
+ });
4414
+ return () => {
4415
+ cancelAnimationFrame(frame);
4416
+ };
4417
+ }
4418
+ setStatus('close');
4419
+ }, [open, floating]);
4420
+ return {
4421
+ isMounted,
4422
+ status
4423
+ };
4424
+ }
4425
+ /**
4426
+ * Provides styles to apply CSS transitions to a floating element, correctly
4427
+ * handling placement-aware transitions. Wrapper around `useTransitionStatus`.
4428
+ * @see https://floating-ui.com/docs/useTransition#usetransitionstyles
4429
+ */
4430
+ function useTransitionStyles(context, props) {
4431
+ if (props === void 0) {
4432
+ props = {};
4433
+ }
4434
+ const {
4435
+ initial: unstable_initial = {
4436
+ opacity: 0
4437
+ },
4438
+ open: unstable_open,
4439
+ close: unstable_close,
4440
+ common: unstable_common,
4441
+ duration = 250
4442
+ } = props;
4443
+ const placement = context.placement;
4444
+ const side = placement.split('-')[0];
4445
+ const fnArgs = React.useMemo(() => ({
4446
+ side,
4447
+ placement
4448
+ }), [side, placement]);
4449
+ const isNumberDuration = typeof duration === 'number';
4450
+ const openDuration = (isNumberDuration ? duration : duration.open) || 0;
4451
+ const closeDuration = (isNumberDuration ? duration : duration.close) || 0;
4452
+ const [styles, setStyles] = React.useState(() => ({
4453
+ ...execWithArgsOrReturn(unstable_common, fnArgs),
4454
+ ...execWithArgsOrReturn(unstable_initial, fnArgs)
4455
+ }));
4456
+ const {
4457
+ isMounted,
4458
+ status
4459
+ } = useTransitionStatus(context, {
4460
+ duration
4461
+ });
4462
+ const initialRef = useLatestRef(unstable_initial);
4463
+ const openRef = useLatestRef(unstable_open);
4464
+ const closeRef = useLatestRef(unstable_close);
4465
+ const commonRef = useLatestRef(unstable_common);
4466
+ index(() => {
4467
+ const initialStyles = execWithArgsOrReturn(initialRef.current, fnArgs);
4468
+ const closeStyles = execWithArgsOrReturn(closeRef.current, fnArgs);
4469
+ const commonStyles = execWithArgsOrReturn(commonRef.current, fnArgs);
4470
+ const openStyles = execWithArgsOrReturn(openRef.current, fnArgs) || Object.keys(initialStyles).reduce((acc, key) => {
4471
+ acc[key] = '';
4472
+ return acc;
4473
+ }, {});
4474
+ if (status === 'initial') {
4475
+ setStyles(styles => ({
4476
+ transitionProperty: styles.transitionProperty,
4477
+ ...commonStyles,
4478
+ ...initialStyles
4479
+ }));
4480
+ }
4481
+ if (status === 'open') {
4482
+ setStyles({
4483
+ transitionProperty: Object.keys(openStyles).map(camelCaseToKebabCase).join(','),
4484
+ transitionDuration: openDuration + "ms",
4485
+ ...commonStyles,
4486
+ ...openStyles
4487
+ });
4488
+ }
4489
+ if (status === 'close') {
4490
+ const styles = closeStyles || initialStyles;
4491
+ setStyles({
4492
+ transitionProperty: Object.keys(styles).map(camelCaseToKebabCase).join(','),
4493
+ transitionDuration: closeDuration + "ms",
4494
+ ...commonStyles,
4495
+ ...styles
4496
+ });
4497
+ }
4498
+ }, [closeDuration, closeRef, initialRef, openRef, commonRef, openDuration, status, fnArgs]);
4499
+ return {
4500
+ isMounted,
4501
+ styles
4502
+ };
4503
+ }
4504
+
4505
+ export { FloatingPortal as F, autoUpdate as a, size as b, useTransitionStyles as c, useMergeRefs as d, useDismiss as e, flip as f, useInteractions as g, FloatingFocusManager as h, inline as i, useId as j, FloatingOverlay as k, offset as o, shift as s, useFloating as u };
4506
+ //# sourceMappingURL=floating-ui.react-feaab622.js.map