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