@jobber/components 8.20.2 → 8.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/dist/BottomSheet-cjs.js +9 -58
  2. package/dist/BottomSheet-es.js +2 -47
  3. package/dist/Card/index.cjs +4 -0
  4. package/dist/Card/index.mjs +4 -0
  5. package/dist/ComboboxChipRemove-cjs.js +3418 -0
  6. package/dist/ComboboxChipRemove-es.js +3366 -0
  7. package/dist/ComboboxPrimitive-cjs.js +170 -0
  8. package/dist/ComboboxPrimitive-es.js +168 -0
  9. package/dist/DataDump/index.cjs +4 -0
  10. package/dist/DataDump/index.mjs +4 -0
  11. package/dist/InputNumberExperimental-cjs.js +45 -44
  12. package/dist/InputNumberExperimental-es.js +3 -2
  13. package/dist/InternalBackdrop-cjs.js +4278 -0
  14. package/dist/InternalBackdrop-es.js +4204 -0
  15. package/dist/Menu/index.cjs +4 -0
  16. package/dist/Menu/index.mjs +4 -0
  17. package/dist/Menu-cjs.js +9 -8
  18. package/dist/Menu-es.js +2 -1
  19. package/dist/MenuSubmenuTrigger-cjs.js +208 -1969
  20. package/dist/MenuSubmenuTrigger-es.js +7 -1759
  21. package/dist/NumberFieldInput-cjs.js +56 -439
  22. package/dist/NumberFieldInput-es.js +6 -376
  23. package/dist/Page/index.cjs +4 -0
  24. package/dist/Page/index.mjs +4 -0
  25. package/dist/ScrollAreaViewport-cjs.js +108 -4356
  26. package/dist/ScrollAreaViewport-es.js +6 -4201
  27. package/dist/buttonRenderAdapter-cjs.js +56 -0
  28. package/dist/buttonRenderAdapter-es.js +51 -0
  29. package/dist/clamp-cjs.js +0 -1194
  30. package/dist/clamp-es.js +1 -1091
  31. package/dist/docs/empty-states/empty-states.md +29 -0
  32. package/dist/index.cjs +4 -0
  33. package/dist/index.mjs +4 -0
  34. package/dist/primitives/BottomSheet/index.cjs +5 -2
  35. package/dist/primitives/BottomSheet/index.mjs +5 -2
  36. package/dist/primitives/ComboboxPrimitive/ComboboxPrimitive.d.ts +32 -0
  37. package/dist/primitives/ComboboxPrimitive/ComboboxPrimitive.types.d.ts +30 -0
  38. package/dist/primitives/ComboboxPrimitive/index.cjs +28 -0
  39. package/dist/primitives/ComboboxPrimitive/index.d.ts +2 -0
  40. package/dist/primitives/ComboboxPrimitive/index.mjs +22 -0
  41. package/dist/primitives/InputNumberExperimental/index.cjs +4 -2
  42. package/dist/primitives/InputNumberExperimental/index.mjs +4 -2
  43. package/dist/primitives/index.cjs +11 -2
  44. package/dist/primitives/index.d.ts +1 -0
  45. package/dist/primitives/index.mjs +10 -2
  46. package/dist/styles.css +767 -0
  47. package/dist/unstyledPrimitives/index.cjs +237 -3588
  48. package/dist/unstyledPrimitives/index.mjs +96 -3447
  49. package/dist/useButton-cjs.js +1196 -0
  50. package/dist/useButton-es.js +1091 -0
  51. package/dist/useCompositeListItem-cjs.js +1792 -0
  52. package/dist/useCompositeListItem-es.js +1762 -0
  53. package/dist/useLabel-cjs.js +411 -0
  54. package/dist/useLabel-es.js +378 -0
  55. package/package.json +2 -2
