@cypress-design/react-tooltip 1.0.1 → 1.0.3

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