@cypress-design/react-tooltip 1.0.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.umd.js CHANGED
@@ -2,7 +2,8 @@
2
2
 
3
3
  var clsx = require('clsx');
4
4
  var React = require('react');
5
- var ReactDOM = require('react-dom');
5
+ var reactDom = require('react-dom');
6
+ var react = require('@floating-ui/react');
6
7
 
7
8
  function _interopNamespaceDefault(e) {
8
9
  var n = Object.create(null);
@@ -22,7 +23,6 @@ function _interopNamespaceDefault(e) {
22
23
  }
23
24
 
24
25
  var React__namespace = /*#__PURE__*/_interopNamespaceDefault(React);
25
- var ReactDOM__namespace = /*#__PURE__*/_interopNamespaceDefault(ReactDOM);
26
26
 
27
27
  /******************************************************************************
28
28
  Copyright (c) Microsoft Corporation.
@@ -79,3315 +79,6 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
79
79
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
80
80
  };
81
81
 
82
- function getNodeName(node) {
83
- if (isNode(node)) {
84
- return (node.nodeName || '').toLowerCase();
85
- }
86
- // Mocked nodes in testing environments may not be instances of Node. By
87
- // returning `#document` an infinite loop won't occur.
88
- // https://github.com/floating-ui/floating-ui/issues/2317
89
- return '#document';
90
- }
91
- function getWindow(node) {
92
- var _node$ownerDocument;
93
- return (node == null || (_node$ownerDocument = node.ownerDocument) == null ? void 0 : _node$ownerDocument.defaultView) || window;
94
- }
95
- function getDocumentElement(node) {
96
- var _ref;
97
- return (_ref = (isNode(node) ? node.ownerDocument : node.document) || window.document) == null ? void 0 : _ref.documentElement;
98
- }
99
- function isNode(value) {
100
- return value instanceof Node || value instanceof getWindow(value).Node;
101
- }
102
- function isElement(value) {
103
- return value instanceof Element || value instanceof getWindow(value).Element;
104
- }
105
- function isHTMLElement(value) {
106
- return value instanceof HTMLElement || value instanceof getWindow(value).HTMLElement;
107
- }
108
- function isShadowRoot(value) {
109
- // Browsers without `ShadowRoot` support.
110
- if (typeof ShadowRoot === 'undefined') {
111
- return false;
112
- }
113
- return value instanceof ShadowRoot || value instanceof getWindow(value).ShadowRoot;
114
- }
115
- function isOverflowElement(element) {
116
- const {
117
- overflow,
118
- overflowX,
119
- overflowY,
120
- display
121
- } = getComputedStyle(element);
122
- return /auto|scroll|overlay|hidden|clip/.test(overflow + overflowY + overflowX) && !['inline', 'contents'].includes(display);
123
- }
124
- function isTableElement(element) {
125
- return ['table', 'td', 'th'].includes(getNodeName(element));
126
- }
127
- function isContainingBlock(element) {
128
- const webkit = isWebKit();
129
- const css = getComputedStyle(element);
130
-
131
- // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block
132
- return css.transform !== 'none' || css.perspective !== 'none' || (css.containerType ? css.containerType !== 'normal' : false) || !webkit && (css.backdropFilter ? css.backdropFilter !== 'none' : false) || !webkit && (css.filter ? css.filter !== 'none' : false) || ['transform', 'perspective', 'filter'].some(value => (css.willChange || '').includes(value)) || ['paint', 'layout', 'strict', 'content'].some(value => (css.contain || '').includes(value));
133
- }
134
- function getContainingBlock(element) {
135
- let currentNode = getParentNode(element);
136
- while (isHTMLElement(currentNode) && !isLastTraversableNode(currentNode)) {
137
- if (isContainingBlock(currentNode)) {
138
- return currentNode;
139
- } else {
140
- currentNode = getParentNode(currentNode);
141
- }
142
- }
143
- return null;
144
- }
145
- function isWebKit() {
146
- if (typeof CSS === 'undefined' || !CSS.supports) return false;
147
- return CSS.supports('-webkit-backdrop-filter', 'none');
148
- }
149
- function isLastTraversableNode(node) {
150
- return ['html', 'body', '#document'].includes(getNodeName(node));
151
- }
152
- function getComputedStyle(element) {
153
- return getWindow(element).getComputedStyle(element);
154
- }
155
- function getNodeScroll(element) {
156
- if (isElement(element)) {
157
- return {
158
- scrollLeft: element.scrollLeft,
159
- scrollTop: element.scrollTop
160
- };
161
- }
162
- return {
163
- scrollLeft: element.pageXOffset,
164
- scrollTop: element.pageYOffset
165
- };
166
- }
167
- function getParentNode(node) {
168
- if (getNodeName(node) === 'html') {
169
- return node;
170
- }
171
- const result =
172
- // Step into the shadow DOM of the parent of a slotted node.
173
- node.assignedSlot ||
174
- // DOM Element detected.
175
- node.parentNode ||
176
- // ShadowRoot detected.
177
- isShadowRoot(node) && node.host ||
178
- // Fallback.
179
- getDocumentElement(node);
180
- return isShadowRoot(result) ? result.host : result;
181
- }
182
- function getNearestOverflowAncestor(node) {
183
- const parentNode = getParentNode(node);
184
- if (isLastTraversableNode(parentNode)) {
185
- return node.ownerDocument ? node.ownerDocument.body : node.body;
186
- }
187
- if (isHTMLElement(parentNode) && isOverflowElement(parentNode)) {
188
- return parentNode;
189
- }
190
- return getNearestOverflowAncestor(parentNode);
191
- }
192
- function getOverflowAncestors(node, list, traverseIframes) {
193
- var _node$ownerDocument2;
194
- if (list === void 0) {
195
- list = [];
196
- }
197
- if (traverseIframes === void 0) {
198
- traverseIframes = true;
199
- }
200
- const scrollableAncestor = getNearestOverflowAncestor(node);
201
- const isBody = scrollableAncestor === ((_node$ownerDocument2 = node.ownerDocument) == null ? void 0 : _node$ownerDocument2.body);
202
- const win = getWindow(scrollableAncestor);
203
- if (isBody) {
204
- return list.concat(win, win.visualViewport || [], isOverflowElement(scrollableAncestor) ? scrollableAncestor : [], win.frameElement && traverseIframes ? getOverflowAncestors(win.frameElement) : []);
205
- }
206
- return list.concat(scrollableAncestor, getOverflowAncestors(scrollableAncestor, [], traverseIframes));
207
- }
208
-
209
- function activeElement(doc) {
210
- let activeElement = doc.activeElement;
211
- while (((_activeElement = activeElement) == null || (_activeElement = _activeElement.shadowRoot) == null ? void 0 : _activeElement.activeElement) != null) {
212
- var _activeElement;
213
- activeElement = activeElement.shadowRoot.activeElement;
214
- }
215
- return activeElement;
216
- }
217
- function contains(parent, child) {
218
- if (!parent || !child) {
219
- return false;
220
- }
221
- const rootNode = child.getRootNode == null ? void 0 : child.getRootNode();
222
-
223
- // First, attempt with faster native method
224
- if (parent.contains(child)) {
225
- return true;
226
- }
227
-
228
- // then fallback to custom implementation with Shadow DOM support
229
- if (rootNode && isShadowRoot(rootNode)) {
230
- let next = child;
231
- while (next) {
232
- if (parent === next) {
233
- return true;
234
- }
235
- // @ts-ignore
236
- next = next.parentNode || next.host;
237
- }
238
- }
239
-
240
- // Give up, the result is false
241
- return false;
242
- }
243
- // Avoid Chrome DevTools blue warning.
244
- function getPlatform() {
245
- const uaData = navigator.userAgentData;
246
- if (uaData != null && uaData.platform) {
247
- return uaData.platform;
248
- }
249
- return navigator.platform;
250
- }
251
- function getUserAgent() {
252
- const uaData = navigator.userAgentData;
253
- if (uaData && Array.isArray(uaData.brands)) {
254
- return uaData.brands.map(_ref => {
255
- let {
256
- brand,
257
- version
258
- } = _ref;
259
- return brand + "/" + version;
260
- }).join(' ');
261
- }
262
- return navigator.userAgent;
263
- }
264
- function isVirtualPointerEvent(event) {
265
- if (isJSDOM()) return false;
266
- return !isAndroid() && event.width === 0 && event.height === 0 || isAndroid() && event.width === 1 && event.height === 1 && event.pressure === 0 && event.detail === 0 && event.pointerType === 'mouse' ||
267
- // iOS VoiceOver returns 0.333• for width/height.
268
- event.width < 1 && event.height < 1 && event.pressure === 0 && event.detail === 0 && event.pointerType === 'touch';
269
- }
270
- function isSafari() {
271
- // Chrome DevTools does not complain about navigator.vendor
272
- return /apple/i.test(navigator.vendor);
273
- }
274
- function isAndroid() {
275
- const re = /android/i;
276
- return re.test(getPlatform()) || re.test(getUserAgent());
277
- }
278
- function isMac() {
279
- return getPlatform().toLowerCase().startsWith('mac') && !navigator.maxTouchPoints;
280
- }
281
- function isJSDOM() {
282
- return getUserAgent().includes('jsdom/');
283
- }
284
- function isMouseLikePointerType(pointerType, strict) {
285
- // On some Linux machines with Chromium, mouse inputs return a `pointerType`
286
- // of "pen": https://github.com/floating-ui/floating-ui/issues/2015
287
- const values = ['mouse', 'pen'];
288
- {
289
- values.push('', undefined);
290
- }
291
- return values.includes(pointerType);
292
- }
293
- function isReactEvent(event) {
294
- return 'nativeEvent' in event;
295
- }
296
- function isRootElement(element) {
297
- return element.matches('html,body');
298
- }
299
- function getDocument(node) {
300
- return (node == null ? void 0 : node.ownerDocument) || document;
301
- }
302
- function isEventTargetWithin(event, node) {
303
- if (node == null) {
304
- return false;
305
- }
306
- if ('composedPath' in event) {
307
- return event.composedPath().includes(node);
308
- }
309
-
310
- // TS thinks `event` is of type never as it assumes all browsers support composedPath, but browsers without shadow dom don't
311
- const e = event;
312
- return e.target != null && node.contains(e.target);
313
- }
314
- function getTarget(event) {
315
- if ('composedPath' in event) {
316
- return event.composedPath()[0];
317
- }
318
-
319
- // TS thinks `event` is of type never as it assumes all browsers support
320
- // `composedPath()`, but browsers without shadow DOM don't.
321
- return event.target;
322
- }
323
- const TYPEABLE_SELECTOR = "input:not([type='hidden']):not([disabled])," + "[contenteditable]:not([contenteditable='false']),textarea:not([disabled])";
324
- function isTypeableElement(element) {
325
- return isHTMLElement(element) && element.matches(TYPEABLE_SELECTOR);
326
- }
327
-
328
- /**
329
- * Custom positioning reference element.
330
- * @see https://floating-ui.com/docs/virtual-elements
331
- */
332
-
333
- const min = Math.min;
334
- const max = Math.max;
335
- const round = Math.round;
336
- const floor = Math.floor;
337
- const createCoords = v => ({
338
- x: v,
339
- y: v
340
- });
341
- const oppositeSideMap = {
342
- left: 'right',
343
- right: 'left',
344
- bottom: 'top',
345
- top: 'bottom'
346
- };
347
- const oppositeAlignmentMap = {
348
- start: 'end',
349
- end: 'start'
350
- };
351
- function clamp(start, value, end) {
352
- return max(start, min(value, end));
353
- }
354
- function evaluate(value, param) {
355
- return typeof value === 'function' ? value(param) : value;
356
- }
357
- function getSide(placement) {
358
- return placement.split('-')[0];
359
- }
360
- function getAlignment(placement) {
361
- return placement.split('-')[1];
362
- }
363
- function getOppositeAxis(axis) {
364
- return axis === 'x' ? 'y' : 'x';
365
- }
366
- function getAxisLength(axis) {
367
- return axis === 'y' ? 'height' : 'width';
368
- }
369
- function getSideAxis(placement) {
370
- return ['top', 'bottom'].includes(getSide(placement)) ? 'y' : 'x';
371
- }
372
- function getAlignmentAxis(placement) {
373
- return getOppositeAxis(getSideAxis(placement));
374
- }
375
- function getAlignmentSides(placement, rects, rtl) {
376
- if (rtl === void 0) {
377
- rtl = false;
378
- }
379
- const alignment = getAlignment(placement);
380
- const alignmentAxis = getAlignmentAxis(placement);
381
- const length = getAxisLength(alignmentAxis);
382
- let mainAlignmentSide = alignmentAxis === 'x' ? alignment === (rtl ? 'end' : 'start') ? 'right' : 'left' : alignment === 'start' ? 'bottom' : 'top';
383
- if (rects.reference[length] > rects.floating[length]) {
384
- mainAlignmentSide = getOppositePlacement(mainAlignmentSide);
385
- }
386
- return [mainAlignmentSide, getOppositePlacement(mainAlignmentSide)];
387
- }
388
- function getExpandedPlacements(placement) {
389
- const oppositePlacement = getOppositePlacement(placement);
390
- return [getOppositeAlignmentPlacement(placement), oppositePlacement, getOppositeAlignmentPlacement(oppositePlacement)];
391
- }
392
- function getOppositeAlignmentPlacement(placement) {
393
- return placement.replace(/start|end/g, alignment => oppositeAlignmentMap[alignment]);
394
- }
395
- function getSideList(side, isStart, rtl) {
396
- const lr = ['left', 'right'];
397
- const rl = ['right', 'left'];
398
- const tb = ['top', 'bottom'];
399
- const bt = ['bottom', 'top'];
400
- switch (side) {
401
- case 'top':
402
- case 'bottom':
403
- if (rtl) return isStart ? rl : lr;
404
- return isStart ? lr : rl;
405
- case 'left':
406
- case 'right':
407
- return isStart ? tb : bt;
408
- default:
409
- return [];
410
- }
411
- }
412
- function getOppositeAxisPlacements(placement, flipAlignment, direction, rtl) {
413
- const alignment = getAlignment(placement);
414
- let list = getSideList(getSide(placement), direction === 'start', rtl);
415
- if (alignment) {
416
- list = list.map(side => side + "-" + alignment);
417
- if (flipAlignment) {
418
- list = list.concat(list.map(getOppositeAlignmentPlacement));
419
- }
420
- }
421
- return list;
422
- }
423
- function getOppositePlacement(placement) {
424
- return placement.replace(/left|right|bottom|top/g, side => oppositeSideMap[side]);
425
- }
426
- function expandPaddingObject(padding) {
427
- return {
428
- top: 0,
429
- right: 0,
430
- bottom: 0,
431
- left: 0,
432
- ...padding
433
- };
434
- }
435
- function getPaddingObject(padding) {
436
- return typeof padding !== 'number' ? expandPaddingObject(padding) : {
437
- top: padding,
438
- right: padding,
439
- bottom: padding,
440
- left: padding
441
- };
442
- }
443
- function rectToClientRect(rect) {
444
- return {
445
- ...rect,
446
- top: rect.y,
447
- left: rect.x,
448
- right: rect.x + rect.width,
449
- bottom: rect.y + rect.height
450
- };
451
- }
452
-
453
- function computeCoordsFromPlacement(_ref, placement, rtl) {
454
- let {
455
- reference,
456
- floating
457
- } = _ref;
458
- const sideAxis = getSideAxis(placement);
459
- const alignmentAxis = getAlignmentAxis(placement);
460
- const alignLength = getAxisLength(alignmentAxis);
461
- const side = getSide(placement);
462
- const isVertical = sideAxis === 'y';
463
- const commonX = reference.x + reference.width / 2 - floating.width / 2;
464
- const commonY = reference.y + reference.height / 2 - floating.height / 2;
465
- const commonAlign = reference[alignLength] / 2 - floating[alignLength] / 2;
466
- let coords;
467
- switch (side) {
468
- case 'top':
469
- coords = {
470
- x: commonX,
471
- y: reference.y - floating.height
472
- };
473
- break;
474
- case 'bottom':
475
- coords = {
476
- x: commonX,
477
- y: reference.y + reference.height
478
- };
479
- break;
480
- case 'right':
481
- coords = {
482
- x: reference.x + reference.width,
483
- y: commonY
484
- };
485
- break;
486
- case 'left':
487
- coords = {
488
- x: reference.x - floating.width,
489
- y: commonY
490
- };
491
- break;
492
- default:
493
- coords = {
494
- x: reference.x,
495
- y: reference.y
496
- };
497
- }
498
- switch (getAlignment(placement)) {
499
- case 'start':
500
- coords[alignmentAxis] -= commonAlign * (rtl && isVertical ? -1 : 1);
501
- break;
502
- case 'end':
503
- coords[alignmentAxis] += commonAlign * (rtl && isVertical ? -1 : 1);
504
- break;
505
- }
506
- return coords;
507
- }
508
-
509
- /**
510
- * Computes the `x` and `y` coordinates that will place the floating element
511
- * next to a given reference element.
512
- *
513
- * This export does not have any `platform` interface logic. You will need to
514
- * write one for the platform you are using Floating UI with.
515
- */
516
- const computePosition$1 = async (reference, floating, config) => {
517
- const {
518
- placement = 'bottom',
519
- strategy = 'absolute',
520
- middleware = [],
521
- platform
522
- } = config;
523
- const validMiddleware = middleware.filter(Boolean);
524
- const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(floating));
525
- let rects = await platform.getElementRects({
526
- reference,
527
- floating,
528
- strategy
529
- });
530
- let {
531
- x,
532
- y
533
- } = computeCoordsFromPlacement(rects, placement, rtl);
534
- let statefulPlacement = placement;
535
- let middlewareData = {};
536
- let resetCount = 0;
537
- for (let i = 0; i < validMiddleware.length; i++) {
538
- const {
539
- name,
540
- fn
541
- } = validMiddleware[i];
542
- const {
543
- x: nextX,
544
- y: nextY,
545
- data,
546
- reset
547
- } = await fn({
548
- x,
549
- y,
550
- initialPlacement: placement,
551
- placement: statefulPlacement,
552
- strategy,
553
- middlewareData,
554
- rects,
555
- platform,
556
- elements: {
557
- reference,
558
- floating
559
- }
560
- });
561
- x = nextX != null ? nextX : x;
562
- y = nextY != null ? nextY : y;
563
- middlewareData = {
564
- ...middlewareData,
565
- [name]: {
566
- ...middlewareData[name],
567
- ...data
568
- }
569
- };
570
- if (reset && resetCount <= 50) {
571
- resetCount++;
572
- if (typeof reset === 'object') {
573
- if (reset.placement) {
574
- statefulPlacement = reset.placement;
575
- }
576
- if (reset.rects) {
577
- rects = reset.rects === true ? await platform.getElementRects({
578
- reference,
579
- floating,
580
- strategy
581
- }) : reset.rects;
582
- }
583
- ({
584
- x,
585
- y
586
- } = computeCoordsFromPlacement(rects, statefulPlacement, rtl));
587
- }
588
- i = -1;
589
- }
590
- }
591
- return {
592
- x,
593
- y,
594
- placement: statefulPlacement,
595
- strategy,
596
- middlewareData
597
- };
598
- };
599
-
600
- /**
601
- * Resolves with an object of overflow side offsets that determine how much the
602
- * element is overflowing a given clipping boundary on each side.
603
- * - positive = overflowing the boundary by that number of pixels
604
- * - negative = how many pixels left before it will overflow
605
- * - 0 = lies flush with the boundary
606
- * @see https://floating-ui.com/docs/detectOverflow
607
- */
608
- async function detectOverflow(state, options) {
609
- var _await$platform$isEle;
610
- if (options === void 0) {
611
- options = {};
612
- }
613
- const {
614
- x,
615
- y,
616
- platform,
617
- rects,
618
- elements,
619
- strategy
620
- } = state;
621
- const {
622
- boundary = 'clippingAncestors',
623
- rootBoundary = 'viewport',
624
- elementContext = 'floating',
625
- altBoundary = false,
626
- padding = 0
627
- } = evaluate(options, state);
628
- const paddingObject = getPaddingObject(padding);
629
- const altContext = elementContext === 'floating' ? 'reference' : 'floating';
630
- const element = elements[altBoundary ? altContext : elementContext];
631
- const clippingClientRect = rectToClientRect(await platform.getClippingRect({
632
- 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))),
633
- boundary,
634
- rootBoundary,
635
- strategy
636
- }));
637
- const rect = elementContext === 'floating' ? {
638
- ...rects.floating,
639
- x,
640
- y
641
- } : rects.reference;
642
- const offsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(elements.floating));
643
- const offsetScale = (await (platform.isElement == null ? void 0 : platform.isElement(offsetParent))) ? (await (platform.getScale == null ? void 0 : platform.getScale(offsetParent))) || {
644
- x: 1,
645
- y: 1
646
- } : {
647
- x: 1,
648
- y: 1
649
- };
650
- const elementClientRect = rectToClientRect(platform.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform.convertOffsetParentRelativeRectToViewportRelativeRect({
651
- elements,
652
- rect,
653
- offsetParent,
654
- strategy
655
- }) : rect);
656
- return {
657
- top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y,
658
- bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y,
659
- left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x,
660
- right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x
661
- };
662
- }
663
-
664
- /**
665
- * Provides data to position an inner element of the floating element so that it
666
- * appears centered to the reference element.
667
- * @see https://floating-ui.com/docs/arrow
668
- */
669
- const arrow$3 = options => ({
670
- name: 'arrow',
671
- options,
672
- async fn(state) {
673
- const {
674
- x,
675
- y,
676
- placement,
677
- rects,
678
- platform,
679
- elements,
680
- middlewareData
681
- } = state;
682
- // Since `element` is required, we don't Partial<> the type.
683
- const {
684
- element,
685
- padding = 0
686
- } = evaluate(options, state) || {};
687
- if (element == null) {
688
- return {};
689
- }
690
- const paddingObject = getPaddingObject(padding);
691
- const coords = {
692
- x,
693
- y
694
- };
695
- const axis = getAlignmentAxis(placement);
696
- const length = getAxisLength(axis);
697
- const arrowDimensions = await platform.getDimensions(element);
698
- const isYAxis = axis === 'y';
699
- const minProp = isYAxis ? 'top' : 'left';
700
- const maxProp = isYAxis ? 'bottom' : 'right';
701
- const clientProp = isYAxis ? 'clientHeight' : 'clientWidth';
702
- const endDiff = rects.reference[length] + rects.reference[axis] - coords[axis] - rects.floating[length];
703
- const startDiff = coords[axis] - rects.reference[axis];
704
- const arrowOffsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(element));
705
- let clientSize = arrowOffsetParent ? arrowOffsetParent[clientProp] : 0;
706
-
707
- // DOM platform can return `window` as the `offsetParent`.
708
- if (!clientSize || !(await (platform.isElement == null ? void 0 : platform.isElement(arrowOffsetParent)))) {
709
- clientSize = elements.floating[clientProp] || rects.floating[length];
710
- }
711
- const centerToReference = endDiff / 2 - startDiff / 2;
712
-
713
- // If the padding is large enough that it causes the arrow to no longer be
714
- // centered, modify the padding so that it is centered.
715
- const largestPossiblePadding = clientSize / 2 - arrowDimensions[length] / 2 - 1;
716
- const minPadding = min(paddingObject[minProp], largestPossiblePadding);
717
- const maxPadding = min(paddingObject[maxProp], largestPossiblePadding);
718
-
719
- // Make sure the arrow doesn't overflow the floating element if the center
720
- // point is outside the floating element's bounds.
721
- const min$1 = minPadding;
722
- const max = clientSize - arrowDimensions[length] - maxPadding;
723
- const center = clientSize / 2 - arrowDimensions[length] / 2 + centerToReference;
724
- const offset = clamp(min$1, center, max);
725
-
726
- // If the reference is small enough that the arrow's padding causes it to
727
- // to point to nothing for an aligned placement, adjust the offset of the
728
- // floating element itself. To ensure `shift()` continues to take action,
729
- // a single reset is performed when this is true.
730
- const shouldAddOffset = !middlewareData.arrow && getAlignment(placement) != null && center !== offset && rects.reference[length] / 2 - (center < min$1 ? minPadding : maxPadding) - arrowDimensions[length] / 2 < 0;
731
- const alignmentOffset = shouldAddOffset ? center < min$1 ? center - min$1 : center - max : 0;
732
- return {
733
- [axis]: coords[axis] + alignmentOffset,
734
- data: {
735
- [axis]: offset,
736
- centerOffset: center - offset - alignmentOffset,
737
- ...(shouldAddOffset && {
738
- alignmentOffset
739
- })
740
- },
741
- reset: shouldAddOffset
742
- };
743
- }
744
- });
745
-
746
- /**
747
- * Optimizes the visibility of the floating element by flipping the `placement`
748
- * in order to keep it in view when the preferred placement(s) will overflow the
749
- * clipping boundary. Alternative to `autoPlacement`.
750
- * @see https://floating-ui.com/docs/flip
751
- */
752
- const flip$2 = function (options) {
753
- if (options === void 0) {
754
- options = {};
755
- }
756
- return {
757
- name: 'flip',
758
- options,
759
- async fn(state) {
760
- var _middlewareData$arrow, _middlewareData$flip;
761
- const {
762
- placement,
763
- middlewareData,
764
- rects,
765
- initialPlacement,
766
- platform,
767
- elements
768
- } = state;
769
- const {
770
- mainAxis: checkMainAxis = true,
771
- crossAxis: checkCrossAxis = true,
772
- fallbackPlacements: specifiedFallbackPlacements,
773
- fallbackStrategy = 'bestFit',
774
- fallbackAxisSideDirection = 'none',
775
- flipAlignment = true,
776
- ...detectOverflowOptions
777
- } = evaluate(options, state);
778
-
779
- // If a reset by the arrow was caused due to an alignment offset being
780
- // added, we should skip any logic now since `flip()` has already done its
781
- // work.
782
- // https://github.com/floating-ui/floating-ui/issues/2549#issuecomment-1719601643
783
- if ((_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {
784
- return {};
785
- }
786
- const side = getSide(placement);
787
- const isBasePlacement = getSide(initialPlacement) === initialPlacement;
788
- const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating));
789
- const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipAlignment ? [getOppositePlacement(initialPlacement)] : getExpandedPlacements(initialPlacement));
790
- if (!specifiedFallbackPlacements && fallbackAxisSideDirection !== 'none') {
791
- fallbackPlacements.push(...getOppositeAxisPlacements(initialPlacement, flipAlignment, fallbackAxisSideDirection, rtl));
792
- }
793
- const placements = [initialPlacement, ...fallbackPlacements];
794
- const overflow = await detectOverflow(state, detectOverflowOptions);
795
- const overflows = [];
796
- let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || [];
797
- if (checkMainAxis) {
798
- overflows.push(overflow[side]);
799
- }
800
- if (checkCrossAxis) {
801
- const sides = getAlignmentSides(placement, rects, rtl);
802
- overflows.push(overflow[sides[0]], overflow[sides[1]]);
803
- }
804
- overflowsData = [...overflowsData, {
805
- placement,
806
- overflows
807
- }];
808
-
809
- // One or more sides is overflowing.
810
- if (!overflows.every(side => side <= 0)) {
811
- var _middlewareData$flip2, _overflowsData$filter;
812
- const nextIndex = (((_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) || 0) + 1;
813
- const nextPlacement = placements[nextIndex];
814
- if (nextPlacement) {
815
- // Try next placement and re-run the lifecycle.
816
- return {
817
- data: {
818
- index: nextIndex,
819
- overflows: overflowsData
820
- },
821
- reset: {
822
- placement: nextPlacement
823
- }
824
- };
825
- }
826
-
827
- // First, find the candidates that fit on the mainAxis side of overflow,
828
- // then find the placement that fits the best on the main crossAxis side.
829
- 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;
830
-
831
- // Otherwise fallback.
832
- if (!resetPlacement) {
833
- switch (fallbackStrategy) {
834
- case 'bestFit':
835
- {
836
- var _overflowsData$map$so;
837
- const placement = (_overflowsData$map$so = overflowsData.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$map$so[0];
838
- if (placement) {
839
- resetPlacement = placement;
840
- }
841
- break;
842
- }
843
- case 'initialPlacement':
844
- resetPlacement = initialPlacement;
845
- break;
846
- }
847
- }
848
- if (placement !== resetPlacement) {
849
- return {
850
- reset: {
851
- placement: resetPlacement
852
- }
853
- };
854
- }
855
- }
856
- return {};
857
- }
858
- };
859
- };
860
-
861
- // For type backwards-compatibility, the `OffsetOptions` type was also
862
- // Derivable.
863
-
864
- async function convertValueToCoords(state, options) {
865
- const {
866
- placement,
867
- platform,
868
- elements
869
- } = state;
870
- const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating));
871
- const side = getSide(placement);
872
- const alignment = getAlignment(placement);
873
- const isVertical = getSideAxis(placement) === 'y';
874
- const mainAxisMulti = ['left', 'top'].includes(side) ? -1 : 1;
875
- const crossAxisMulti = rtl && isVertical ? -1 : 1;
876
- const rawValue = evaluate(options, state);
877
- let {
878
- mainAxis,
879
- crossAxis,
880
- alignmentAxis
881
- } = typeof rawValue === 'number' ? {
882
- mainAxis: rawValue,
883
- crossAxis: 0,
884
- alignmentAxis: null
885
- } : {
886
- mainAxis: 0,
887
- crossAxis: 0,
888
- alignmentAxis: null,
889
- ...rawValue
890
- };
891
- if (alignment && typeof alignmentAxis === 'number') {
892
- crossAxis = alignment === 'end' ? alignmentAxis * -1 : alignmentAxis;
893
- }
894
- return isVertical ? {
895
- x: crossAxis * crossAxisMulti,
896
- y: mainAxis * mainAxisMulti
897
- } : {
898
- x: mainAxis * mainAxisMulti,
899
- y: crossAxis * crossAxisMulti
900
- };
901
- }
902
-
903
- /**
904
- * Modifies the placement by translating the floating element along the
905
- * specified axes.
906
- * A number (shorthand for `mainAxis` or distance), or an axes configuration
907
- * object may be passed.
908
- * @see https://floating-ui.com/docs/offset
909
- */
910
- const offset$2 = function (options) {
911
- if (options === void 0) {
912
- options = 0;
913
- }
914
- return {
915
- name: 'offset',
916
- options,
917
- async fn(state) {
918
- var _middlewareData$offse, _middlewareData$arrow;
919
- const {
920
- x,
921
- y,
922
- placement,
923
- middlewareData
924
- } = state;
925
- const diffCoords = await convertValueToCoords(state, options);
926
-
927
- // If the placement is the same and the arrow caused an alignment offset
928
- // then we don't need to change the positioning coordinates.
929
- if (placement === ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse.placement) && (_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {
930
- return {};
931
- }
932
- return {
933
- x: x + diffCoords.x,
934
- y: y + diffCoords.y,
935
- data: {
936
- ...diffCoords,
937
- placement
938
- }
939
- };
940
- }
941
- };
942
- };
943
-
944
- /**
945
- * Optimizes the visibility of the floating element by shifting it in order to
946
- * keep it in view when it will overflow the clipping boundary.
947
- * @see https://floating-ui.com/docs/shift
948
- */
949
- const shift$2 = function (options) {
950
- if (options === void 0) {
951
- options = {};
952
- }
953
- return {
954
- name: 'shift',
955
- options,
956
- async fn(state) {
957
- const {
958
- x,
959
- y,
960
- placement
961
- } = state;
962
- const {
963
- mainAxis: checkMainAxis = true,
964
- crossAxis: checkCrossAxis = false,
965
- limiter = {
966
- fn: _ref => {
967
- let {
968
- x,
969
- y
970
- } = _ref;
971
- return {
972
- x,
973
- y
974
- };
975
- }
976
- },
977
- ...detectOverflowOptions
978
- } = evaluate(options, state);
979
- const coords = {
980
- x,
981
- y
982
- };
983
- const overflow = await detectOverflow(state, detectOverflowOptions);
984
- const crossAxis = getSideAxis(getSide(placement));
985
- const mainAxis = getOppositeAxis(crossAxis);
986
- let mainAxisCoord = coords[mainAxis];
987
- let crossAxisCoord = coords[crossAxis];
988
- if (checkMainAxis) {
989
- const minSide = mainAxis === 'y' ? 'top' : 'left';
990
- const maxSide = mainAxis === 'y' ? 'bottom' : 'right';
991
- const min = mainAxisCoord + overflow[minSide];
992
- const max = mainAxisCoord - overflow[maxSide];
993
- mainAxisCoord = clamp(min, mainAxisCoord, max);
994
- }
995
- if (checkCrossAxis) {
996
- const minSide = crossAxis === 'y' ? 'top' : 'left';
997
- const maxSide = crossAxis === 'y' ? 'bottom' : 'right';
998
- const min = crossAxisCoord + overflow[minSide];
999
- const max = crossAxisCoord - overflow[maxSide];
1000
- crossAxisCoord = clamp(min, crossAxisCoord, max);
1001
- }
1002
- const limitedCoords = limiter.fn({
1003
- ...state,
1004
- [mainAxis]: mainAxisCoord,
1005
- [crossAxis]: crossAxisCoord
1006
- });
1007
- return {
1008
- ...limitedCoords,
1009
- data: {
1010
- x: limitedCoords.x - x,
1011
- y: limitedCoords.y - y
1012
- }
1013
- };
1014
- }
1015
- };
1016
- };
1017
-
1018
- function getCssDimensions(element) {
1019
- const css = getComputedStyle(element);
1020
- // In testing environments, the `width` and `height` properties are empty
1021
- // strings for SVG elements, returning NaN. Fallback to `0` in this case.
1022
- let width = parseFloat(css.width) || 0;
1023
- let height = parseFloat(css.height) || 0;
1024
- const hasOffset = isHTMLElement(element);
1025
- const offsetWidth = hasOffset ? element.offsetWidth : width;
1026
- const offsetHeight = hasOffset ? element.offsetHeight : height;
1027
- const shouldFallback = round(width) !== offsetWidth || round(height) !== offsetHeight;
1028
- if (shouldFallback) {
1029
- width = offsetWidth;
1030
- height = offsetHeight;
1031
- }
1032
- return {
1033
- width,
1034
- height,
1035
- $: shouldFallback
1036
- };
1037
- }
1038
-
1039
- function unwrapElement(element) {
1040
- return !isElement(element) ? element.contextElement : element;
1041
- }
1042
-
1043
- function getScale(element) {
1044
- const domElement = unwrapElement(element);
1045
- if (!isHTMLElement(domElement)) {
1046
- return createCoords(1);
1047
- }
1048
- const rect = domElement.getBoundingClientRect();
1049
- const {
1050
- width,
1051
- height,
1052
- $
1053
- } = getCssDimensions(domElement);
1054
- let x = ($ ? round(rect.width) : rect.width) / width;
1055
- let y = ($ ? round(rect.height) : rect.height) / height;
1056
-
1057
- // 0, NaN, or Infinity should always fallback to 1.
1058
-
1059
- if (!x || !Number.isFinite(x)) {
1060
- x = 1;
1061
- }
1062
- if (!y || !Number.isFinite(y)) {
1063
- y = 1;
1064
- }
1065
- return {
1066
- x,
1067
- y
1068
- };
1069
- }
1070
-
1071
- const noOffsets = /*#__PURE__*/createCoords(0);
1072
- function getVisualOffsets(element) {
1073
- const win = getWindow(element);
1074
- if (!isWebKit() || !win.visualViewport) {
1075
- return noOffsets;
1076
- }
1077
- return {
1078
- x: win.visualViewport.offsetLeft,
1079
- y: win.visualViewport.offsetTop
1080
- };
1081
- }
1082
- function shouldAddVisualOffsets(element, isFixed, floatingOffsetParent) {
1083
- if (isFixed === void 0) {
1084
- isFixed = false;
1085
- }
1086
- if (!floatingOffsetParent || isFixed && floatingOffsetParent !== getWindow(element)) {
1087
- return false;
1088
- }
1089
- return isFixed;
1090
- }
1091
-
1092
- function getBoundingClientRect(element, includeScale, isFixedStrategy, offsetParent) {
1093
- if (includeScale === void 0) {
1094
- includeScale = false;
1095
- }
1096
- if (isFixedStrategy === void 0) {
1097
- isFixedStrategy = false;
1098
- }
1099
- const clientRect = element.getBoundingClientRect();
1100
- const domElement = unwrapElement(element);
1101
- let scale = createCoords(1);
1102
- if (includeScale) {
1103
- if (offsetParent) {
1104
- if (isElement(offsetParent)) {
1105
- scale = getScale(offsetParent);
1106
- }
1107
- } else {
1108
- scale = getScale(element);
1109
- }
1110
- }
1111
- const visualOffsets = shouldAddVisualOffsets(domElement, isFixedStrategy, offsetParent) ? getVisualOffsets(domElement) : createCoords(0);
1112
- let x = (clientRect.left + visualOffsets.x) / scale.x;
1113
- let y = (clientRect.top + visualOffsets.y) / scale.y;
1114
- let width = clientRect.width / scale.x;
1115
- let height = clientRect.height / scale.y;
1116
- if (domElement) {
1117
- const win = getWindow(domElement);
1118
- const offsetWin = offsetParent && isElement(offsetParent) ? getWindow(offsetParent) : offsetParent;
1119
- let currentWin = win;
1120
- let currentIFrame = currentWin.frameElement;
1121
- while (currentIFrame && offsetParent && offsetWin !== currentWin) {
1122
- const iframeScale = getScale(currentIFrame);
1123
- const iframeRect = currentIFrame.getBoundingClientRect();
1124
- const css = getComputedStyle(currentIFrame);
1125
- const left = iframeRect.left + (currentIFrame.clientLeft + parseFloat(css.paddingLeft)) * iframeScale.x;
1126
- const top = iframeRect.top + (currentIFrame.clientTop + parseFloat(css.paddingTop)) * iframeScale.y;
1127
- x *= iframeScale.x;
1128
- y *= iframeScale.y;
1129
- width *= iframeScale.x;
1130
- height *= iframeScale.y;
1131
- x += left;
1132
- y += top;
1133
- currentWin = getWindow(currentIFrame);
1134
- currentIFrame = currentWin.frameElement;
1135
- }
1136
- }
1137
- return rectToClientRect({
1138
- width,
1139
- height,
1140
- x,
1141
- y
1142
- });
1143
- }
1144
-
1145
- const topLayerSelectors = [':popover-open', ':modal'];
1146
- function isTopLayer(element) {
1147
- return topLayerSelectors.some(selector => {
1148
- try {
1149
- return element.matches(selector);
1150
- } catch (e) {
1151
- return false;
1152
- }
1153
- });
1154
- }
1155
-
1156
- function convertOffsetParentRelativeRectToViewportRelativeRect(_ref) {
1157
- let {
1158
- elements,
1159
- rect,
1160
- offsetParent,
1161
- strategy
1162
- } = _ref;
1163
- const isFixed = strategy === 'fixed';
1164
- const documentElement = getDocumentElement(offsetParent);
1165
- const topLayer = elements ? isTopLayer(elements.floating) : false;
1166
- if (offsetParent === documentElement || topLayer && isFixed) {
1167
- return rect;
1168
- }
1169
- let scroll = {
1170
- scrollLeft: 0,
1171
- scrollTop: 0
1172
- };
1173
- let scale = createCoords(1);
1174
- const offsets = createCoords(0);
1175
- const isOffsetParentAnElement = isHTMLElement(offsetParent);
1176
- if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
1177
- if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) {
1178
- scroll = getNodeScroll(offsetParent);
1179
- }
1180
- if (isHTMLElement(offsetParent)) {
1181
- const offsetRect = getBoundingClientRect(offsetParent);
1182
- scale = getScale(offsetParent);
1183
- offsets.x = offsetRect.x + offsetParent.clientLeft;
1184
- offsets.y = offsetRect.y + offsetParent.clientTop;
1185
- }
1186
- }
1187
- return {
1188
- width: rect.width * scale.x,
1189
- height: rect.height * scale.y,
1190
- x: rect.x * scale.x - scroll.scrollLeft * scale.x + offsets.x,
1191
- y: rect.y * scale.y - scroll.scrollTop * scale.y + offsets.y
1192
- };
1193
- }
1194
-
1195
- function getClientRects(element) {
1196
- return Array.from(element.getClientRects());
1197
- }
1198
-
1199
- function getWindowScrollBarX(element) {
1200
- // If <html> has a CSS width greater than the viewport, then this will be
1201
- // incorrect for RTL.
1202
- return getBoundingClientRect(getDocumentElement(element)).left + getNodeScroll(element).scrollLeft;
1203
- }
1204
-
1205
- // Gets the entire size of the scrollable document area, even extending outside
1206
- // of the `<html>` and `<body>` rect bounds if horizontally scrollable.
1207
- function getDocumentRect(element) {
1208
- const html = getDocumentElement(element);
1209
- const scroll = getNodeScroll(element);
1210
- const body = element.ownerDocument.body;
1211
- const width = max(html.scrollWidth, html.clientWidth, body.scrollWidth, body.clientWidth);
1212
- const height = max(html.scrollHeight, html.clientHeight, body.scrollHeight, body.clientHeight);
1213
- let x = -scroll.scrollLeft + getWindowScrollBarX(element);
1214
- const y = -scroll.scrollTop;
1215
- if (getComputedStyle(body).direction === 'rtl') {
1216
- x += max(html.clientWidth, body.clientWidth) - width;
1217
- }
1218
- return {
1219
- width,
1220
- height,
1221
- x,
1222
- y
1223
- };
1224
- }
1225
-
1226
- function getViewportRect(element, strategy) {
1227
- const win = getWindow(element);
1228
- const html = getDocumentElement(element);
1229
- const visualViewport = win.visualViewport;
1230
- let width = html.clientWidth;
1231
- let height = html.clientHeight;
1232
- let x = 0;
1233
- let y = 0;
1234
- if (visualViewport) {
1235
- width = visualViewport.width;
1236
- height = visualViewport.height;
1237
- const visualViewportBased = isWebKit();
1238
- if (!visualViewportBased || visualViewportBased && strategy === 'fixed') {
1239
- x = visualViewport.offsetLeft;
1240
- y = visualViewport.offsetTop;
1241
- }
1242
- }
1243
- return {
1244
- width,
1245
- height,
1246
- x,
1247
- y
1248
- };
1249
- }
1250
-
1251
- // Returns the inner client rect, subtracting scrollbars if present.
1252
- function getInnerBoundingClientRect(element, strategy) {
1253
- const clientRect = getBoundingClientRect(element, true, strategy === 'fixed');
1254
- const top = clientRect.top + element.clientTop;
1255
- const left = clientRect.left + element.clientLeft;
1256
- const scale = isHTMLElement(element) ? getScale(element) : createCoords(1);
1257
- const width = element.clientWidth * scale.x;
1258
- const height = element.clientHeight * scale.y;
1259
- const x = left * scale.x;
1260
- const y = top * scale.y;
1261
- return {
1262
- width,
1263
- height,
1264
- x,
1265
- y
1266
- };
1267
- }
1268
- function getClientRectFromClippingAncestor(element, clippingAncestor, strategy) {
1269
- let rect;
1270
- if (clippingAncestor === 'viewport') {
1271
- rect = getViewportRect(element, strategy);
1272
- } else if (clippingAncestor === 'document') {
1273
- rect = getDocumentRect(getDocumentElement(element));
1274
- } else if (isElement(clippingAncestor)) {
1275
- rect = getInnerBoundingClientRect(clippingAncestor, strategy);
1276
- } else {
1277
- const visualOffsets = getVisualOffsets(element);
1278
- rect = {
1279
- ...clippingAncestor,
1280
- x: clippingAncestor.x - visualOffsets.x,
1281
- y: clippingAncestor.y - visualOffsets.y
1282
- };
1283
- }
1284
- return rectToClientRect(rect);
1285
- }
1286
- function hasFixedPositionAncestor(element, stopNode) {
1287
- const parentNode = getParentNode(element);
1288
- if (parentNode === stopNode || !isElement(parentNode) || isLastTraversableNode(parentNode)) {
1289
- return false;
1290
- }
1291
- return getComputedStyle(parentNode).position === 'fixed' || hasFixedPositionAncestor(parentNode, stopNode);
1292
- }
1293
-
1294
- // A "clipping ancestor" is an `overflow` element with the characteristic of
1295
- // clipping (or hiding) child elements. This returns all clipping ancestors
1296
- // of the given element up the tree.
1297
- function getClippingElementAncestors(element, cache) {
1298
- const cachedResult = cache.get(element);
1299
- if (cachedResult) {
1300
- return cachedResult;
1301
- }
1302
- let result = getOverflowAncestors(element, [], false).filter(el => isElement(el) && getNodeName(el) !== 'body');
1303
- let currentContainingBlockComputedStyle = null;
1304
- const elementIsFixed = getComputedStyle(element).position === 'fixed';
1305
- let currentNode = elementIsFixed ? getParentNode(element) : element;
1306
-
1307
- // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block
1308
- while (isElement(currentNode) && !isLastTraversableNode(currentNode)) {
1309
- const computedStyle = getComputedStyle(currentNode);
1310
- const currentNodeIsContaining = isContainingBlock(currentNode);
1311
- if (!currentNodeIsContaining && computedStyle.position === 'fixed') {
1312
- currentContainingBlockComputedStyle = null;
1313
- }
1314
- const shouldDropCurrentNode = elementIsFixed ? !currentNodeIsContaining && !currentContainingBlockComputedStyle : !currentNodeIsContaining && computedStyle.position === 'static' && !!currentContainingBlockComputedStyle && ['absolute', 'fixed'].includes(currentContainingBlockComputedStyle.position) || isOverflowElement(currentNode) && !currentNodeIsContaining && hasFixedPositionAncestor(element, currentNode);
1315
- if (shouldDropCurrentNode) {
1316
- // Drop non-containing blocks.
1317
- result = result.filter(ancestor => ancestor !== currentNode);
1318
- } else {
1319
- // Record last containing block for next iteration.
1320
- currentContainingBlockComputedStyle = computedStyle;
1321
- }
1322
- currentNode = getParentNode(currentNode);
1323
- }
1324
- cache.set(element, result);
1325
- return result;
1326
- }
1327
-
1328
- // Gets the maximum area that the element is visible in due to any number of
1329
- // clipping ancestors.
1330
- function getClippingRect(_ref) {
1331
- let {
1332
- element,
1333
- boundary,
1334
- rootBoundary,
1335
- strategy
1336
- } = _ref;
1337
- const elementClippingAncestors = boundary === 'clippingAncestors' ? isTopLayer(element) ? [] : getClippingElementAncestors(element, this._c) : [].concat(boundary);
1338
- const clippingAncestors = [...elementClippingAncestors, rootBoundary];
1339
- const firstClippingAncestor = clippingAncestors[0];
1340
- const clippingRect = clippingAncestors.reduce((accRect, clippingAncestor) => {
1341
- const rect = getClientRectFromClippingAncestor(element, clippingAncestor, strategy);
1342
- accRect.top = max(rect.top, accRect.top);
1343
- accRect.right = min(rect.right, accRect.right);
1344
- accRect.bottom = min(rect.bottom, accRect.bottom);
1345
- accRect.left = max(rect.left, accRect.left);
1346
- return accRect;
1347
- }, getClientRectFromClippingAncestor(element, firstClippingAncestor, strategy));
1348
- return {
1349
- width: clippingRect.right - clippingRect.left,
1350
- height: clippingRect.bottom - clippingRect.top,
1351
- x: clippingRect.left,
1352
- y: clippingRect.top
1353
- };
1354
- }
1355
-
1356
- function getDimensions(element) {
1357
- const {
1358
- width,
1359
- height
1360
- } = getCssDimensions(element);
1361
- return {
1362
- width,
1363
- height
1364
- };
1365
- }
1366
-
1367
- function getRectRelativeToOffsetParent(element, offsetParent, strategy) {
1368
- const isOffsetParentAnElement = isHTMLElement(offsetParent);
1369
- const documentElement = getDocumentElement(offsetParent);
1370
- const isFixed = strategy === 'fixed';
1371
- const rect = getBoundingClientRect(element, true, isFixed, offsetParent);
1372
- let scroll = {
1373
- scrollLeft: 0,
1374
- scrollTop: 0
1375
- };
1376
- const offsets = createCoords(0);
1377
- if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
1378
- if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) {
1379
- scroll = getNodeScroll(offsetParent);
1380
- }
1381
- if (isOffsetParentAnElement) {
1382
- const offsetRect = getBoundingClientRect(offsetParent, true, isFixed, offsetParent);
1383
- offsets.x = offsetRect.x + offsetParent.clientLeft;
1384
- offsets.y = offsetRect.y + offsetParent.clientTop;
1385
- } else if (documentElement) {
1386
- offsets.x = getWindowScrollBarX(documentElement);
1387
- }
1388
- }
1389
- const x = rect.left + scroll.scrollLeft - offsets.x;
1390
- const y = rect.top + scroll.scrollTop - offsets.y;
1391
- return {
1392
- x,
1393
- y,
1394
- width: rect.width,
1395
- height: rect.height
1396
- };
1397
- }
1398
-
1399
- function isStaticPositioned(element) {
1400
- return getComputedStyle(element).position === 'static';
1401
- }
1402
-
1403
- function getTrueOffsetParent(element, polyfill) {
1404
- if (!isHTMLElement(element) || getComputedStyle(element).position === 'fixed') {
1405
- return null;
1406
- }
1407
- if (polyfill) {
1408
- return polyfill(element);
1409
- }
1410
- return element.offsetParent;
1411
- }
1412
-
1413
- // Gets the closest ancestor positioned element. Handles some edge cases,
1414
- // such as table ancestors and cross browser bugs.
1415
- function getOffsetParent(element, polyfill) {
1416
- const win = getWindow(element);
1417
- if (isTopLayer(element)) {
1418
- return win;
1419
- }
1420
- if (!isHTMLElement(element)) {
1421
- let svgOffsetParent = getParentNode(element);
1422
- while (svgOffsetParent && !isLastTraversableNode(svgOffsetParent)) {
1423
- if (isElement(svgOffsetParent) && !isStaticPositioned(svgOffsetParent)) {
1424
- return svgOffsetParent;
1425
- }
1426
- svgOffsetParent = getParentNode(svgOffsetParent);
1427
- }
1428
- return win;
1429
- }
1430
- let offsetParent = getTrueOffsetParent(element, polyfill);
1431
- while (offsetParent && isTableElement(offsetParent) && isStaticPositioned(offsetParent)) {
1432
- offsetParent = getTrueOffsetParent(offsetParent, polyfill);
1433
- }
1434
- if (offsetParent && isLastTraversableNode(offsetParent) && isStaticPositioned(offsetParent) && !isContainingBlock(offsetParent)) {
1435
- return win;
1436
- }
1437
- return offsetParent || getContainingBlock(element) || win;
1438
- }
1439
-
1440
- const getElementRects = async function (data) {
1441
- const getOffsetParentFn = this.getOffsetParent || getOffsetParent;
1442
- const getDimensionsFn = this.getDimensions;
1443
- const floatingDimensions = await getDimensionsFn(data.floating);
1444
- return {
1445
- reference: getRectRelativeToOffsetParent(data.reference, await getOffsetParentFn(data.floating), data.strategy),
1446
- floating: {
1447
- x: 0,
1448
- y: 0,
1449
- width: floatingDimensions.width,
1450
- height: floatingDimensions.height
1451
- }
1452
- };
1453
- };
1454
-
1455
- function isRTL(element) {
1456
- return getComputedStyle(element).direction === 'rtl';
1457
- }
1458
-
1459
- const platform = {
1460
- convertOffsetParentRelativeRectToViewportRelativeRect,
1461
- getDocumentElement,
1462
- getClippingRect,
1463
- getOffsetParent,
1464
- getElementRects,
1465
- getClientRects,
1466
- getDimensions,
1467
- getScale,
1468
- isElement,
1469
- isRTL
1470
- };
1471
-
1472
- // https://samthor.au/2021/observing-dom/
1473
- function observeMove(element, onMove) {
1474
- let io = null;
1475
- let timeoutId;
1476
- const root = getDocumentElement(element);
1477
- function cleanup() {
1478
- var _io;
1479
- clearTimeout(timeoutId);
1480
- (_io = io) == null || _io.disconnect();
1481
- io = null;
1482
- }
1483
- function refresh(skip, threshold) {
1484
- if (skip === void 0) {
1485
- skip = false;
1486
- }
1487
- if (threshold === void 0) {
1488
- threshold = 1;
1489
- }
1490
- cleanup();
1491
- const {
1492
- left,
1493
- top,
1494
- width,
1495
- height
1496
- } = element.getBoundingClientRect();
1497
- if (!skip) {
1498
- onMove();
1499
- }
1500
- if (!width || !height) {
1501
- return;
1502
- }
1503
- const insetTop = floor(top);
1504
- const insetRight = floor(root.clientWidth - (left + width));
1505
- const insetBottom = floor(root.clientHeight - (top + height));
1506
- const insetLeft = floor(left);
1507
- const rootMargin = -insetTop + "px " + -insetRight + "px " + -insetBottom + "px " + -insetLeft + "px";
1508
- const options = {
1509
- rootMargin,
1510
- threshold: max(0, min(1, threshold)) || 1
1511
- };
1512
- let isFirstUpdate = true;
1513
- function handleObserve(entries) {
1514
- const ratio = entries[0].intersectionRatio;
1515
- if (ratio !== threshold) {
1516
- if (!isFirstUpdate) {
1517
- return refresh();
1518
- }
1519
- if (!ratio) {
1520
- // If the reference is clipped, the ratio is 0. Throttle the refresh
1521
- // to prevent an infinite loop of updates.
1522
- timeoutId = setTimeout(() => {
1523
- refresh(false, 1e-7);
1524
- }, 1000);
1525
- } else {
1526
- refresh(false, ratio);
1527
- }
1528
- }
1529
- isFirstUpdate = false;
1530
- }
1531
-
1532
- // Older browsers don't support a `document` as the root and will throw an
1533
- // error.
1534
- try {
1535
- io = new IntersectionObserver(handleObserve, {
1536
- ...options,
1537
- // Handle <iframe>s
1538
- root: root.ownerDocument
1539
- });
1540
- } catch (e) {
1541
- io = new IntersectionObserver(handleObserve, options);
1542
- }
1543
- io.observe(element);
1544
- }
1545
- refresh(true);
1546
- return cleanup;
1547
- }
1548
-
1549
- /**
1550
- * Automatically updates the position of the floating element when necessary.
1551
- * Should only be called when the floating element is mounted on the DOM or
1552
- * visible on the screen.
1553
- * @returns cleanup function that should be invoked when the floating element is
1554
- * removed from the DOM or hidden from the screen.
1555
- * @see https://floating-ui.com/docs/autoUpdate
1556
- */
1557
- function autoUpdate(reference, floating, update, options) {
1558
- if (options === void 0) {
1559
- options = {};
1560
- }
1561
- const {
1562
- ancestorScroll = true,
1563
- ancestorResize = true,
1564
- elementResize = typeof ResizeObserver === 'function',
1565
- layoutShift = typeof IntersectionObserver === 'function',
1566
- animationFrame = false
1567
- } = options;
1568
- const referenceEl = unwrapElement(reference);
1569
- const ancestors = ancestorScroll || ancestorResize ? [...(referenceEl ? getOverflowAncestors(referenceEl) : []), ...getOverflowAncestors(floating)] : [];
1570
- ancestors.forEach(ancestor => {
1571
- ancestorScroll && ancestor.addEventListener('scroll', update, {
1572
- passive: true
1573
- });
1574
- ancestorResize && ancestor.addEventListener('resize', update);
1575
- });
1576
- const cleanupIo = referenceEl && layoutShift ? observeMove(referenceEl, update) : null;
1577
- let reobserveFrame = -1;
1578
- let resizeObserver = null;
1579
- if (elementResize) {
1580
- resizeObserver = new ResizeObserver(_ref => {
1581
- let [firstEntry] = _ref;
1582
- if (firstEntry && firstEntry.target === referenceEl && resizeObserver) {
1583
- // Prevent update loops when using the `size` middleware.
1584
- // https://github.com/floating-ui/floating-ui/issues/1740
1585
- resizeObserver.unobserve(floating);
1586
- cancelAnimationFrame(reobserveFrame);
1587
- reobserveFrame = requestAnimationFrame(() => {
1588
- var _resizeObserver;
1589
- (_resizeObserver = resizeObserver) == null || _resizeObserver.observe(floating);
1590
- });
1591
- }
1592
- update();
1593
- });
1594
- if (referenceEl && !animationFrame) {
1595
- resizeObserver.observe(referenceEl);
1596
- }
1597
- resizeObserver.observe(floating);
1598
- }
1599
- let frameId;
1600
- let prevRefRect = animationFrame ? getBoundingClientRect(reference) : null;
1601
- if (animationFrame) {
1602
- frameLoop();
1603
- }
1604
- function frameLoop() {
1605
- const nextRefRect = getBoundingClientRect(reference);
1606
- if (prevRefRect && (nextRefRect.x !== prevRefRect.x || nextRefRect.y !== prevRefRect.y || nextRefRect.width !== prevRefRect.width || nextRefRect.height !== prevRefRect.height)) {
1607
- update();
1608
- }
1609
- prevRefRect = nextRefRect;
1610
- frameId = requestAnimationFrame(frameLoop);
1611
- }
1612
- update();
1613
- return () => {
1614
- var _resizeObserver2;
1615
- ancestors.forEach(ancestor => {
1616
- ancestorScroll && ancestor.removeEventListener('scroll', update);
1617
- ancestorResize && ancestor.removeEventListener('resize', update);
1618
- });
1619
- cleanupIo == null || cleanupIo();
1620
- (_resizeObserver2 = resizeObserver) == null || _resizeObserver2.disconnect();
1621
- resizeObserver = null;
1622
- if (animationFrame) {
1623
- cancelAnimationFrame(frameId);
1624
- }
1625
- };
1626
- }
1627
-
1628
- /**
1629
- * Modifies the placement by translating the floating element along the
1630
- * specified axes.
1631
- * A number (shorthand for `mainAxis` or distance), or an axes configuration
1632
- * object may be passed.
1633
- * @see https://floating-ui.com/docs/offset
1634
- */
1635
- const offset$1 = offset$2;
1636
-
1637
- /**
1638
- * Optimizes the visibility of the floating element by shifting it in order to
1639
- * keep it in view when it will overflow the clipping boundary.
1640
- * @see https://floating-ui.com/docs/shift
1641
- */
1642
- const shift$1 = shift$2;
1643
-
1644
- /**
1645
- * Optimizes the visibility of the floating element by flipping the `placement`
1646
- * in order to keep it in view when the preferred placement(s) will overflow the
1647
- * clipping boundary. Alternative to `autoPlacement`.
1648
- * @see https://floating-ui.com/docs/flip
1649
- */
1650
- const flip$1 = flip$2;
1651
-
1652
- /**
1653
- * Provides data to position an inner element of the floating element so that it
1654
- * appears centered to the reference element.
1655
- * @see https://floating-ui.com/docs/arrow
1656
- */
1657
- const arrow$2 = arrow$3;
1658
-
1659
- /**
1660
- * Computes the `x` and `y` coordinates that will place the floating element
1661
- * next to a given reference element.
1662
- */
1663
- const computePosition = (reference, floating, options) => {
1664
- // This caches the expensive `getClippingElementAncestors` function so that
1665
- // multiple lifecycle resets re-use the same result. It only lives for a
1666
- // single call. If other functions become expensive, we can add them as well.
1667
- const cache = new Map();
1668
- const mergedOptions = {
1669
- platform,
1670
- ...options
1671
- };
1672
- const platformWithCache = {
1673
- ...mergedOptions.platform,
1674
- _c: cache
1675
- };
1676
- return computePosition$1(reference, floating, {
1677
- ...mergedOptions,
1678
- platform: platformWithCache
1679
- });
1680
- };
1681
-
1682
- var index$1 = typeof document !== 'undefined' ? React.useLayoutEffect : React.useEffect;
1683
-
1684
- // Fork of `fast-deep-equal` that only does the comparisons we need and compares
1685
- // functions
1686
- function deepEqual(a, b) {
1687
- if (a === b) {
1688
- return true;
1689
- }
1690
- if (typeof a !== typeof b) {
1691
- return false;
1692
- }
1693
- if (typeof a === 'function' && a.toString() === b.toString()) {
1694
- return true;
1695
- }
1696
- let length;
1697
- let i;
1698
- let keys;
1699
- if (a && b && typeof a === 'object') {
1700
- if (Array.isArray(a)) {
1701
- length = a.length;
1702
- if (length !== b.length) return false;
1703
- for (i = length; i-- !== 0;) {
1704
- if (!deepEqual(a[i], b[i])) {
1705
- return false;
1706
- }
1707
- }
1708
- return true;
1709
- }
1710
- keys = Object.keys(a);
1711
- length = keys.length;
1712
- if (length !== Object.keys(b).length) {
1713
- return false;
1714
- }
1715
- for (i = length; i-- !== 0;) {
1716
- if (!{}.hasOwnProperty.call(b, keys[i])) {
1717
- return false;
1718
- }
1719
- }
1720
- for (i = length; i-- !== 0;) {
1721
- const key = keys[i];
1722
- if (key === '_owner' && a.$$typeof) {
1723
- continue;
1724
- }
1725
- if (!deepEqual(a[key], b[key])) {
1726
- return false;
1727
- }
1728
- }
1729
- return true;
1730
- }
1731
- return a !== a && b !== b;
1732
- }
1733
-
1734
- function getDPR(element) {
1735
- if (typeof window === 'undefined') {
1736
- return 1;
1737
- }
1738
- const win = element.ownerDocument.defaultView || window;
1739
- return win.devicePixelRatio || 1;
1740
- }
1741
-
1742
- function roundByDPR(element, value) {
1743
- const dpr = getDPR(element);
1744
- return Math.round(value * dpr) / dpr;
1745
- }
1746
-
1747
- function useLatestRef$1(value) {
1748
- const ref = React__namespace.useRef(value);
1749
- index$1(() => {
1750
- ref.current = value;
1751
- });
1752
- return ref;
1753
- }
1754
-
1755
- /**
1756
- * Provides data to position a floating element.
1757
- * @see https://floating-ui.com/docs/useFloating
1758
- */
1759
- function useFloating$1(options) {
1760
- if (options === void 0) {
1761
- options = {};
1762
- }
1763
- const {
1764
- placement = 'bottom',
1765
- strategy = 'absolute',
1766
- middleware = [],
1767
- platform,
1768
- elements: {
1769
- reference: externalReference,
1770
- floating: externalFloating
1771
- } = {},
1772
- transform = true,
1773
- whileElementsMounted,
1774
- open
1775
- } = options;
1776
- const [data, setData] = React__namespace.useState({
1777
- x: 0,
1778
- y: 0,
1779
- strategy,
1780
- placement,
1781
- middlewareData: {},
1782
- isPositioned: false
1783
- });
1784
- const [latestMiddleware, setLatestMiddleware] = React__namespace.useState(middleware);
1785
- if (!deepEqual(latestMiddleware, middleware)) {
1786
- setLatestMiddleware(middleware);
1787
- }
1788
- const [_reference, _setReference] = React__namespace.useState(null);
1789
- const [_floating, _setFloating] = React__namespace.useState(null);
1790
- const setReference = React__namespace.useCallback(node => {
1791
- if (node !== referenceRef.current) {
1792
- referenceRef.current = node;
1793
- _setReference(node);
1794
- }
1795
- }, []);
1796
- const setFloating = React__namespace.useCallback(node => {
1797
- if (node !== floatingRef.current) {
1798
- floatingRef.current = node;
1799
- _setFloating(node);
1800
- }
1801
- }, []);
1802
- const referenceEl = externalReference || _reference;
1803
- const floatingEl = externalFloating || _floating;
1804
- const referenceRef = React__namespace.useRef(null);
1805
- const floatingRef = React__namespace.useRef(null);
1806
- const dataRef = React__namespace.useRef(data);
1807
- const hasWhileElementsMounted = whileElementsMounted != null;
1808
- const whileElementsMountedRef = useLatestRef$1(whileElementsMounted);
1809
- const platformRef = useLatestRef$1(platform);
1810
- const update = React__namespace.useCallback(() => {
1811
- if (!referenceRef.current || !floatingRef.current) {
1812
- return;
1813
- }
1814
- const config = {
1815
- placement,
1816
- strategy,
1817
- middleware: latestMiddleware
1818
- };
1819
- if (platformRef.current) {
1820
- config.platform = platformRef.current;
1821
- }
1822
- computePosition(referenceRef.current, floatingRef.current, config).then(data => {
1823
- const fullData = {
1824
- ...data,
1825
- isPositioned: true
1826
- };
1827
- if (isMountedRef.current && !deepEqual(dataRef.current, fullData)) {
1828
- dataRef.current = fullData;
1829
- ReactDOM__namespace.flushSync(() => {
1830
- setData(fullData);
1831
- });
1832
- }
1833
- });
1834
- }, [latestMiddleware, placement, strategy, platformRef]);
1835
- index$1(() => {
1836
- if (open === false && dataRef.current.isPositioned) {
1837
- dataRef.current.isPositioned = false;
1838
- setData(data => ({
1839
- ...data,
1840
- isPositioned: false
1841
- }));
1842
- }
1843
- }, [open]);
1844
- const isMountedRef = React__namespace.useRef(false);
1845
- index$1(() => {
1846
- isMountedRef.current = true;
1847
- return () => {
1848
- isMountedRef.current = false;
1849
- };
1850
- }, []);
1851
- index$1(() => {
1852
- if (referenceEl) referenceRef.current = referenceEl;
1853
- if (floatingEl) floatingRef.current = floatingEl;
1854
- if (referenceEl && floatingEl) {
1855
- if (whileElementsMountedRef.current) {
1856
- return whileElementsMountedRef.current(referenceEl, floatingEl, update);
1857
- }
1858
- update();
1859
- }
1860
- }, [referenceEl, floatingEl, update, whileElementsMountedRef, hasWhileElementsMounted]);
1861
- const refs = React__namespace.useMemo(() => ({
1862
- reference: referenceRef,
1863
- floating: floatingRef,
1864
- setReference,
1865
- setFloating
1866
- }), [setReference, setFloating]);
1867
- const elements = React__namespace.useMemo(() => ({
1868
- reference: referenceEl,
1869
- floating: floatingEl
1870
- }), [referenceEl, floatingEl]);
1871
- const floatingStyles = React__namespace.useMemo(() => {
1872
- const initialStyles = {
1873
- position: strategy,
1874
- left: 0,
1875
- top: 0
1876
- };
1877
- if (!elements.floating) {
1878
- return initialStyles;
1879
- }
1880
- const x = roundByDPR(elements.floating, data.x);
1881
- const y = roundByDPR(elements.floating, data.y);
1882
- if (transform) {
1883
- return {
1884
- ...initialStyles,
1885
- transform: "translate(" + x + "px, " + y + "px)",
1886
- ...(getDPR(elements.floating) >= 1.5 && {
1887
- willChange: 'transform'
1888
- })
1889
- };
1890
- }
1891
- return {
1892
- position: strategy,
1893
- left: x,
1894
- top: y
1895
- };
1896
- }, [strategy, transform, elements.floating, data.x, data.y]);
1897
- return React__namespace.useMemo(() => ({
1898
- ...data,
1899
- update,
1900
- refs,
1901
- elements,
1902
- floatingStyles
1903
- }), [data, update, refs, elements, floatingStyles]);
1904
- }
1905
-
1906
- /**
1907
- * Provides data to position an inner element of the floating element so that it
1908
- * appears centered to the reference element.
1909
- * This wraps the core `arrow` middleware to allow React refs as the element.
1910
- * @see https://floating-ui.com/docs/arrow
1911
- */
1912
- const arrow$1 = options => {
1913
- function isRef(value) {
1914
- return {}.hasOwnProperty.call(value, 'current');
1915
- }
1916
- return {
1917
- name: 'arrow',
1918
- options,
1919
- fn(state) {
1920
- const {
1921
- element,
1922
- padding
1923
- } = typeof options === 'function' ? options(state) : options;
1924
- if (element && isRef(element)) {
1925
- if (element.current != null) {
1926
- return arrow$2({
1927
- element: element.current,
1928
- padding
1929
- }).fn(state);
1930
- }
1931
- return {};
1932
- }
1933
- if (element) {
1934
- return arrow$2({
1935
- element,
1936
- padding
1937
- }).fn(state);
1938
- }
1939
- return {};
1940
- }
1941
- };
1942
- };
1943
-
1944
- /**
1945
- * Modifies the placement by translating the floating element along the
1946
- * specified axes.
1947
- * A number (shorthand for `mainAxis` or distance), or an axes configuration
1948
- * object may be passed.
1949
- * @see https://floating-ui.com/docs/offset
1950
- */
1951
- const offset = (options, deps) => ({
1952
- ...offset$1(options),
1953
- options: [options, deps]
1954
- });
1955
-
1956
- /**
1957
- * Optimizes the visibility of the floating element by shifting it in order to
1958
- * keep it in view when it will overflow the clipping boundary.
1959
- * @see https://floating-ui.com/docs/shift
1960
- */
1961
- const shift = (options, deps) => ({
1962
- ...shift$1(options),
1963
- options: [options, deps]
1964
- });
1965
-
1966
- /**
1967
- * Optimizes the visibility of the floating element by flipping the `placement`
1968
- * in order to keep it in view when the preferred placement(s) will overflow the
1969
- * clipping boundary. Alternative to `autoPlacement`.
1970
- * @see https://floating-ui.com/docs/flip
1971
- */
1972
- const flip = (options, deps) => ({
1973
- ...flip$1(options),
1974
- options: [options, deps]
1975
- });
1976
-
1977
- /**
1978
- * Provides data to position an inner element of the floating element so that it
1979
- * appears centered to the reference element.
1980
- * This wraps the core `arrow` middleware to allow React refs as the element.
1981
- * @see https://floating-ui.com/docs/arrow
1982
- */
1983
- const arrow = (options, deps) => ({
1984
- ...arrow$1(options),
1985
- options: [options, deps]
1986
- });
1987
-
1988
- // https://github.com/mui/material-ui/issues/41190#issuecomment-2040873379
1989
- const SafeReact = {
1990
- ...React__namespace
1991
- };
1992
-
1993
- const useInsertionEffect = SafeReact.useInsertionEffect;
1994
- const useSafeInsertionEffect = useInsertionEffect || (fn => fn());
1995
- function useEffectEvent(callback) {
1996
- const ref = React__namespace.useRef(() => {
1997
- if (process.env.NODE_ENV !== "production") {
1998
- throw new Error('Cannot call an event handler while rendering.');
1999
- }
2000
- });
2001
- useSafeInsertionEffect(() => {
2002
- ref.current = callback;
2003
- });
2004
- return React__namespace.useCallback(function () {
2005
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
2006
- args[_key] = arguments[_key];
2007
- }
2008
- return ref.current == null ? void 0 : ref.current(...args);
2009
- }, []);
2010
- }
2011
-
2012
- var index = typeof document !== 'undefined' ? React.useLayoutEffect : React.useEffect;
2013
-
2014
- let serverHandoffComplete = false;
2015
- let count = 0;
2016
- const genId = () => // Ensure the id is unique with multiple independent versions of Floating UI
2017
- // on <React 18
2018
- "floating-ui-" + Math.random().toString(36).slice(2, 6) + count++;
2019
- function useFloatingId() {
2020
- const [id, setId] = React__namespace.useState(() => serverHandoffComplete ? genId() : undefined);
2021
- index(() => {
2022
- if (id == null) {
2023
- setId(genId());
2024
- }
2025
- // eslint-disable-next-line react-hooks/exhaustive-deps
2026
- }, []);
2027
- React__namespace.useEffect(() => {
2028
- serverHandoffComplete = true;
2029
- }, []);
2030
- return id;
2031
- }
2032
- const useReactId = SafeReact.useId;
2033
-
2034
- /**
2035
- * Uses React 18's built-in `useId()` when available, or falls back to a
2036
- * slightly less performant (requiring a double render) implementation for
2037
- * earlier React versions.
2038
- * @see https://floating-ui.com/docs/react-utils#useid
2039
- */
2040
- const useId = useReactId || useFloatingId;
2041
-
2042
- let devMessageSet;
2043
- if (process.env.NODE_ENV !== "production") {
2044
- devMessageSet = /*#__PURE__*/new Set();
2045
- }
2046
- function error() {
2047
- var _devMessageSet3;
2048
- for (var _len2 = arguments.length, messages = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
2049
- messages[_key2] = arguments[_key2];
2050
- }
2051
- const message = "Floating UI: " + messages.join(' ');
2052
- if (!((_devMessageSet3 = devMessageSet) != null && _devMessageSet3.has(message))) {
2053
- var _devMessageSet4;
2054
- (_devMessageSet4 = devMessageSet) == null || _devMessageSet4.add(message);
2055
- console.error(message);
2056
- }
2057
- }
2058
-
2059
- function createPubSub() {
2060
- const map = new Map();
2061
- return {
2062
- emit(event, data) {
2063
- var _map$get;
2064
- (_map$get = map.get(event)) == null || _map$get.forEach(handler => handler(data));
2065
- },
2066
- on(event, listener) {
2067
- map.set(event, [...(map.get(event) || []), listener]);
2068
- },
2069
- off(event, listener) {
2070
- var _map$get2;
2071
- map.set(event, ((_map$get2 = map.get(event)) == null ? void 0 : _map$get2.filter(l => l !== listener)) || []);
2072
- }
2073
- };
2074
- }
2075
-
2076
- const FloatingNodeContext = /*#__PURE__*/React__namespace.createContext(null);
2077
- const FloatingTreeContext = /*#__PURE__*/React__namespace.createContext(null);
2078
-
2079
- /**
2080
- * Returns the parent node id for nested floating elements, if available.
2081
- * Returns `null` for top-level floating elements.
2082
- */
2083
- const useFloatingParentNodeId = () => {
2084
- var _React$useContext;
2085
- return ((_React$useContext = React__namespace.useContext(FloatingNodeContext)) == null ? void 0 : _React$useContext.id) || null;
2086
- };
2087
-
2088
- /**
2089
- * Returns the nearest floating tree context, if available.
2090
- */
2091
- const useFloatingTree = () => React__namespace.useContext(FloatingTreeContext);
2092
-
2093
- function createAttribute(name) {
2094
- return "data-floating-ui-" + name;
2095
- }
2096
-
2097
- function useLatestRef(value) {
2098
- const ref = React.useRef(value);
2099
- index(() => {
2100
- ref.current = value;
2101
- });
2102
- return ref;
2103
- }
2104
-
2105
- const safePolygonIdentifier = /*#__PURE__*/createAttribute('safe-polygon');
2106
- function getDelay(value, prop, pointerType) {
2107
- if (pointerType && !isMouseLikePointerType(pointerType)) {
2108
- return 0;
2109
- }
2110
- if (typeof value === 'number') {
2111
- return value;
2112
- }
2113
- return value == null ? void 0 : value[prop];
2114
- }
2115
- /**
2116
- * Opens the floating element while hovering over the reference element, like
2117
- * CSS `:hover`.
2118
- * @see https://floating-ui.com/docs/useHover
2119
- */
2120
- function useHover(context, props) {
2121
- if (props === void 0) {
2122
- props = {};
2123
- }
2124
- const {
2125
- open,
2126
- onOpenChange,
2127
- dataRef,
2128
- events,
2129
- elements: {
2130
- domReference,
2131
- floating
2132
- }
2133
- } = context;
2134
- const {
2135
- enabled = true,
2136
- delay = 0,
2137
- handleClose = null,
2138
- mouseOnly = false,
2139
- restMs = 0,
2140
- move = true
2141
- } = props;
2142
- const tree = useFloatingTree();
2143
- const parentId = useFloatingParentNodeId();
2144
- const handleCloseRef = useLatestRef(handleClose);
2145
- const delayRef = useLatestRef(delay);
2146
- const pointerTypeRef = React__namespace.useRef();
2147
- const timeoutRef = React__namespace.useRef(-1);
2148
- const handlerRef = React__namespace.useRef();
2149
- const restTimeoutRef = React__namespace.useRef(-1);
2150
- const blockMouseMoveRef = React__namespace.useRef(true);
2151
- const performedPointerEventsMutationRef = React__namespace.useRef(false);
2152
- const unbindMouseMoveRef = React__namespace.useRef(() => {});
2153
- const isHoverOpen = React__namespace.useCallback(() => {
2154
- var _dataRef$current$open;
2155
- const type = (_dataRef$current$open = dataRef.current.openEvent) == null ? void 0 : _dataRef$current$open.type;
2156
- return (type == null ? void 0 : type.includes('mouse')) && type !== 'mousedown';
2157
- }, [dataRef]);
2158
-
2159
- // When closing before opening, clear the delay timeouts to cancel it
2160
- // from showing.
2161
- React__namespace.useEffect(() => {
2162
- if (!enabled) {
2163
- return;
2164
- }
2165
- function onOpenChange(_ref) {
2166
- let {
2167
- open
2168
- } = _ref;
2169
- if (!open) {
2170
- clearTimeout(timeoutRef.current);
2171
- clearTimeout(restTimeoutRef.current);
2172
- blockMouseMoveRef.current = true;
2173
- }
2174
- }
2175
- events.on('openchange', onOpenChange);
2176
- return () => {
2177
- events.off('openchange', onOpenChange);
2178
- };
2179
- }, [enabled, events]);
2180
- React__namespace.useEffect(() => {
2181
- if (!enabled || !handleCloseRef.current || !open) {
2182
- return;
2183
- }
2184
- function onLeave(event) {
2185
- if (isHoverOpen()) {
2186
- onOpenChange(false, event, 'hover');
2187
- }
2188
- }
2189
- const html = getDocument(floating).documentElement;
2190
- html.addEventListener('mouseleave', onLeave);
2191
- return () => {
2192
- html.removeEventListener('mouseleave', onLeave);
2193
- };
2194
- }, [floating, open, onOpenChange, enabled, handleCloseRef, isHoverOpen]);
2195
- const closeWithDelay = React__namespace.useCallback(function (event, runElseBranch, reason) {
2196
- if (runElseBranch === void 0) {
2197
- runElseBranch = true;
2198
- }
2199
- if (reason === void 0) {
2200
- reason = 'hover';
2201
- }
2202
- const closeDelay = getDelay(delayRef.current, 'close', pointerTypeRef.current);
2203
- if (closeDelay && !handlerRef.current) {
2204
- clearTimeout(timeoutRef.current);
2205
- timeoutRef.current = window.setTimeout(() => onOpenChange(false, event, reason), closeDelay);
2206
- } else if (runElseBranch) {
2207
- clearTimeout(timeoutRef.current);
2208
- onOpenChange(false, event, reason);
2209
- }
2210
- }, [delayRef, onOpenChange]);
2211
- const cleanupMouseMoveHandler = useEffectEvent(() => {
2212
- unbindMouseMoveRef.current();
2213
- handlerRef.current = undefined;
2214
- });
2215
- const clearPointerEvents = useEffectEvent(() => {
2216
- if (performedPointerEventsMutationRef.current) {
2217
- const body = getDocument(floating).body;
2218
- body.style.pointerEvents = '';
2219
- body.removeAttribute(safePolygonIdentifier);
2220
- performedPointerEventsMutationRef.current = false;
2221
- }
2222
- });
2223
-
2224
- // Registering the mouse events on the reference directly to bypass React's
2225
- // delegation system. If the cursor was on a disabled element and then entered
2226
- // the reference (no gap), `mouseenter` doesn't fire in the delegation system.
2227
- React__namespace.useEffect(() => {
2228
- if (!enabled) {
2229
- return;
2230
- }
2231
- function isClickLikeOpenEvent() {
2232
- return dataRef.current.openEvent ? ['click', 'mousedown'].includes(dataRef.current.openEvent.type) : false;
2233
- }
2234
- function onMouseEnter(event) {
2235
- clearTimeout(timeoutRef.current);
2236
- blockMouseMoveRef.current = false;
2237
- if (mouseOnly && !isMouseLikePointerType(pointerTypeRef.current) || restMs > 0 && !getDelay(delayRef.current, 'open')) {
2238
- return;
2239
- }
2240
- const openDelay = getDelay(delayRef.current, 'open', pointerTypeRef.current);
2241
- if (openDelay) {
2242
- timeoutRef.current = window.setTimeout(() => {
2243
- onOpenChange(true, event, 'hover');
2244
- }, openDelay);
2245
- } else {
2246
- onOpenChange(true, event, 'hover');
2247
- }
2248
- }
2249
- function onMouseLeave(event) {
2250
- if (isClickLikeOpenEvent()) return;
2251
- unbindMouseMoveRef.current();
2252
- const doc = getDocument(floating);
2253
- clearTimeout(restTimeoutRef.current);
2254
- if (handleCloseRef.current && dataRef.current.floatingContext) {
2255
- // Prevent clearing `onScrollMouseLeave` timeout.
2256
- if (!open) {
2257
- clearTimeout(timeoutRef.current);
2258
- }
2259
- handlerRef.current = handleCloseRef.current({
2260
- ...dataRef.current.floatingContext,
2261
- tree,
2262
- x: event.clientX,
2263
- y: event.clientY,
2264
- onClose() {
2265
- clearPointerEvents();
2266
- cleanupMouseMoveHandler();
2267
- closeWithDelay(event, true, 'safe-polygon');
2268
- }
2269
- });
2270
- const handler = handlerRef.current;
2271
- doc.addEventListener('mousemove', handler);
2272
- unbindMouseMoveRef.current = () => {
2273
- doc.removeEventListener('mousemove', handler);
2274
- };
2275
- return;
2276
- }
2277
-
2278
- // Allow interactivity without `safePolygon` on touch devices. With a
2279
- // pointer, a short close delay is an alternative, so it should work
2280
- // consistently.
2281
- const shouldClose = pointerTypeRef.current === 'touch' ? !contains(floating, event.relatedTarget) : true;
2282
- if (shouldClose) {
2283
- closeWithDelay(event);
2284
- }
2285
- }
2286
-
2287
- // Ensure the floating element closes after scrolling even if the pointer
2288
- // did not move.
2289
- // https://github.com/floating-ui/floating-ui/discussions/1692
2290
- function onScrollMouseLeave(event) {
2291
- if (isClickLikeOpenEvent()) return;
2292
- if (!dataRef.current.floatingContext) return;
2293
- handleCloseRef.current == null || handleCloseRef.current({
2294
- ...dataRef.current.floatingContext,
2295
- tree,
2296
- x: event.clientX,
2297
- y: event.clientY,
2298
- onClose() {
2299
- clearPointerEvents();
2300
- cleanupMouseMoveHandler();
2301
- closeWithDelay(event);
2302
- }
2303
- })(event);
2304
- }
2305
- if (isElement(domReference)) {
2306
- const ref = domReference;
2307
- open && ref.addEventListener('mouseleave', onScrollMouseLeave);
2308
- floating == null || floating.addEventListener('mouseleave', onScrollMouseLeave);
2309
- move && ref.addEventListener('mousemove', onMouseEnter, {
2310
- once: true
2311
- });
2312
- ref.addEventListener('mouseenter', onMouseEnter);
2313
- ref.addEventListener('mouseleave', onMouseLeave);
2314
- return () => {
2315
- open && ref.removeEventListener('mouseleave', onScrollMouseLeave);
2316
- floating == null || floating.removeEventListener('mouseleave', onScrollMouseLeave);
2317
- move && ref.removeEventListener('mousemove', onMouseEnter);
2318
- ref.removeEventListener('mouseenter', onMouseEnter);
2319
- ref.removeEventListener('mouseleave', onMouseLeave);
2320
- };
2321
- }
2322
- }, [domReference, floating, enabled, context, mouseOnly, restMs, move, closeWithDelay, cleanupMouseMoveHandler, clearPointerEvents, onOpenChange, open, tree, delayRef, handleCloseRef, dataRef]);
2323
-
2324
- // Block pointer-events of every element other than the reference and floating
2325
- // while the floating element is open and has a `handleClose` handler. Also
2326
- // handles nested floating elements.
2327
- // https://github.com/floating-ui/floating-ui/issues/1722
2328
- index(() => {
2329
- var _handleCloseRef$curre;
2330
- if (!enabled) {
2331
- return;
2332
- }
2333
- if (open && (_handleCloseRef$curre = handleCloseRef.current) != null && _handleCloseRef$curre.__options.blockPointerEvents && isHoverOpen()) {
2334
- const body = getDocument(floating).body;
2335
- body.setAttribute(safePolygonIdentifier, '');
2336
- body.style.pointerEvents = 'none';
2337
- performedPointerEventsMutationRef.current = true;
2338
- if (isElement(domReference) && floating) {
2339
- var _tree$nodesRef$curren;
2340
- const ref = domReference;
2341
- const parentFloating = tree == null || (_tree$nodesRef$curren = tree.nodesRef.current.find(node => node.id === parentId)) == null || (_tree$nodesRef$curren = _tree$nodesRef$curren.context) == null ? void 0 : _tree$nodesRef$curren.elements.floating;
2342
- if (parentFloating) {
2343
- parentFloating.style.pointerEvents = '';
2344
- }
2345
- ref.style.pointerEvents = 'auto';
2346
- floating.style.pointerEvents = 'auto';
2347
- return () => {
2348
- ref.style.pointerEvents = '';
2349
- floating.style.pointerEvents = '';
2350
- };
2351
- }
2352
- }
2353
- }, [enabled, open, parentId, floating, domReference, tree, handleCloseRef, isHoverOpen]);
2354
- index(() => {
2355
- if (!open) {
2356
- pointerTypeRef.current = undefined;
2357
- cleanupMouseMoveHandler();
2358
- clearPointerEvents();
2359
- }
2360
- }, [open, cleanupMouseMoveHandler, clearPointerEvents]);
2361
- React__namespace.useEffect(() => {
2362
- return () => {
2363
- cleanupMouseMoveHandler();
2364
- clearTimeout(timeoutRef.current);
2365
- clearTimeout(restTimeoutRef.current);
2366
- clearPointerEvents();
2367
- };
2368
- }, [enabled, domReference, cleanupMouseMoveHandler, clearPointerEvents]);
2369
- return React__namespace.useMemo(() => {
2370
- if (!enabled) {
2371
- return {};
2372
- }
2373
- function setPointerRef(event) {
2374
- pointerTypeRef.current = event.pointerType;
2375
- }
2376
- return {
2377
- reference: {
2378
- onPointerDown: setPointerRef,
2379
- onPointerEnter: setPointerRef,
2380
- onMouseMove(event) {
2381
- const {
2382
- nativeEvent
2383
- } = event;
2384
- function handleMouseMove() {
2385
- if (!blockMouseMoveRef.current) {
2386
- onOpenChange(true, nativeEvent, 'hover');
2387
- }
2388
- }
2389
- if (mouseOnly && !isMouseLikePointerType(pointerTypeRef.current)) {
2390
- return;
2391
- }
2392
- if (open || restMs === 0) {
2393
- return;
2394
- }
2395
- clearTimeout(restTimeoutRef.current);
2396
- if (pointerTypeRef.current === 'touch') {
2397
- handleMouseMove();
2398
- } else {
2399
- restTimeoutRef.current = window.setTimeout(handleMouseMove, restMs);
2400
- }
2401
- }
2402
- },
2403
- floating: {
2404
- onMouseEnter() {
2405
- clearTimeout(timeoutRef.current);
2406
- },
2407
- onMouseLeave(event) {
2408
- closeWithDelay(event.nativeEvent, false);
2409
- }
2410
- }
2411
- };
2412
- }, [enabled, mouseOnly, open, restMs, onOpenChange, closeWithDelay]);
2413
- }
2414
-
2415
- function getChildren(nodes, id) {
2416
- let allChildren = nodes.filter(node => {
2417
- var _node$context;
2418
- return node.parentId === id && ((_node$context = node.context) == null ? void 0 : _node$context.open);
2419
- });
2420
- let currentChildren = allChildren;
2421
- while (currentChildren.length) {
2422
- currentChildren = nodes.filter(node => {
2423
- var _currentChildren;
2424
- return (_currentChildren = currentChildren) == null ? void 0 : _currentChildren.some(n => {
2425
- var _node$context2;
2426
- return node.parentId === n.id && ((_node$context2 = node.context) == null ? void 0 : _node$context2.open);
2427
- });
2428
- });
2429
- allChildren = allChildren.concat(currentChildren);
2430
- }
2431
- return allChildren;
2432
- }
2433
-
2434
- const bubbleHandlerKeys = {
2435
- pointerdown: 'onPointerDown',
2436
- mousedown: 'onMouseDown',
2437
- click: 'onClick'
2438
- };
2439
- const captureHandlerKeys = {
2440
- pointerdown: 'onPointerDownCapture',
2441
- mousedown: 'onMouseDownCapture',
2442
- click: 'onClickCapture'
2443
- };
2444
- const normalizeProp = normalizable => {
2445
- var _normalizable$escapeK, _normalizable$outside;
2446
- return {
2447
- escapeKey: typeof normalizable === 'boolean' ? normalizable : (_normalizable$escapeK = normalizable == null ? void 0 : normalizable.escapeKey) != null ? _normalizable$escapeK : false,
2448
- outsidePress: typeof normalizable === 'boolean' ? normalizable : (_normalizable$outside = normalizable == null ? void 0 : normalizable.outsidePress) != null ? _normalizable$outside : true
2449
- };
2450
- };
2451
- /**
2452
- * Closes the floating element when a dismissal is requested — by default, when
2453
- * the user presses the `escape` key or outside of the floating element.
2454
- * @see https://floating-ui.com/docs/useDismiss
2455
- */
2456
- function useDismiss(context, props) {
2457
- if (props === void 0) {
2458
- props = {};
2459
- }
2460
- const {
2461
- open,
2462
- onOpenChange,
2463
- elements: {
2464
- reference,
2465
- domReference,
2466
- floating
2467
- },
2468
- dataRef
2469
- } = context;
2470
- const {
2471
- enabled = true,
2472
- escapeKey = true,
2473
- outsidePress: unstable_outsidePress = true,
2474
- outsidePressEvent = 'pointerdown',
2475
- referencePress = false,
2476
- referencePressEvent = 'pointerdown',
2477
- ancestorScroll = false,
2478
- bubbles,
2479
- capture
2480
- } = props;
2481
- const tree = useFloatingTree();
2482
- const outsidePressFn = useEffectEvent(typeof unstable_outsidePress === 'function' ? unstable_outsidePress : () => false);
2483
- const outsidePress = typeof unstable_outsidePress === 'function' ? outsidePressFn : unstable_outsidePress;
2484
- const insideReactTreeRef = React__namespace.useRef(false);
2485
- const endedOrStartedInsideRef = React__namespace.useRef(false);
2486
- const {
2487
- escapeKey: escapeKeyBubbles,
2488
- outsidePress: outsidePressBubbles
2489
- } = normalizeProp(bubbles);
2490
- const {
2491
- escapeKey: escapeKeyCapture,
2492
- outsidePress: outsidePressCapture
2493
- } = normalizeProp(capture);
2494
- const closeOnEscapeKeyDown = useEffectEvent(event => {
2495
- var _dataRef$current$floa;
2496
- if (!open || !enabled || !escapeKey || event.key !== 'Escape') {
2497
- return;
2498
- }
2499
- const nodeId = (_dataRef$current$floa = dataRef.current.floatingContext) == null ? void 0 : _dataRef$current$floa.nodeId;
2500
- const children = tree ? getChildren(tree.nodesRef.current, nodeId) : [];
2501
- if (!escapeKeyBubbles) {
2502
- event.stopPropagation();
2503
- if (children.length > 0) {
2504
- let shouldDismiss = true;
2505
- children.forEach(child => {
2506
- var _child$context;
2507
- if ((_child$context = child.context) != null && _child$context.open && !child.context.dataRef.current.__escapeKeyBubbles) {
2508
- shouldDismiss = false;
2509
- return;
2510
- }
2511
- });
2512
- if (!shouldDismiss) {
2513
- return;
2514
- }
2515
- }
2516
- }
2517
- onOpenChange(false, isReactEvent(event) ? event.nativeEvent : event, 'escape-key');
2518
- });
2519
- const closeOnEscapeKeyDownCapture = useEffectEvent(event => {
2520
- var _getTarget2;
2521
- const callback = () => {
2522
- var _getTarget;
2523
- closeOnEscapeKeyDown(event);
2524
- (_getTarget = getTarget(event)) == null || _getTarget.removeEventListener('keydown', callback);
2525
- };
2526
- (_getTarget2 = getTarget(event)) == null || _getTarget2.addEventListener('keydown', callback);
2527
- });
2528
- const closeOnPressOutside = useEffectEvent(event => {
2529
- var _dataRef$current$floa2;
2530
- // Given developers can stop the propagation of the synthetic event,
2531
- // we can only be confident with a positive value.
2532
- const insideReactTree = insideReactTreeRef.current;
2533
- insideReactTreeRef.current = false;
2534
-
2535
- // When click outside is lazy (`click` event), handle dragging.
2536
- // Don't close if:
2537
- // - The click started inside the floating element.
2538
- // - The click ended inside the floating element.
2539
- const endedOrStartedInside = endedOrStartedInsideRef.current;
2540
- endedOrStartedInsideRef.current = false;
2541
- if (outsidePressEvent === 'click' && endedOrStartedInside) {
2542
- return;
2543
- }
2544
- if (insideReactTree) {
2545
- return;
2546
- }
2547
- if (typeof outsidePress === 'function' && !outsidePress(event)) {
2548
- return;
2549
- }
2550
- const target = getTarget(event);
2551
- const inertSelector = "[" + createAttribute('inert') + "]";
2552
- const markers = getDocument(floating).querySelectorAll(inertSelector);
2553
- let targetRootAncestor = isElement(target) ? target : null;
2554
- while (targetRootAncestor && !isLastTraversableNode(targetRootAncestor)) {
2555
- const nextParent = getParentNode(targetRootAncestor);
2556
- if (isLastTraversableNode(nextParent) || !isElement(nextParent)) {
2557
- break;
2558
- }
2559
- targetRootAncestor = nextParent;
2560
- }
2561
-
2562
- // Check if the click occurred on a third-party element injected after the
2563
- // floating element rendered.
2564
- if (markers.length && isElement(target) && !isRootElement(target) &&
2565
- // Clicked on a direct ancestor (e.g. FloatingOverlay).
2566
- !contains(target, floating) &&
2567
- // If the target root element contains none of the markers, then the
2568
- // element was injected after the floating element rendered.
2569
- Array.from(markers).every(marker => !contains(targetRootAncestor, marker))) {
2570
- return;
2571
- }
2572
-
2573
- // Check if the click occurred on the scrollbar
2574
- if (isHTMLElement(target) && floating) {
2575
- // In Firefox, `target.scrollWidth > target.clientWidth` for inline
2576
- // elements.
2577
- const canScrollX = target.clientWidth > 0 && target.scrollWidth > target.clientWidth;
2578
- const canScrollY = target.clientHeight > 0 && target.scrollHeight > target.clientHeight;
2579
- let xCond = canScrollY && event.offsetX > target.clientWidth;
2580
-
2581
- // In some browsers it is possible to change the <body> (or window)
2582
- // scrollbar to the left side, but is very rare and is difficult to
2583
- // check for. Plus, for modal dialogs with backdrops, it is more
2584
- // important that the backdrop is checked but not so much the window.
2585
- if (canScrollY) {
2586
- const isRTL = getComputedStyle(target).direction === 'rtl';
2587
- if (isRTL) {
2588
- xCond = event.offsetX <= target.offsetWidth - target.clientWidth;
2589
- }
2590
- }
2591
- if (xCond || canScrollX && event.offsetY > target.clientHeight) {
2592
- return;
2593
- }
2594
- }
2595
- const nodeId = (_dataRef$current$floa2 = dataRef.current.floatingContext) == null ? void 0 : _dataRef$current$floa2.nodeId;
2596
- const targetIsInsideChildren = tree && getChildren(tree.nodesRef.current, nodeId).some(node => {
2597
- var _node$context;
2598
- return isEventTargetWithin(event, (_node$context = node.context) == null ? void 0 : _node$context.elements.floating);
2599
- });
2600
- if (isEventTargetWithin(event, floating) || isEventTargetWithin(event, domReference) || targetIsInsideChildren) {
2601
- return;
2602
- }
2603
- const children = tree ? getChildren(tree.nodesRef.current, nodeId) : [];
2604
- if (children.length > 0) {
2605
- let shouldDismiss = true;
2606
- children.forEach(child => {
2607
- var _child$context2;
2608
- if ((_child$context2 = child.context) != null && _child$context2.open && !child.context.dataRef.current.__outsidePressBubbles) {
2609
- shouldDismiss = false;
2610
- return;
2611
- }
2612
- });
2613
- if (!shouldDismiss) {
2614
- return;
2615
- }
2616
- }
2617
- onOpenChange(false, event, 'outside-press');
2618
- });
2619
- const closeOnPressOutsideCapture = useEffectEvent(event => {
2620
- var _getTarget4;
2621
- const callback = () => {
2622
- var _getTarget3;
2623
- closeOnPressOutside(event);
2624
- (_getTarget3 = getTarget(event)) == null || _getTarget3.removeEventListener(outsidePressEvent, callback);
2625
- };
2626
- (_getTarget4 = getTarget(event)) == null || _getTarget4.addEventListener(outsidePressEvent, callback);
2627
- });
2628
- React__namespace.useEffect(() => {
2629
- if (!open || !enabled) {
2630
- return;
2631
- }
2632
- dataRef.current.__escapeKeyBubbles = escapeKeyBubbles;
2633
- dataRef.current.__outsidePressBubbles = outsidePressBubbles;
2634
- function onScroll(event) {
2635
- onOpenChange(false, event, 'ancestor-scroll');
2636
- }
2637
- const doc = getDocument(floating);
2638
- escapeKey && doc.addEventListener('keydown', escapeKeyCapture ? closeOnEscapeKeyDownCapture : closeOnEscapeKeyDown, escapeKeyCapture);
2639
- outsidePress && doc.addEventListener(outsidePressEvent, outsidePressCapture ? closeOnPressOutsideCapture : closeOnPressOutside, outsidePressCapture);
2640
- let ancestors = [];
2641
- if (ancestorScroll) {
2642
- if (isElement(domReference)) {
2643
- ancestors = getOverflowAncestors(domReference);
2644
- }
2645
- if (isElement(floating)) {
2646
- ancestors = ancestors.concat(getOverflowAncestors(floating));
2647
- }
2648
- if (!isElement(reference) && reference && reference.contextElement) {
2649
- ancestors = ancestors.concat(getOverflowAncestors(reference.contextElement));
2650
- }
2651
- }
2652
-
2653
- // Ignore the visual viewport for scrolling dismissal (allow pinch-zoom)
2654
- ancestors = ancestors.filter(ancestor => {
2655
- var _doc$defaultView;
2656
- return ancestor !== ((_doc$defaultView = doc.defaultView) == null ? void 0 : _doc$defaultView.visualViewport);
2657
- });
2658
- ancestors.forEach(ancestor => {
2659
- ancestor.addEventListener('scroll', onScroll, {
2660
- passive: true
2661
- });
2662
- });
2663
- return () => {
2664
- escapeKey && doc.removeEventListener('keydown', escapeKeyCapture ? closeOnEscapeKeyDownCapture : closeOnEscapeKeyDown, escapeKeyCapture);
2665
- outsidePress && doc.removeEventListener(outsidePressEvent, outsidePressCapture ? closeOnPressOutsideCapture : closeOnPressOutside, outsidePressCapture);
2666
- ancestors.forEach(ancestor => {
2667
- ancestor.removeEventListener('scroll', onScroll);
2668
- });
2669
- };
2670
- }, [dataRef, floating, domReference, reference, escapeKey, outsidePress, outsidePressEvent, open, onOpenChange, ancestorScroll, enabled, escapeKeyBubbles, outsidePressBubbles, closeOnEscapeKeyDown, escapeKeyCapture, closeOnEscapeKeyDownCapture, closeOnPressOutside, outsidePressCapture, closeOnPressOutsideCapture]);
2671
- React__namespace.useEffect(() => {
2672
- insideReactTreeRef.current = false;
2673
- }, [outsidePress, outsidePressEvent]);
2674
- return React__namespace.useMemo(() => {
2675
- if (!enabled) {
2676
- return {};
2677
- }
2678
- return {
2679
- reference: {
2680
- onKeyDown: closeOnEscapeKeyDown,
2681
- [bubbleHandlerKeys[referencePressEvent]]: event => {
2682
- if (referencePress) {
2683
- onOpenChange(false, event.nativeEvent, 'reference-press');
2684
- }
2685
- }
2686
- },
2687
- floating: {
2688
- onKeyDown: closeOnEscapeKeyDown,
2689
- onMouseDown() {
2690
- endedOrStartedInsideRef.current = true;
2691
- },
2692
- onMouseUp() {
2693
- endedOrStartedInsideRef.current = true;
2694
- },
2695
- [captureHandlerKeys[outsidePressEvent]]: () => {
2696
- insideReactTreeRef.current = true;
2697
- }
2698
- }
2699
- };
2700
- }, [enabled, referencePress, outsidePressEvent, referencePressEvent, onOpenChange, closeOnEscapeKeyDown]);
2701
- }
2702
-
2703
- function useFloatingRootContext(options) {
2704
- const {
2705
- open = false,
2706
- onOpenChange: onOpenChangeProp,
2707
- elements: elementsProp
2708
- } = options;
2709
- const floatingId = useId();
2710
- const dataRef = React__namespace.useRef({});
2711
- const [events] = React__namespace.useState(() => createPubSub());
2712
- const nested = useFloatingParentNodeId() != null;
2713
- if (process.env.NODE_ENV !== "production") {
2714
- const optionDomReference = elementsProp.reference;
2715
- if (optionDomReference && !isElement(optionDomReference)) {
2716
- error('Cannot pass a virtual element to the `elements.reference` option,', 'as it must be a real DOM element. Use `refs.setPositionReference()`', 'instead.');
2717
- }
2718
- }
2719
- const [positionReference, setPositionReference] = React__namespace.useState(elementsProp.reference);
2720
- const onOpenChange = useEffectEvent((open, event, reason) => {
2721
- dataRef.current.openEvent = open ? event : undefined;
2722
- events.emit('openchange', {
2723
- open,
2724
- event,
2725
- reason,
2726
- nested
2727
- });
2728
- onOpenChangeProp == null || onOpenChangeProp(open, event, reason);
2729
- });
2730
- const refs = React__namespace.useMemo(() => ({
2731
- setPositionReference
2732
- }), []);
2733
- const elements = React__namespace.useMemo(() => ({
2734
- reference: positionReference || elementsProp.reference || null,
2735
- floating: elementsProp.floating || null,
2736
- domReference: elementsProp.reference
2737
- }), [positionReference, elementsProp.reference, elementsProp.floating]);
2738
- return React__namespace.useMemo(() => ({
2739
- dataRef,
2740
- open,
2741
- onOpenChange,
2742
- elements,
2743
- events,
2744
- floatingId,
2745
- refs
2746
- }), [open, onOpenChange, elements, events, floatingId, refs]);
2747
- }
2748
-
2749
- /**
2750
- * Provides data to position a floating element and context to add interactions.
2751
- * @see https://floating-ui.com/docs/useFloating
2752
- */
2753
- function useFloating(options) {
2754
- if (options === void 0) {
2755
- options = {};
2756
- }
2757
- const {
2758
- nodeId
2759
- } = options;
2760
- const internalRootContext = useFloatingRootContext({
2761
- ...options,
2762
- elements: {
2763
- reference: null,
2764
- floating: null,
2765
- ...options.elements
2766
- }
2767
- });
2768
- const rootContext = options.rootContext || internalRootContext;
2769
- const computedElements = rootContext.elements;
2770
- const [_domReference, setDomReference] = React__namespace.useState(null);
2771
- const [positionReference, _setPositionReference] = React__namespace.useState(null);
2772
- const optionDomReference = computedElements == null ? void 0 : computedElements.reference;
2773
- const domReference = optionDomReference || _domReference;
2774
- const domReferenceRef = React__namespace.useRef(null);
2775
- const tree = useFloatingTree();
2776
- index(() => {
2777
- if (domReference) {
2778
- domReferenceRef.current = domReference;
2779
- }
2780
- }, [domReference]);
2781
- const position = useFloating$1({
2782
- ...options,
2783
- elements: {
2784
- ...computedElements,
2785
- ...(positionReference && {
2786
- reference: positionReference
2787
- })
2788
- }
2789
- });
2790
- const setPositionReference = React__namespace.useCallback(node => {
2791
- const computedPositionReference = isElement(node) ? {
2792
- getBoundingClientRect: () => node.getBoundingClientRect(),
2793
- contextElement: node
2794
- } : node;
2795
- // Store the positionReference in state if the DOM reference is specified externally via the
2796
- // `elements.reference` option. This ensures that it won't be overridden on future renders.
2797
- _setPositionReference(computedPositionReference);
2798
- position.refs.setReference(computedPositionReference);
2799
- }, [position.refs]);
2800
- const setReference = React__namespace.useCallback(node => {
2801
- if (isElement(node) || node === null) {
2802
- domReferenceRef.current = node;
2803
- setDomReference(node);
2804
- }
2805
-
2806
- // Backwards-compatibility for passing a virtual element to `reference`
2807
- // after it has set the DOM reference.
2808
- if (isElement(position.refs.reference.current) || position.refs.reference.current === null ||
2809
- // Don't allow setting virtual elements using the old technique back to
2810
- // `null` to support `positionReference` + an unstable `reference`
2811
- // callback ref.
2812
- node !== null && !isElement(node)) {
2813
- position.refs.setReference(node);
2814
- }
2815
- }, [position.refs]);
2816
- const refs = React__namespace.useMemo(() => ({
2817
- ...position.refs,
2818
- setReference,
2819
- setPositionReference,
2820
- domReference: domReferenceRef
2821
- }), [position.refs, setReference, setPositionReference]);
2822
- const elements = React__namespace.useMemo(() => ({
2823
- ...position.elements,
2824
- domReference: domReference
2825
- }), [position.elements, domReference]);
2826
- const context = React__namespace.useMemo(() => ({
2827
- ...position,
2828
- ...rootContext,
2829
- refs,
2830
- elements,
2831
- nodeId
2832
- }), [position, refs, elements, nodeId, rootContext]);
2833
- index(() => {
2834
- rootContext.dataRef.current.floatingContext = context;
2835
- const node = tree == null ? void 0 : tree.nodesRef.current.find(node => node.id === nodeId);
2836
- if (node) {
2837
- node.context = context;
2838
- }
2839
- });
2840
- return React__namespace.useMemo(() => ({
2841
- ...position,
2842
- context,
2843
- refs,
2844
- elements
2845
- }), [position, refs, elements, context]);
2846
- }
2847
-
2848
- /**
2849
- * Opens the floating element while the reference element has focus, like CSS
2850
- * `:focus`.
2851
- * @see https://floating-ui.com/docs/useFocus
2852
- */
2853
- function useFocus(context, props) {
2854
- if (props === void 0) {
2855
- props = {};
2856
- }
2857
- const {
2858
- open,
2859
- onOpenChange,
2860
- events,
2861
- dataRef,
2862
- elements: {
2863
- domReference
2864
- }
2865
- } = context;
2866
- const {
2867
- enabled = true,
2868
- visibleOnly = true
2869
- } = props;
2870
- const blockFocusRef = React__namespace.useRef(false);
2871
- const timeoutRef = React__namespace.useRef();
2872
- const keyboardModalityRef = React__namespace.useRef(true);
2873
- React__namespace.useEffect(() => {
2874
- if (!enabled) {
2875
- return;
2876
- }
2877
- const win = getWindow(domReference);
2878
-
2879
- // If the reference was focused and the user left the tab/window, and the
2880
- // floating element was not open, the focus should be blocked when they
2881
- // return to the tab/window.
2882
- function onBlur() {
2883
- if (!open && isHTMLElement(domReference) && domReference === activeElement(getDocument(domReference))) {
2884
- blockFocusRef.current = true;
2885
- }
2886
- }
2887
- function onKeyDown() {
2888
- keyboardModalityRef.current = true;
2889
- }
2890
- win.addEventListener('blur', onBlur);
2891
- win.addEventListener('keydown', onKeyDown, true);
2892
- return () => {
2893
- win.removeEventListener('blur', onBlur);
2894
- win.removeEventListener('keydown', onKeyDown, true);
2895
- };
2896
- }, [domReference, open, enabled]);
2897
- React__namespace.useEffect(() => {
2898
- if (!enabled) {
2899
- return;
2900
- }
2901
- function onOpenChange(_ref) {
2902
- let {
2903
- reason
2904
- } = _ref;
2905
- if (reason === 'reference-press' || reason === 'escape-key') {
2906
- blockFocusRef.current = true;
2907
- }
2908
- }
2909
- events.on('openchange', onOpenChange);
2910
- return () => {
2911
- events.off('openchange', onOpenChange);
2912
- };
2913
- }, [events, enabled]);
2914
- React__namespace.useEffect(() => {
2915
- return () => {
2916
- clearTimeout(timeoutRef.current);
2917
- };
2918
- }, []);
2919
- return React__namespace.useMemo(() => {
2920
- if (!enabled) {
2921
- return {};
2922
- }
2923
- return {
2924
- reference: {
2925
- onPointerDown(event) {
2926
- if (isVirtualPointerEvent(event.nativeEvent)) return;
2927
- keyboardModalityRef.current = false;
2928
- },
2929
- onMouseLeave() {
2930
- blockFocusRef.current = false;
2931
- },
2932
- onFocus(event) {
2933
- if (blockFocusRef.current) return;
2934
- const target = getTarget(event.nativeEvent);
2935
- if (visibleOnly && isElement(target)) {
2936
- try {
2937
- // Mac Safari unreliably matches `:focus-visible` on the reference
2938
- // if focus was outside the page initially - use the fallback
2939
- // instead.
2940
- if (isSafari() && isMac()) throw Error();
2941
- if (!target.matches(':focus-visible')) return;
2942
- } catch (e) {
2943
- // Old browsers will throw an error when using `:focus-visible`.
2944
- if (!keyboardModalityRef.current && !isTypeableElement(target)) {
2945
- return;
2946
- }
2947
- }
2948
- }
2949
- onOpenChange(true, event.nativeEvent, 'focus');
2950
- },
2951
- onBlur(event) {
2952
- blockFocusRef.current = false;
2953
- const relatedTarget = event.relatedTarget;
2954
-
2955
- // Hit the non-modal focus management portal guard. Focus will be
2956
- // moved into the floating element immediately after.
2957
- const movedToFocusGuard = isElement(relatedTarget) && relatedTarget.hasAttribute(createAttribute('focus-guard')) && relatedTarget.getAttribute('data-type') === 'outside';
2958
-
2959
- // Wait for the window blur listener to fire.
2960
- timeoutRef.current = window.setTimeout(() => {
2961
- var _dataRef$current$floa;
2962
- const activeEl = activeElement(domReference ? domReference.ownerDocument : document);
2963
-
2964
- // Focus left the page, keep it open.
2965
- if (!relatedTarget && activeEl === domReference) return;
2966
-
2967
- // When focusing the reference element (e.g. regular click), then
2968
- // clicking into the floating element, prevent it from hiding.
2969
- // Note: it must be focusable, e.g. `tabindex="-1"`.
2970
- // We can not rely on relatedTarget to point to the correct element
2971
- // as it will only point to the shadow host of the newly focused element
2972
- // and not the element that actually has received focus if it is located
2973
- // inside a shadow root.
2974
- if (contains((_dataRef$current$floa = dataRef.current.floatingContext) == null ? void 0 : _dataRef$current$floa.refs.floating.current, activeEl) || contains(domReference, activeEl) || movedToFocusGuard) {
2975
- return;
2976
- }
2977
- onOpenChange(false, event.nativeEvent, 'focus');
2978
- });
2979
- }
2980
- }
2981
- };
2982
- }, [enabled, visibleOnly, dataRef, domReference, onOpenChange]);
2983
- }
2984
-
2985
- const ACTIVE_KEY = 'active';
2986
- const SELECTED_KEY = 'selected';
2987
- function mergeProps(userProps, propsList, elementKey) {
2988
- const map = new Map();
2989
- const isItem = elementKey === 'item';
2990
- let domUserProps = userProps;
2991
- if (isItem && userProps) {
2992
- const {
2993
- [ACTIVE_KEY]: _,
2994
- [SELECTED_KEY]: __,
2995
- ...validProps
2996
- } = userProps;
2997
- domUserProps = validProps;
2998
- }
2999
- return {
3000
- ...(elementKey === 'floating' && {
3001
- tabIndex: -1
3002
- }),
3003
- ...domUserProps,
3004
- ...propsList.map(value => {
3005
- const propsOrGetProps = value ? value[elementKey] : null;
3006
- if (typeof propsOrGetProps === 'function') {
3007
- return userProps ? propsOrGetProps(userProps) : null;
3008
- }
3009
- return propsOrGetProps;
3010
- }).concat(userProps).reduce((acc, props) => {
3011
- if (!props) {
3012
- return acc;
3013
- }
3014
- Object.entries(props).forEach(_ref => {
3015
- let [key, value] = _ref;
3016
- if (isItem && [ACTIVE_KEY, SELECTED_KEY].includes(key)) {
3017
- return;
3018
- }
3019
- if (key.indexOf('on') === 0) {
3020
- if (!map.has(key)) {
3021
- map.set(key, []);
3022
- }
3023
- if (typeof value === 'function') {
3024
- var _map$get;
3025
- (_map$get = map.get(key)) == null || _map$get.push(value);
3026
- acc[key] = function () {
3027
- var _map$get2;
3028
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
3029
- args[_key] = arguments[_key];
3030
- }
3031
- return (_map$get2 = map.get(key)) == null ? void 0 : _map$get2.map(fn => fn(...args)).find(val => val !== undefined);
3032
- };
3033
- }
3034
- } else {
3035
- acc[key] = value;
3036
- }
3037
- });
3038
- return acc;
3039
- }, {})
3040
- };
3041
- }
3042
- /**
3043
- * Merges an array of interaction hooks' props into prop getters, allowing
3044
- * event handler functions to be composed together without overwriting one
3045
- * another.
3046
- * @see https://floating-ui.com/docs/useInteractions
3047
- */
3048
- function useInteractions(propsList) {
3049
- if (propsList === void 0) {
3050
- propsList = [];
3051
- }
3052
- // The dependencies are a dynamic array, so we can't use the linter's
3053
- // suggestion to add it to the deps array.
3054
- const deps = propsList;
3055
- const getReferenceProps = React__namespace.useCallback(userProps => mergeProps(userProps, propsList, 'reference'),
3056
- // eslint-disable-next-line react-hooks/exhaustive-deps
3057
- deps);
3058
- const getFloatingProps = React__namespace.useCallback(userProps => mergeProps(userProps, propsList, 'floating'),
3059
- // eslint-disable-next-line react-hooks/exhaustive-deps
3060
- deps);
3061
- const getItemProps = React__namespace.useCallback(userProps => mergeProps(userProps, propsList, 'item'),
3062
- // Granularly check for `item` changes, because the `getItemProps` getter
3063
- // should be as referentially stable as possible since it may be passed as
3064
- // a prop to many components. All `item` key values must therefore be
3065
- // memoized.
3066
- // eslint-disable-next-line react-hooks/exhaustive-deps
3067
- propsList.map(key => key == null ? void 0 : key.item));
3068
- return React__namespace.useMemo(() => ({
3069
- getReferenceProps,
3070
- getFloatingProps,
3071
- getItemProps
3072
- }), [getReferenceProps, getFloatingProps, getItemProps]);
3073
- }
3074
-
3075
- const componentRoleToAriaRoleMap = /*#__PURE__*/new Map([['select', 'listbox'], ['combobox', 'listbox'], ['label', false]]);
3076
-
3077
- /**
3078
- * Adds base screen reader props to the reference and floating elements for a
3079
- * given floating element `role`.
3080
- * @see https://floating-ui.com/docs/useRole
3081
- */
3082
- function useRole(context, props) {
3083
- var _componentRoleToAriaR;
3084
- if (props === void 0) {
3085
- props = {};
3086
- }
3087
- const {
3088
- open,
3089
- floatingId
3090
- } = context;
3091
- const {
3092
- enabled = true,
3093
- role = 'dialog'
3094
- } = props;
3095
- const ariaRole = (_componentRoleToAriaR = componentRoleToAriaRoleMap.get(role)) != null ? _componentRoleToAriaR : role;
3096
- const referenceId = useId();
3097
- const parentId = useFloatingParentNodeId();
3098
- const isNested = parentId != null;
3099
- return React__namespace.useMemo(() => {
3100
- if (!enabled) return {};
3101
- const floatingProps = {
3102
- id: floatingId,
3103
- ...(ariaRole && {
3104
- role: ariaRole
3105
- })
3106
- };
3107
- if (ariaRole === 'tooltip' || role === 'label') {
3108
- return {
3109
- reference: {
3110
- ["aria-" + (role === 'label' ? 'labelledby' : 'describedby')]: open ? floatingId : undefined
3111
- },
3112
- floating: floatingProps
3113
- };
3114
- }
3115
- return {
3116
- reference: {
3117
- 'aria-expanded': open ? 'true' : 'false',
3118
- 'aria-haspopup': ariaRole === 'alertdialog' ? 'dialog' : ariaRole,
3119
- 'aria-controls': open ? floatingId : undefined,
3120
- ...(ariaRole === 'listbox' && {
3121
- role: 'combobox'
3122
- }),
3123
- ...(ariaRole === 'menu' && {
3124
- id: referenceId
3125
- }),
3126
- ...(ariaRole === 'menu' && isNested && {
3127
- role: 'menuitem'
3128
- }),
3129
- ...(role === 'select' && {
3130
- 'aria-autocomplete': 'none'
3131
- }),
3132
- ...(role === 'combobox' && {
3133
- 'aria-autocomplete': 'list'
3134
- })
3135
- },
3136
- floating: {
3137
- ...floatingProps,
3138
- ...(ariaRole === 'menu' && {
3139
- 'aria-labelledby': referenceId
3140
- })
3141
- },
3142
- item(_ref) {
3143
- let {
3144
- active,
3145
- selected
3146
- } = _ref;
3147
- const commonProps = {
3148
- role: 'option',
3149
- ...(active && {
3150
- id: floatingId + "-option"
3151
- })
3152
- };
3153
-
3154
- // For `menu`, we are unable to tell if the item is a `menuitemradio`
3155
- // or `menuitemcheckbox`. For backwards-compatibility reasons, also
3156
- // avoid defaulting to `menuitem` as it may overwrite custom role props.
3157
- switch (role) {
3158
- case 'select':
3159
- return {
3160
- ...commonProps,
3161
- 'aria-selected': active && selected
3162
- };
3163
- case 'combobox':
3164
- {
3165
- return {
3166
- ...commonProps,
3167
- ...(active && {
3168
- 'aria-selected': true
3169
- })
3170
- };
3171
- }
3172
- }
3173
- return {};
3174
- }
3175
- };
3176
- }, [enabled, role, ariaRole, open, floatingId, referenceId, isNested]);
3177
- }
3178
-
3179
- function isPointInPolygon(point, polygon) {
3180
- const [x, y] = point;
3181
- let isInside = false;
3182
- const length = polygon.length;
3183
- for (let i = 0, j = length - 1; i < length; j = i++) {
3184
- const [xi, yi] = polygon[i] || [0, 0];
3185
- const [xj, yj] = polygon[j] || [0, 0];
3186
- const intersect = yi >= y !== yj >= y && x <= (xj - xi) * (y - yi) / (yj - yi) + xi;
3187
- if (intersect) {
3188
- isInside = !isInside;
3189
- }
3190
- }
3191
- return isInside;
3192
- }
3193
- function isInside(point, rect) {
3194
- return point[0] >= rect.x && point[0] <= rect.x + rect.width && point[1] >= rect.y && point[1] <= rect.y + rect.height;
3195
- }
3196
- /**
3197
- * Generates a safe polygon area that the user can traverse without closing the
3198
- * floating element once leaving the reference element.
3199
- * @see https://floating-ui.com/docs/useHover#safepolygon
3200
- */
3201
- function safePolygon(options) {
3202
- if (options === void 0) {
3203
- options = {};
3204
- }
3205
- const {
3206
- buffer = 0.5,
3207
- blockPointerEvents = false,
3208
- requireIntent = true
3209
- } = options;
3210
- let timeoutId;
3211
- let hasLanded = false;
3212
- let lastX = null;
3213
- let lastY = null;
3214
- let lastCursorTime = performance.now();
3215
- function getCursorSpeed(x, y) {
3216
- const currentTime = performance.now();
3217
- const elapsedTime = currentTime - lastCursorTime;
3218
- if (lastX === null || lastY === null || elapsedTime === 0) {
3219
- lastX = x;
3220
- lastY = y;
3221
- lastCursorTime = currentTime;
3222
- return null;
3223
- }
3224
- const deltaX = x - lastX;
3225
- const deltaY = y - lastY;
3226
- const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
3227
- const speed = distance / elapsedTime; // px / ms
3228
-
3229
- lastX = x;
3230
- lastY = y;
3231
- lastCursorTime = currentTime;
3232
- return speed;
3233
- }
3234
- const fn = _ref => {
3235
- let {
3236
- x,
3237
- y,
3238
- placement,
3239
- elements,
3240
- onClose,
3241
- nodeId,
3242
- tree
3243
- } = _ref;
3244
- return function onMouseMove(event) {
3245
- function close() {
3246
- clearTimeout(timeoutId);
3247
- onClose();
3248
- }
3249
- clearTimeout(timeoutId);
3250
- if (!elements.domReference || !elements.floating || placement == null || x == null || y == null) {
3251
- return;
3252
- }
3253
- const {
3254
- clientX,
3255
- clientY
3256
- } = event;
3257
- const clientPoint = [clientX, clientY];
3258
- const target = getTarget(event);
3259
- const isLeave = event.type === 'mouseleave';
3260
- const isOverFloatingEl = contains(elements.floating, target);
3261
- const isOverReferenceEl = contains(elements.domReference, target);
3262
- const refRect = elements.domReference.getBoundingClientRect();
3263
- const rect = elements.floating.getBoundingClientRect();
3264
- const side = placement.split('-')[0];
3265
- const cursorLeaveFromRight = x > rect.right - rect.width / 2;
3266
- const cursorLeaveFromBottom = y > rect.bottom - rect.height / 2;
3267
- const isOverReferenceRect = isInside(clientPoint, refRect);
3268
- const isFloatingWider = rect.width > refRect.width;
3269
- const isFloatingTaller = rect.height > refRect.height;
3270
- const left = (isFloatingWider ? refRect : rect).left;
3271
- const right = (isFloatingWider ? refRect : rect).right;
3272
- const top = (isFloatingTaller ? refRect : rect).top;
3273
- const bottom = (isFloatingTaller ? refRect : rect).bottom;
3274
- if (isOverFloatingEl) {
3275
- hasLanded = true;
3276
- if (!isLeave) {
3277
- return;
3278
- }
3279
- }
3280
- if (isOverReferenceEl) {
3281
- hasLanded = false;
3282
- }
3283
- if (isOverReferenceEl && !isLeave) {
3284
- hasLanded = true;
3285
- return;
3286
- }
3287
-
3288
- // Prevent overlapping floating element from being stuck in an open-close
3289
- // loop: https://github.com/floating-ui/floating-ui/issues/1910
3290
- if (isLeave && isElement(event.relatedTarget) && contains(elements.floating, event.relatedTarget)) {
3291
- return;
3292
- }
3293
-
3294
- // If any nested child is open, abort.
3295
- if (tree && getChildren(tree.nodesRef.current, nodeId).some(_ref2 => {
3296
- let {
3297
- context
3298
- } = _ref2;
3299
- return context == null ? void 0 : context.open;
3300
- })) {
3301
- return;
3302
- }
3303
-
3304
- // If the pointer is leaving from the opposite side, the "buffer" logic
3305
- // creates a point where the floating element remains open, but should be
3306
- // ignored.
3307
- // A constant of 1 handles floating point rounding errors.
3308
- if (side === 'top' && y >= refRect.bottom - 1 || side === 'bottom' && y <= refRect.top + 1 || side === 'left' && x >= refRect.right - 1 || side === 'right' && x <= refRect.left + 1) {
3309
- return close();
3310
- }
3311
-
3312
- // Ignore when the cursor is within the rectangular trough between the
3313
- // two elements. Since the triangle is created from the cursor point,
3314
- // which can start beyond the ref element's edge, traversing back and
3315
- // forth from the ref to the floating element can cause it to close. This
3316
- // ensures it always remains open in that case.
3317
- let rectPoly = [];
3318
- switch (side) {
3319
- case 'top':
3320
- rectPoly = [[left, refRect.top + 1], [left, rect.bottom - 1], [right, rect.bottom - 1], [right, refRect.top + 1]];
3321
- break;
3322
- case 'bottom':
3323
- rectPoly = [[left, rect.top + 1], [left, refRect.bottom - 1], [right, refRect.bottom - 1], [right, rect.top + 1]];
3324
- break;
3325
- case 'left':
3326
- rectPoly = [[rect.right - 1, bottom], [rect.right - 1, top], [refRect.left + 1, top], [refRect.left + 1, bottom]];
3327
- break;
3328
- case 'right':
3329
- rectPoly = [[refRect.right - 1, bottom], [refRect.right - 1, top], [rect.left + 1, top], [rect.left + 1, bottom]];
3330
- break;
3331
- }
3332
- function getPolygon(_ref3) {
3333
- let [x, y] = _ref3;
3334
- switch (side) {
3335
- case 'top':
3336
- {
3337
- const cursorPointOne = [isFloatingWider ? x + buffer / 2 : cursorLeaveFromRight ? x + buffer * 4 : x - buffer * 4, y + buffer + 1];
3338
- const cursorPointTwo = [isFloatingWider ? x - buffer / 2 : cursorLeaveFromRight ? x + buffer * 4 : x - buffer * 4, y + buffer + 1];
3339
- const commonPoints = [[rect.left, cursorLeaveFromRight ? rect.bottom - buffer : isFloatingWider ? rect.bottom - buffer : rect.top], [rect.right, cursorLeaveFromRight ? isFloatingWider ? rect.bottom - buffer : rect.top : rect.bottom - buffer]];
3340
- return [cursorPointOne, cursorPointTwo, ...commonPoints];
3341
- }
3342
- case 'bottom':
3343
- {
3344
- const cursorPointOne = [isFloatingWider ? x + buffer / 2 : cursorLeaveFromRight ? x + buffer * 4 : x - buffer * 4, y - buffer];
3345
- const cursorPointTwo = [isFloatingWider ? x - buffer / 2 : cursorLeaveFromRight ? x + buffer * 4 : x - buffer * 4, y - buffer];
3346
- const commonPoints = [[rect.left, cursorLeaveFromRight ? rect.top + buffer : isFloatingWider ? rect.top + buffer : rect.bottom], [rect.right, cursorLeaveFromRight ? isFloatingWider ? rect.top + buffer : rect.bottom : rect.top + buffer]];
3347
- return [cursorPointOne, cursorPointTwo, ...commonPoints];
3348
- }
3349
- case 'left':
3350
- {
3351
- const cursorPointOne = [x + buffer + 1, isFloatingTaller ? y + buffer / 2 : cursorLeaveFromBottom ? y + buffer * 4 : y - buffer * 4];
3352
- const cursorPointTwo = [x + buffer + 1, isFloatingTaller ? y - buffer / 2 : cursorLeaveFromBottom ? y + buffer * 4 : y - buffer * 4];
3353
- const commonPoints = [[cursorLeaveFromBottom ? rect.right - buffer : isFloatingTaller ? rect.right - buffer : rect.left, rect.top], [cursorLeaveFromBottom ? isFloatingTaller ? rect.right - buffer : rect.left : rect.right - buffer, rect.bottom]];
3354
- return [...commonPoints, cursorPointOne, cursorPointTwo];
3355
- }
3356
- case 'right':
3357
- {
3358
- const cursorPointOne = [x - buffer, isFloatingTaller ? y + buffer / 2 : cursorLeaveFromBottom ? y + buffer * 4 : y - buffer * 4];
3359
- const cursorPointTwo = [x - buffer, isFloatingTaller ? y - buffer / 2 : cursorLeaveFromBottom ? y + buffer * 4 : y - buffer * 4];
3360
- const commonPoints = [[cursorLeaveFromBottom ? rect.left + buffer : isFloatingTaller ? rect.left + buffer : rect.right, rect.top], [cursorLeaveFromBottom ? isFloatingTaller ? rect.left + buffer : rect.right : rect.left + buffer, rect.bottom]];
3361
- return [cursorPointOne, cursorPointTwo, ...commonPoints];
3362
- }
3363
- }
3364
- }
3365
- if (isPointInPolygon([clientX, clientY], rectPoly)) {
3366
- return;
3367
- }
3368
- if (hasLanded && !isOverReferenceRect) {
3369
- return close();
3370
- }
3371
- if (!isLeave && requireIntent) {
3372
- const cursorSpeed = getCursorSpeed(event.clientX, event.clientY);
3373
- const cursorSpeedThreshold = 0.1;
3374
- if (cursorSpeed !== null && cursorSpeed < cursorSpeedThreshold) {
3375
- return close();
3376
- }
3377
- }
3378
- if (!isPointInPolygon([clientX, clientY], getPolygon([x, y]))) {
3379
- close();
3380
- } else if (!hasLanded && requireIntent) {
3381
- timeoutId = window.setTimeout(close, 40);
3382
- }
3383
- };
3384
- };
3385
- fn.__options = {
3386
- blockPointerEvents
3387
- };
3388
- return fn;
3389
- }
3390
-
3391
82
  var ROTATE_MAP = {
3392
83
  bottom: 180,
3393
84
  left: 270,
@@ -3404,7 +95,7 @@ var Tooltip = function (_a) {
3404
95
  setOpen(true);
3405
96
  }
3406
97
  }, [forceOpen]);
