@radui/ui 0.0.5 → 0.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,37 +1,8 @@
1
1
  'use client';
2
- import * as React$1 from 'react';
3
- import { useLayoutEffect, useEffect, useRef, useState } from 'react';
4
- import * as ReactDOM from 'react-dom';
2
+ import Popper from '~/components/tools/Popper/Popper';
5
3
 
6
- function _iterableToArrayLimit(r, l) {
7
- var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
8
- if (null != t) {
9
- var e,
10
- n,
11
- i,
12
- u,
13
- a = [],
14
- f = !0,
15
- o = !1;
16
- try {
17
- if (i = (t = t.call(r)).next, 0 === l) {
18
- if (Object(t) !== t) return;
19
- f = !1;
20
- } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
21
- } catch (r) {
22
- o = !0, n = r;
23
- } finally {
24
- try {
25
- if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
26
- } finally {
27
- if (o) throw n;
28
- }
29
- }
30
- return a;
31
- }
32
- }
33
- function _extends$1() {
34
- _extends$1 = Object.assign ? Object.assign.bind() : function (target) {
4
+ function _extends() {
5
+ _extends = Object.assign ? Object.assign.bind() : function (target) {
35
6
  for (var i = 1; i < arguments.length; i++) {
36
7
  var source = arguments[i];
37
8
  for (var key in source) {
@@ -42,7 +13,7 @@ function _extends$1() {
42
13
  }
43
14
  return target;
44
15
  };
45
- return _extends$1.apply(this, arguments);
16
+ return _extends.apply(this, arguments);
46
17
  }
47
18
  function _objectWithoutPropertiesLoose(source, excluded) {
48
19
  if (source == null) return {};
@@ -71,2717 +42,6 @@ function _objectWithoutProperties(source, excluded) {
71
42
  }
72
43
  return target;
73
44
  }
74
- function _slicedToArray(arr, i) {
75
- return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
76
- }
77
- function _arrayWithHoles(arr) {
78
- if (Array.isArray(arr)) return arr;
79
- }
80
- function _unsupportedIterableToArray(o, minLen) {
81
- if (!o) return;
82
- if (typeof o === "string") return _arrayLikeToArray(o, minLen);
83
- var n = Object.prototype.toString.call(o).slice(8, -1);
84
- if (n === "Object" && o.constructor) n = o.constructor.name;
85
- if (n === "Map" || n === "Set") return Array.from(o);
86
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
87
- }
88
- function _arrayLikeToArray(arr, len) {
89
- if (len == null || len > arr.length) len = arr.length;
90
- for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
91
- return arr2;
92
- }
93
- function _nonIterableRest() {
94
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
95
- }
96
-
97
- var RAD_UI_CLASS_PREFIX = 'rad-ui';
98
- var customClassSwitcher = function customClassSwitcher(customRootClass) {
99
- var componentName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
100
- // applies a custom root class the user provides, else applies the default rad-ui classes to the component
101
- // rad ui's classes are based on this logic
102
-
103
- // add dashes between capitalized words
104
- var componentClassName = componentName.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
105
- if (customRootClass) return customRootClass;
106
- if (componentName) return "".concat(RAD_UI_CLASS_PREFIX, "-").concat(componentClassName);
107
- return '';
108
- };
109
-
110
- function getNodeName(node) {
111
- if (isNode(node)) {
112
- return (node.nodeName || '').toLowerCase();
113
- }
114
- // Mocked nodes in testing environments may not be instances of Node. By
115
- // returning `#document` an infinite loop won't occur.
116
- // https://github.com/floating-ui/floating-ui/issues/2317
117
- return '#document';
118
- }
119
- function getWindow(node) {
120
- var _node$ownerDocument;
121
- return (node == null ? void 0 : (_node$ownerDocument = node.ownerDocument) == null ? void 0 : _node$ownerDocument.defaultView) || window;
122
- }
123
- function getDocumentElement(node) {
124
- var _ref;
125
- return (_ref = (isNode(node) ? node.ownerDocument : node.document) || window.document) == null ? void 0 : _ref.documentElement;
126
- }
127
- function isNode(value) {
128
- return value instanceof Node || value instanceof getWindow(value).Node;
129
- }
130
- function isElement(value) {
131
- return value instanceof Element || value instanceof getWindow(value).Element;
132
- }
133
- function isHTMLElement(value) {
134
- return value instanceof HTMLElement || value instanceof getWindow(value).HTMLElement;
135
- }
136
- function isShadowRoot(value) {
137
- // Browsers without `ShadowRoot` support.
138
- if (typeof ShadowRoot === 'undefined') {
139
- return false;
140
- }
141
- return value instanceof ShadowRoot || value instanceof getWindow(value).ShadowRoot;
142
- }
143
- function isOverflowElement(element) {
144
- const {
145
- overflow,
146
- overflowX,
147
- overflowY,
148
- display
149
- } = getComputedStyle(element);
150
- return /auto|scroll|overlay|hidden|clip/.test(overflow + overflowY + overflowX) && !['inline', 'contents'].includes(display);
151
- }
152
- function isTableElement(element) {
153
- return ['table', 'td', 'th'].includes(getNodeName(element));
154
- }
155
- function isContainingBlock(element) {
156
- const webkit = isWebKit();
157
- const css = getComputedStyle(element);
158
-
159
- // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block
160
- 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));
161
- }
162
- function getContainingBlock(element) {
163
- let currentNode = getParentNode(element);
164
- while (isHTMLElement(currentNode) && !isLastTraversableNode(currentNode)) {
165
- if (isContainingBlock(currentNode)) {
166
- return currentNode;
167
- } else {
168
- currentNode = getParentNode(currentNode);
169
- }
170
- }
171
- return null;
172
- }
173
- function isWebKit() {
174
- if (typeof CSS === 'undefined' || !CSS.supports) return false;
175
- return CSS.supports('-webkit-backdrop-filter', 'none');
176
- }
177
- function isLastTraversableNode(node) {
178
- return ['html', 'body', '#document'].includes(getNodeName(node));
179
- }
180
- function getComputedStyle(element) {
181
- return getWindow(element).getComputedStyle(element);
182
- }
183
- function getNodeScroll(element) {
184
- if (isElement(element)) {
185
- return {
186
- scrollLeft: element.scrollLeft,
187
- scrollTop: element.scrollTop
188
- };
189
- }
190
- return {
191
- scrollLeft: element.pageXOffset,
192
- scrollTop: element.pageYOffset
193
- };
194
- }
195
- function getParentNode(node) {
196
- if (getNodeName(node) === 'html') {
197
- return node;
198
- }
199
- const result =
200
- // Step into the shadow DOM of the parent of a slotted node.
201
- node.assignedSlot ||
202
- // DOM Element detected.
203
- node.parentNode ||
204
- // ShadowRoot detected.
205
- isShadowRoot(node) && node.host ||
206
- // Fallback.
207
- getDocumentElement(node);
208
- return isShadowRoot(result) ? result.host : result;
209
- }
210
- function getNearestOverflowAncestor(node) {
211
- const parentNode = getParentNode(node);
212
- if (isLastTraversableNode(parentNode)) {
213
- return node.ownerDocument ? node.ownerDocument.body : node.body;
214
- }
215
- if (isHTMLElement(parentNode) && isOverflowElement(parentNode)) {
216
- return parentNode;
217
- }
218
- return getNearestOverflowAncestor(parentNode);
219
- }
220
- function getOverflowAncestors(node, list, traverseIframes) {
221
- var _node$ownerDocument2;
222
- if (list === void 0) {
223
- list = [];
224
- }
225
- if (traverseIframes === void 0) {
226
- traverseIframes = true;
227
- }
228
- const scrollableAncestor = getNearestOverflowAncestor(node);
229
- const isBody = scrollableAncestor === ((_node$ownerDocument2 = node.ownerDocument) == null ? void 0 : _node$ownerDocument2.body);
230
- const win = getWindow(scrollableAncestor);
231
- if (isBody) {
232
- return list.concat(win, win.visualViewport || [], isOverflowElement(scrollableAncestor) ? scrollableAncestor : [], win.frameElement && traverseIframes ? getOverflowAncestors(win.frameElement) : []);
233
- }
234
- return list.concat(scrollableAncestor, getOverflowAncestors(scrollableAncestor, [], traverseIframes));
235
- }
236
-
237
- function contains(parent, child) {
238
- if (!parent || !child) {
239
- return false;
240
- }
241
- const rootNode = child.getRootNode && child.getRootNode();
242
-
243
- // First, attempt with faster native method
244
- if (parent.contains(child)) {
245
- return true;
246
- }
247
-
248
- // then fallback to custom implementation with Shadow DOM support
249
- if (rootNode && isShadowRoot(rootNode)) {
250
- let next = child;
251
- while (next) {
252
- if (parent === next) {
253
- return true;
254
- }
255
- // @ts-ignore
256
- next = next.parentNode || next.host;
257
- }
258
- }
259
-
260
- // Give up, the result is false
261
- return false;
262
- }
263
- function isMouseLikePointerType(pointerType, strict) {
264
- // On some Linux machines with Chromium, mouse inputs return a `pointerType`
265
- // of "pen": https://github.com/floating-ui/floating-ui/issues/2015
266
- const values = ['mouse', 'pen'];
267
- if (!strict) {
268
- values.push('', undefined);
269
- }
270
- return values.includes(pointerType);
271
- }
272
- function isReactEvent(event) {
273
- return 'nativeEvent' in event;
274
- }
275
- function isRootElement(element) {
276
- return element.matches('html,body');
277
- }
278
- function getDocument(node) {
279
- return (node == null ? void 0 : node.ownerDocument) || document;
280
- }
281
- function isEventTargetWithin(event, node) {
282
- if (node == null) {
283
- return false;
284
- }
285
- if ('composedPath' in event) {
286
- return event.composedPath().includes(node);
287
- }
288
-
289
- // TS thinks `event` is of type never as it assumes all browsers support composedPath, but browsers without shadow dom don't
290
- const e = event;
291
- return e.target != null && node.contains(e.target);
292
- }
293
- function getTarget(event) {
294
- if ('composedPath' in event) {
295
- return event.composedPath()[0];
296
- }
297
-
298
- // TS thinks `event` is of type never as it assumes all browsers support
299
- // `composedPath()`, but browsers without shadow DOM don't.
300
- return event.target;
301
- }
302
-
303
- const min = Math.min;
304
- const max = Math.max;
305
- const round = Math.round;
306
- const createCoords = v => ({
307
- x: v,
308
- y: v
309
- });
310
- const oppositeSideMap = {
311
- left: 'right',
312
- right: 'left',
313
- bottom: 'top',
314
- top: 'bottom'
315
- };
316
- const oppositeAlignmentMap = {
317
- start: 'end',
318
- end: 'start'
319
- };
320
- function clamp(start, value, end) {
321
- return max(start, min(value, end));
322
- }
323
- function evaluate(value, param) {
324
- return typeof value === 'function' ? value(param) : value;
325
- }
326
- function getSide(placement) {
327
- return placement.split('-')[0];
328
- }
329
- function getAlignment(placement) {
330
- return placement.split('-')[1];
331
- }
332
- function getOppositeAxis(axis) {
333
- return axis === 'x' ? 'y' : 'x';
334
- }
335
- function getAxisLength(axis) {
336
- return axis === 'y' ? 'height' : 'width';
337
- }
338
- function getSideAxis(placement) {
339
- return ['top', 'bottom'].includes(getSide(placement)) ? 'y' : 'x';
340
- }
341
- function getAlignmentAxis(placement) {
342
- return getOppositeAxis(getSideAxis(placement));
343
- }
344
- function getAlignmentSides(placement, rects, rtl) {
345
- if (rtl === void 0) {
346
- rtl = false;
347
- }
348
- const alignment = getAlignment(placement);
349
- const alignmentAxis = getAlignmentAxis(placement);
350
- const length = getAxisLength(alignmentAxis);
351
- let mainAlignmentSide = alignmentAxis === 'x' ? alignment === (rtl ? 'end' : 'start') ? 'right' : 'left' : alignment === 'start' ? 'bottom' : 'top';
352
- if (rects.reference[length] > rects.floating[length]) {
353
- mainAlignmentSide = getOppositePlacement(mainAlignmentSide);
354
- }
355
- return [mainAlignmentSide, getOppositePlacement(mainAlignmentSide)];
356
- }
357
- function getExpandedPlacements(placement) {
358
- const oppositePlacement = getOppositePlacement(placement);
359
- return [getOppositeAlignmentPlacement(placement), oppositePlacement, getOppositeAlignmentPlacement(oppositePlacement)];
360
- }
361
- function getOppositeAlignmentPlacement(placement) {
362
- return placement.replace(/start|end/g, alignment => oppositeAlignmentMap[alignment]);
363
- }
364
- function getSideList(side, isStart, rtl) {
365
- const lr = ['left', 'right'];
366
- const rl = ['right', 'left'];
367
- const tb = ['top', 'bottom'];
368
- const bt = ['bottom', 'top'];
369
- switch (side) {
370
- case 'top':
371
- case 'bottom':
372
- if (rtl) return isStart ? rl : lr;
373
- return isStart ? lr : rl;
374
- case 'left':
375
- case 'right':
376
- return isStart ? tb : bt;
377
- default:
378
- return [];
379
- }
380
- }
381
- function getOppositeAxisPlacements(placement, flipAlignment, direction, rtl) {
382
- const alignment = getAlignment(placement);
383
- let list = getSideList(getSide(placement), direction === 'start', rtl);
384
- if (alignment) {
385
- list = list.map(side => side + "-" + alignment);
386
- if (flipAlignment) {
387
- list = list.concat(list.map(getOppositeAlignmentPlacement));
388
- }
389
- }
390
- return list;
391
- }
392
- function getOppositePlacement(placement) {
393
- return placement.replace(/left|right|bottom|top/g, side => oppositeSideMap[side]);
394
- }
395
- function expandPaddingObject(padding) {
396
- return {
397
- top: 0,
398
- right: 0,
399
- bottom: 0,
400
- left: 0,
401
- ...padding
402
- };
403
- }
404
- function getPaddingObject(padding) {
405
- return typeof padding !== 'number' ? expandPaddingObject(padding) : {
406
- top: padding,
407
- right: padding,
408
- bottom: padding,
409
- left: padding
410
- };
411
- }
412
- function rectToClientRect(rect) {
413
- return {
414
- ...rect,
415
- top: rect.y,
416
- left: rect.x,
417
- right: rect.x + rect.width,
418
- bottom: rect.y + rect.height
419
- };
420
- }
421
-
422
- function computeCoordsFromPlacement(_ref, placement, rtl) {
423
- let {
424
- reference,
425
- floating
426
- } = _ref;
427
- const sideAxis = getSideAxis(placement);
428
- const alignmentAxis = getAlignmentAxis(placement);
429
- const alignLength = getAxisLength(alignmentAxis);
430
- const side = getSide(placement);
431
- const isVertical = sideAxis === 'y';
432
- const commonX = reference.x + reference.width / 2 - floating.width / 2;
433
- const commonY = reference.y + reference.height / 2 - floating.height / 2;
434
- const commonAlign = reference[alignLength] / 2 - floating[alignLength] / 2;
435
- let coords;
436
- switch (side) {
437
- case 'top':
438
- coords = {
439
- x: commonX,
440
- y: reference.y - floating.height
441
- };
442
- break;
443
- case 'bottom':
444
- coords = {
445
- x: commonX,
446
- y: reference.y + reference.height
447
- };
448
- break;
449
- case 'right':
450
- coords = {
451
- x: reference.x + reference.width,
452
- y: commonY
453
- };
454
- break;
455
- case 'left':
456
- coords = {
457
- x: reference.x - floating.width,
458
- y: commonY
459
- };
460
- break;
461
- default:
462
- coords = {
463
- x: reference.x,
464
- y: reference.y
465
- };
466
- }
467
- switch (getAlignment(placement)) {
468
- case 'start':
469
- coords[alignmentAxis] -= commonAlign * (rtl && isVertical ? -1 : 1);
470
- break;
471
- case 'end':
472
- coords[alignmentAxis] += commonAlign * (rtl && isVertical ? -1 : 1);
473
- break;
474
- }
475
- return coords;
476
- }
477
-
478
- /**
479
- * Computes the `x` and `y` coordinates that will place the floating element
480
- * next to a reference element when it is given a certain positioning strategy.
481
- *
482
- * This export does not have any `platform` interface logic. You will need to
483
- * write one for the platform you are using Floating UI with.
484
- */
485
- const computePosition$1 = async (reference, floating, config) => {
486
- const {
487
- placement = 'bottom',
488
- strategy = 'absolute',
489
- middleware = [],
490
- platform
491
- } = config;
492
- const validMiddleware = middleware.filter(Boolean);
493
- const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(floating));
494
- let rects = await platform.getElementRects({
495
- reference,
496
- floating,
497
- strategy
498
- });
499
- let {
500
- x,
501
- y
502
- } = computeCoordsFromPlacement(rects, placement, rtl);
503
- let statefulPlacement = placement;
504
- let middlewareData = {};
505
- let resetCount = 0;
506
- for (let i = 0; i < validMiddleware.length; i++) {
507
- const {
508
- name,
509
- fn
510
- } = validMiddleware[i];
511
- const {
512
- x: nextX,
513
- y: nextY,
514
- data,
515
- reset
516
- } = await fn({
517
- x,
518
- y,
519
- initialPlacement: placement,
520
- placement: statefulPlacement,
521
- strategy,
522
- middlewareData,
523
- rects,
524
- platform,
525
- elements: {
526
- reference,
527
- floating
528
- }
529
- });
530
- x = nextX != null ? nextX : x;
531
- y = nextY != null ? nextY : y;
532
- middlewareData = {
533
- ...middlewareData,
534
- [name]: {
535
- ...middlewareData[name],
536
- ...data
537
- }
538
- };
539
- if (reset && resetCount <= 50) {
540
- resetCount++;
541
- if (typeof reset === 'object') {
542
- if (reset.placement) {
543
- statefulPlacement = reset.placement;
544
- }
545
- if (reset.rects) {
546
- rects = reset.rects === true ? await platform.getElementRects({
547
- reference,
548
- floating,
549
- strategy
550
- }) : reset.rects;
551
- }
552
- ({
553
- x,
554
- y
555
- } = computeCoordsFromPlacement(rects, statefulPlacement, rtl));
556
- }
557
- i = -1;
558
- continue;
559
- }
560
- }
561
- return {
562
- x,
563
- y,
564
- placement: statefulPlacement,
565
- strategy,
566
- middlewareData
567
- };
568
- };
569
-
570
- /**
571
- * Resolves with an object of overflow side offsets that determine how much the
572
- * element is overflowing a given clipping boundary on each side.
573
- * - positive = overflowing the boundary by that number of pixels
574
- * - negative = how many pixels left before it will overflow
575
- * - 0 = lies flush with the boundary
576
- * @see https://floating-ui.com/docs/detectOverflow
577
- */
578
- async function detectOverflow(state, options) {
579
- var _await$platform$isEle;
580
- if (options === void 0) {
581
- options = {};
582
- }
583
- const {
584
- x,
585
- y,
586
- platform,
587
- rects,
588
- elements,
589
- strategy
590
- } = state;
591
- const {
592
- boundary = 'clippingAncestors',
593
- rootBoundary = 'viewport',
594
- elementContext = 'floating',
595
- altBoundary = false,
596
- padding = 0
597
- } = evaluate(options, state);
598
- const paddingObject = getPaddingObject(padding);
599
- const altContext = elementContext === 'floating' ? 'reference' : 'floating';
600
- const element = elements[altBoundary ? altContext : elementContext];
601
- const clippingClientRect = rectToClientRect(await platform.getClippingRect({
602
- 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))),
603
- boundary,
604
- rootBoundary,
605
- strategy
606
- }));
607
- const rect = elementContext === 'floating' ? {
608
- ...rects.floating,
609
- x,
610
- y
611
- } : rects.reference;
612
- const offsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(elements.floating));
613
- const offsetScale = (await (platform.isElement == null ? void 0 : platform.isElement(offsetParent))) ? (await (platform.getScale == null ? void 0 : platform.getScale(offsetParent))) || {
614
- x: 1,
615
- y: 1
616
- } : {
617
- x: 1,
618
- y: 1
619
- };
620
- const elementClientRect = rectToClientRect(platform.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform.convertOffsetParentRelativeRectToViewportRelativeRect({
621
- rect,
622
- offsetParent,
623
- strategy
624
- }) : rect);
625
- return {
626
- top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y,
627
- bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y,
628
- left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x,
629
- right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x
630
- };
631
- }
632
-
633
- /**
634
- * Provides data to position an inner element of the floating element so that it
635
- * appears centered to the reference element.
636
- * @see https://floating-ui.com/docs/arrow
637
- */
638
- const arrow$1 = options => ({
639
- name: 'arrow',
640
- options,
641
- async fn(state) {
642
- const {
643
- x,
644
- y,
645
- placement,
646
- rects,
647
- platform,
648
- elements,
649
- middlewareData
650
- } = state;
651
- // Since `element` is required, we don't Partial<> the type.
652
- const {
653
- element,
654
- padding = 0
655
- } = evaluate(options, state) || {};
656
- if (element == null) {
657
- return {};
658
- }
659
- const paddingObject = getPaddingObject(padding);
660
- const coords = {
661
- x,
662
- y
663
- };
664
- const axis = getAlignmentAxis(placement);
665
- const length = getAxisLength(axis);
666
- const arrowDimensions = await platform.getDimensions(element);
667
- const isYAxis = axis === 'y';
668
- const minProp = isYAxis ? 'top' : 'left';
669
- const maxProp = isYAxis ? 'bottom' : 'right';
670
- const clientProp = isYAxis ? 'clientHeight' : 'clientWidth';
671
- const endDiff = rects.reference[length] + rects.reference[axis] - coords[axis] - rects.floating[length];
672
- const startDiff = coords[axis] - rects.reference[axis];
673
- const arrowOffsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(element));
674
- let clientSize = arrowOffsetParent ? arrowOffsetParent[clientProp] : 0;
675
-
676
- // DOM platform can return `window` as the `offsetParent`.
677
- if (!clientSize || !(await (platform.isElement == null ? void 0 : platform.isElement(arrowOffsetParent)))) {
678
- clientSize = elements.floating[clientProp] || rects.floating[length];
679
- }
680
- const centerToReference = endDiff / 2 - startDiff / 2;
681
-
682
- // If the padding is large enough that it causes the arrow to no longer be
683
- // centered, modify the padding so that it is centered.
684
- const largestPossiblePadding = clientSize / 2 - arrowDimensions[length] / 2 - 1;
685
- const minPadding = min(paddingObject[minProp], largestPossiblePadding);
686
- const maxPadding = min(paddingObject[maxProp], largestPossiblePadding);
687
-
688
- // Make sure the arrow doesn't overflow the floating element if the center
689
- // point is outside the floating element's bounds.
690
- const min$1 = minPadding;
691
- const max = clientSize - arrowDimensions[length] - maxPadding;
692
- const center = clientSize / 2 - arrowDimensions[length] / 2 + centerToReference;
693
- const offset = clamp(min$1, center, max);
694
-
695
- // If the reference is small enough that the arrow's padding causes it to
696
- // to point to nothing for an aligned placement, adjust the offset of the
697
- // floating element itself. To ensure `shift()` continues to take action,
698
- // a single reset is performed when this is true.
699
- const shouldAddOffset = !middlewareData.arrow && getAlignment(placement) != null && center != offset && rects.reference[length] / 2 - (center < min$1 ? minPadding : maxPadding) - arrowDimensions[length] / 2 < 0;
700
- const alignmentOffset = shouldAddOffset ? center < min$1 ? center - min$1 : center - max : 0;
701
- return {
702
- [axis]: coords[axis] + alignmentOffset,
703
- data: {
704
- [axis]: offset,
705
- centerOffset: center - offset - alignmentOffset,
706
- ...(shouldAddOffset && {
707
- alignmentOffset
708
- })
709
- },
710
- reset: shouldAddOffset
711
- };
712
- }
713
- });
714
-
715
- /**
716
- * Optimizes the visibility of the floating element by flipping the `placement`
717
- * in order to keep it in view when the preferred placement(s) will overflow the
718
- * clipping boundary. Alternative to `autoPlacement`.
719
- * @see https://floating-ui.com/docs/flip
720
- */
721
- const flip = function (options) {
722
- if (options === void 0) {
723
- options = {};
724
- }
725
- return {
726
- name: 'flip',
727
- options,
728
- async fn(state) {
729
- var _middlewareData$arrow, _middlewareData$flip;
730
- const {
731
- placement,
732
- middlewareData,
733
- rects,
734
- initialPlacement,
735
- platform,
736
- elements
737
- } = state;
738
- const {
739
- mainAxis: checkMainAxis = true,
740
- crossAxis: checkCrossAxis = true,
741
- fallbackPlacements: specifiedFallbackPlacements,
742
- fallbackStrategy = 'bestFit',
743
- fallbackAxisSideDirection = 'none',
744
- flipAlignment = true,
745
- ...detectOverflowOptions
746
- } = evaluate(options, state);
747
-
748
- // If a reset by the arrow was caused due to an alignment offset being
749
- // added, we should skip any logic now since `flip()` has already done its
750
- // work.
751
- // https://github.com/floating-ui/floating-ui/issues/2549#issuecomment-1719601643
752
- if ((_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {
753
- return {};
754
- }
755
- const side = getSide(placement);
756
- const isBasePlacement = getSide(initialPlacement) === initialPlacement;
757
- const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating));
758
- const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipAlignment ? [getOppositePlacement(initialPlacement)] : getExpandedPlacements(initialPlacement));
759
- if (!specifiedFallbackPlacements && fallbackAxisSideDirection !== 'none') {
760
- fallbackPlacements.push(...getOppositeAxisPlacements(initialPlacement, flipAlignment, fallbackAxisSideDirection, rtl));
761
- }
762
- const placements = [initialPlacement, ...fallbackPlacements];
763
- const overflow = await detectOverflow(state, detectOverflowOptions);
764
- const overflows = [];
765
- let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || [];
766
- if (checkMainAxis) {
767
- overflows.push(overflow[side]);
768
- }
769
- if (checkCrossAxis) {
770
- const sides = getAlignmentSides(placement, rects, rtl);
771
- overflows.push(overflow[sides[0]], overflow[sides[1]]);
772
- }
773
- overflowsData = [...overflowsData, {
774
- placement,
775
- overflows
776
- }];
777
-
778
- // One or more sides is overflowing.
779
- if (!overflows.every(side => side <= 0)) {
780
- var _middlewareData$flip2, _overflowsData$filter;
781
- const nextIndex = (((_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) || 0) + 1;
782
- const nextPlacement = placements[nextIndex];
783
- if (nextPlacement) {
784
- // Try next placement and re-run the lifecycle.
785
- return {
786
- data: {
787
- index: nextIndex,
788
- overflows: overflowsData
789
- },
790
- reset: {
791
- placement: nextPlacement
792
- }
793
- };
794
- }
795
-
796
- // First, find the candidates that fit on the mainAxis side of overflow,
797
- // then find the placement that fits the best on the main crossAxis side.
798
- 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;
799
-
800
- // Otherwise fallback.
801
- if (!resetPlacement) {
802
- switch (fallbackStrategy) {
803
- case 'bestFit':
804
- {
805
- var _overflowsData$map$so;
806
- 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];
807
- if (placement) {
808
- resetPlacement = placement;
809
- }
810
- break;
811
- }
812
- case 'initialPlacement':
813
- resetPlacement = initialPlacement;
814
- break;
815
- }
816
- }
817
- if (placement !== resetPlacement) {
818
- return {
819
- reset: {
820
- placement: resetPlacement
821
- }
822
- };
823
- }
824
- }
825
- return {};
826
- }
827
- };
828
- };
829
-
830
- // For type backwards-compatibility, the `OffsetOptions` type was also
831
- // Derivable.
832
- async function convertValueToCoords(state, options) {
833
- const {
834
- placement,
835
- platform,
836
- elements
837
- } = state;
838
- const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating));
839
- const side = getSide(placement);
840
- const alignment = getAlignment(placement);
841
- const isVertical = getSideAxis(placement) === 'y';
842
- const mainAxisMulti = ['left', 'top'].includes(side) ? -1 : 1;
843
- const crossAxisMulti = rtl && isVertical ? -1 : 1;
844
- const rawValue = evaluate(options, state);
845
-
846
- // eslint-disable-next-line prefer-const
847
- let {
848
- mainAxis,
849
- crossAxis,
850
- alignmentAxis
851
- } = typeof rawValue === 'number' ? {
852
- mainAxis: rawValue,
853
- crossAxis: 0,
854
- alignmentAxis: null
855
- } : {
856
- mainAxis: 0,
857
- crossAxis: 0,
858
- alignmentAxis: null,
859
- ...rawValue
860
- };
861
- if (alignment && typeof alignmentAxis === 'number') {
862
- crossAxis = alignment === 'end' ? alignmentAxis * -1 : alignmentAxis;
863
- }
864
- return isVertical ? {
865
- x: crossAxis * crossAxisMulti,
866
- y: mainAxis * mainAxisMulti
867
- } : {
868
- x: mainAxis * mainAxisMulti,
869
- y: crossAxis * crossAxisMulti
870
- };
871
- }
872
-
873
- /**
874
- * Modifies the placement by translating the floating element along the
875
- * specified axes.
876
- * A number (shorthand for `mainAxis` or distance), or an axes configuration
877
- * object may be passed.
878
- * @see https://floating-ui.com/docs/offset
879
- */
880
- const offset = function (options) {
881
- if (options === void 0) {
882
- options = 0;
883
- }
884
- return {
885
- name: 'offset',
886
- options,
887
- async fn(state) {
888
- var _middlewareData$offse, _middlewareData$arrow;
889
- const {
890
- x,
891
- y,
892
- placement,
893
- middlewareData
894
- } = state;
895
- const diffCoords = await convertValueToCoords(state, options);
896
-
897
- // If the placement is the same and the arrow caused an alignment offset
898
- // then we don't need to change the positioning coordinates.
899
- if (placement === ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse.placement) && (_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {
900
- return {};
901
- }
902
- return {
903
- x: x + diffCoords.x,
904
- y: y + diffCoords.y,
905
- data: {
906
- ...diffCoords,
907
- placement
908
- }
909
- };
910
- }
911
- };
912
- };
913
-
914
- function getCssDimensions(element) {
915
- const css = getComputedStyle(element);
916
- // In testing environments, the `width` and `height` properties are empty
917
- // strings for SVG elements, returning NaN. Fallback to `0` in this case.
918
- let width = parseFloat(css.width) || 0;
919
- let height = parseFloat(css.height) || 0;
920
- const hasOffset = isHTMLElement(element);
921
- const offsetWidth = hasOffset ? element.offsetWidth : width;
922
- const offsetHeight = hasOffset ? element.offsetHeight : height;
923
- const shouldFallback = round(width) !== offsetWidth || round(height) !== offsetHeight;
924
- if (shouldFallback) {
925
- width = offsetWidth;
926
- height = offsetHeight;
927
- }
928
- return {
929
- width,
930
- height,
931
- $: shouldFallback
932
- };
933
- }
934
-
935
- function unwrapElement(element) {
936
- return !isElement(element) ? element.contextElement : element;
937
- }
938
-
939
- function getScale(element) {
940
- const domElement = unwrapElement(element);
941
- if (!isHTMLElement(domElement)) {
942
- return createCoords(1);
943
- }
944
- const rect = domElement.getBoundingClientRect();
945
- const {
946
- width,
947
- height,
948
- $
949
- } = getCssDimensions(domElement);
950
- let x = ($ ? round(rect.width) : rect.width) / width;
951
- let y = ($ ? round(rect.height) : rect.height) / height;
952
-
953
- // 0, NaN, or Infinity should always fallback to 1.
954
-
955
- if (!x || !Number.isFinite(x)) {
956
- x = 1;
957
- }
958
- if (!y || !Number.isFinite(y)) {
959
- y = 1;
960
- }
961
- return {
962
- x,
963
- y
964
- };
965
- }
966
-
967
- const noOffsets = /*#__PURE__*/createCoords(0);
968
- function getVisualOffsets(element) {
969
- const win = getWindow(element);
970
- if (!isWebKit() || !win.visualViewport) {
971
- return noOffsets;
972
- }
973
- return {
974
- x: win.visualViewport.offsetLeft,
975
- y: win.visualViewport.offsetTop
976
- };
977
- }
978
- function shouldAddVisualOffsets(element, isFixed, floatingOffsetParent) {
979
- if (isFixed === void 0) {
980
- isFixed = false;
981
- }
982
- if (!floatingOffsetParent || isFixed && floatingOffsetParent !== getWindow(element)) {
983
- return false;
984
- }
985
- return isFixed;
986
- }
987
-
988
- function getBoundingClientRect(element, includeScale, isFixedStrategy, offsetParent) {
989
- if (includeScale === void 0) {
990
- includeScale = false;
991
- }
992
- if (isFixedStrategy === void 0) {
993
- isFixedStrategy = false;
994
- }
995
- const clientRect = element.getBoundingClientRect();
996
- const domElement = unwrapElement(element);
997
- let scale = createCoords(1);
998
- if (includeScale) {
999
- if (offsetParent) {
1000
- if (isElement(offsetParent)) {
1001
- scale = getScale(offsetParent);
1002
- }
1003
- } else {
1004
- scale = getScale(element);
1005
- }
1006
- }
1007
- const visualOffsets = shouldAddVisualOffsets(domElement, isFixedStrategy, offsetParent) ? getVisualOffsets(domElement) : createCoords(0);
1008
- let x = (clientRect.left + visualOffsets.x) / scale.x;
1009
- let y = (clientRect.top + visualOffsets.y) / scale.y;
1010
- let width = clientRect.width / scale.x;
1011
- let height = clientRect.height / scale.y;
1012
- if (domElement) {
1013
- const win = getWindow(domElement);
1014
- const offsetWin = offsetParent && isElement(offsetParent) ? getWindow(offsetParent) : offsetParent;
1015
- let currentIFrame = win.frameElement;
1016
- while (currentIFrame && offsetParent && offsetWin !== win) {
1017
- const iframeScale = getScale(currentIFrame);
1018
- const iframeRect = currentIFrame.getBoundingClientRect();
1019
- const css = getComputedStyle(currentIFrame);
1020
- const left = iframeRect.left + (currentIFrame.clientLeft + parseFloat(css.paddingLeft)) * iframeScale.x;
1021
- const top = iframeRect.top + (currentIFrame.clientTop + parseFloat(css.paddingTop)) * iframeScale.y;
1022
- x *= iframeScale.x;
1023
- y *= iframeScale.y;
1024
- width *= iframeScale.x;
1025
- height *= iframeScale.y;
1026
- x += left;
1027
- y += top;
1028
- currentIFrame = getWindow(currentIFrame).frameElement;
1029
- }
1030
- }
1031
- return rectToClientRect({
1032
- width,
1033
- height,
1034
- x,
1035
- y
1036
- });
1037
- }
1038
-
1039
- function convertOffsetParentRelativeRectToViewportRelativeRect(_ref) {
1040
- let {
1041
- rect,
1042
- offsetParent,
1043
- strategy
1044
- } = _ref;
1045
- const isOffsetParentAnElement = isHTMLElement(offsetParent);
1046
- const documentElement = getDocumentElement(offsetParent);
1047
- if (offsetParent === documentElement) {
1048
- return rect;
1049
- }
1050
- let scroll = {
1051
- scrollLeft: 0,
1052
- scrollTop: 0
1053
- };
1054
- let scale = createCoords(1);
1055
- const offsets = createCoords(0);
1056
- if (isOffsetParentAnElement || !isOffsetParentAnElement && strategy !== 'fixed') {
1057
- if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) {
1058
- scroll = getNodeScroll(offsetParent);
1059
- }
1060
- if (isHTMLElement(offsetParent)) {
1061
- const offsetRect = getBoundingClientRect(offsetParent);
1062
- scale = getScale(offsetParent);
1063
- offsets.x = offsetRect.x + offsetParent.clientLeft;
1064
- offsets.y = offsetRect.y + offsetParent.clientTop;
1065
- }
1066
- }
1067
- return {
1068
- width: rect.width * scale.x,
1069
- height: rect.height * scale.y,
1070
- x: rect.x * scale.x - scroll.scrollLeft * scale.x + offsets.x,
1071
- y: rect.y * scale.y - scroll.scrollTop * scale.y + offsets.y
1072
- };
1073
- }
1074
-
1075
- function getClientRects(element) {
1076
- return Array.from(element.getClientRects());
1077
- }
1078
-
1079
- function getWindowScrollBarX(element) {
1080
- // If <html> has a CSS width greater than the viewport, then this will be
1081
- // incorrect for RTL.
1082
- return getBoundingClientRect(getDocumentElement(element)).left + getNodeScroll(element).scrollLeft;
1083
- }
1084
-
1085
- // Gets the entire size of the scrollable document area, even extending outside
1086
- // of the `<html>` and `<body>` rect bounds if horizontally scrollable.
1087
- function getDocumentRect(element) {
1088
- const html = getDocumentElement(element);
1089
- const scroll = getNodeScroll(element);
1090
- const body = element.ownerDocument.body;
1091
- const width = max(html.scrollWidth, html.clientWidth, body.scrollWidth, body.clientWidth);
1092
- const height = max(html.scrollHeight, html.clientHeight, body.scrollHeight, body.clientHeight);
1093
- let x = -scroll.scrollLeft + getWindowScrollBarX(element);
1094
- const y = -scroll.scrollTop;
1095
- if (getComputedStyle(body).direction === 'rtl') {
1096
- x += max(html.clientWidth, body.clientWidth) - width;
1097
- }
1098
- return {
1099
- width,
1100
- height,
1101
- x,
1102
- y
1103
- };
1104
- }
1105
-
1106
- function getViewportRect(element, strategy) {
1107
- const win = getWindow(element);
1108
- const html = getDocumentElement(element);
1109
- const visualViewport = win.visualViewport;
1110
- let width = html.clientWidth;
1111
- let height = html.clientHeight;
1112
- let x = 0;
1113
- let y = 0;
1114
- if (visualViewport) {
1115
- width = visualViewport.width;
1116
- height = visualViewport.height;
1117
- const visualViewportBased = isWebKit();
1118
- if (!visualViewportBased || visualViewportBased && strategy === 'fixed') {
1119
- x = visualViewport.offsetLeft;
1120
- y = visualViewport.offsetTop;
1121
- }
1122
- }
1123
- return {
1124
- width,
1125
- height,
1126
- x,
1127
- y
1128
- };
1129
- }
1130
-
1131
- // Returns the inner client rect, subtracting scrollbars if present.
1132
- function getInnerBoundingClientRect(element, strategy) {
1133
- const clientRect = getBoundingClientRect(element, true, strategy === 'fixed');
1134
- const top = clientRect.top + element.clientTop;
1135
- const left = clientRect.left + element.clientLeft;
1136
- const scale = isHTMLElement(element) ? getScale(element) : createCoords(1);
1137
- const width = element.clientWidth * scale.x;
1138
- const height = element.clientHeight * scale.y;
1139
- const x = left * scale.x;
1140
- const y = top * scale.y;
1141
- return {
1142
- width,
1143
- height,
1144
- x,
1145
- y
1146
- };
1147
- }
1148
- function getClientRectFromClippingAncestor(element, clippingAncestor, strategy) {
1149
- let rect;
1150
- if (clippingAncestor === 'viewport') {
1151
- rect = getViewportRect(element, strategy);
1152
- } else if (clippingAncestor === 'document') {
1153
- rect = getDocumentRect(getDocumentElement(element));
1154
- } else if (isElement(clippingAncestor)) {
1155
- rect = getInnerBoundingClientRect(clippingAncestor, strategy);
1156
- } else {
1157
- const visualOffsets = getVisualOffsets(element);
1158
- rect = {
1159
- ...clippingAncestor,
1160
- x: clippingAncestor.x - visualOffsets.x,
1161
- y: clippingAncestor.y - visualOffsets.y
1162
- };
1163
- }
1164
- return rectToClientRect(rect);
1165
- }
1166
- function hasFixedPositionAncestor(element, stopNode) {
1167
- const parentNode = getParentNode(element);
1168
- if (parentNode === stopNode || !isElement(parentNode) || isLastTraversableNode(parentNode)) {
1169
- return false;
1170
- }
1171
- return getComputedStyle(parentNode).position === 'fixed' || hasFixedPositionAncestor(parentNode, stopNode);
1172
- }
1173
-
1174
- // A "clipping ancestor" is an `overflow` element with the characteristic of
1175
- // clipping (or hiding) child elements. This returns all clipping ancestors
1176
- // of the given element up the tree.
1177
- function getClippingElementAncestors(element, cache) {
1178
- const cachedResult = cache.get(element);
1179
- if (cachedResult) {
1180
- return cachedResult;
1181
- }
1182
- let result = getOverflowAncestors(element, [], false).filter(el => isElement(el) && getNodeName(el) !== 'body');
1183
- let currentContainingBlockComputedStyle = null;
1184
- const elementIsFixed = getComputedStyle(element).position === 'fixed';
1185
- let currentNode = elementIsFixed ? getParentNode(element) : element;
1186
-
1187
- // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block
1188
- while (isElement(currentNode) && !isLastTraversableNode(currentNode)) {
1189
- const computedStyle = getComputedStyle(currentNode);
1190
- const currentNodeIsContaining = isContainingBlock(currentNode);
1191
- if (!currentNodeIsContaining && computedStyle.position === 'fixed') {
1192
- currentContainingBlockComputedStyle = null;
1193
- }
1194
- const shouldDropCurrentNode = elementIsFixed ? !currentNodeIsContaining && !currentContainingBlockComputedStyle : !currentNodeIsContaining && computedStyle.position === 'static' && !!currentContainingBlockComputedStyle && ['absolute', 'fixed'].includes(currentContainingBlockComputedStyle.position) || isOverflowElement(currentNode) && !currentNodeIsContaining && hasFixedPositionAncestor(element, currentNode);
1195
- if (shouldDropCurrentNode) {
1196
- // Drop non-containing blocks.
1197
- result = result.filter(ancestor => ancestor !== currentNode);
1198
- } else {
1199
- // Record last containing block for next iteration.
1200
- currentContainingBlockComputedStyle = computedStyle;
1201
- }
1202
- currentNode = getParentNode(currentNode);
1203
- }
1204
- cache.set(element, result);
1205
- return result;
1206
- }
1207
-
1208
- // Gets the maximum area that the element is visible in due to any number of
1209
- // clipping ancestors.
1210
- function getClippingRect(_ref) {
1211
- let {
1212
- element,
1213
- boundary,
1214
- rootBoundary,
1215
- strategy
1216
- } = _ref;
1217
- const elementClippingAncestors = boundary === 'clippingAncestors' ? getClippingElementAncestors(element, this._c) : [].concat(boundary);
1218
- const clippingAncestors = [...elementClippingAncestors, rootBoundary];
1219
- const firstClippingAncestor = clippingAncestors[0];
1220
- const clippingRect = clippingAncestors.reduce((accRect, clippingAncestor) => {
1221
- const rect = getClientRectFromClippingAncestor(element, clippingAncestor, strategy);
1222
- accRect.top = max(rect.top, accRect.top);
1223
- accRect.right = min(rect.right, accRect.right);
1224
- accRect.bottom = min(rect.bottom, accRect.bottom);
1225
- accRect.left = max(rect.left, accRect.left);
1226
- return accRect;
1227
- }, getClientRectFromClippingAncestor(element, firstClippingAncestor, strategy));
1228
- return {
1229
- width: clippingRect.right - clippingRect.left,
1230
- height: clippingRect.bottom - clippingRect.top,
1231
- x: clippingRect.left,
1232
- y: clippingRect.top
1233
- };
1234
- }
1235
-
1236
- function getDimensions(element) {
1237
- return getCssDimensions(element);
1238
- }
1239
-
1240
- function getRectRelativeToOffsetParent(element, offsetParent, strategy) {
1241
- const isOffsetParentAnElement = isHTMLElement(offsetParent);
1242
- const documentElement = getDocumentElement(offsetParent);
1243
- const isFixed = strategy === 'fixed';
1244
- const rect = getBoundingClientRect(element, true, isFixed, offsetParent);
1245
- let scroll = {
1246
- scrollLeft: 0,
1247
- scrollTop: 0
1248
- };
1249
- const offsets = createCoords(0);
1250
- if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
1251
- if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) {
1252
- scroll = getNodeScroll(offsetParent);
1253
- }
1254
- if (isOffsetParentAnElement) {
1255
- const offsetRect = getBoundingClientRect(offsetParent, true, isFixed, offsetParent);
1256
- offsets.x = offsetRect.x + offsetParent.clientLeft;
1257
- offsets.y = offsetRect.y + offsetParent.clientTop;
1258
- } else if (documentElement) {
1259
- offsets.x = getWindowScrollBarX(documentElement);
1260
- }
1261
- }
1262
- return {
1263
- x: rect.left + scroll.scrollLeft - offsets.x,
1264
- y: rect.top + scroll.scrollTop - offsets.y,
1265
- width: rect.width,
1266
- height: rect.height
1267
- };
1268
- }
1269
-
1270
- function getTrueOffsetParent(element, polyfill) {
1271
- if (!isHTMLElement(element) || getComputedStyle(element).position === 'fixed') {
1272
- return null;
1273
- }
1274
- if (polyfill) {
1275
- return polyfill(element);
1276
- }
1277
- return element.offsetParent;
1278
- }
1279
-
1280
- // Gets the closest ancestor positioned element. Handles some edge cases,
1281
- // such as table ancestors and cross browser bugs.
1282
- function getOffsetParent(element, polyfill) {
1283
- const window = getWindow(element);
1284
- if (!isHTMLElement(element)) {
1285
- return window;
1286
- }
1287
- let offsetParent = getTrueOffsetParent(element, polyfill);
1288
- while (offsetParent && isTableElement(offsetParent) && getComputedStyle(offsetParent).position === 'static') {
1289
- offsetParent = getTrueOffsetParent(offsetParent, polyfill);
1290
- }
1291
- if (offsetParent && (getNodeName(offsetParent) === 'html' || getNodeName(offsetParent) === 'body' && getComputedStyle(offsetParent).position === 'static' && !isContainingBlock(offsetParent))) {
1292
- return window;
1293
- }
1294
- return offsetParent || getContainingBlock(element) || window;
1295
- }
1296
-
1297
- const getElementRects = async function (_ref) {
1298
- let {
1299
- reference,
1300
- floating,
1301
- strategy
1302
- } = _ref;
1303
- const getOffsetParentFn = this.getOffsetParent || getOffsetParent;
1304
- const getDimensionsFn = this.getDimensions;
1305
- return {
1306
- reference: getRectRelativeToOffsetParent(reference, await getOffsetParentFn(floating), strategy),
1307
- floating: {
1308
- x: 0,
1309
- y: 0,
1310
- ...(await getDimensionsFn(floating))
1311
- }
1312
- };
1313
- };
1314
-
1315
- function isRTL(element) {
1316
- return getComputedStyle(element).direction === 'rtl';
1317
- }
1318
-
1319
- const platform = {
1320
- convertOffsetParentRelativeRectToViewportRelativeRect,
1321
- getDocumentElement,
1322
- getClippingRect,
1323
- getOffsetParent,
1324
- getElementRects,
1325
- getClientRects,
1326
- getDimensions,
1327
- getScale,
1328
- isElement,
1329
- isRTL
1330
- };
1331
-
1332
- /**
1333
- * Computes the `x` and `y` coordinates that will place the floating element
1334
- * next to a reference element when it is given a certain CSS positioning
1335
- * strategy.
1336
- */
1337
- const computePosition = (reference, floating, options) => {
1338
- // This caches the expensive `getClippingElementAncestors` function so that
1339
- // multiple lifecycle resets re-use the same result. It only lives for a
1340
- // single call. If other functions become expensive, we can add them as well.
1341
- const cache = new Map();
1342
- const mergedOptions = {
1343
- platform,
1344
- ...options
1345
- };
1346
- const platformWithCache = {
1347
- ...mergedOptions.platform,
1348
- _c: cache
1349
- };
1350
- return computePosition$1(reference, floating, {
1351
- ...mergedOptions,
1352
- platform: platformWithCache
1353
- });
1354
- };
1355
-
1356
- /**
1357
- * Provides data to position an inner element of the floating element so that it
1358
- * appears centered to the reference element.
1359
- * This wraps the core `arrow` middleware to allow React refs as the element.
1360
- * @see https://floating-ui.com/docs/arrow
1361
- */
1362
- const arrow = options => {
1363
- function isRef(value) {
1364
- return {}.hasOwnProperty.call(value, 'current');
1365
- }
1366
- return {
1367
- name: 'arrow',
1368
- options,
1369
- fn(state) {
1370
- const {
1371
- element,
1372
- padding
1373
- } = typeof options === 'function' ? options(state) : options;
1374
- if (element && isRef(element)) {
1375
- if (element.current != null) {
1376
- return arrow$1({
1377
- element: element.current,
1378
- padding
1379
- }).fn(state);
1380
- }
1381
- return {};
1382
- } else if (element) {
1383
- return arrow$1({
1384
- element,
1385
- padding
1386
- }).fn(state);
1387
- }
1388
- return {};
1389
- }
1390
- };
1391
- };
1392
-
1393
- var index$1 = typeof document !== 'undefined' ? useLayoutEffect : useEffect;
1394
-
1395
- // Fork of `fast-deep-equal` that only does the comparisons we need and compares
1396
- // functions
1397
- function deepEqual(a, b) {
1398
- if (a === b) {
1399
- return true;
1400
- }
1401
- if (typeof a !== typeof b) {
1402
- return false;
1403
- }
1404
- if (typeof a === 'function' && a.toString() === b.toString()) {
1405
- return true;
1406
- }
1407
- let length, i, keys;
1408
- if (a && b && typeof a == 'object') {
1409
- if (Array.isArray(a)) {
1410
- length = a.length;
1411
- if (length != b.length) return false;
1412
- for (i = length; i-- !== 0;) {
1413
- if (!deepEqual(a[i], b[i])) {
1414
- return false;
1415
- }
1416
- }
1417
- return true;
1418
- }
1419
- keys = Object.keys(a);
1420
- length = keys.length;
1421
- if (length !== Object.keys(b).length) {
1422
- return false;
1423
- }
1424
- for (i = length; i-- !== 0;) {
1425
- if (!{}.hasOwnProperty.call(b, keys[i])) {
1426
- return false;
1427
- }
1428
- }
1429
- for (i = length; i-- !== 0;) {
1430
- const key = keys[i];
1431
- if (key === '_owner' && a.$$typeof) {
1432
- continue;
1433
- }
1434
- if (!deepEqual(a[key], b[key])) {
1435
- return false;
1436
- }
1437
- }
1438
- return true;
1439
- }
1440
- return a !== a && b !== b;
1441
- }
1442
-
1443
- function getDPR(element) {
1444
- if (typeof window === 'undefined') {
1445
- return 1;
1446
- }
1447
- const win = element.ownerDocument.defaultView || window;
1448
- return win.devicePixelRatio || 1;
1449
- }
1450
-
1451
- function roundByDPR(element, value) {
1452
- const dpr = getDPR(element);
1453
- return Math.round(value * dpr) / dpr;
1454
- }
1455
-
1456
- function useLatestRef$1(value) {
1457
- const ref = React$1.useRef(value);
1458
- index$1(() => {
1459
- ref.current = value;
1460
- });
1461
- return ref;
1462
- }
1463
-
1464
- /**
1465
- * Provides data to position a floating element.
1466
- * @see https://floating-ui.com/docs/useFloating
1467
- */
1468
- function useFloating$1(options) {
1469
- if (options === void 0) {
1470
- options = {};
1471
- }
1472
- const {
1473
- placement = 'bottom',
1474
- strategy = 'absolute',
1475
- middleware = [],
1476
- platform,
1477
- elements: {
1478
- reference: externalReference,
1479
- floating: externalFloating
1480
- } = {},
1481
- transform = true,
1482
- whileElementsMounted,
1483
- open
1484
- } = options;
1485
- const [data, setData] = React$1.useState({
1486
- x: 0,
1487
- y: 0,
1488
- strategy,
1489
- placement,
1490
- middlewareData: {},
1491
- isPositioned: false
1492
- });
1493
- const [latestMiddleware, setLatestMiddleware] = React$1.useState(middleware);
1494
- if (!deepEqual(latestMiddleware, middleware)) {
1495
- setLatestMiddleware(middleware);
1496
- }
1497
- const [_reference, _setReference] = React$1.useState(null);
1498
- const [_floating, _setFloating] = React$1.useState(null);
1499
- const setReference = React$1.useCallback(node => {
1500
- if (node != referenceRef.current) {
1501
- referenceRef.current = node;
1502
- _setReference(node);
1503
- }
1504
- }, [_setReference]);
1505
- const setFloating = React$1.useCallback(node => {
1506
- if (node !== floatingRef.current) {
1507
- floatingRef.current = node;
1508
- _setFloating(node);
1509
- }
1510
- }, [_setFloating]);
1511
- const referenceEl = externalReference || _reference;
1512
- const floatingEl = externalFloating || _floating;
1513
- const referenceRef = React$1.useRef(null);
1514
- const floatingRef = React$1.useRef(null);
1515
- const dataRef = React$1.useRef(data);
1516
- const whileElementsMountedRef = useLatestRef$1(whileElementsMounted);
1517
- const platformRef = useLatestRef$1(platform);
1518
- const update = React$1.useCallback(() => {
1519
- if (!referenceRef.current || !floatingRef.current) {
1520
- return;
1521
- }
1522
- const config = {
1523
- placement,
1524
- strategy,
1525
- middleware: latestMiddleware
1526
- };
1527
- if (platformRef.current) {
1528
- config.platform = platformRef.current;
1529
- }
1530
- computePosition(referenceRef.current, floatingRef.current, config).then(data => {
1531
- const fullData = {
1532
- ...data,
1533
- isPositioned: true
1534
- };
1535
- if (isMountedRef.current && !deepEqual(dataRef.current, fullData)) {
1536
- dataRef.current = fullData;
1537
- ReactDOM.flushSync(() => {
1538
- setData(fullData);
1539
- });
1540
- }
1541
- });
1542
- }, [latestMiddleware, placement, strategy, platformRef]);
1543
- index$1(() => {
1544
- if (open === false && dataRef.current.isPositioned) {
1545
- dataRef.current.isPositioned = false;
1546
- setData(data => ({
1547
- ...data,
1548
- isPositioned: false
1549
- }));
1550
- }
1551
- }, [open]);
1552
- const isMountedRef = React$1.useRef(false);
1553
- index$1(() => {
1554
- isMountedRef.current = true;
1555
- return () => {
1556
- isMountedRef.current = false;
1557
- };
1558
- }, []);
1559
- index$1(() => {
1560
- if (referenceEl) referenceRef.current = referenceEl;
1561
- if (floatingEl) floatingRef.current = floatingEl;
1562
- if (referenceEl && floatingEl) {
1563
- if (whileElementsMountedRef.current) {
1564
- return whileElementsMountedRef.current(referenceEl, floatingEl, update);
1565
- } else {
1566
- update();
1567
- }
1568
- }
1569
- }, [referenceEl, floatingEl, update, whileElementsMountedRef]);
1570
- const refs = React$1.useMemo(() => ({
1571
- reference: referenceRef,
1572
- floating: floatingRef,
1573
- setReference,
1574
- setFloating
1575
- }), [setReference, setFloating]);
1576
- const elements = React$1.useMemo(() => ({
1577
- reference: referenceEl,
1578
- floating: floatingEl
1579
- }), [referenceEl, floatingEl]);
1580
- const floatingStyles = React$1.useMemo(() => {
1581
- const initialStyles = {
1582
- position: strategy,
1583
- left: 0,
1584
- top: 0
1585
- };
1586
- if (!elements.floating) {
1587
- return initialStyles;
1588
- }
1589
- const x = roundByDPR(elements.floating, data.x);
1590
- const y = roundByDPR(elements.floating, data.y);
1591
- if (transform) {
1592
- return {
1593
- ...initialStyles,
1594
- transform: "translate(" + x + "px, " + y + "px)",
1595
- ...(getDPR(elements.floating) >= 1.5 && {
1596
- willChange: 'transform'
1597
- })
1598
- };
1599
- }
1600
- return {
1601
- position: strategy,
1602
- left: x,
1603
- top: y
1604
- };
1605
- }, [strategy, transform, elements.floating, data.x, data.y]);
1606
- return React$1.useMemo(() => ({
1607
- ...data,
1608
- update,
1609
- refs,
1610
- elements,
1611
- floatingStyles
1612
- }), [data, update, refs, elements, floatingStyles]);
1613
- }
1614
-
1615
- // `toString()` prevents bundlers from trying to `import { useInsertionEffect } from 'react'`
1616
- const useInsertionEffect = React$1[/*#__PURE__*/'useInsertionEffect'.toString()];
1617
- const useSafeInsertionEffect = useInsertionEffect || (fn => fn());
1618
- function useEffectEvent(callback) {
1619
- const ref = React$1.useRef(() => {
1620
- if (process.env.NODE_ENV !== "production") {
1621
- throw new Error('Cannot call an event handler while rendering.');
1622
- }
1623
- });
1624
- useSafeInsertionEffect(() => {
1625
- ref.current = callback;
1626
- });
1627
- return React$1.useCallback(function () {
1628
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1629
- args[_key] = arguments[_key];
1630
- }
1631
- return ref.current == null ? void 0 : ref.current(...args);
1632
- }, []);
1633
- }
1634
-
1635
- var index = typeof document !== 'undefined' ? useLayoutEffect : useEffect;
1636
-
1637
- function _extends() {
1638
- _extends = Object.assign ? Object.assign.bind() : function (target) {
1639
- for (var i = 1; i < arguments.length; i++) {
1640
- var source = arguments[i];
1641
- for (var key in source) {
1642
- if (Object.prototype.hasOwnProperty.call(source, key)) {
1643
- target[key] = source[key];
1644
- }
1645
- }
1646
- }
1647
- return target;
1648
- };
1649
- return _extends.apply(this, arguments);
1650
- }
1651
-
1652
- let serverHandoffComplete = false;
1653
- let count = 0;
1654
- const genId = () => "floating-ui-" + count++;
1655
- function useFloatingId() {
1656
- const [id, setId] = React$1.useState(() => serverHandoffComplete ? genId() : undefined);
1657
- index(() => {
1658
- if (id == null) {
1659
- setId(genId());
1660
- }
1661
- // eslint-disable-next-line react-hooks/exhaustive-deps
1662
- }, []);
1663
- React$1.useEffect(() => {
1664
- if (!serverHandoffComplete) {
1665
- serverHandoffComplete = true;
1666
- }
1667
- }, []);
1668
- return id;
1669
- }
1670
-
1671
- // `toString()` prevents bundlers from trying to `import { useId } from 'react'`
1672
- const useReactId = React$1[/*#__PURE__*/'useId'.toString()];
1673
-
1674
- /**
1675
- * Uses React 18's built-in `useId()` when available, or falls back to a
1676
- * slightly less performant (requiring a double render) implementation for
1677
- * earlier React versions.
1678
- * @see https://floating-ui.com/docs/useId
1679
- */
1680
- const useId = useReactId || useFloatingId;
1681
-
1682
- /**
1683
- * Renders a pointing arrow triangle.
1684
- * @see https://floating-ui.com/docs/FloatingArrow
1685
- */
1686
- const FloatingArrow = /*#__PURE__*/React$1.forwardRef(function FloatingArrow(_ref, ref) {
1687
- let {
1688
- context: {
1689
- placement,
1690
- elements: {
1691
- floating
1692
- },
1693
- middlewareData: {
1694
- arrow
1695
- }
1696
- },
1697
- width = 14,
1698
- height = 7,
1699
- tipRadius = 0,
1700
- strokeWidth = 0,
1701
- staticOffset,
1702
- stroke,
1703
- d,
1704
- style: {
1705
- transform,
1706
- ...restStyle
1707
- } = {},
1708
- ...rest
1709
- } = _ref;
1710
- if (process.env.NODE_ENV !== "production") {
1711
- if (!ref) {
1712
- console.warn('Floating UI: The `ref` prop is required for the `FloatingArrow`', 'component.');
1713
- }
1714
- }
1715
- const clipPathId = useId();
1716
- if (!floating) {
1717
- return null;
1718
- }
1719
-
1720
- // Strokes must be double the border width, this ensures the stroke's width
1721
- // works as you'd expect.
1722
- strokeWidth *= 2;
1723
- const halfStrokeWidth = strokeWidth / 2;
1724
- const svgX = width / 2 * (tipRadius / -8 + 1);
1725
- const svgY = height / 2 * tipRadius / 4;
1726
- const [side, alignment] = placement.split('-');
1727
- const isRTL = platform.isRTL(floating);
1728
- const isCustomShape = !!d;
1729
- const isVerticalSide = side === 'top' || side === 'bottom';
1730
- const yOffsetProp = staticOffset && alignment === 'end' ? 'bottom' : 'top';
1731
- let xOffsetProp = staticOffset && alignment === 'end' ? 'right' : 'left';
1732
- if (staticOffset && isRTL) {
1733
- xOffsetProp = alignment === 'end' ? 'left' : 'right';
1734
- }
1735
- const arrowX = (arrow == null ? void 0 : arrow.x) != null ? staticOffset || arrow.x : '';
1736
- const arrowY = (arrow == null ? void 0 : arrow.y) != null ? staticOffset || arrow.y : '';
1737
- const dValue = d || 'M0,0' + (" H" + width) + (" L" + (width - svgX) + "," + (height - svgY)) + (" Q" + width / 2 + "," + height + " " + svgX + "," + (height - svgY)) + ' Z';
1738
- const rotation = {
1739
- top: isCustomShape ? 'rotate(180deg)' : '',
1740
- left: isCustomShape ? 'rotate(90deg)' : 'rotate(-90deg)',
1741
- bottom: isCustomShape ? '' : 'rotate(180deg)',
1742
- right: isCustomShape ? 'rotate(-90deg)' : 'rotate(90deg)'
1743
- }[side];
1744
- return /*#__PURE__*/React$1.createElement("svg", _extends({}, rest, {
1745
- "aria-hidden": true,
1746
- ref: ref,
1747
- width: isCustomShape ? width : width + strokeWidth,
1748
- height: width,
1749
- viewBox: "0 0 " + width + " " + (height > width ? height : width),
1750
- style: {
1751
- position: 'absolute',
1752
- pointerEvents: 'none',
1753
- [xOffsetProp]: arrowX,
1754
- [yOffsetProp]: arrowY,
1755
- [side]: isVerticalSide || isCustomShape ? '100%' : "calc(100% - " + strokeWidth / 2 + "px)",
1756
- transform: "" + rotation + (transform != null ? transform : ''),
1757
- ...restStyle
1758
- }
1759
- }), strokeWidth > 0 && /*#__PURE__*/React$1.createElement("path", {
1760
- clipPath: "url(#" + clipPathId + ")",
1761
- fill: "none",
1762
- stroke: stroke
1763
- // Account for the stroke on the fill path rendered below.
1764
- ,
1765
- strokeWidth: strokeWidth + (d ? 0 : 1),
1766
- d: dValue
1767
- }), /*#__PURE__*/React$1.createElement("path", {
1768
- stroke: strokeWidth && !d ? rest.fill : 'none',
1769
- d: dValue
1770
- }), /*#__PURE__*/React$1.createElement("clipPath", {
1771
- id: clipPathId
1772
- }, /*#__PURE__*/React$1.createElement("rect", {
1773
- x: -halfStrokeWidth,
1774
- y: halfStrokeWidth * (isCustomShape ? -1 : 1),
1775
- width: width + strokeWidth,
1776
- height: width
1777
- })));
1778
- });
1779
-
1780
- function createPubSub() {
1781
- const map = new Map();
1782
- return {
1783
- emit(event, data) {
1784
- var _map$get;
1785
- (_map$get = map.get(event)) == null || _map$get.forEach(handler => handler(data));
1786
- },
1787
- on(event, listener) {
1788
- map.set(event, [...(map.get(event) || []), listener]);
1789
- },
1790
- off(event, listener) {
1791
- var _map$get2;
1792
- map.set(event, ((_map$get2 = map.get(event)) == null ? void 0 : _map$get2.filter(l => l !== listener)) || []);
1793
- }
1794
- };
1795
- }
1796
-
1797
- const FloatingNodeContext = /*#__PURE__*/React$1.createContext(null);
1798
- const FloatingTreeContext = /*#__PURE__*/React$1.createContext(null);
1799
- const useFloatingParentNodeId = () => {
1800
- var _React$useContext;
1801
- return ((_React$useContext = React$1.useContext(FloatingNodeContext)) == null ? void 0 : _React$useContext.id) || null;
1802
- };
1803
- const useFloatingTree = () => React$1.useContext(FloatingTreeContext);
1804
-
1805
- function createAttribute(name) {
1806
- return "data-floating-ui-" + name;
1807
- }
1808
-
1809
- function useLatestRef(value) {
1810
- const ref = useRef(value);
1811
- index(() => {
1812
- ref.current = value;
1813
- });
1814
- return ref;
1815
- }
1816
-
1817
- const safePolygonIdentifier = /*#__PURE__*/createAttribute('safe-polygon');
1818
- function getDelay(value, prop, pointerType) {
1819
- if (pointerType && !isMouseLikePointerType(pointerType)) {
1820
- return 0;
1821
- }
1822
- if (typeof value === 'number') {
1823
- return value;
1824
- }
1825
- return value == null ? void 0 : value[prop];
1826
- }
1827
- /**
1828
- * Opens the floating element while hovering over the reference element, like
1829
- * CSS `:hover`.
1830
- * @see https://floating-ui.com/docs/useHover
1831
- */
1832
- function useHover(context, props) {
1833
- if (props === void 0) {
1834
- props = {};
1835
- }
1836
- const {
1837
- open,
1838
- onOpenChange,
1839
- dataRef,
1840
- events,
1841
- elements: {
1842
- domReference,
1843
- floating
1844
- },
1845
- refs
1846
- } = context;
1847
- const {
1848
- enabled = true,
1849
- delay = 0,
1850
- handleClose = null,
1851
- mouseOnly = false,
1852
- restMs = 0,
1853
- move = true
1854
- } = props;
1855
- const tree = useFloatingTree();
1856
- const parentId = useFloatingParentNodeId();
1857
- const handleCloseRef = useLatestRef(handleClose);
1858
- const delayRef = useLatestRef(delay);
1859
- const pointerTypeRef = React$1.useRef();
1860
- const timeoutRef = React$1.useRef();
1861
- const handlerRef = React$1.useRef();
1862
- const restTimeoutRef = React$1.useRef();
1863
- const blockMouseMoveRef = React$1.useRef(true);
1864
- const performedPointerEventsMutationRef = React$1.useRef(false);
1865
- const unbindMouseMoveRef = React$1.useRef(() => {});
1866
- const isHoverOpen = React$1.useCallback(() => {
1867
- var _dataRef$current$open;
1868
- const type = (_dataRef$current$open = dataRef.current.openEvent) == null ? void 0 : _dataRef$current$open.type;
1869
- return (type == null ? void 0 : type.includes('mouse')) && type !== 'mousedown';
1870
- }, [dataRef]);
1871
-
1872
- // When closing before opening, clear the delay timeouts to cancel it
1873
- // from showing.
1874
- React$1.useEffect(() => {
1875
- if (!enabled) {
1876
- return;
1877
- }
1878
- function onOpenChange(_ref) {
1879
- let {
1880
- open
1881
- } = _ref;
1882
- if (!open) {
1883
- clearTimeout(timeoutRef.current);
1884
- clearTimeout(restTimeoutRef.current);
1885
- blockMouseMoveRef.current = true;
1886
- }
1887
- }
1888
- events.on('openchange', onOpenChange);
1889
- return () => {
1890
- events.off('openchange', onOpenChange);
1891
- };
1892
- }, [enabled, events]);
1893
- React$1.useEffect(() => {
1894
- if (!enabled || !handleCloseRef.current || !open) {
1895
- return;
1896
- }
1897
- function onLeave(event) {
1898
- if (isHoverOpen()) {
1899
- onOpenChange(false, event, 'hover');
1900
- }
1901
- }
1902
- const html = getDocument(floating).documentElement;
1903
- html.addEventListener('mouseleave', onLeave);
1904
- return () => {
1905
- html.removeEventListener('mouseleave', onLeave);
1906
- };
1907
- }, [floating, open, onOpenChange, enabled, handleCloseRef, dataRef, isHoverOpen]);
1908
- const closeWithDelay = React$1.useCallback(function (event, runElseBranch, reason) {
1909
- if (runElseBranch === void 0) {
1910
- runElseBranch = true;
1911
- }
1912
- if (reason === void 0) {
1913
- reason = 'hover';
1914
- }
1915
- const closeDelay = getDelay(delayRef.current, 'close', pointerTypeRef.current);
1916
- if (closeDelay && !handlerRef.current) {
1917
- clearTimeout(timeoutRef.current);
1918
- timeoutRef.current = setTimeout(() => onOpenChange(false, event, reason), closeDelay);
1919
- } else if (runElseBranch) {
1920
- clearTimeout(timeoutRef.current);
1921
- onOpenChange(false, event, reason);
1922
- }
1923
- }, [delayRef, onOpenChange]);
1924
- const cleanupMouseMoveHandler = React$1.useCallback(() => {
1925
- unbindMouseMoveRef.current();
1926
- handlerRef.current = undefined;
1927
- }, []);
1928
- const clearPointerEvents = React$1.useCallback(() => {
1929
- if (performedPointerEventsMutationRef.current) {
1930
- const body = getDocument(refs.floating.current).body;
1931
- body.style.pointerEvents = '';
1932
- body.removeAttribute(safePolygonIdentifier);
1933
- performedPointerEventsMutationRef.current = false;
1934
- }
1935
- }, [refs]);
1936
-
1937
- // Registering the mouse events on the reference directly to bypass React's
1938
- // delegation system. If the cursor was on a disabled element and then entered
1939
- // the reference (no gap), `mouseenter` doesn't fire in the delegation system.
1940
- React$1.useEffect(() => {
1941
- if (!enabled) {
1942
- return;
1943
- }
1944
- function isClickLikeOpenEvent() {
1945
- return dataRef.current.openEvent ? ['click', 'mousedown'].includes(dataRef.current.openEvent.type) : false;
1946
- }
1947
- function onMouseEnter(event) {
1948
- clearTimeout(timeoutRef.current);
1949
- blockMouseMoveRef.current = false;
1950
- if (mouseOnly && !isMouseLikePointerType(pointerTypeRef.current) || restMs > 0 && getDelay(delayRef.current, 'open') === 0) {
1951
- return;
1952
- }
1953
- const openDelay = getDelay(delayRef.current, 'open', pointerTypeRef.current);
1954
- if (openDelay) {
1955
- timeoutRef.current = setTimeout(() => {
1956
- onOpenChange(true, event, 'hover');
1957
- }, openDelay);
1958
- } else {
1959
- onOpenChange(true, event, 'hover');
1960
- }
1961
- }
1962
- function onMouseLeave(event) {
1963
- if (isClickLikeOpenEvent()) {
1964
- return;
1965
- }
1966
- unbindMouseMoveRef.current();
1967
- const doc = getDocument(floating);
1968
- clearTimeout(restTimeoutRef.current);
1969
- if (handleCloseRef.current) {
1970
- // Prevent clearing `onScrollMouseLeave` timeout.
1971
- if (!open) {
1972
- clearTimeout(timeoutRef.current);
1973
- }
1974
- handlerRef.current = handleCloseRef.current({
1975
- ...context,
1976
- tree,
1977
- x: event.clientX,
1978
- y: event.clientY,
1979
- onClose() {
1980
- clearPointerEvents();
1981
- cleanupMouseMoveHandler();
1982
- closeWithDelay(event, true, 'safe-polygon');
1983
- }
1984
- });
1985
- const handler = handlerRef.current;
1986
- doc.addEventListener('mousemove', handler);
1987
- unbindMouseMoveRef.current = () => {
1988
- doc.removeEventListener('mousemove', handler);
1989
- };
1990
- return;
1991
- }
1992
-
1993
- // Allow interactivity without `safePolygon` on touch devices. With a
1994
- // pointer, a short close delay is an alternative, so it should work
1995
- // consistently.
1996
- const shouldClose = pointerTypeRef.current === 'touch' ? !contains(floating, event.relatedTarget) : true;
1997
- if (shouldClose) {
1998
- closeWithDelay(event);
1999
- }
2000
- }
2001
-
2002
- // Ensure the floating element closes after scrolling even if the pointer
2003
- // did not move.
2004
- // https://github.com/floating-ui/floating-ui/discussions/1692
2005
- function onScrollMouseLeave(event) {
2006
- if (isClickLikeOpenEvent()) {
2007
- return;
2008
- }
2009
- handleCloseRef.current == null || handleCloseRef.current({
2010
- ...context,
2011
- tree,
2012
- x: event.clientX,
2013
- y: event.clientY,
2014
- onClose() {
2015
- clearPointerEvents();
2016
- cleanupMouseMoveHandler();
2017
- closeWithDelay(event);
2018
- }
2019
- })(event);
2020
- }
2021
- if (isElement(domReference)) {
2022
- const ref = domReference;
2023
- open && ref.addEventListener('mouseleave', onScrollMouseLeave);
2024
- floating == null || floating.addEventListener('mouseleave', onScrollMouseLeave);
2025
- move && ref.addEventListener('mousemove', onMouseEnter, {
2026
- once: true
2027
- });
2028
- ref.addEventListener('mouseenter', onMouseEnter);
2029
- ref.addEventListener('mouseleave', onMouseLeave);
2030
- return () => {
2031
- open && ref.removeEventListener('mouseleave', onScrollMouseLeave);
2032
- floating == null || floating.removeEventListener('mouseleave', onScrollMouseLeave);
2033
- move && ref.removeEventListener('mousemove', onMouseEnter);
2034
- ref.removeEventListener('mouseenter', onMouseEnter);
2035
- ref.removeEventListener('mouseleave', onMouseLeave);
2036
- };
2037
- }
2038
- }, [domReference, floating, enabled, context, mouseOnly, restMs, move, closeWithDelay, cleanupMouseMoveHandler, clearPointerEvents, onOpenChange, open, tree, delayRef, handleCloseRef, dataRef]);
2039
-
2040
- // Block pointer-events of every element other than the reference and floating
2041
- // while the floating element is open and has a `handleClose` handler. Also
2042
- // handles nested floating elements.
2043
- // https://github.com/floating-ui/floating-ui/issues/1722
2044
- index(() => {
2045
- var _handleCloseRef$curre;
2046
- if (!enabled) {
2047
- return;
2048
- }
2049
- if (open && (_handleCloseRef$curre = handleCloseRef.current) != null && _handleCloseRef$curre.__options.blockPointerEvents && isHoverOpen()) {
2050
- const body = getDocument(floating).body;
2051
- body.setAttribute(safePolygonIdentifier, '');
2052
- body.style.pointerEvents = 'none';
2053
- performedPointerEventsMutationRef.current = true;
2054
- if (isElement(domReference) && floating) {
2055
- var _tree$nodesRef$curren;
2056
- const ref = domReference;
2057
- 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;
2058
- if (parentFloating) {
2059
- parentFloating.style.pointerEvents = '';
2060
- }
2061
- ref.style.pointerEvents = 'auto';
2062
- floating.style.pointerEvents = 'auto';
2063
- return () => {
2064
- ref.style.pointerEvents = '';
2065
- floating.style.pointerEvents = '';
2066
- };
2067
- }
2068
- }
2069
- }, [enabled, open, parentId, floating, domReference, tree, handleCloseRef, dataRef, isHoverOpen]);
2070
- index(() => {
2071
- if (!open) {
2072
- pointerTypeRef.current = undefined;
2073
- cleanupMouseMoveHandler();
2074
- clearPointerEvents();
2075
- }
2076
- }, [open, cleanupMouseMoveHandler, clearPointerEvents]);
2077
- React$1.useEffect(() => {
2078
- return () => {
2079
- cleanupMouseMoveHandler();
2080
- clearTimeout(timeoutRef.current);
2081
- clearTimeout(restTimeoutRef.current);
2082
- clearPointerEvents();
2083
- };
2084
- }, [enabled, domReference, cleanupMouseMoveHandler, clearPointerEvents]);
2085
- return React$1.useMemo(() => {
2086
- if (!enabled) {
2087
- return {};
2088
- }
2089
- function setPointerRef(event) {
2090
- pointerTypeRef.current = event.pointerType;
2091
- }
2092
- return {
2093
- reference: {
2094
- onPointerDown: setPointerRef,
2095
- onPointerEnter: setPointerRef,
2096
- onMouseMove(event) {
2097
- if (open || restMs === 0) {
2098
- return;
2099
- }
2100
- clearTimeout(restTimeoutRef.current);
2101
- restTimeoutRef.current = setTimeout(() => {
2102
- if (!blockMouseMoveRef.current) {
2103
- onOpenChange(true, event.nativeEvent, 'hover');
2104
- }
2105
- }, restMs);
2106
- }
2107
- },
2108
- floating: {
2109
- onMouseEnter() {
2110
- clearTimeout(timeoutRef.current);
2111
- },
2112
- onMouseLeave(event) {
2113
- closeWithDelay(event.nativeEvent, false);
2114
- }
2115
- }
2116
- };
2117
- }, [enabled, restMs, open, onOpenChange, closeWithDelay]);
2118
- }
2119
-
2120
- function getChildren(nodes, id) {
2121
- let allChildren = nodes.filter(node => {
2122
- var _node$context;
2123
- return node.parentId === id && ((_node$context = node.context) == null ? void 0 : _node$context.open);
2124
- });
2125
- let currentChildren = allChildren;
2126
- while (currentChildren.length) {
2127
- currentChildren = nodes.filter(node => {
2128
- var _currentChildren;
2129
- return (_currentChildren = currentChildren) == null ? void 0 : _currentChildren.some(n => {
2130
- var _node$context2;
2131
- return node.parentId === n.id && ((_node$context2 = node.context) == null ? void 0 : _node$context2.open);
2132
- });
2133
- });
2134
- allChildren = allChildren.concat(currentChildren);
2135
- }
2136
- return allChildren;
2137
- }
2138
-
2139
- const bubbleHandlerKeys = {
2140
- pointerdown: 'onPointerDown',
2141
- mousedown: 'onMouseDown',
2142
- click: 'onClick'
2143
- };
2144
- const captureHandlerKeys = {
2145
- pointerdown: 'onPointerDownCapture',
2146
- mousedown: 'onMouseDownCapture',
2147
- click: 'onClickCapture'
2148
- };
2149
- const normalizeProp = normalizable => {
2150
- var _normalizable$escapeK, _normalizable$outside;
2151
- return {
2152
- escapeKey: typeof normalizable === 'boolean' ? normalizable : (_normalizable$escapeK = normalizable == null ? void 0 : normalizable.escapeKey) != null ? _normalizable$escapeK : false,
2153
- outsidePress: typeof normalizable === 'boolean' ? normalizable : (_normalizable$outside = normalizable == null ? void 0 : normalizable.outsidePress) != null ? _normalizable$outside : true
2154
- };
2155
- };
2156
- /**
2157
- * Closes the floating element when a dismissal is requested — by default, when
2158
- * the user presses the `escape` key or outside of the floating element.
2159
- * @see https://floating-ui.com/docs/useDismiss
2160
- */
2161
- function useDismiss(context, props) {
2162
- if (props === void 0) {
2163
- props = {};
2164
- }
2165
- const {
2166
- open,
2167
- onOpenChange,
2168
- nodeId,
2169
- elements: {
2170
- reference,
2171
- domReference,
2172
- floating
2173
- },
2174
- dataRef
2175
- } = context;
2176
- const {
2177
- enabled = true,
2178
- escapeKey = true,
2179
- outsidePress: unstable_outsidePress = true,
2180
- outsidePressEvent = 'pointerdown',
2181
- referencePress = false,
2182
- referencePressEvent = 'pointerdown',
2183
- ancestorScroll = false,
2184
- bubbles,
2185
- capture
2186
- } = props;
2187
- const tree = useFloatingTree();
2188
- const outsidePressFn = useEffectEvent(typeof unstable_outsidePress === 'function' ? unstable_outsidePress : () => false);
2189
- const outsidePress = typeof unstable_outsidePress === 'function' ? outsidePressFn : unstable_outsidePress;
2190
- const insideReactTreeRef = React$1.useRef(false);
2191
- const endedOrStartedInsideRef = React$1.useRef(false);
2192
- const {
2193
- escapeKey: escapeKeyBubbles,
2194
- outsidePress: outsidePressBubbles
2195
- } = normalizeProp(bubbles);
2196
- const {
2197
- escapeKey: escapeKeyCapture,
2198
- outsidePress: outsidePressCapture
2199
- } = normalizeProp(capture);
2200
- const closeOnEscapeKeyDown = useEffectEvent(event => {
2201
- if (!open || !enabled || !escapeKey || event.key !== 'Escape') {
2202
- return;
2203
- }
2204
- const children = tree ? getChildren(tree.nodesRef.current, nodeId) : [];
2205
- if (!escapeKeyBubbles) {
2206
- event.stopPropagation();
2207
- if (children.length > 0) {
2208
- let shouldDismiss = true;
2209
- children.forEach(child => {
2210
- var _child$context;
2211
- if ((_child$context = child.context) != null && _child$context.open && !child.context.dataRef.current.__escapeKeyBubbles) {
2212
- shouldDismiss = false;
2213
- return;
2214
- }
2215
- });
2216
- if (!shouldDismiss) {
2217
- return;
2218
- }
2219
- }
2220
- }
2221
- onOpenChange(false, isReactEvent(event) ? event.nativeEvent : event, 'escape-key');
2222
- });
2223
- const closeOnEscapeKeyDownCapture = useEffectEvent(event => {
2224
- var _getTarget2;
2225
- const callback = () => {
2226
- var _getTarget;
2227
- closeOnEscapeKeyDown(event);
2228
- (_getTarget = getTarget(event)) == null || _getTarget.removeEventListener('keydown', callback);
2229
- };
2230
- (_getTarget2 = getTarget(event)) == null || _getTarget2.addEventListener('keydown', callback);
2231
- });
2232
- const closeOnPressOutside = useEffectEvent(event => {
2233
- // Given developers can stop the propagation of the synthetic event,
2234
- // we can only be confident with a positive value.
2235
- const insideReactTree = insideReactTreeRef.current;
2236
- insideReactTreeRef.current = false;
2237
-
2238
- // When click outside is lazy (`click` event), handle dragging.
2239
- // Don't close if:
2240
- // - The click started inside the floating element.
2241
- // - The click ended inside the floating element.
2242
- const endedOrStartedInside = endedOrStartedInsideRef.current;
2243
- endedOrStartedInsideRef.current = false;
2244
- if (outsidePressEvent === 'click' && endedOrStartedInside) {
2245
- return;
2246
- }
2247
- if (insideReactTree) {
2248
- return;
2249
- }
2250
- if (typeof outsidePress === 'function' && !outsidePress(event)) {
2251
- return;
2252
- }
2253
- const target = getTarget(event);
2254
- const inertSelector = "[" + createAttribute('inert') + "]";
2255
- const markers = getDocument(floating).querySelectorAll(inertSelector);
2256
- let targetRootAncestor = isElement(target) ? target : null;
2257
- while (targetRootAncestor && !isLastTraversableNode(targetRootAncestor)) {
2258
- const nextParent = getParentNode(targetRootAncestor);
2259
- if (isLastTraversableNode(nextParent) || !isElement(nextParent)) {
2260
- break;
2261
- } else {
2262
- targetRootAncestor = nextParent;
2263
- }
2264
- }
2265
-
2266
- // Check if the click occurred on a third-party element injected after the
2267
- // floating element rendered.
2268
- if (markers.length && isElement(target) && !isRootElement(target) &&
2269
- // Clicked on a direct ancestor (e.g. FloatingOverlay).
2270
- !contains(target, floating) &&
2271
- // If the target root element contains none of the markers, then the
2272
- // element was injected after the floating element rendered.
2273
- Array.from(markers).every(marker => !contains(targetRootAncestor, marker))) {
2274
- return;
2275
- }
2276
-
2277
- // Check if the click occurred on the scrollbar
2278
- if (isHTMLElement(target) && floating) {
2279
- // In Firefox, `target.scrollWidth > target.clientWidth` for inline
2280
- // elements.
2281
- const canScrollX = target.clientWidth > 0 && target.scrollWidth > target.clientWidth;
2282
- const canScrollY = target.clientHeight > 0 && target.scrollHeight > target.clientHeight;
2283
- let xCond = canScrollY && event.offsetX > target.clientWidth;
2284
-
2285
- // In some browsers it is possible to change the <body> (or window)
2286
- // scrollbar to the left side, but is very rare and is difficult to
2287
- // check for. Plus, for modal dialogs with backdrops, it is more
2288
- // important that the backdrop is checked but not so much the window.
2289
- if (canScrollY) {
2290
- const isRTL = getComputedStyle(target).direction === 'rtl';
2291
- if (isRTL) {
2292
- xCond = event.offsetX <= target.offsetWidth - target.clientWidth;
2293
- }
2294
- }
2295
- if (xCond || canScrollX && event.offsetY > target.clientHeight) {
2296
- return;
2297
- }
2298
- }
2299
- const targetIsInsideChildren = tree && getChildren(tree.nodesRef.current, nodeId).some(node => {
2300
- var _node$context;
2301
- return isEventTargetWithin(event, (_node$context = node.context) == null ? void 0 : _node$context.elements.floating);
2302
- });
2303
- if (isEventTargetWithin(event, floating) || isEventTargetWithin(event, domReference) || targetIsInsideChildren) {
2304
- return;
2305
- }
2306
- const children = tree ? getChildren(tree.nodesRef.current, nodeId) : [];
2307
- if (children.length > 0) {
2308
- let shouldDismiss = true;
2309
- children.forEach(child => {
2310
- var _child$context2;
2311
- if ((_child$context2 = child.context) != null && _child$context2.open && !child.context.dataRef.current.__outsidePressBubbles) {
2312
- shouldDismiss = false;
2313
- return;
2314
- }
2315
- });
2316
- if (!shouldDismiss) {
2317
- return;
2318
- }
2319
- }
2320
- onOpenChange(false, event, 'outside-press');
2321
- });
2322
- const closeOnPressOutsideCapture = useEffectEvent(event => {
2323
- var _getTarget4;
2324
- const callback = () => {
2325
- var _getTarget3;
2326
- closeOnPressOutside(event);
2327
- (_getTarget3 = getTarget(event)) == null || _getTarget3.removeEventListener(outsidePressEvent, callback);
2328
- };
2329
- (_getTarget4 = getTarget(event)) == null || _getTarget4.addEventListener(outsidePressEvent, callback);
2330
- });
2331
- React$1.useEffect(() => {
2332
- if (!open || !enabled) {
2333
- return;
2334
- }
2335
- dataRef.current.__escapeKeyBubbles = escapeKeyBubbles;
2336
- dataRef.current.__outsidePressBubbles = outsidePressBubbles;
2337
- function onScroll(event) {
2338
- onOpenChange(false, event, 'ancestor-scroll');
2339
- }
2340
- const doc = getDocument(floating);
2341
- escapeKey && doc.addEventListener('keydown', escapeKeyCapture ? closeOnEscapeKeyDownCapture : closeOnEscapeKeyDown, escapeKeyCapture);
2342
- outsidePress && doc.addEventListener(outsidePressEvent, outsidePressCapture ? closeOnPressOutsideCapture : closeOnPressOutside, outsidePressCapture);
2343
- let ancestors = [];
2344
- if (ancestorScroll) {
2345
- if (isElement(domReference)) {
2346
- ancestors = getOverflowAncestors(domReference);
2347
- }
2348
- if (isElement(floating)) {
2349
- ancestors = ancestors.concat(getOverflowAncestors(floating));
2350
- }
2351
- if (!isElement(reference) && reference && reference.contextElement) {
2352
- ancestors = ancestors.concat(getOverflowAncestors(reference.contextElement));
2353
- }
2354
- }
2355
-
2356
- // Ignore the visual viewport for scrolling dismissal (allow pinch-zoom)
2357
- ancestors = ancestors.filter(ancestor => {
2358
- var _doc$defaultView;
2359
- return ancestor !== ((_doc$defaultView = doc.defaultView) == null ? void 0 : _doc$defaultView.visualViewport);
2360
- });
2361
- ancestors.forEach(ancestor => {
2362
- ancestor.addEventListener('scroll', onScroll, {
2363
- passive: true
2364
- });
2365
- });
2366
- return () => {
2367
- escapeKey && doc.removeEventListener('keydown', escapeKeyCapture ? closeOnEscapeKeyDownCapture : closeOnEscapeKeyDown, escapeKeyCapture);
2368
- outsidePress && doc.removeEventListener(outsidePressEvent, outsidePressCapture ? closeOnPressOutsideCapture : closeOnPressOutside, outsidePressCapture);
2369
- ancestors.forEach(ancestor => {
2370
- ancestor.removeEventListener('scroll', onScroll);
2371
- });
2372
- };
2373
- }, [dataRef, floating, domReference, reference, escapeKey, outsidePress, outsidePressEvent, open, onOpenChange, ancestorScroll, enabled, escapeKeyBubbles, outsidePressBubbles, closeOnEscapeKeyDown, escapeKeyCapture, closeOnEscapeKeyDownCapture, closeOnPressOutside, outsidePressCapture, closeOnPressOutsideCapture]);
2374
- React$1.useEffect(() => {
2375
- insideReactTreeRef.current = false;
2376
- }, [outsidePress, outsidePressEvent]);
2377
- return React$1.useMemo(() => {
2378
- if (!enabled) {
2379
- return {};
2380
- }
2381
- return {
2382
- reference: {
2383
- onKeyDown: closeOnEscapeKeyDown,
2384
- [bubbleHandlerKeys[referencePressEvent]]: event => {
2385
- if (referencePress) {
2386
- onOpenChange(false, event.nativeEvent, 'reference-press');
2387
- }
2388
- }
2389
- },
2390
- floating: {
2391
- onKeyDown: closeOnEscapeKeyDown,
2392
- onMouseDown() {
2393
- endedOrStartedInsideRef.current = true;
2394
- },
2395
- onMouseUp() {
2396
- endedOrStartedInsideRef.current = true;
2397
- },
2398
- [captureHandlerKeys[outsidePressEvent]]: () => {
2399
- insideReactTreeRef.current = true;
2400
- }
2401
- }
2402
- };
2403
- }, [enabled, referencePress, outsidePressEvent, referencePressEvent, onOpenChange, closeOnEscapeKeyDown]);
2404
- }
2405
-
2406
- let devMessageSet;
2407
- if (process.env.NODE_ENV !== "production") {
2408
- devMessageSet = /*#__PURE__*/new Set();
2409
- }
2410
-
2411
- /**
2412
- * Provides data to position a floating element and context to add interactions.
2413
- * @see https://floating-ui.com/docs/useFloating
2414
- */
2415
- function useFloating(options) {
2416
- var _options$elements2;
2417
- if (options === void 0) {
2418
- options = {};
2419
- }
2420
- const {
2421
- open = false,
2422
- onOpenChange: unstable_onOpenChange,
2423
- nodeId
2424
- } = options;
2425
- if (process.env.NODE_ENV !== "production") {
2426
- var _options$elements;
2427
- const err = 'Floating UI: Cannot pass a virtual element to the ' + '`elements.reference` option, as it must be a real DOM element. ' + 'Use `refs.setPositionReference` instead.';
2428
- if ((_options$elements = options.elements) != null && _options$elements.reference && !isElement(options.elements.reference)) {
2429
- var _devMessageSet;
2430
- if (!((_devMessageSet = devMessageSet) != null && _devMessageSet.has(err))) {
2431
- var _devMessageSet2;
2432
- (_devMessageSet2 = devMessageSet) == null || _devMessageSet2.add(err);
2433
- console.error(err);
2434
- }
2435
- }
2436
- }
2437
- const [_domReference, setDomReference] = React$1.useState(null);
2438
- const domReference = ((_options$elements2 = options.elements) == null ? void 0 : _options$elements2.reference) || _domReference;
2439
- const position = useFloating$1(options);
2440
- const tree = useFloatingTree();
2441
- const nested = useFloatingParentNodeId() != null;
2442
- const onOpenChange = useEffectEvent((open, event, reason) => {
2443
- if (open) {
2444
- dataRef.current.openEvent = event;
2445
- }
2446
- events.emit('openchange', {
2447
- open,
2448
- event,
2449
- reason,
2450
- nested
2451
- });
2452
- unstable_onOpenChange == null || unstable_onOpenChange(open, event, reason);
2453
- });
2454
- const domReferenceRef = React$1.useRef(null);
2455
- const dataRef = React$1.useRef({});
2456
- const events = React$1.useState(() => createPubSub())[0];
2457
- const floatingId = useId();
2458
- const setPositionReference = React$1.useCallback(node => {
2459
- const positionReference = isElement(node) ? {
2460
- getBoundingClientRect: () => node.getBoundingClientRect(),
2461
- contextElement: node
2462
- } : node;
2463
- position.refs.setReference(positionReference);
2464
- }, [position.refs]);
2465
- const setReference = React$1.useCallback(node => {
2466
- if (isElement(node) || node === null) {
2467
- domReferenceRef.current = node;
2468
- setDomReference(node);
2469
- }
2470
-
2471
- // Backwards-compatibility for passing a virtual element to `reference`
2472
- // after it has set the DOM reference.
2473
- if (isElement(position.refs.reference.current) || position.refs.reference.current === null ||
2474
- // Don't allow setting virtual elements using the old technique back to
2475
- // `null` to support `positionReference` + an unstable `reference`
2476
- // callback ref.
2477
- node !== null && !isElement(node)) {
2478
- position.refs.setReference(node);
2479
- }
2480
- }, [position.refs]);
2481
- const refs = React$1.useMemo(() => ({
2482
- ...position.refs,
2483
- setReference,
2484
- setPositionReference,
2485
- domReference: domReferenceRef
2486
- }), [position.refs, setReference, setPositionReference]);
2487
- const elements = React$1.useMemo(() => ({
2488
- ...position.elements,
2489
- domReference: domReference
2490
- }), [position.elements, domReference]);
2491
- const context = React$1.useMemo(() => ({
2492
- ...position,
2493
- refs,
2494
- elements,
2495
- dataRef,
2496
- nodeId,
2497
- floatingId,
2498
- events,
2499
- open,
2500
- onOpenChange
2501
- }), [position, nodeId, floatingId, events, open, onOpenChange, refs, elements]);
2502
- index(() => {
2503
- const node = tree == null ? void 0 : tree.nodesRef.current.find(node => node.id === nodeId);
2504
- if (node) {
2505
- node.context = context;
2506
- }
2507
- });
2508
- return React$1.useMemo(() => ({
2509
- ...position,
2510
- context,
2511
- refs,
2512
- elements
2513
- }), [position, refs, elements, context]);
2514
- }
2515
-
2516
- const ACTIVE_KEY = 'active';
2517
- const SELECTED_KEY = 'selected';
2518
- function mergeProps(userProps, propsList, elementKey) {
2519
- const map = new Map();
2520
- const isItem = elementKey === 'item';
2521
- let domUserProps = userProps;
2522
- if (isItem && userProps) {
2523
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
2524
- const {
2525
- [ACTIVE_KEY]: _,
2526
- [SELECTED_KEY]: __,
2527
- ...validProps
2528
- } = userProps;
2529
- domUserProps = validProps;
2530
- }
2531
- return {
2532
- ...(elementKey === 'floating' && {
2533
- tabIndex: -1
2534
- }),
2535
- ...domUserProps,
2536
- ...propsList.map(value => {
2537
- const propsOrGetProps = value ? value[elementKey] : null;
2538
- if (typeof propsOrGetProps === 'function') {
2539
- return userProps ? propsOrGetProps(userProps) : null;
2540
- }
2541
- return propsOrGetProps;
2542
- }).concat(userProps).reduce((acc, props) => {
2543
- if (!props) {
2544
- return acc;
2545
- }
2546
- Object.entries(props).forEach(_ref => {
2547
- let [key, value] = _ref;
2548
- if (isItem && [ACTIVE_KEY, SELECTED_KEY].includes(key)) {
2549
- return;
2550
- }
2551
- if (key.indexOf('on') === 0) {
2552
- if (!map.has(key)) {
2553
- map.set(key, []);
2554
- }
2555
- if (typeof value === 'function') {
2556
- var _map$get;
2557
- (_map$get = map.get(key)) == null || _map$get.push(value);
2558
- acc[key] = function () {
2559
- var _map$get2;
2560
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
2561
- args[_key] = arguments[_key];
2562
- }
2563
- return (_map$get2 = map.get(key)) == null ? void 0 : _map$get2.map(fn => fn(...args)).find(val => val !== undefined);
2564
- };
2565
- }
2566
- } else {
2567
- acc[key] = value;
2568
- }
2569
- });
2570
- return acc;
2571
- }, {})
2572
- };
2573
- }
2574
-
2575
- /**
2576
- * Merges an array of interaction hooks' props into prop getters, allowing
2577
- * event handler functions to be composed together without overwriting one
2578
- * another.
2579
- * @see https://floating-ui.com/docs/useInteractions
2580
- */
2581
- function useInteractions(propsList) {
2582
- if (propsList === void 0) {
2583
- propsList = [];
2584
- }
2585
- // The dependencies are a dynamic array, so we can't use the linter's
2586
- // suggestion to add it to the deps array.
2587
- const deps = propsList;
2588
- const getReferenceProps = React$1.useCallback(userProps => mergeProps(userProps, propsList, 'reference'),
2589
- // eslint-disable-next-line react-hooks/exhaustive-deps
2590
- deps);
2591
- const getFloatingProps = React$1.useCallback(userProps => mergeProps(userProps, propsList, 'floating'),
2592
- // eslint-disable-next-line react-hooks/exhaustive-deps
2593
- deps);
2594
- const getItemProps = React$1.useCallback(userProps => mergeProps(userProps, propsList, 'item'),
2595
- // Granularly check for `item` changes, because the `getItemProps` getter
2596
- // should be as referentially stable as possible since it may be passed as
2597
- // a prop to many components. All `item` key values must therefore be
2598
- // memoized.
2599
- // eslint-disable-next-line react-hooks/exhaustive-deps
2600
- propsList.map(key => key == null ? void 0 : key.item));
2601
- return React$1.useMemo(() => ({
2602
- getReferenceProps,
2603
- getFloatingProps,
2604
- getItemProps
2605
- }), [getReferenceProps, getFloatingProps, getItemProps]);
2606
- }
2607
-
2608
- const componentRoleToAriaRoleMap = /*#__PURE__*/new Map([['select', 'listbox'], ['combobox', 'listbox'], ['label', false]]);
2609
-
2610
- /**
2611
- * Adds base screen reader props to the reference and floating elements for a
2612
- * given floating element `role`.
2613
- * @see https://floating-ui.com/docs/useRole
2614
- */
2615
- function useRole(context, props) {
2616
- var _componentRoleToAriaR;
2617
- if (props === void 0) {
2618
- props = {};
2619
- }
2620
- const {
2621
- open,
2622
- floatingId
2623
- } = context;
2624
- const {
2625
- enabled = true,
2626
- role = 'dialog'
2627
- } = props;
2628
- const ariaRole = (_componentRoleToAriaR = componentRoleToAriaRoleMap.get(role)) != null ? _componentRoleToAriaR : role;
2629
- const referenceId = useId();
2630
- const parentId = useFloatingParentNodeId();
2631
- const isNested = parentId != null;
2632
- return React$1.useMemo(() => {
2633
- if (!enabled) return {};
2634
- const floatingProps = {
2635
- id: floatingId,
2636
- ...(ariaRole && {
2637
- role: ariaRole
2638
- })
2639
- };
2640
- if (ariaRole === 'tooltip' || role === 'label') {
2641
- return {
2642
- reference: {
2643
- ["aria-" + (role === 'label' ? 'labelledby' : 'describedby')]: open ? floatingId : undefined
2644
- },
2645
- floating: floatingProps
2646
- };
2647
- }
2648
- return {
2649
- reference: {
2650
- 'aria-expanded': open ? 'true' : 'false',
2651
- 'aria-haspopup': ariaRole === 'alertdialog' ? 'dialog' : ariaRole,
2652
- 'aria-controls': open ? floatingId : undefined,
2653
- ...(ariaRole === 'listbox' && {
2654
- role: 'combobox'
2655
- }),
2656
- ...(ariaRole === 'menu' && {
2657
- id: referenceId
2658
- }),
2659
- ...(ariaRole === 'menu' && isNested && {
2660
- role: 'menuitem'
2661
- }),
2662
- ...(role === 'select' && {
2663
- 'aria-autocomplete': 'none'
2664
- }),
2665
- ...(role === 'combobox' && {
2666
- 'aria-autocomplete': 'list'
2667
- })
2668
- },
2669
- floating: {
2670
- ...floatingProps,
2671
- ...(ariaRole === 'menu' && {
2672
- 'aria-labelledby': referenceId
2673
- })
2674
- },
2675
- item(_ref) {
2676
- let {
2677
- active,
2678
- selected
2679
- } = _ref;
2680
- const commonProps = {
2681
- role: 'option',
2682
- ...(active && {
2683
- id: floatingId + "-option"
2684
- })
2685
- };
2686
-
2687
- // For `menu`, we are unable to tell if the item is a `menuitemradio`
2688
- // or `menuitemcheckbox`. For backwards-compatibility reasons, also
2689
- // avoid defaulting to `menuitem` as it may overwrite custom role props.
2690
- switch (role) {
2691
- case 'select':
2692
- return {
2693
- ...commonProps,
2694
- 'aria-selected': active && selected
2695
- };
2696
- case 'combobox':
2697
- {
2698
- return {
2699
- ...commonProps,
2700
- ...(active && {
2701
- 'aria-selected': true
2702
- })
2703
- };
2704
- }
2705
- }
2706
- return {};
2707
- }
2708
- };
2709
- }, [enabled, role, ariaRole, open, floatingId, referenceId, isNested]);
2710
- }
2711
-
2712
- var _excluded$1 = ["popperName", "customRootClass", "className", "children", "open", "hoverDelay", "showArrow", "pop"];
2713
-
2714
- // TODO : Use Floating Portal?
2715
- // TODO : Collisions dont seem to be working as expected, need to investigate
2716
-
2717
- var ARROW_HEIGHT = 7;
2718
- var GAP = 2;
2719
- var Popper = function Popper(_ref) {
2720
- var _ref$popperName = _ref.popperName,
2721
- popperName = _ref$popperName === void 0 ? '' : _ref$popperName,
2722
- _ref$customRootClass = _ref.customRootClass,
2723
- customRootClass = _ref$customRootClass === void 0 ? '' : _ref$customRootClass,
2724
- _ref$className = _ref.className,
2725
- className = _ref$className === void 0 ? '' : _ref$className,
2726
- children = _ref.children,
2727
- _ref$open = _ref.open,
2728
- open = _ref$open === void 0 ? false : _ref$open;
2729
- _ref.hoverDelay;
2730
- var _ref$showArrow = _ref.showArrow,
2731
- showArrow = _ref$showArrow === void 0 ? true : _ref$showArrow,
2732
- _ref$pop = _ref.pop,
2733
- pop = _ref$pop === void 0 ? /*#__PURE__*/React.createElement(React.Fragment, null) : _ref$pop;
2734
- _objectWithoutProperties(_ref, _excluded$1);
2735
- var rootClass = customClassSwitcher(customRootClass, popperName);
2736
- var arrowRef = useRef(null);
2737
- var _useState = useState(open),
2738
- _useState2 = _slicedToArray(_useState, 2),
2739
- isOpen = _useState2[0],
2740
- setIsOpen = _useState2[1];
2741
- var _useFloating = useFloating({
2742
- open: isOpen,
2743
- middleware: [arrow({
2744
- element: arrowRef
2745
- }), offset(ARROW_HEIGHT + GAP),
2746
- // autoPlacement({
2747
- // crossAxis: 'center',
2748
- // alignment: 'start',
2749
- // autoAlignment: true,
2750
- // allowedPlacements: ['top', 'bottom', 'left', 'right'],
2751
- // padding: 5,
2752
- // }),
2753
- flip()],
2754
- onOpenChange: setIsOpen,
2755
- placement: 'top'
2756
- }),
2757
- refs = _useFloating.refs,
2758
- floatingStyles = _useFloating.floatingStyles,
2759
- context = _useFloating.context;
2760
- var role = useRole(context);
2761
- var dismiss = useDismiss(context);
2762
- var hover = useHover(context, {
2763
- // delay: hoverDelay,
2764
- });
2765
- var _useInteractions = useInteractions([hover, role, dismiss]),
2766
- getReferenceProps = _useInteractions.getReferenceProps,
2767
- getFloatingProps = _useInteractions.getFloatingProps;
2768
- return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("span", _extends$1({
2769
- className: "".concat(rootClass, "-reference-element ").concat(className),
2770
- ref: refs.setReference
2771
- }, getReferenceProps({
2772
- onClick: function onClick() {
2773
- console.log('click');
2774
- }
2775
- })), children), isOpen && /*#__PURE__*/React.createElement("div", _extends$1({
2776
- className: "".concat(rootClass, "-floating-element"),
2777
- ref: refs.setFloating,
2778
- style: floatingStyles
2779
- }, getFloatingProps()), showArrow && /*#__PURE__*/React.createElement(FloatingArrow, {
2780
- className: "rad-ui-arrow ".concat(rootClass, "-arrow"),
2781
- ref: arrowRef,
2782
- context: context
2783
- }), pop));
2784
- };
2785
45
 
2786
46
  var _excluded = ["children", "label"];
2787
47
  var COMPONENT_NAME = 'Tooltip';
@@ -2789,7 +49,7 @@ var Tooltip = function Tooltip(_ref) {
2789
49
  var children = _ref.children;
2790
50
  _ref.label;
2791
51
  var props = _objectWithoutProperties(_ref, _excluded);
2792
- return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(Popper, _extends$1({
52
+ return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(Popper, _extends({
2793
53
  popperName: COMPONENT_NAME,
2794
54
  pop: 'hello'
2795
55
  }, props), children));