@geneui/components 3.0.0-next-b458115-12022025 → 3.0.0-next-ca44d76-15022025

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