3407
- var _f = useFloating({
98
+ var _f = react.useFloating({
3408
99
  placement: placement,
3409
100
  open: open,
3410
101
  onOpenChange: function (open) { return setOpen(open); },
@@ -3414,23 +105,23 @@ var Tooltip = function (_a) {
3414
105
  name: 'no-flip',
3415
106
  fn: function (obj) { return obj; },
3416
107
  }
3417
- : flip(),
3418
- offset(16),
3419
- arrow({ element: arrowRef, padding: 24 }),
3420
- shift({ padding: 16 }),
108
+ : react.flip(),
109
+ react.offset(16),
110
+ react.arrow({ element: arrowRef, padding: 24 }),
111
+ react.shift({ padding: 16 }),
3421
112
  ],
3422
- whileElementsMounted: autoUpdate,
113
+ whileElementsMounted: react.autoUpdate,
3423
114
  }), floatingStyles = _f.floatingStyles, refs = _f.refs, calculatedPlacement = _f.placement, context = _f.context, _g = _f.middlewareData.arrow, _h = _g === void 0 ? {} : _g, arrowX = _h.x, arrowY = _h.y;
3424
- var dismissHook = useDismiss(context);
3425
- var _j = useInteractions(__spreadArray([
3426
- useHover(context, {
3427
- handleClose: interactive ? safePolygon() : undefined,
115
+ var dismissHook = react.useDismiss(context);
116
+ var _j = react.useInteractions(__spreadArray([
117
+ react.useHover(context, {
118
+ handleClose: interactive ? react.safePolygon() : undefined,
3428
119
  enabled: !disabled && !forceOpen,
3429
120
  }),
3430
- useFocus(context, {
121
+ react.useFocus(context, {
3431
122
  enabled: !disabled && !forceOpen,
3432
123
  }),
3433
- useRole(context, { role: 'tooltip' })
124
+ react.useRole(context, { role: 'tooltip' })
3434
125
  ], (!forceOpen ? [dismissHook] : []), true)), getReferenceProps = _j.getReferenceProps, getFloatingProps = _j.getFloatingProps;
3435
126
  var placementSide = calculatedPlacement.split('-')[0];
3436
127
  var arrowRotate = ROTATE_MAP[placementSide];
@@ -3473,7 +164,7 @@ var Tooltip = function (_a) {
3473
164
  : open
3474
165
  ? // NOTE: we could have used the "FloatingPortal" component
3475
166
  // but it fails miserably and the native portal from react 18 is great...
3476
- ReactDOM.createPortal(React__namespace.createElement("div", __assign({ ref: refs.setFloating, style: __assign(__assign({}, floatingStyles), { zIndex: 100 }), role: "tooltip" }, getFloatingProps()),
167
+ reactDom.createPortal(React__namespace.createElement("div", __assign({ ref: refs.setFloating, style: __assign(__assign({}, floatingStyles), { zIndex: 100 }), role: "tooltip" }, getFloatingProps()),
3477
168
  React__namespace.createElement("div", { className: clsx('rounded shadow-tooltip border', [
3478
169
  colors.background,
3479
170
  colors.block,