@@ -0,0 +1,1792 @@
1
+ 'use strict';
2
+
3
+ var React = require('react');
4
+ var floatingUi_utils_dom = require('./floating-ui.utils.dom-cjs.js');
5
+ var useButton = require('./useButton-cjs.js');
6
+ var InternalBackdrop = require('./InternalBackdrop-cjs.js');
7
+ var useRenderElement = require('./useRenderElement-cjs.js');
8
+ var jsxRuntime = require('react/jsx-runtime');
9
+ var index_esm = require('./index.esm-cjs.js');
10
+ var floatingUi_reactDom = require('./floating-ui.react-dom-cjs.js');
11
+
12
+ function _interopNamespaceDefault(e) {
13
+ var n = Object.create(null);
14
+ if (e) {
15
+ Object.keys(e).forEach(function (k) {
16
+ if (k !== 'default') {
17
+ var d = Object.getOwnPropertyDescriptor(e, k);
18
+ Object.defineProperty(n, k, d.get ? d : {
19
+ enumerable: true,
20
+ get: function () { return e[k]; }
21
+ });
22
+ }
23
+ });
24
+ }
25
+ n.default = e;
26
+ return Object.freeze(n);
27
+ }
28
+
29
+ var React__namespace = /*#__PURE__*/_interopNamespaceDefault(React);
30
+
31
+ function useFloatingRootContext(options) {
32
+ const {
33
+ open = false,
34
+ onOpenChange,
35
+ elements = {}
36
+ } = options;
37
+ const floatingId = useButton.useId();
38
+ const nested = InternalBackdrop.useFloatingParentNodeId() != null;
39
+ if (process.env.NODE_ENV !== 'production') {
40
+ const optionDomReference = elements.reference;
41
+ if (optionDomReference && !floatingUi_utils_dom.isElement(optionDomReference)) {
42
+ console.error('Cannot pass a virtual element to the `elements.reference` option,', 'as it must be a real DOM element. Use `context.setPositionReference()`', 'instead.');
43
+ }
44
+ }
45
+ const store = useRenderElement.useRefWithInit(() => new InternalBackdrop.FloatingRootStore({
46
+ open,
47
+ onOpenChange,
48
+ referenceElement: elements.reference ?? null,
49
+ floatingElement: elements.floating ?? null,
50
+ triggerElements: new InternalBackdrop.PopupTriggerMap(),
51
+ floatingId,
52
+ nested,
53
+ noEmit: false
54
+ })).current;
55
+ useButton.useIsoLayoutEffect(() => {
56
+ const valuesToSync = {
57
+ open,
58
+ floatingId
59
+ };
60
+
61
+ // Only sync elements that are defined to avoid overwriting existing ones
62
+ if (elements.reference !== undefined) {
63
+ valuesToSync.referenceElement = elements.reference;
64
+ valuesToSync.domReferenceElement = floatingUi_utils_dom.isElement(elements.reference) ? elements.reference : null;
65
+ }
66
+ if (elements.floating !== undefined) {
67
+ valuesToSync.floatingElement = elements.floating;
68
+ }
69
+ store.update(valuesToSync);
70
+ }, [open, floatingId, elements.reference, elements.floating, store]);
71
+ store.context.onOpenChange = onOpenChange;
72
+ store.context.nested = nested;
73
+ store.context.noEmit = false;
74
+ return store;
75
+ }
76
+
77
+ /**
78
+ * Provides data to position a floating element and context to add interactions.
79
+ * @see https://floating-ui.com/docs/useFloating
80
+ */
81
+ function useFloating(options = {}) {
82
+ const {
83
+ nodeId,
84
+ externalTree
85
+ } = options;
86
+ const internalRootStore = useFloatingRootContext(options);
87
+ const rootContext = options.rootContext || internalRootStore;
88
+ const rootContextElements = {
89
+ reference: rootContext.useState('referenceElement'),
90
+ floating: rootContext.useState('floatingElement'),
91
+ domReference: rootContext.useState('domReferenceElement')
92
+ };
93
+ const [positionReference, setPositionReferenceRaw] = React__namespace.useState(null);
94
+ const domReferenceRef = React__namespace.useRef(null);
95
+ const tree = InternalBackdrop.useFloatingTree(externalTree);
96
+ useButton.useIsoLayoutEffect(() => {
97
+ if (rootContextElements.domReference) {
98
+ domReferenceRef.current = rootContextElements.domReference;
99
+ }
100
+ }, [rootContextElements.domReference]);
101
+ const position = floatingUi_reactDom.useFloating({
102
+ ...options,
103
+ elements: {
104
+ ...rootContextElements,
105
+ ...(positionReference && {
106
+ reference: positionReference
107
+ })
108
+ }
109
+ });
110
+ const setPositionReference = React__namespace.useCallback(node => {
111
+ const computedPositionReference = floatingUi_utils_dom.isElement(node) ? {
112
+ getBoundingClientRect: () => node.getBoundingClientRect(),
113
+ getClientRects: () => node.getClientRects(),
114
+ contextElement: node
115
+ } : node;
116
+ // Store the positionReference in state if the DOM reference is specified externally via the
117
+ // `elements.reference` option. This ensures that it won't be overridden on future renders.
118
+ setPositionReferenceRaw(computedPositionReference);
119
+ position.refs.setReference(computedPositionReference);
120
+ }, [position.refs]);
121
+ const [localDomReference, setLocalDomReference] = React__namespace.useState(null);
122
+ const [localFloatingElement, setLocalFloatingElement] = React__namespace.useState(null);
123
+ rootContext.useSyncedValue('referenceElement', localDomReference);
124
+ rootContext.useSyncedValue('domReferenceElement', floatingUi_utils_dom.isElement(localDomReference) ? localDomReference : null);
125
+ rootContext.useSyncedValue('floatingElement', localFloatingElement);
126
+ const setReference = React__namespace.useCallback(node => {
127
+ if (floatingUi_utils_dom.isElement(node) || node === null) {
128
+ domReferenceRef.current = node;
129
+ setLocalDomReference(node);
130
+ }
131
+
132
+ // Backwards-compatibility for passing a virtual element to `reference`
133
+ // after it has set the DOM reference.
134
+ if (floatingUi_utils_dom.isElement(position.refs.reference.current) || position.refs.reference.current === null ||
135
+ // Don't allow setting virtual elements using the old technique back to
136
+ // `null` to support `positionReference` + an unstable `reference`
137
+ // callback ref.
138
+ node !== null && !floatingUi_utils_dom.isElement(node)) {
139
+ position.refs.setReference(node);
140
+ }
141
+ }, [position.refs, setLocalDomReference]);
142
+ const setFloating = React__namespace.useCallback(node => {
143
+ setLocalFloatingElement(node);
144
+ position.refs.setFloating(node);
145
+ }, [position.refs]);
146
+ const refs = React__namespace.useMemo(() => ({
147
+ ...position.refs,
148
+ setReference,
149
+ setFloating,
150
+ setPositionReference,
151
+ domReference: domReferenceRef
152
+ }), [position.refs, setReference, setFloating, setPositionReference]);
153
+ const elements = React__namespace.useMemo(() => ({
154
+ ...position.elements,
155
+ domReference: rootContextElements.domReference
156
+ }), [position.elements, rootContextElements.domReference]);
157
+ const open = rootContext.useState('open');
158
+ const floatingId = rootContext.useState('floatingId');
159
+ const context = React__namespace.useMemo(() => ({
160
+ ...position,
161
+ dataRef: rootContext.context.dataRef,
162
+ open,
163
+ onOpenChange: rootContext.setOpen,
164
+ events: rootContext.context.events,
165
+ floatingId,
166
+ refs,
167
+ elements,
168
+ nodeId,
169
+ rootStore: rootContext
170
+ }), [position, refs, elements, nodeId, rootContext, open, floatingId]);
171
+ useButton.useIsoLayoutEffect(() => {
172
+ rootContext.context.dataRef.current.floatingContext = context;
173
+ const node = tree?.nodesRef.current.find(n => n.id === nodeId);
174
+ if (node) {
175
+ node.context = context;
176
+ }
177
+ });
178
+ return React__namespace.useMemo(() => ({
179
+ ...position,
180
+ context,
181
+ refs,
182
+ elements,
183
+ rootStore: rootContext
184
+ }), [position, refs, elements, context, rootContext]);
185
+ }
186
+
187
+ const ESCAPE = 'Escape';
188
+ function doSwitch(orientation, vertical, horizontal) {
189
+ switch (orientation) {
190
+ case 'vertical':
191
+ return vertical;
192
+ case 'horizontal':
193
+ return horizontal;
194
+ default:
195
+ return vertical || horizontal;
196
+ }
197
+ }
198
+ function isMainOrientationKey(key, orientation) {
199
+ const vertical = key === useButton.ARROW_UP || key === useButton.ARROW_DOWN;
200
+ const horizontal = key === useButton.ARROW_LEFT || key === useButton.ARROW_RIGHT;
201
+ return doSwitch(orientation, vertical, horizontal);
202
+ }
203
+ function isMainOrientationToEndKey(key, orientation, rtl) {
204
+ const vertical = key === useButton.ARROW_DOWN;
205
+ const horizontal = rtl ? key === useButton.ARROW_LEFT : key === useButton.ARROW_RIGHT;
206
+ return doSwitch(orientation, vertical, horizontal) || key === 'Enter' || key === ' ' || key === '';
207
+ }
208
+ function isCrossOrientationOpenKey(key, orientation, rtl) {
209
+ const vertical = rtl ? key === useButton.ARROW_LEFT : key === useButton.ARROW_RIGHT;
210
+ const horizontal = key === useButton.ARROW_DOWN;
211
+ return doSwitch(orientation, vertical, horizontal);
212
+ }
213
+ function isCrossOrientationCloseKey(key, orientation, rtl, cols) {
214
+ const vertical = rtl ? key === useButton.ARROW_RIGHT : key === useButton.ARROW_LEFT;
215
+ const horizontal = key === useButton.ARROW_UP;
216
+ if (orientation === 'both' || orientation === 'horizontal' && cols && cols > 1) {
217
+ return key === ESCAPE;
218
+ }
219
+ return doSwitch(orientation, vertical, horizontal);
220
+ }
221
+ /**
222
+ * Adds arrow key-based navigation of a list of items, either using real DOM
223
+ * focus or virtual focus.
224
+ * @see https://floating-ui.com/docs/useListNavigation
225
+ */
226
+ function useListNavigation(context, props) {
227
+ const store = 'rootStore' in context ? context.rootStore : context;
228
+ const open = store.useState('open');
229
+ const floatingElement = store.useState('floatingElement');
230
+ const domReferenceElement = store.useState('domReferenceElement');
231
+ const dataRef = store.context.dataRef;
232
+ const {
233
+ listRef,
234
+ activeIndex,
235
+ onNavigate: onNavigateProp = () => {},
236
+ enabled = true,
237
+ selectedIndex = null,
238
+ allowEscape = false,
239
+ loopFocus = false,
240
+ nested = false,
241
+ rtl = false,
242
+ virtual = false,
243
+ focusItemOnOpen = 'auto',
244
+ focusItemOnHover = true,
245
+ openOnArrowKeyDown = true,
246
+ disabledIndices = undefined,
247
+ orientation = 'vertical',
248
+ parentOrientation,
249
+ cols = 1,
250
+ id,
251
+ resetOnPointerLeave = true,
252
+ externalTree
253
+ } = props;
254
+ if (process.env.NODE_ENV !== 'production') {
255
+ if (allowEscape) {
256
+ if (!loopFocus) {
257
+ console.warn('`useListNavigation` looping must be enabled to allow escaping.');
258
+ }
259
+ if (!virtual) {
260
+ console.warn('`useListNavigation` must be virtual to allow escaping.');
261
+ }
262
+ }
263
+ if (orientation === 'vertical' && cols > 1) {
264
+ console.warn('In grid list navigation mode (`cols` > 1), the `orientation` should', 'be either "horizontal" or "both".');
265
+ }
266
+ }
267
+ const floatingFocusElement = useButton.getFloatingFocusElement(floatingElement);
268
+ const floatingFocusElementRef = useButton.useValueAsRef(floatingFocusElement);
269
+ const parentId = InternalBackdrop.useFloatingParentNodeId();
270
+ const tree = InternalBackdrop.useFloatingTree(externalTree);
271
+ useButton.useIsoLayoutEffect(() => {
272
+ dataRef.current.orientation = orientation;
273
+ }, [dataRef, orientation]);
274
+ const typeableComboboxReference = useButton.isTypeableCombobox(domReferenceElement);
275
+ const focusItemOnOpenRef = React__namespace.useRef(focusItemOnOpen);
276
+ const indexRef = React__namespace.useRef(selectedIndex ?? -1);
277
+ const keyRef = React__namespace.useRef(null);
278
+ const isPointerModalityRef = React__namespace.useRef(true);
279
+ const onNavigate = useButton.useStableCallback(event => {
280
+ onNavigateProp(indexRef.current === -1 ? null : indexRef.current, event);
281
+ });
282
+ const previousOnNavigateRef = React__namespace.useRef(onNavigate);
283
+ const previousMountedRef = React__namespace.useRef(!!floatingElement);
284
+ const previousOpenRef = React__namespace.useRef(open);
285
+ const forceSyncFocusRef = React__namespace.useRef(false);
286
+ const forceScrollIntoViewRef = React__namespace.useRef(false);
287
+ const disabledIndicesRef = useButton.useValueAsRef(disabledIndices);
288
+ const latestOpenRef = useButton.useValueAsRef(open);
289
+ const selectedIndexRef = useButton.useValueAsRef(selectedIndex);
290
+ const resetOnPointerLeaveRef = useButton.useValueAsRef(resetOnPointerLeave);
291
+ const focusItem = useButton.useStableCallback(() => {
292
+ function runFocus(item) {
293
+ if (virtual) {
294
+ tree?.events.emit('virtualfocus', item);
295
+ } else {
296
+ InternalBackdrop.enqueueFocus(item, {
297
+ sync: forceSyncFocusRef.current,
298
+ preventScroll: true
299
+ });
300
+ }
301
+ }
302
+ const initialItem = listRef.current[indexRef.current];
303
+ const forceScrollIntoView = forceScrollIntoViewRef.current;
304
+ if (initialItem) {
305
+ runFocus(initialItem);
306
+ }
307
+ const scheduler = forceSyncFocusRef.current ? v => v() : requestAnimationFrame;
308
+ scheduler(() => {
309
+ const waitedItem = listRef.current[indexRef.current] || initialItem;
310
+ if (!waitedItem) {
311
+ return;
312
+ }
313
+ if (!initialItem) {
314
+ runFocus(waitedItem);
315
+ }
316
+ const shouldScrollIntoView =
317
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
318
+ item && (forceScrollIntoView || !isPointerModalityRef.current);
319
+ if (shouldScrollIntoView) {
320
+ // JSDOM doesn't support `.scrollIntoView()` but it's widely supported
321
+ // by all browsers.
322
+ waitedItem.scrollIntoView?.({
323
+ block: 'nearest',
324
+ inline: 'nearest'
325
+ });
326
+ }
327
+ });
328
+ });
329
+
330
+ // Sync `selectedIndex` to be the `activeIndex` upon opening the floating
331
+ // element. Also, reset `activeIndex` upon closing the floating element.
332
+ useButton.useIsoLayoutEffect(() => {
333
+ if (!enabled) {
334
+ return;
335
+ }
336
+ if (open && floatingElement) {
337
+ indexRef.current = selectedIndex ?? -1;
338
+ if (focusItemOnOpenRef.current && selectedIndex != null) {
339
+ // Regardless of the pointer modality, we want to ensure the selected
340
+ // item comes into view when the floating element is opened.
341
+ forceScrollIntoViewRef.current = true;
342
+ onNavigate();
343
+ }
344
+ } else if (previousMountedRef.current) {
345
+ // Since the user can specify `onNavigate` conditionally
346
+ // (onNavigate: open ? setActiveIndex : setSelectedIndex),
347
+ // we store and call the previous function.
348
+ indexRef.current = -1;
349
+ previousOnNavigateRef.current();
350
+ }
351
+ }, [enabled, open, floatingElement, selectedIndex, onNavigate]);
352
+
353
+ // Sync `activeIndex` to be the focused item while the floating element is
354
+ // open.
355
+ useButton.useIsoLayoutEffect(() => {
356
+ if (!enabled) {
357
+ return;
358
+ }
359
+ if (!open) {
360
+ forceSyncFocusRef.current = false;
361
+ return;
362
+ }
363
+ if (!floatingElement) {
364
+ return;
365
+ }
366
+ if (activeIndex == null) {
367
+ forceSyncFocusRef.current = false;
368
+ if (selectedIndexRef.current != null) {
369
+ return;
370
+ }
371
+
372
+ // Reset while the floating element was open (e.g. the list changed).
373
+ if (previousMountedRef.current) {
374
+ indexRef.current = -1;
375
+ focusItem();
376
+ }
377
+
378
+ // Initial sync.
379
+ if ((!previousOpenRef.current || !previousMountedRef.current) && focusItemOnOpenRef.current && (keyRef.current != null || focusItemOnOpenRef.current === true && keyRef.current == null)) {
380
+ let runs = 0;
381
+ const waitForListPopulated = () => {
382
+ if (listRef.current[0] == null) {
383
+ // Avoid letting the browser paint if possible on the first try,
384
+ // otherwise use rAF. Don't try more than twice, since something
385
+ // is wrong otherwise.
386
+ if (runs < 2) {
387
+ const scheduler = runs ? requestAnimationFrame : queueMicrotask;
388
+ scheduler(waitForListPopulated);
389
+ }
390
+ runs += 1;
391
+ } else {
392
+ // initially focus the first non-disabled item
393
+ indexRef.current = keyRef.current == null || isMainOrientationToEndKey(keyRef.current, orientation, rtl) || nested ? InternalBackdrop.getMinListIndex(listRef) : InternalBackdrop.getMaxListIndex(listRef);
394
+ keyRef.current = null;
395
+ onNavigate();
396
+ }
397
+ };
398
+ waitForListPopulated();
399
+ }
400
+ } else if (!InternalBackdrop.isIndexOutOfListBounds(listRef, activeIndex)) {
401
+ indexRef.current = activeIndex;
402
+ focusItem();
403
+ forceScrollIntoViewRef.current = false;
404
+ }
405
+ }, [enabled, open, floatingElement, activeIndex, selectedIndexRef, nested, listRef, orientation, rtl, onNavigate, focusItem, disabledIndicesRef]);
406
+
407
+ // Ensure the parent floating element has focus when a nested child closes
408
+ // to allow arrow key navigation to work after the pointer leaves the child.
409
+ useButton.useIsoLayoutEffect(() => {
410
+ if (!enabled || floatingElement || !tree || virtual || !previousMountedRef.current) {
411
+ return;
412
+ }
413
+ const nodes = tree.nodesRef.current;
414
+ const parent = nodes.find(node => node.id === parentId)?.context?.elements.floating;
415
+ const activeEl = useButton.activeElement(useButton.ownerDocument(floatingElement));
416
+ const treeContainsActiveEl = nodes.some(node => node.context && useButton.contains(node.context.elements.floating, activeEl));
417
+ if (parent && !treeContainsActiveEl && isPointerModalityRef.current) {
418
+ parent.focus({
419
+ preventScroll: true
420
+ });
421
+ }
422
+ }, [enabled, floatingElement, tree, parentId, virtual]);
423
+ useButton.useIsoLayoutEffect(() => {
424
+ previousOnNavigateRef.current = onNavigate;
425
+ previousOpenRef.current = open;
426
+ previousMountedRef.current = !!floatingElement;
427
+ });
428
+ useButton.useIsoLayoutEffect(() => {
429
+ if (!open) {
430
+ keyRef.current = null;
431
+ focusItemOnOpenRef.current = focusItemOnOpen;
432
+ }
433
+ }, [open, focusItemOnOpen]);
434
+ const hasActiveIndex = activeIndex != null;
435
+ const item = React__namespace.useMemo(() => {
436
+ function syncCurrentTarget(event) {
437
+ if (!latestOpenRef.current) {
438
+ return;
439
+ }
440
+ const index = listRef.current.indexOf(event.currentTarget);
441
+ if (index !== -1 && indexRef.current !== index) {
442
+ indexRef.current = index;
443
+ onNavigate(event);
444
+ }
445
+ }
446
+ const itemProps = {
447
+ onFocus(event) {
448
+ forceSyncFocusRef.current = true;
449
+ syncCurrentTarget(event);
450
+ },
451
+ onClick: ({
452
+ currentTarget
453
+ }) => currentTarget.focus({
454
+ preventScroll: true
455
+ }),
456
+ // Safari
457
+ onMouseMove(event) {
458
+ forceSyncFocusRef.current = true;
459
+ forceScrollIntoViewRef.current = false;
460
+ if (focusItemOnHover) {
461
+ syncCurrentTarget(event);
462
+ }
463
+ },
464
+ onPointerLeave(event) {
465
+ if (!latestOpenRef.current || !isPointerModalityRef.current || event.pointerType === 'touch') {
466
+ return;
467
+ }
468
+ forceSyncFocusRef.current = true;
469
+ const relatedTarget = event.relatedTarget;
470
+ if (!focusItemOnHover || listRef.current.includes(relatedTarget)) {
471
+ return;
472
+ }
473
+ if (!resetOnPointerLeaveRef.current) {
474
+ return;
475
+ }
476
+ InternalBackdrop.enqueueFocus(null, {
477
+ sync: true
478
+ });
479
+ indexRef.current = -1;
480
+ onNavigate(event);
481
+ if (!virtual) {
482
+ const floatingFocusEl = floatingFocusElementRef.current;
483
+ const activeEl = useButton.activeElement(useButton.ownerDocument(floatingFocusEl));
484
+ if (floatingFocusEl && useButton.contains(floatingFocusEl, activeEl)) {
485
+ floatingFocusEl.focus({
486
+ preventScroll: true
487
+ });
488
+ }
489
+ }
490
+ }
491
+ };
492
+ return itemProps;
493
+ }, [latestOpenRef, floatingFocusElementRef, focusItemOnHover, listRef, onNavigate, resetOnPointerLeaveRef, virtual]);
494
+ const getParentOrientation = React__namespace.useCallback(() => {
495
+ return parentOrientation ?? tree?.nodesRef.current.find(node => node.id === parentId)?.context?.dataRef?.current.orientation;
496
+ }, [parentId, tree, parentOrientation]);
497
+ const commonOnKeyDown = useButton.useStableCallback(event => {
498
+ isPointerModalityRef.current = false;
499
+ forceSyncFocusRef.current = true;
500
+
501
+ // When composing a character, Chrome fires ArrowDown twice. Firefox/Safari
502
+ // don't appear to suffer from this. `event.isComposing` is avoided due to
503
+ // Safari not supporting it properly (although it's not needed in the first
504
+ // place for Safari, just avoiding any possible issues).
505
+ if (event.which === 229) {
506
+ return;
507
+ }
508
+
509
+ // If the floating element is animating out, ignore navigation. Otherwise,
510
+ // the `activeIndex` gets set to 0 despite not being open so the next time
511
+ // the user ArrowDowns, the first item won't be focused.
512
+ if (!latestOpenRef.current && event.currentTarget === floatingFocusElementRef.current) {
513
+ return;
514
+ }
515
+ if (nested && isCrossOrientationCloseKey(event.key, orientation, rtl, cols)) {
516
+ // If the nested list's close key is also the parent navigation key,
517
+ // let the parent navigate. Otherwise, stop propagating the event.
518
+ if (!isMainOrientationKey(event.key, getParentOrientation())) {
519
+ useButton.stopEvent(event);
520
+ }
521
+ store.setOpen(false, useButton.createChangeEventDetails(useButton.listNavigation, event.nativeEvent));
522
+ if (floatingUi_utils_dom.isHTMLElement(domReferenceElement)) {
523
+ if (virtual) {
524
+ tree?.events.emit('virtualfocus', domReferenceElement);
525
+ } else {
526
+ domReferenceElement.focus();
527
+ }
528
+ }
529
+ return;
530
+ }
531
+ const currentIndex = indexRef.current;
532
+ const minIndex = InternalBackdrop.getMinListIndex(listRef, disabledIndices);
533
+ const maxIndex = InternalBackdrop.getMaxListIndex(listRef, disabledIndices);
534
+ if (!typeableComboboxReference) {
535
+ if (event.key === 'Home') {
536
+ useButton.stopEvent(event);
537
+ indexRef.current = minIndex;
538
+ onNavigate(event);
539
+ }
540
+ if (event.key === 'End') {
541
+ useButton.stopEvent(event);
542
+ indexRef.current = maxIndex;
543
+ onNavigate(event);
544
+ }
545
+ }
546
+
547
+ // Grid navigation.
548
+ if (cols > 1) {
549
+ const sizes = Array.from({
550
+ length: listRef.current.length
551
+ }, () => ({
552
+ width: 1,
553
+ height: 1
554
+ }));
555
+ // To calculate movements on the grid, we use hypothetical cell indices
556
+ // as if every item was 1x1, then convert back to real indices.
557
+ const cellMap = InternalBackdrop.createGridCellMap(sizes, cols);
558
+ const minGridIndex = cellMap.findIndex(index => index != null && !InternalBackdrop.isListIndexDisabled(listRef, index, disabledIndices));
559
+ // last enabled index
560
+ const maxGridIndex = cellMap.reduce((foundIndex, index, cellIndex) => index != null && !InternalBackdrop.isListIndexDisabled(listRef, index, disabledIndices) ? cellIndex : foundIndex, -1);
561
+ const index = cellMap[InternalBackdrop.getGridNavigatedIndex({
562
+ current: cellMap.map(itemIndex => itemIndex != null ? listRef.current[itemIndex] : null)
563
+ }, {
564
+ event,
565
+ orientation,
566
+ loopFocus,
567
+ rtl,
568
+ cols,
569
+ // treat undefined (empty grid spaces) as disabled indices so we
570
+ // don't end up in them
571
+ disabledIndices: InternalBackdrop.getGridCellIndices([...((typeof disabledIndices !== 'function' ? disabledIndices : null) || listRef.current.map((_, listIndex) => InternalBackdrop.isListIndexDisabled(listRef, listIndex, disabledIndices) ? listIndex : undefined)), undefined], cellMap),
572
+ minIndex: minGridIndex,
573
+ maxIndex: maxGridIndex,
574
+ prevIndex: InternalBackdrop.getGridCellIndexOfCorner(indexRef.current > maxIndex ? minIndex : indexRef.current, sizes, cellMap, cols,
575
+ // use a corner matching the edge closest to the direction
576
+ // we're moving in so we don't end up in the same item. Prefer
577
+ // top/left over bottom/right.
578
+ // eslint-disable-next-line no-nested-ternary
579
+ event.key === useButton.ARROW_DOWN ? 'bl' : event.key === (rtl ? useButton.ARROW_LEFT : useButton.ARROW_RIGHT) ? 'tr' : 'tl'),
580
+ stopEvent: true
581
+ })];
582
+ if (index != null) {
583
+ indexRef.current = index;
584
+ onNavigate(event);
585
+ }
586
+ if (orientation === 'both') {
587
+ return;
588
+ }
589
+ }
590
+ if (isMainOrientationKey(event.key, orientation)) {
591
+ useButton.stopEvent(event);
592
+
593
+ // Reset the index if no item is focused.
594
+ if (open && !virtual && useButton.activeElement(event.currentTarget.ownerDocument) === event.currentTarget) {
595
+ indexRef.current = isMainOrientationToEndKey(event.key, orientation, rtl) ? minIndex : maxIndex;
596
+ onNavigate(event);
597
+ return;
598
+ }
599
+ if (isMainOrientationToEndKey(event.key, orientation, rtl)) {
600
+ if (loopFocus) {
601
+ if (currentIndex >= maxIndex) {
602
+ if (allowEscape && currentIndex !== listRef.current.length) {
603
+ indexRef.current = -1;
604
+ } else {
605
+ // Give time for virtualizers to update the listRef.
606
+ forceSyncFocusRef.current = false;
607
+ indexRef.current = minIndex;
608
+ }
609
+ } else {
610
+ indexRef.current = InternalBackdrop.findNonDisabledListIndex(listRef, {
611
+ startingIndex: currentIndex,
612
+ disabledIndices
613
+ });
614
+ }
615
+ } else {
616
+ indexRef.current = Math.min(maxIndex, InternalBackdrop.findNonDisabledListIndex(listRef, {
617
+ startingIndex: currentIndex,
618
+ disabledIndices
619
+ }));
620
+ }
621
+ } else if (loopFocus) {
622
+ if (currentIndex <= minIndex) {
623
+ if (allowEscape && currentIndex !== -1) {
624
+ indexRef.current = listRef.current.length;
625
+ } else {
626
+ // Give time for virtualizers to update the listRef.
627
+ forceSyncFocusRef.current = false;
628
+ indexRef.current = maxIndex;
629
+ }
630
+ } else {
631
+ indexRef.current = InternalBackdrop.findNonDisabledListIndex(listRef, {
632
+ startingIndex: currentIndex,
633
+ decrement: true,
634
+ disabledIndices
635
+ });
636
+ }
637
+ } else {
638
+ indexRef.current = Math.max(minIndex, InternalBackdrop.findNonDisabledListIndex(listRef, {
639
+ startingIndex: currentIndex,
640
+ decrement: true,
641
+ disabledIndices
642
+ }));
643
+ }
644
+ if (InternalBackdrop.isIndexOutOfListBounds(listRef, indexRef.current)) {
645
+ indexRef.current = -1;
646
+ }
647
+ onNavigate(event);
648
+ }
649
+ });
650
+ const ariaActiveDescendantProp = React__namespace.useMemo(() => {
651
+ return virtual && open && hasActiveIndex && {
652
+ 'aria-activedescendant': `${id}-${activeIndex}`
653
+ };
654
+ }, [virtual, open, hasActiveIndex, id, activeIndex]);
655
+ const floating = React__namespace.useMemo(() => {
656
+ return {
657
+ 'aria-orientation': orientation === 'both' ? undefined : orientation,
658
+ ...(!typeableComboboxReference ? ariaActiveDescendantProp : {}),
659
+ onKeyDown(event) {
660
+ // Close submenu on Shift+Tab
661
+ if (event.key === 'Tab' && event.shiftKey && open && !virtual) {
662
+ // If the event originated from within a nested element (e.g., a Dialog opened from
663
+ // within the menu), don't close the menu. The nested element has its own focus
664
+ // management and should handle the Tab key.
665
+ const target = useButton.getTarget(event.nativeEvent);
666
+ if (target && !useButton.contains(floatingFocusElementRef.current, target)) {
667
+ return;
668
+ }
669
+ useButton.stopEvent(event);
670
+ store.setOpen(false, useButton.createChangeEventDetails(useButton.focusOut, event.nativeEvent));
671
+ if (floatingUi_utils_dom.isHTMLElement(domReferenceElement)) {
672
+ domReferenceElement.focus();
673
+ }
674
+ return;
675
+ }
676
+ commonOnKeyDown(event);
677
+ },
678
+ onPointerMove() {
679
+ isPointerModalityRef.current = true;
680
+ }
681
+ };
682
+ }, [ariaActiveDescendantProp, commonOnKeyDown, floatingFocusElementRef, orientation, typeableComboboxReference, store, open, virtual, domReferenceElement]);
683
+ const trigger = React__namespace.useMemo(() => {
684
+ function checkVirtualMouse(event) {
685
+ if (focusItemOnOpen === 'auto' && useButton.isVirtualClick(event.nativeEvent)) {
686
+ focusItemOnOpenRef.current = !virtual;
687
+ }
688
+ }
689
+ function checkVirtualPointer(event) {
690
+ // `pointerdown` fires first, reset the state then perform the checks.
691
+ focusItemOnOpenRef.current = focusItemOnOpen;
692
+ if (focusItemOnOpen === 'auto' && useButton.isVirtualPointerEvent(event.nativeEvent)) {
693
+ focusItemOnOpenRef.current = true;
694
+ }
695
+ }
696
+ return {
697
+ onKeyDown(event) {
698
+ // non-reactive open state (to prevent re-creation of the handler)
699
+ const currentOpen = store.select('open');
700
+ isPointerModalityRef.current = false;
701
+ const isArrowKey = event.key.startsWith('Arrow');
702
+ const isParentCrossOpenKey = isCrossOrientationOpenKey(event.key, getParentOrientation(), rtl);
703
+ const isMainKey = isMainOrientationKey(event.key, orientation);
704
+ const isNavigationKey = (nested ? isParentCrossOpenKey : isMainKey) || event.key === 'Enter' || event.key.trim() === '';
705
+ if (virtual && currentOpen) {
706
+ return commonOnKeyDown(event);
707
+ }
708
+
709
+ // If a floating element should not open on arrow key down, avoid
710
+ // setting `activeIndex` while it's closed.
711
+ if (!currentOpen && !openOnArrowKeyDown && isArrowKey) {
712
+ return undefined;
713
+ }
714
+ if (isNavigationKey) {
715
+ const isParentMainKey = isMainOrientationKey(event.key, getParentOrientation());
716
+ keyRef.current = nested && isParentMainKey ? null : event.key;
717
+ }
718
+ if (nested) {
719
+ if (isParentCrossOpenKey) {
720
+ useButton.stopEvent(event);
721
+ if (currentOpen) {
722
+ indexRef.current = InternalBackdrop.getMinListIndex(listRef, disabledIndicesRef.current);
723
+ onNavigate(event);
724
+ } else {
725
+ store.setOpen(true, useButton.createChangeEventDetails(useButton.listNavigation, event.nativeEvent, event.currentTarget));
726
+ }
727
+ }
728
+ return undefined;
729
+ }
730
+ if (isMainKey) {
731
+ if (selectedIndexRef.current != null) {
732
+ indexRef.current = selectedIndexRef.current;
733
+ }
734
+ useButton.stopEvent(event);
735
+ if (!currentOpen && openOnArrowKeyDown) {
736
+ store.setOpen(true, useButton.createChangeEventDetails(useButton.listNavigation, event.nativeEvent, event.currentTarget));
737
+ } else {
738
+ commonOnKeyDown(event);
739
+ }
740
+ if (currentOpen) {
741
+ onNavigate(event);
742
+ }
743
+ }
744
+ return undefined;
745
+ },
746
+ onFocus(event) {
747
+ if (store.select('open') && !virtual) {
748
+ indexRef.current = -1;
749
+ onNavigate(event);
750
+ }
751
+ },
752
+ onPointerDown: checkVirtualPointer,
753
+ onPointerEnter: checkVirtualPointer,
754
+ onMouseDown: checkVirtualMouse,
755
+ onClick: checkVirtualMouse
756
+ };
757
+ }, [commonOnKeyDown, disabledIndicesRef, focusItemOnOpen, listRef, nested, onNavigate, store, openOnArrowKeyDown, orientation, getParentOrientation, rtl, selectedIndexRef, virtual]);
758
+ const reference = React__namespace.useMemo(() => {
759
+ return {
760
+ ...ariaActiveDescendantProp,
761
+ ...trigger
762
+ };
763
+ }, [ariaActiveDescendantProp, trigger]);
764
+ return React__namespace.useMemo(() => enabled ? {
765
+ reference,
766
+ floating,
767
+ item,
768
+ trigger
769
+ } : {}, [enabled, reference, floating, trigger, item]);
770
+ }
771
+
772
+ /**
773
+ * Provides a matching callback that can be used to focus an item as the user
774
+ * types, often used in tandem with `useListNavigation()`.
775
+ * @see https://floating-ui.com/docs/useTypeahead
776
+ */
777
+ function useTypeahead(context, props) {
778
+ const store = 'rootStore' in context ? context.rootStore : context;
779
+ const dataRef = store.context.dataRef;
780
+ const open = store.useState('open');
781
+ const {
782
+ listRef,
783
+ elementsRef,
784
+ activeIndex,
785
+ onMatch: onMatchProp,
786
+ onTypingChange,
787
+ enabled = true,
788
+ resetMs = 750,
789
+ selectedIndex = null
790
+ } = props;
791
+ const timeout = useButton.useTimeout();
792
+ const stringRef = React__namespace.useRef('');
793
+ const prevIndexRef = React__namespace.useRef(selectedIndex ?? activeIndex ?? -1);
794
+ const matchIndexRef = React__namespace.useRef(null);
795
+ useButton.useIsoLayoutEffect(() => {
796
+ if (!open && selectedIndex !== null) {
797
+ return;
798
+ }
799
+ timeout.clear();
800
+ matchIndexRef.current = null;
801
+ if (stringRef.current !== '') {
802
+ stringRef.current = '';
803
+ }
804
+ }, [open, selectedIndex, timeout]);
805
+ useButton.useIsoLayoutEffect(() => {
806
+ // Sync arrow key navigation but not typeahead navigation.
807
+ if (open && stringRef.current === '') {
808
+ prevIndexRef.current = selectedIndex ?? activeIndex ?? -1;
809
+ }
810
+ }, [open, selectedIndex, activeIndex]);
811
+ const setTypingChange = useButton.useStableCallback(value => {
812
+ if (value) {
813
+ if (!dataRef.current.typing) {
814
+ dataRef.current.typing = value;
815
+ onTypingChange?.(value);
816
+ }
817
+ } else if (dataRef.current.typing) {
818
+ dataRef.current.typing = value;
819
+ onTypingChange?.(value);
820
+ }
821
+ });
822
+ const onKeyDown = useButton.useStableCallback(event => {
823
+ function isVisible(index) {
824
+ const element = elementsRef?.current[index];
825
+ return !element || InternalBackdrop.isElementVisible(element);
826
+ }
827
+ function getMatchingIndex(list, string, startIndex = 0) {
828
+ if (list.length === 0) {
829
+ return -1;
830
+ }
831
+ const normalizedStartIndex = (startIndex % list.length + list.length) % list.length;
832
+ const lowerString = string.toLocaleLowerCase();
833
+ for (let offset = 0; offset < list.length; offset += 1) {
834
+ const index = (normalizedStartIndex + offset) % list.length;
835
+ const text = list[index];
836
+ if (!text?.toLocaleLowerCase().startsWith(lowerString) || !isVisible(index)) {
837
+ continue;
838
+ }
839
+ return index;
840
+ }
841
+ return -1;
842
+ }
843
+ const listContent = listRef.current;
844
+ if (stringRef.current.length > 0 && event.key === ' ') {
845
+ // Space should continue the in-progress typeahead session.
846
+ useButton.stopEvent(event);
847
+ setTypingChange(true);
848
+ }
849
+ if (stringRef.current.length > 0 && stringRef.current[0] !== ' ') {
850
+ if (getMatchingIndex(listContent, stringRef.current) === -1 && event.key !== ' ') {
851
+ setTypingChange(false);
852
+ }
853
+ }
854
+ if (listContent == null ||
855
+ // Character key.
856
+ event.key.length !== 1 ||
857
+ // Modifier key.
858
+ event.ctrlKey || event.metaKey || event.altKey) {
859
+ return;
860
+ }
861
+ if (open && event.key !== ' ') {
862
+ useButton.stopEvent(event);
863
+ setTypingChange(true);
864
+ }
865
+
866
+ // Capture whether this is a new typing session before mutating the string.
867
+ const isNewSession = stringRef.current === '';
868
+ if (isNewSession) {
869
+ prevIndexRef.current = selectedIndex ?? activeIndex ?? -1;
870
+ }
871
+
872
+ // Bail out if the list contains a word like "llama" or "aaron". TODO:
873
+ // allow it in this case, too.
874
+ const allowRapidSuccessionOfFirstLetter = listContent.every(text => text ? text[0]?.toLocaleLowerCase() !== text[1]?.toLocaleLowerCase() : true);
875
+
876
+ // Allows the user to cycle through items that start with the same letter
877
+ // in rapid succession.
878
+ if (allowRapidSuccessionOfFirstLetter && stringRef.current === event.key) {
879
+ stringRef.current = '';
880
+ prevIndexRef.current = matchIndexRef.current;
881
+ }
882
+ stringRef.current += event.key;
883
+ timeout.start(resetMs, () => {
884
+ stringRef.current = '';
885
+ prevIndexRef.current = matchIndexRef.current;
886
+ setTypingChange(false);
887
+ });
888
+
889
+ // Compute the starting index for this search.
890
+ // If this is a new typing session (string is empty), base it on the current
891
+ // selection/active item; otherwise continue from the last matched index.
892
+ const prevIndex = isNewSession ? selectedIndex ?? activeIndex ?? -1 : prevIndexRef.current;
893
+ const startIndex = (prevIndex ?? 0) + 1;
894
+ const index = getMatchingIndex(listContent, stringRef.current, startIndex);
895
+ if (index !== -1) {
896
+ onMatchProp?.(index);
897
+ matchIndexRef.current = index;
898
+ } else if (event.key !== ' ') {
899
+ stringRef.current = '';
900
+ setTypingChange(false);
901
+ }
902
+ });
903
+ const onBlur = useButton.useStableCallback(event => {
904
+ const next = event.relatedTarget;
905
+ const currentDomReferenceElement = store.select('domReferenceElement');
906
+ const currentFloatingElement = store.select('floatingElement');
907
+ const withinReference = useButton.contains(currentDomReferenceElement, next);
908
+ const withinFloating = useButton.contains(currentFloatingElement, next);
909
+
910
+ // Keep the session if focus moves within the composite (reference <-> floating).
911
+ if (withinReference || withinFloating) {
912
+ return;
913
+ }
914
+
915
+ // End the current typing session when focus leaves the composite entirely.
916
+ timeout.clear();
917
+ stringRef.current = '';
918
+ prevIndexRef.current = matchIndexRef.current;
919
+ setTypingChange(false);
920
+ });
921
+ const reference = React__namespace.useMemo(() => ({
922
+ onKeyDown,
923
+ onBlur
924
+ }), [onKeyDown, onBlur]);
925
+ const floating = React__namespace.useMemo(() => {
926
+ return {
927
+ onKeyDown,
928
+ onBlur
929
+ };
930
+ }, [onKeyDown, onBlur]);
931
+ return React__namespace.useMemo(() => enabled ? {
932
+ reference,
933
+ floating
934
+ } : {}, [enabled, reference, floating]);
935
+ }
936
+
937
+ function getPseudoElementBounds(element) {
938
+ const elementRect = element.getBoundingClientRect();
939
+
940
+ // Avoid "Not implemented: window.getComputedStyle(elt, pseudoElt)"
941
+ if (process.env.NODE_ENV !== 'production') {
942
+ return elementRect;
943
+ }
944
+ const beforeStyles = window.getComputedStyle(element, '::before');
945
+ const afterStyles = window.getComputedStyle(element, '::after');
946
+ const hasPseudoElements = beforeStyles.content !== 'none' || afterStyles.content !== 'none';
947
+ if (!hasPseudoElements) {
948
+ return elementRect;
949
+ }
950
+
951
+ // Get dimensions of pseudo-elements
952
+ const beforeWidth = parseFloat(beforeStyles.width) || 0;
953
+ const beforeHeight = parseFloat(beforeStyles.height) || 0;
954
+ const afterWidth = parseFloat(afterStyles.width) || 0;
955
+ const afterHeight = parseFloat(afterStyles.height) || 0;
956
+
957
+ // Calculate max dimensions including pseudo-elements
958
+ const totalWidth = Math.max(elementRect.width, beforeWidth, afterWidth);
959
+ const totalHeight = Math.max(elementRect.height, beforeHeight, afterHeight);
960
+
961
+ // Calculate the differences to extend the bounds
962
+ const widthDiff = totalWidth - elementRect.width;
963
+ const heightDiff = totalHeight - elementRect.height;
964
+ return {
965
+ left: elementRect.left - widthDiff / 2,
966
+ right: elementRect.right + widthDiff / 2,
967
+ top: elementRect.top - heightDiff / 2,
968
+ bottom: elementRect.bottom + heightDiff / 2
969
+ };
970
+ }
971
+
972
+ const CompositeListContext = /*#__PURE__*/React__namespace.createContext({
973
+ register: () => {},
974
+ unregister: () => {},
975
+ subscribeMapChange: () => {
976
+ return () => {};
977
+ },
978
+ elementsRef: {
979
+ current: []
980
+ },
981
+ nextIndexRef: {
982
+ current: 0
983
+ }
984
+ });
985
+ if (process.env.NODE_ENV !== "production") CompositeListContext.displayName = "CompositeListContext";
986
+ function useCompositeListContext() {
987
+ return React__namespace.useContext(CompositeListContext);
988
+ }
989
+
990
+ /* eslint-disable no-bitwise */
991
+ /**
992
+ * Provides context for a list of items in a composite component.
993
+ * @internal
994
+ */
995
+ function CompositeList(props) {
996
+ const {
997
+ children,
998
+ elementsRef,
999
+ labelsRef,
1000
+ onMapChange: onMapChangeProp
1001
+ } = props;
1002
+ const onMapChange = useButton.useStableCallback(onMapChangeProp);
1003
+ const nextIndexRef = React__namespace.useRef(0);
1004
+ const listeners = useRenderElement.useRefWithInit(createListeners).current;
1005
+
1006
+ // We use a stable `map` to avoid O(n^2) re-allocation costs for large lists.
1007
+ // `mapTick` is our re-render trigger mechanism. We also need to update the
1008
+ // elements and label refs, but there's a lot of async work going on and sometimes
1009
+ // the effect that handles `onMapChange` gets called after those refs have been
1010
+ // filled, and we don't want to lose those values by setting their lengths to `0`.
1011
+ // We also need to have them at the proper length because floating-ui uses that
1012
+ // information for list navigation.
1013
+
1014
+ const map = useRenderElement.useRefWithInit(createMap).current;
1015
+ // `mapTick` uses a counter rather than objects for low precision-loss risk and better memory efficiency
1016
+ const [mapTick, setMapTick] = React__namespace.useState(0);
1017
+ const lastTickRef = React__namespace.useRef(mapTick);
1018
+ const register = useButton.useStableCallback((node, metadata) => {
1019
+ map.set(node, metadata ?? null);
1020
+ lastTickRef.current += 1;
1021
+ setMapTick(lastTickRef.current);
1022
+ });
1023
+ const unregister = useButton.useStableCallback(node => {
1024
+ map.delete(node);
1025
+ lastTickRef.current += 1;
1026
+ setMapTick(lastTickRef.current);
1027
+ });
1028
+ const sortedMap = React__namespace.useMemo(() => {
1029
+ const newMap = new Map();
1030
+ // Filter out disconnected elements before sorting to avoid inconsistent
1031
+ // compareDocumentPosition results when elements are detached from the DOM.
1032
+ const sortedNodes = Array.from(map.keys()).filter(node => node.isConnected).sort(sortByDocumentPosition);
1033
+ sortedNodes.forEach((node, index) => {
1034
+ const metadata = map.get(node) ?? {};
1035
+ newMap.set(node, {
1036
+ ...metadata,
1037
+ index
1038
+ });
1039
+ });
1040
+ return newMap;
1041
+ }, [map, mapTick]);
1042
+ useButton.useIsoLayoutEffect(() => {
1043
+ if (typeof MutationObserver !== 'function' || sortedMap.size === 0) {
1044
+ return undefined;
1045
+ }
1046
+ const mutationObserver = new MutationObserver(entries => {
1047
+ const diff = new Set();
1048
+ const updateDiff = node => diff.has(node) ? diff.delete(node) : diff.add(node);
1049
+ entries.forEach(entry => {
1050
+ entry.removedNodes.forEach(updateDiff);
1051
+ entry.addedNodes.forEach(updateDiff);
1052
+ });
1053
+ if (diff.size === 0) {
1054
+ lastTickRef.current += 1;
1055
+ setMapTick(lastTickRef.current);
1056
+ }
1057
+ });
1058
+ sortedMap.forEach((_, node) => {
1059
+ if (node.parentElement) {
1060
+ mutationObserver.observe(node.parentElement, {
1061
+ childList: true
1062
+ });
1063
+ }
1064
+ });
1065
+ return () => {
1066
+ mutationObserver.disconnect();
1067
+ };
1068
+ }, [sortedMap]);
1069
+ useButton.useIsoLayoutEffect(() => {
1070
+ const shouldUpdateLengths = lastTickRef.current === mapTick;
1071
+ if (shouldUpdateLengths) {
1072
+ if (elementsRef.current.length !== sortedMap.size) {
1073
+ elementsRef.current.length = sortedMap.size;
1074
+ }
1075
+ if (labelsRef && labelsRef.current.length !== sortedMap.size) {
1076
+ labelsRef.current.length = sortedMap.size;
1077
+ }
1078
+ nextIndexRef.current = sortedMap.size;
1079
+ }
1080
+ onMapChange(sortedMap);
1081
+ }, [onMapChange, sortedMap, elementsRef, labelsRef, mapTick]);
1082
+ useButton.useIsoLayoutEffect(() => {
1083
+ return () => {
1084
+ elementsRef.current = [];
1085
+ };
1086
+ }, [elementsRef]);
1087
+ useButton.useIsoLayoutEffect(() => {
1088
+ return () => {
1089
+ if (labelsRef) {
1090
+ labelsRef.current = [];
1091
+ }
1092
+ };
1093
+ }, [labelsRef]);
1094
+ const subscribeMapChange = useButton.useStableCallback(fn => {
1095
+ listeners.add(fn);
1096
+ return () => {
1097
+ listeners.delete(fn);
1098
+ };
1099
+ });
1100
+ useButton.useIsoLayoutEffect(() => {
1101
+ listeners.forEach(l => l(sortedMap));
1102
+ }, [listeners, sortedMap]);
1103
+ const contextValue = React__namespace.useMemo(() => ({
1104
+ register,
1105
+ unregister,
1106
+ subscribeMapChange,
1107
+ elementsRef,
1108
+ labelsRef,
1109
+ nextIndexRef
1110
+ }), [register, unregister, subscribeMapChange, elementsRef, labelsRef, nextIndexRef]);
1111
+ return /*#__PURE__*/jsxRuntime.jsx(CompositeListContext.Provider, {
1112
+ value: contextValue,
1113
+ children: children
1114
+ });
1115
+ }
1116
+ function createMap() {
1117
+ return new Map();
1118
+ }
1119
+ function createListeners() {
1120
+ return new Set();
1121
+ }
1122
+ function sortByDocumentPosition(a, b) {
1123
+ const position = a.compareDocumentPosition(b);
1124
+ if (position & Node.DOCUMENT_POSITION_FOLLOWING || position & Node.DOCUMENT_POSITION_CONTAINED_BY) {
1125
+ return -1;
1126
+ }
1127
+ if (position & Node.DOCUMENT_POSITION_PRECEDING || position & Node.DOCUMENT_POSITION_CONTAINS) {
1128
+ return 1;
1129
+ }
1130
+ return 0;
1131
+ }
1132
+
1133
+ /**
1134
+ * Fork of the original `arrow` middleware from Floating UI that allows
1135
+ * configuring the offset parent.
1136
+ */
1137
+ const baseArrow = options => ({
1138
+ name: 'arrow',
1139
+ options,
1140
+ async fn(state) {
1141
+ const {
1142
+ x,
1143
+ y,
1144
+ placement,
1145
+ rects,
1146
+ platform,
1147
+ elements,
1148
+ middlewareData
1149
+ } = state;
1150
+ // Since `element` is required, we don't Partial<> the type.
1151
+ const {
1152
+ element,
1153
+ padding = 0,
1154
+ offsetParent = 'real'
1155
+ } = index_esm.evaluate(options, state) || {};
1156
+ if (element == null) {
1157
+ return {};
1158
+ }
1159
+ const paddingObject = index_esm.getPaddingObject(padding);
1160
+ const coords = {
1161
+ x,
1162
+ y
1163
+ };
1164
+ const axis = index_esm.getAlignmentAxis(placement);
1165
+ const length = index_esm.getAxisLength(axis);
1166
+ const arrowDimensions = await platform.getDimensions(element);
1167
+ const isYAxis = axis === 'y';
1168
+ const minProp = isYAxis ? 'top' : 'left';
1169
+ const maxProp = isYAxis ? 'bottom' : 'right';
1170
+ const clientProp = isYAxis ? 'clientHeight' : 'clientWidth';
1171
+ const endDiff = rects.reference[length] + rects.reference[axis] - coords[axis] - rects.floating[length];
1172
+ const startDiff = coords[axis] - rects.reference[axis];
1173
+ const arrowOffsetParent = offsetParent === 'real' ? await platform.getOffsetParent?.(element) : elements.floating;
1174
+ let clientSize = elements.floating[clientProp] || rects.floating[length];
1175
+
1176
+ // DOM platform can return `window` as the `offsetParent`.
1177
+ if (!clientSize || !(await platform.isElement?.(arrowOffsetParent))) {
1178
+ clientSize = elements.floating[clientProp] || rects.floating[length];
1179
+ }
1180
+ const centerToReference = endDiff / 2 - startDiff / 2;
1181
+
1182
+ // If the padding is large enough that it causes the arrow to no longer be
1183
+ // centered, modify the padding so that it is centered.
1184
+ const largestPossiblePadding = clientSize / 2 - arrowDimensions[length] / 2 - 1;
1185
+ const minPadding = Math.min(paddingObject[minProp], largestPossiblePadding);
1186
+ const maxPadding = Math.min(paddingObject[maxProp], largestPossiblePadding);
1187
+
1188
+ // Make sure the arrow doesn't overflow the floating element if the center
1189
+ // point is outside the floating element's bounds.
1190
+ const min = minPadding;
1191
+ const max = clientSize - arrowDimensions[length] - maxPadding;
1192
+ const center = clientSize / 2 - arrowDimensions[length] / 2 + centerToReference;
1193
+ const offset = index_esm.clamp(min, center, max);
1194
+
1195
+ // If the reference is small enough that the arrow's padding causes it to
1196
+ // to point to nothing for an aligned placement, adjust the offset of the
1197
+ // floating element itself. To ensure `shift()` continues to take action,
1198
+ // a single reset is performed when this is true.
1199
+ const shouldAddOffset = !middlewareData.arrow && index_esm.getAlignment(placement) != null && center !== offset && rects.reference[length] / 2 - (center < min ? minPadding : maxPadding) - arrowDimensions[length] / 2 < 0;
1200
+ // eslint-disable-next-line no-nested-ternary
1201
+ const alignmentOffset = shouldAddOffset ? center < min ? center - min : center - max : 0;
1202
+ return {
1203
+ [axis]: coords[axis] + alignmentOffset,
1204
+ data: {
1205
+ [axis]: offset,
1206
+ centerOffset: center - offset - alignmentOffset,
1207
+ ...(shouldAddOffset && {
1208
+ alignmentOffset
1209
+ })
1210
+ },
1211
+ reset: shouldAddOffset
1212
+ };
1213
+ }
1214
+ });
1215
+
1216
+ /**
1217
+ * Provides data to position an inner element of the floating element so that it
1218
+ * appears centered to the reference element.
1219
+ * This wraps the core `arrow` middleware to allow React refs as the element.
1220
+ * @see https://floating-ui.com/docs/arrow
1221
+ */
1222
+ const arrow = (options, deps) => ({
1223
+ ...baseArrow(options),
1224
+ options: [options, deps]
1225
+ });
1226
+
1227
+ const hide = {
1228
+ name: 'hide',
1229
+ async fn(state) {
1230
+ const {
1231
+ width,
1232
+ height,
1233
+ x,
1234
+ y
1235
+ } = state.rects.reference;
1236
+ const anchorHidden = width === 0 && height === 0 && x === 0 && y === 0;
1237
+ const nativeHideResult = await floatingUi_reactDom.hide().fn(state);
1238
+ return {
1239
+ data: {
1240
+ referenceHidden: nativeHideResult.data?.referenceHidden || anchorHidden
1241
+ }
1242
+ };
1243
+ }
1244
+ };
1245
+
1246
+ const DEFAULT_SIDES = {
1247
+ sideX: 'left',
1248
+ sideY: 'top'
1249
+ };
1250
+ const adaptiveOrigin = {
1251
+ name: 'adaptiveOrigin',
1252
+ async fn(state) {
1253
+ const {
1254
+ x: rawX,
1255
+ y: rawY,
1256
+ rects: {
1257
+ floating: floatRect
1258
+ },
1259
+ elements: {
1260
+ floating
1261
+ },
1262
+ platform,
1263
+ strategy,
1264
+ placement
1265
+ } = state;
1266
+ const win = floatingUi_utils_dom.getWindow(floating);
1267
+ const styles = win.getComputedStyle(floating);
1268
+ const hasTransition = styles.transitionDuration !== '0s' && styles.transitionDuration !== '';
1269
+ if (!hasTransition) {
1270
+ return {
1271
+ x: rawX,
1272
+ y: rawY,
1273
+ data: DEFAULT_SIDES
1274
+ };
1275
+ }
1276
+ const offsetParent = await platform.getOffsetParent?.(floating);
1277
+ let offsetDimensions = {
1278
+ width: 0,
1279
+ height: 0
1280
+ };
1281
+
1282
+ // For fixed strategy, prefer visualViewport if available
1283
+ if (strategy === 'fixed' && win?.visualViewport) {
1284
+ offsetDimensions = {
1285
+ width: win.visualViewport.width,
1286
+ height: win.visualViewport.height
1287
+ };
1288
+ } else if (offsetParent === win) {
1289
+ const doc = useButton.ownerDocument(floating);
1290
+ offsetDimensions = {
1291
+ width: doc.documentElement.clientWidth,
1292
+ height: doc.documentElement.clientHeight
1293
+ };
1294
+ } else if (await platform.isElement?.(offsetParent)) {
1295
+ offsetDimensions = await platform.getDimensions(offsetParent);
1296
+ }
1297
+ const currentSide = index_esm.getSide(placement);
1298
+ let x = rawX;
1299
+ let y = rawY;
1300
+ if (currentSide === 'left') {
1301
+ x = offsetDimensions.width - (rawX + floatRect.width);
1302
+ }
1303
+ if (currentSide === 'top') {
1304
+ y = offsetDimensions.height - (rawY + floatRect.height);
1305
+ }
1306
+ const sideX = currentSide === 'left' ? 'right' : DEFAULT_SIDES.sideX;
1307
+ const sideY = currentSide === 'top' ? 'bottom' : DEFAULT_SIDES.sideY;
1308
+ return {
1309
+ x,
1310
+ y,
1311
+ data: {
1312
+ sideX,
1313
+ sideY
1314
+ }
1315
+ };
1316
+ }
1317
+ };
1318
+
1319
+ function getLogicalSide(sideParam, renderedSide, isRtl) {
1320
+ const isLogicalSideParam = sideParam === 'inline-start' || sideParam === 'inline-end';
1321
+ const logicalRight = isRtl ? 'inline-start' : 'inline-end';
1322
+ const logicalLeft = isRtl ? 'inline-end' : 'inline-start';
1323
+ return {
1324
+ top: 'top',
1325
+ right: isLogicalSideParam ? logicalRight : 'right',
1326
+ bottom: 'bottom',
1327
+ left: isLogicalSideParam ? logicalLeft : 'left'
1328
+ }[renderedSide];
1329
+ }
1330
+ function getOffsetData(state, sideParam, isRtl) {
1331
+ const {
1332
+ rects,
1333
+ placement
1334
+ } = state;
1335
+ const data = {
1336
+ side: getLogicalSide(sideParam, index_esm.getSide(placement), isRtl),
1337
+ align: index_esm.getAlignment(placement) || 'center',
1338
+ anchor: {
1339
+ width: rects.reference.width,
1340
+ height: rects.reference.height
1341
+ },
1342
+ positioner: {
1343
+ width: rects.floating.width,
1344
+ height: rects.floating.height
1345
+ }
1346
+ };
1347
+ return data;
1348
+ }
1349
+ /**
1350
+ * Provides standardized anchor positioning behavior for floating elements. Wraps Floating UI's
1351
+ * `useFloating` hook.
1352
+ */
1353
+ function useAnchorPositioning(params) {
1354
+ const {
1355
+ // Public parameters
1356
+ anchor,
1357
+ positionMethod = 'absolute',
1358
+ side: sideParam = 'bottom',
1359
+ sideOffset = 0,
1360
+ align = 'center',
1361
+ alignOffset = 0,
1362
+ collisionBoundary,
1363
+ collisionPadding: collisionPaddingParam = 5,
1364
+ sticky = false,
1365
+ arrowPadding = 5,
1366
+ disableAnchorTracking = false,
1367
+ // Private parameters
1368
+ keepMounted = false,
1369
+ floatingRootContext,
1370
+ mounted,
1371
+ collisionAvoidance,
1372
+ shiftCrossAxis = false,
1373
+ nodeId,
1374
+ adaptiveOrigin,
1375
+ lazyFlip = false,
1376
+ externalTree
1377
+ } = params;
1378
+ const [mountSide, setMountSide] = React__namespace.useState(null);
1379
+ if (!mounted && mountSide !== null) {
1380
+ setMountSide(null);
1381
+ }
1382
+ const collisionAvoidanceSide = collisionAvoidance.side || 'flip';
1383
+ const collisionAvoidanceAlign = collisionAvoidance.align || 'flip';
1384
+ const collisionAvoidanceFallbackAxisSide = collisionAvoidance.fallbackAxisSide || 'end';
1385
+ const anchorFn = typeof anchor === 'function' ? anchor : undefined;
1386
+ const anchorFnCallback = useButton.useStableCallback(anchorFn);
1387
+ const anchorDep = anchorFn ? anchorFnCallback : anchor;
1388
+ const anchorValueRef = useButton.useValueAsRef(anchor);
1389
+ const direction = InternalBackdrop.useDirection();
1390
+ const isRtl = direction === 'rtl';
1391
+ const side = mountSide || {
1392
+ top: 'top',
1393
+ right: 'right',
1394
+ bottom: 'bottom',
1395
+ left: 'left',
1396
+ 'inline-end': isRtl ? 'left' : 'right',
1397
+ 'inline-start': isRtl ? 'right' : 'left'
1398
+ }[sideParam];
1399
+ const placement = align === 'center' ? side : `${side}-${align}`;
1400
+ let collisionPadding = collisionPaddingParam;
1401
+
1402
+ // Create a bias to the preferred side.
1403
+ // On iOS, when the mobile software keyboard opens, the input is exactly centered
1404
+ // in the viewport, but this can cause it to flip to the top undesirably.
1405
+ const bias = 1;
1406
+ const biasTop = sideParam === 'bottom' ? bias : 0;
1407
+ const biasBottom = sideParam === 'top' ? bias : 0;
1408
+ const biasLeft = sideParam === 'right' ? bias : 0;
1409
+ const biasRight = sideParam === 'left' ? bias : 0;
1410
+ if (typeof collisionPadding === 'number') {
1411
+ collisionPadding = {
1412
+ top: collisionPadding + biasTop,
1413
+ right: collisionPadding + biasRight,
1414
+ bottom: collisionPadding + biasBottom,
1415
+ left: collisionPadding + biasLeft
1416
+ };
1417
+ } else if (collisionPadding) {
1418
+ collisionPadding = {
1419
+ top: (collisionPadding.top || 0) + biasTop,
1420
+ right: (collisionPadding.right || 0) + biasRight,
1421
+ bottom: (collisionPadding.bottom || 0) + biasBottom,
1422
+ left: (collisionPadding.left || 0) + biasLeft
1423
+ };
1424
+ }
1425
+ const commonCollisionProps = {
1426
+ boundary: collisionBoundary === 'clipping-ancestors' ? 'clippingAncestors' : collisionBoundary,
1427
+ padding: collisionPadding
1428
+ };
1429
+
1430
+ // Using a ref assumes that the arrow element is always present in the DOM for the lifetime of the
1431
+ // popup. If this assumption ends up being false, we can switch to state to manage the arrow's
1432
+ // presence.
1433
+ const arrowRef = React__namespace.useRef(null);
1434
+
1435
+ // Keep these reactive if they're not functions
1436
+ const sideOffsetRef = useButton.useValueAsRef(sideOffset);
1437
+ const alignOffsetRef = useButton.useValueAsRef(alignOffset);
1438
+ const sideOffsetDep = typeof sideOffset !== 'function' ? sideOffset : 0;
1439
+ const alignOffsetDep = typeof alignOffset !== 'function' ? alignOffset : 0;
1440
+ const middleware = [floatingUi_reactDom.offset(state => {
1441
+ const data = getOffsetData(state, sideParam, isRtl);
1442
+ const sideAxis = typeof sideOffsetRef.current === 'function' ? sideOffsetRef.current(data) : sideOffsetRef.current;
1443
+ const alignAxis = typeof alignOffsetRef.current === 'function' ? alignOffsetRef.current(data) : alignOffsetRef.current;
1444
+ return {
1445
+ mainAxis: sideAxis,
1446
+ crossAxis: alignAxis,
1447
+ alignmentAxis: alignAxis
1448
+ };
1449
+ }, [sideOffsetDep, alignOffsetDep, isRtl, sideParam])];
1450
+ const shiftDisabled = collisionAvoidanceAlign === 'none' && collisionAvoidanceSide !== 'shift';
1451
+ const crossAxisShiftEnabled = !shiftDisabled && (sticky || shiftCrossAxis || collisionAvoidanceSide === 'shift');
1452
+ const flipMiddleware = collisionAvoidanceSide === 'none' ? null : floatingUi_reactDom.flip({
1453
+ ...commonCollisionProps,
1454
+ // Ensure the popup flips if it's been limited by its --available-height and it resizes.
1455
+ // Since the size() padding is smaller than the flip() padding, flip() will take precedence.
1456
+ padding: {
1457
+ top: collisionPadding.top + bias,
1458
+ right: collisionPadding.right + bias,
1459
+ bottom: collisionPadding.bottom + bias,
1460
+ left: collisionPadding.left + bias
1461
+ },
1462
+ mainAxis: !shiftCrossAxis && collisionAvoidanceSide === 'flip',
1463
+ crossAxis: collisionAvoidanceAlign === 'flip' ? 'alignment' : false,
1464
+ fallbackAxisSideDirection: collisionAvoidanceFallbackAxisSide
1465
+ });
1466
+ const shiftMiddleware = shiftDisabled ? null : floatingUi_reactDom.shift(data => {
1467
+ const html = useButton.ownerDocument(data.elements.floating).documentElement;
1468
+ return {
1469
+ ...commonCollisionProps,
1470
+ // Use the Layout Viewport to avoid shifting around when pinch-zooming
1471
+ // for context menus.
1472
+ rootBoundary: shiftCrossAxis ? {
1473
+ x: 0,
1474
+ y: 0,
1475
+ width: html.clientWidth,
1476
+ height: html.clientHeight
1477
+ } : undefined,
1478
+ mainAxis: collisionAvoidanceAlign !== 'none',
1479
+ crossAxis: crossAxisShiftEnabled,
1480
+ limiter: sticky || shiftCrossAxis ? undefined : floatingUi_reactDom.limitShift(limitData => {
1481
+ if (!arrowRef.current) {
1482
+ return {};
1483
+ }
1484
+ const {
1485
+ width,
1486
+ height
1487
+ } = arrowRef.current.getBoundingClientRect();
1488
+ const sideAxis = index_esm.getSideAxis(index_esm.getSide(limitData.placement));
1489
+ const arrowSize = sideAxis === 'y' ? width : height;
1490
+ const offsetAmount = sideAxis === 'y' ? collisionPadding.left + collisionPadding.right : collisionPadding.top + collisionPadding.bottom;
1491
+ return {
1492
+ offset: arrowSize / 2 + offsetAmount / 2
1493
+ };
1494
+ })
1495
+ };
1496
+ }, [commonCollisionProps, sticky, shiftCrossAxis, collisionPadding, collisionAvoidanceAlign]);
1497
+
1498
+ // https://floating-ui.com/docs/flip#combining-with-shift
1499
+ if (collisionAvoidanceSide === 'shift' || collisionAvoidanceAlign === 'shift' || align === 'center') {
1500
+ middleware.push(shiftMiddleware, flipMiddleware);
1501
+ } else {
1502
+ middleware.push(flipMiddleware, shiftMiddleware);
1503
+ }
1504
+ middleware.push(floatingUi_reactDom.size({
1505
+ ...commonCollisionProps,
1506
+ apply({
1507
+ elements: {
1508
+ floating
1509
+ },
1510
+ availableWidth,
1511
+ availableHeight,
1512
+ rects
1513
+ }) {
1514
+ const floatingStyle = floating.style;
1515
+ floatingStyle.setProperty('--available-width', `${availableWidth}px`);
1516
+ floatingStyle.setProperty('--available-height', `${availableHeight}px`);
1517
+
1518
+ // Snap anchor dimensions to device pixels to ensure the popup's visual width matches the anchor's one.
1519
+ const dpr = window.devicePixelRatio || 1;
1520
+ const {
1521
+ x,
1522
+ y,
1523
+ width,
1524
+ height
1525
+ } = rects.reference;
1526
+ const anchorWidth = (Math.round((x + width) * dpr) - Math.round(x * dpr)) / dpr;
1527
+ const anchorHeight = (Math.round((y + height) * dpr) - Math.round(y * dpr)) / dpr;
1528
+ floatingStyle.setProperty('--anchor-width', `${anchorWidth}px`);
1529
+ floatingStyle.setProperty('--anchor-height', `${anchorHeight}px`);
1530
+ }
1531
+ }), arrow(() => ({
1532
+ // `transform-origin` calculations rely on an element existing. If the arrow hasn't been set,
1533
+ // we'll create a fake element.
1534
+ element: arrowRef.current || document.createElement('div'),
1535
+ padding: arrowPadding,
1536
+ offsetParent: 'floating'
1537
+ }), [arrowPadding]), {
1538
+ name: 'transformOrigin',
1539
+ fn(state) {
1540
+ const {
1541
+ elements,
1542
+ middlewareData,
1543
+ placement: renderedPlacement,
1544
+ rects,
1545
+ y
1546
+ } = state;
1547
+ const currentRenderedSide = index_esm.getSide(renderedPlacement);
1548
+ const currentRenderedAxis = index_esm.getSideAxis(currentRenderedSide);
1549
+ const arrowEl = arrowRef.current;
1550
+ const arrowX = middlewareData.arrow?.x || 0;
1551
+ const arrowY = middlewareData.arrow?.y || 0;
1552
+ const arrowWidth = arrowEl?.clientWidth || 0;
1553
+ const arrowHeight = arrowEl?.clientHeight || 0;
1554
+ const transformX = arrowX + arrowWidth / 2;
1555
+ const transformY = arrowY + arrowHeight / 2;
1556
+ const shiftY = Math.abs(middlewareData.shift?.y || 0);
1557
+ const halfAnchorHeight = rects.reference.height / 2;
1558
+ const sideOffsetValue = typeof sideOffset === 'function' ? sideOffset(getOffsetData(state, sideParam, isRtl)) : sideOffset;
1559
+ const isOverlappingAnchor = shiftY > sideOffsetValue;
1560
+ const adjacentTransformOrigin = {
1561
+ top: `${transformX}px calc(100% + ${sideOffsetValue}px)`,
1562
+ bottom: `${transformX}px ${-sideOffsetValue}px`,
1563
+ left: `calc(100% + ${sideOffsetValue}px) ${transformY}px`,
1564
+ right: `${-sideOffsetValue}px ${transformY}px`
1565
+ }[currentRenderedSide];
1566
+ const overlapTransformOrigin = `${transformX}px ${rects.reference.y + halfAnchorHeight - y}px`;
1567
+ elements.floating.style.setProperty('--transform-origin', crossAxisShiftEnabled && currentRenderedAxis === 'y' && isOverlappingAnchor ? overlapTransformOrigin : adjacentTransformOrigin);
1568
+ return {};
1569
+ }
1570
+ }, hide, adaptiveOrigin);
1571
+ useButton.useIsoLayoutEffect(() => {
1572
+ // Ensure positioning doesn't run initially for `keepMounted` elements that
1573
+ // aren't initially open.
1574
+ if (!mounted && floatingRootContext) {
1575
+ floatingRootContext.update({
1576
+ referenceElement: null,
1577
+ floatingElement: null,
1578
+ domReferenceElement: null
1579
+ });
1580
+ }
1581
+ }, [mounted, floatingRootContext]);
1582
+ const autoUpdateOptions = React__namespace.useMemo(() => ({
1583
+ elementResize: !disableAnchorTracking && typeof ResizeObserver !== 'undefined',
1584
+ layoutShift: !disableAnchorTracking && typeof IntersectionObserver !== 'undefined'
1585
+ }), [disableAnchorTracking]);
1586
+ const {
1587
+ refs,
1588
+ elements,
1589
+ x,
1590
+ y,
1591
+ middlewareData,
1592
+ update,
1593
+ placement: renderedPlacement,
1594
+ context,
1595
+ isPositioned,
1596
+ floatingStyles: originalFloatingStyles
1597
+ } = useFloating({
1598
+ rootContext: floatingRootContext,
1599
+ placement,
1600
+ middleware,
1601
+ strategy: positionMethod,
1602
+ whileElementsMounted: keepMounted ? undefined : (...args) => floatingUi_reactDom.autoUpdate(...args, autoUpdateOptions),
1603
+ nodeId,
1604
+ externalTree
1605
+ });
1606
+ const {
1607
+ sideX,
1608
+ sideY
1609
+ } = middlewareData.adaptiveOrigin || DEFAULT_SIDES;
1610
+
1611
+ // Default to `fixed` when not positioned to prevent `autoFocus` scroll jumps.
1612
+ // This ensures the popup is inside the viewport initially before it gets positioned.
1613
+ const resolvedPosition = isPositioned ? positionMethod : 'fixed';
1614
+ const floatingStyles = React__namespace.useMemo(() => {
1615
+ const base = adaptiveOrigin ? {
1616
+ position: resolvedPosition,
1617
+ [sideX]: x,
1618
+ [sideY]: y
1619
+ } : {
1620
+ position: resolvedPosition,
1621
+ ...originalFloatingStyles
1622
+ };
1623
+ if (!isPositioned) {
1624
+ base.opacity = 0;
1625
+ }
1626
+ return base;
1627
+ }, [adaptiveOrigin, resolvedPosition, sideX, x, sideY, y, originalFloatingStyles, isPositioned]);
1628
+ const registeredPositionReferenceRef = React__namespace.useRef(null);
1629
+ useButton.useIsoLayoutEffect(() => {
1630
+ if (!mounted) {
1631
+ return;
1632
+ }
1633
+ const anchorValue = anchorValueRef.current;
1634
+ const resolvedAnchor = typeof anchorValue === 'function' ? anchorValue() : anchorValue;
1635
+ const unwrappedElement = (isRef(resolvedAnchor) ? resolvedAnchor.current : resolvedAnchor) || null;
1636
+ const finalAnchor = unwrappedElement || null;
1637
+ if (finalAnchor !== registeredPositionReferenceRef.current) {
1638
+ refs.setPositionReference(finalAnchor);
1639
+ registeredPositionReferenceRef.current = finalAnchor;
1640
+ }
1641
+ }, [mounted, refs, anchorDep, anchorValueRef]);
1642
+ React__namespace.useEffect(() => {
1643
+ if (!mounted) {
1644
+ return;
1645
+ }
1646
+ const anchorValue = anchorValueRef.current;
1647
+
1648
+ // Refs from parent components are set after useLayoutEffect runs and are available in useEffect.
1649
+ // Therefore, if the anchor is a ref, we need to update the position reference in useEffect.
1650
+ if (typeof anchorValue === 'function') {
1651
+ return;
1652
+ }
1653
+ if (isRef(anchorValue) && anchorValue.current !== registeredPositionReferenceRef.current) {
1654
+ refs.setPositionReference(anchorValue.current);
1655
+ registeredPositionReferenceRef.current = anchorValue.current;
1656
+ }
1657
+ }, [mounted, refs, anchorDep, anchorValueRef]);
1658
+ React__namespace.useEffect(() => {
1659
+ if (keepMounted && mounted && elements.domReference && elements.floating) {
1660
+ return floatingUi_reactDom.autoUpdate(elements.domReference, elements.floating, update, autoUpdateOptions);
1661
+ }
1662
+ return undefined;
1663
+ }, [keepMounted, mounted, elements, update, autoUpdateOptions]);
1664
+ const renderedSide = index_esm.getSide(renderedPlacement);
1665
+ const logicalRenderedSide = getLogicalSide(sideParam, renderedSide, isRtl);
1666
+ const renderedAlign = index_esm.getAlignment(renderedPlacement) || 'center';
1667
+ const anchorHidden = Boolean(middlewareData.hide?.referenceHidden);
1668
+
1669
+ /**
1670
+ * Locks the flip (makes it "sticky") so it doesn't prefer a given placement
1671
+ * and flips back lazily, not eagerly. Ideal for filtered lists that change
1672
+ * the size of the popup dynamically to avoid unwanted flipping when typing.
1673
+ */
1674
+ useButton.useIsoLayoutEffect(() => {
1675
+ if (lazyFlip && mounted && isPositioned) {
1676
+ setMountSide(renderedSide);
1677
+ }
1678
+ }, [lazyFlip, mounted, isPositioned, renderedSide]);
1679
+ const arrowStyles = React__namespace.useMemo(() => ({
1680
+ position: 'absolute',
1681
+ top: middlewareData.arrow?.y,
1682
+ left: middlewareData.arrow?.x
1683
+ }), [middlewareData.arrow]);
1684
+ const arrowUncentered = middlewareData.arrow?.centerOffset !== 0;
1685
+ return React__namespace.useMemo(() => ({
1686
+ positionerStyles: floatingStyles,
1687
+ arrowStyles,
1688
+ arrowRef,
1689
+ arrowUncentered,
1690
+ side: logicalRenderedSide,
1691
+ align: renderedAlign,
1692
+ physicalSide: renderedSide,
1693
+ anchorHidden,
1694
+ refs,
1695
+ context,
1696
+ isPositioned,
1697
+ update
1698
+ }), [floatingStyles, arrowStyles, arrowRef, arrowUncentered, logicalRenderedSide, renderedAlign, renderedSide, anchorHidden, refs, context, isPositioned, update]);
1699
+ }
1700
+ function isRef(param) {
1701
+ return param != null && 'current' in param;
1702
+ }
1703
+
1704
+ function getDisabledMountTransitionStyles(transitionStatus) {
1705
+ return transitionStatus === 'starting' ? InternalBackdrop.DISABLED_TRANSITIONS_STYLE : useRenderElement.EMPTY_OBJECT;
1706
+ }
1707
+
1708
+ let IndexGuessBehavior = /*#__PURE__*/function (IndexGuessBehavior) {
1709
+ IndexGuessBehavior[IndexGuessBehavior["None"] = 0] = "None";
1710
+ IndexGuessBehavior[IndexGuessBehavior["GuessFromOrder"] = 1] = "GuessFromOrder";
1711
+ return IndexGuessBehavior;
1712
+ }({});
1713
+
1714
+ /**
1715
+ * Used to register a list item and its index (DOM position) in the `CompositeList`.
1716
+ */
1717
+ function useCompositeListItem(params = {}) {
1718
+ const {
1719
+ label,
1720
+ metadata,
1721
+ textRef,
1722
+ indexGuessBehavior,
1723
+ index: externalIndex
1724
+ } = params;
1725
+ const {
1726
+ register,
1727
+ unregister,
1728
+ subscribeMapChange,
1729
+ elementsRef,
1730
+ labelsRef,
1731
+ nextIndexRef
1732
+ } = useCompositeListContext();
1733
+ const indexRef = React__namespace.useRef(-1);
1734
+ const [index, setIndex] = React__namespace.useState(externalIndex ?? (indexGuessBehavior === IndexGuessBehavior.GuessFromOrder ? () => {
1735
+ if (indexRef.current === -1) {
1736
+ const newIndex = nextIndexRef.current;
1737
+ nextIndexRef.current += 1;
1738
+ indexRef.current = newIndex;
1739
+ }
1740
+ return indexRef.current;
1741
+ } : -1));
1742
+ const componentRef = React__namespace.useRef(null);
1743
+ const ref = React__namespace.useCallback(node => {
1744
+ componentRef.current = node;
1745
+ if (index !== -1 && node !== null) {
1746
+ elementsRef.current[index] = node;
1747
+ if (labelsRef) {
1748
+ const isLabelDefined = label !== undefined;
1749
+ labelsRef.current[index] = isLabelDefined ? label : textRef?.current?.textContent ?? node.textContent;
1750
+ }
1751
+ }
1752
+ }, [index, elementsRef, labelsRef, label, textRef]);
1753
+ useButton.useIsoLayoutEffect(() => {
1754
+ if (externalIndex != null) {
1755
+ return undefined;
1756
+ }
1757
+ const node = componentRef.current;
1758
+ if (node) {
1759
+ register(node, metadata);
1760
+ return () => {
1761
+ unregister(node);
1762
+ };
1763
+ }
1764
+ return undefined;
1765
+ }, [externalIndex, register, unregister, metadata]);
1766
+ useButton.useIsoLayoutEffect(() => {
1767
+ if (externalIndex != null) {
1768
+ return undefined;
1769
+ }
1770
+ return subscribeMapChange(map => {
1771
+ const i = componentRef.current ? map.get(componentRef.current)?.index : null;
1772
+ if (i != null) {
1773
+ setIndex(i);
1774
+ }
1775
+ });
1776
+ }, [externalIndex, subscribeMapChange, setIndex]);
1777
+ return React__namespace.useMemo(() => ({
1778
+ ref,
1779
+ index
1780
+ }), [index, ref]);
1781
+ }
1782
+
1783
+ exports.CompositeList = CompositeList;
1784
+ exports.IndexGuessBehavior = IndexGuessBehavior;
1785
+ exports.adaptiveOrigin = adaptiveOrigin;
1786
+ exports.getDisabledMountTransitionStyles = getDisabledMountTransitionStyles;
1787
+ exports.getPseudoElementBounds = getPseudoElementBounds;
1788
+ exports.useAnchorPositioning = useAnchorPositioning;
1789
+ exports.useCompositeListItem = useCompositeListItem;
1790
+ exports.useFloatingRootContext = useFloatingRootContext;
1791
+ exports.useListNavigation = useListNavigation;
1792
+ exports.useTypeahead = useTypeahead;