-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathmenu.tsx
1178 lines (1039 loc) · 35.3 KB
/
menu.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use client'
// WAI-ARIA: https://www.w3.org/WAI/ARIA/apg/patterns/menubutton/
import { useFocusRing } from '@react-aria/focus'
import { useHover } from '@react-aria/interactions'
import React, {
Fragment,
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useReducer,
useRef,
useState,
type CSSProperties,
type Dispatch,
type ElementType,
type MutableRefObject,
type KeyboardEvent as ReactKeyboardEvent,
type MouseEvent as ReactMouseEvent,
type Ref,
} from 'react'
import { flushSync } from 'react-dom'
import { useActivePress } from '../../hooks/use-active-press'
import { useDidElementMove } from '../../hooks/use-did-element-move'
import { useDisposables } from '../../hooks/use-disposables'
import { useElementSize } from '../../hooks/use-element-size'
import { useEvent } from '../../hooks/use-event'
import { useId } from '../../hooks/use-id'
import { useInertOthers } from '../../hooks/use-inert-others'
import { useIsoMorphicEffect } from '../../hooks/use-iso-morphic-effect'
import { useOnDisappear } from '../../hooks/use-on-disappear'
import { useOutsideClick } from '../../hooks/use-outside-click'
import { useOwnerDocument } from '../../hooks/use-owner'
import { useResolveButtonType } from '../../hooks/use-resolve-button-type'
import { useScrollLock } from '../../hooks/use-scroll-lock'
import { useSyncRefs } from '../../hooks/use-sync-refs'
import { useTextValue } from '../../hooks/use-text-value'
import { useTrackedPointer } from '../../hooks/use-tracked-pointer'
import { transitionDataAttributes, useTransition } from '../../hooks/use-transition'
import { useTreeWalker } from '../../hooks/use-tree-walker'
import {
FloatingProvider,
useFloatingPanel,
useFloatingPanelProps,
useFloatingReference,
useFloatingReferenceProps,
useResolvedAnchor,
type AnchorProps,
} from '../../internal/floating'
import { OpenClosedProvider, State, useOpenClosed } from '../../internal/open-closed'
import type { Props } from '../../types'
import { isDisabledReactIssue7711 } from '../../utils/bugs'
import { Focus, calculateActiveIndex } from '../../utils/calculate-active-index'
import { disposables } from '../../utils/disposables'
import {
Focus as FocusManagementFocus,
FocusableMode,
focusFrom,
isFocusableElement,
restoreFocusIfNecessary,
sortByDomNode,
} from '../../utils/focus-management'
import { match } from '../../utils/match'
import {
RenderFeatures,
forwardRefWithAs,
mergeProps,
useRender,
type HasDisplayName,
type RefProp,
} from '../../utils/render'
import { useDescriptions } from '../description/description'
import { Keys } from '../keyboard'
import { useLabelContext, useLabels } from '../label/label'
import { Portal } from '../portal/portal'
enum MenuStates {
Open,
Closed,
}
enum ActivationTrigger {
Pointer,
Other,
}
type MenuItemDataRef = MutableRefObject<{
textValue?: string
disabled: boolean
domRef: MutableRefObject<HTMLElement | null>
}>
interface StateDefinition {
__demoMode: boolean
menuState: MenuStates
buttonElement: HTMLButtonElement | null
itemsElement: HTMLElement | null
items: { id: string; dataRef: MenuItemDataRef }[]
searchQuery: string
activeItemIndex: number | null
activationTrigger: ActivationTrigger
}
enum ActionTypes {
OpenMenu,
CloseMenu,
GoToItem,
Search,
ClearSearch,
RegisterItem,
UnregisterItem,
SetButtonElement,
SetItemsElement,
}
function adjustOrderedState(
state: StateDefinition,
adjustment: (items: StateDefinition['items']) => StateDefinition['items'] = (i) => i
) {
let currentActiveItem = state.activeItemIndex !== null ? state.items[state.activeItemIndex] : null
let sortedItems = sortByDomNode(
adjustment(state.items.slice()),
(item) => item.dataRef.current.domRef.current
)
// If we inserted an item before the current active item then the active item index
// would be wrong. To fix this, we will re-lookup the correct index.
let adjustedActiveItemIndex = currentActiveItem ? sortedItems.indexOf(currentActiveItem) : null
// Reset to `null` in case the currentActiveItem was removed.
if (adjustedActiveItemIndex === -1) {
adjustedActiveItemIndex = null
}
return {
items: sortedItems,
activeItemIndex: adjustedActiveItemIndex,
}
}
type Actions =
| { type: ActionTypes.CloseMenu }
| { type: ActionTypes.OpenMenu }
| { type: ActionTypes.GoToItem; focus: Focus.Specific; id: string; trigger?: ActivationTrigger }
| {
type: ActionTypes.GoToItem
focus: Exclude<Focus, Focus.Specific>
trigger?: ActivationTrigger
}
| { type: ActionTypes.Search; value: string }
| { type: ActionTypes.ClearSearch }
| { type: ActionTypes.RegisterItem; id: string; dataRef: MenuItemDataRef }
| { type: ActionTypes.UnregisterItem; id: string }
| { type: ActionTypes.SetButtonElement; element: HTMLButtonElement | null }
| { type: ActionTypes.SetItemsElement; element: HTMLElement | null }
let reducers: {
[P in ActionTypes]: (
state: StateDefinition,
action: Extract<Actions, { type: P }>
) => StateDefinition
} = {
[ActionTypes.CloseMenu](state) {
if (state.menuState === MenuStates.Closed) return state
return { ...state, activeItemIndex: null, menuState: MenuStates.Closed }
},
[ActionTypes.OpenMenu](state) {
if (state.menuState === MenuStates.Open) return state
return {
...state,
/* We can turn off demo mode once we re-open the `Menu` */
__demoMode: false,
menuState: MenuStates.Open,
}
},
[ActionTypes.GoToItem]: (state, action) => {
if (state.menuState === MenuStates.Closed) return state
let base = {
...state,
searchQuery: '',
activationTrigger: action.trigger ?? ActivationTrigger.Other,
__demoMode: false,
}
// Optimization:
//
// There is no need to sort the DOM nodes if we know that we don't want to focus anything
if (action.focus === Focus.Nothing) {
return {
...base,
activeItemIndex: null,
}
}
// Optimization:
//
// There is no need to sort the DOM nodes if we know exactly where to go
if (action.focus === Focus.Specific) {
return {
...base,
activeItemIndex: state.items.findIndex((o) => o.id === action.id),
}
}
// Optimization:
//
// If the current DOM node and the previous DOM node are next to each other,
// or if the previous DOM node is already the first DOM node, then we don't
// have to sort all the DOM nodes.
else if (action.focus === Focus.Previous) {
let activeItemIdx = state.activeItemIndex
if (activeItemIdx !== null) {
let currentDom = state.items[activeItemIdx].dataRef.current.domRef
let previousItemIndex = calculateActiveIndex(action, {
resolveItems: () => state.items,
resolveActiveIndex: () => state.activeItemIndex,
resolveId: (item) => item.id,
resolveDisabled: (item) => item.dataRef.current.disabled,
})
if (previousItemIndex !== null) {
let previousDom = state.items[previousItemIndex].dataRef.current.domRef
if (
// Next to each other
currentDom.current?.previousElementSibling === previousDom.current ||
// Or already the first element
previousDom.current?.previousElementSibling === null
) {
return {
...base,
activeItemIndex: previousItemIndex,
}
}
}
}
}
// Optimization:
//
// If the current DOM node and the next DOM node are next to each other, or
// if the next DOM node is already the last DOM node, then we don't have to
// sort all the DOM nodes.
else if (action.focus === Focus.Next) {
let activeItemIdx = state.activeItemIndex
if (activeItemIdx !== null) {
let currentDom = state.items[activeItemIdx].dataRef.current.domRef
let nextItemIndex = calculateActiveIndex(action, {
resolveItems: () => state.items,
resolveActiveIndex: () => state.activeItemIndex,
resolveId: (item) => item.id,
resolveDisabled: (item) => item.dataRef.current.disabled,
})
if (nextItemIndex !== null) {
let nextDom = state.items[nextItemIndex].dataRef.current.domRef
if (
// Next to each other
currentDom.current?.nextElementSibling === nextDom.current ||
// Or already the last element
nextDom.current?.nextElementSibling === null
) {
return {
...base,
activeItemIndex: nextItemIndex,
}
}
}
}
}
// Slow path:
//
// Ensure all the items are correctly sorted according to DOM position
let adjustedState = adjustOrderedState(state)
let activeItemIndex = calculateActiveIndex(action, {
resolveItems: () => adjustedState.items,
resolveActiveIndex: () => adjustedState.activeItemIndex,
resolveId: (item) => item.id,
resolveDisabled: (item) => item.dataRef.current.disabled,
})
return {
...base,
...adjustedState,
activeItemIndex,
}
},
[ActionTypes.Search]: (state, action) => {
let wasAlreadySearching = state.searchQuery !== ''
let offset = wasAlreadySearching ? 0 : 1
let searchQuery = state.searchQuery + action.value.toLowerCase()
let reOrderedItems =
state.activeItemIndex !== null
? state.items
.slice(state.activeItemIndex + offset)
.concat(state.items.slice(0, state.activeItemIndex + offset))
: state.items
let matchingItem = reOrderedItems.find(
(item) =>
item.dataRef.current.textValue?.startsWith(searchQuery) && !item.dataRef.current.disabled
)
let matchIdx = matchingItem ? state.items.indexOf(matchingItem) : -1
if (matchIdx === -1 || matchIdx === state.activeItemIndex) return { ...state, searchQuery }
return {
...state,
searchQuery,
activeItemIndex: matchIdx,
activationTrigger: ActivationTrigger.Other,
}
},
[ActionTypes.ClearSearch](state) {
if (state.searchQuery === '') return state
return { ...state, searchQuery: '', searchActiveItemIndex: null }
},
[ActionTypes.RegisterItem]: (state, action) => {
let adjustedState = adjustOrderedState(state, (items) => [
...items,
{ id: action.id, dataRef: action.dataRef },
])
return { ...state, ...adjustedState }
},
[ActionTypes.UnregisterItem]: (state, action) => {
let adjustedState = adjustOrderedState(state, (items) => {
let idx = items.findIndex((a) => a.id === action.id)
if (idx !== -1) items.splice(idx, 1)
return items
})
return {
...state,
...adjustedState,
activationTrigger: ActivationTrigger.Other,
}
},
[ActionTypes.SetButtonElement]: (state, action) => {
if (state.buttonElement === action.element) return state
return { ...state, buttonElement: action.element }
},
[ActionTypes.SetItemsElement]: (state, action) => {
if (state.itemsElement === action.element) return state
return { ...state, itemsElement: action.element }
},
}
let MenuContext = createContext<[StateDefinition, Dispatch<Actions>] | null>(null)
MenuContext.displayName = 'MenuContext'
function useMenuContext(component: string) {
let context = useContext(MenuContext)
if (context === null) {
let err = new Error(`<${component} /> is missing a parent <Menu /> component.`)
if (Error.captureStackTrace) Error.captureStackTrace(err, useMenuContext)
throw err
}
return context
}
function stateReducer(state: StateDefinition, action: Actions) {
return match(action.type, reducers, state, action)
}
// ---
let DEFAULT_MENU_TAG = Fragment
type MenuRenderPropArg = {
open: boolean
close: () => void
}
type MenuPropsWeControl = never
export type MenuProps<TTag extends ElementType = typeof DEFAULT_MENU_TAG> = Props<
TTag,
MenuRenderPropArg,
MenuPropsWeControl,
{
__demoMode?: boolean
outsideClickScope?: string
}
>
function MenuFn<TTag extends ElementType = typeof DEFAULT_MENU_TAG>(
props: MenuProps<TTag>,
ref: Ref<HTMLElement>
) {
let { __demoMode = false, outsideClickScope, ...theirProps } = props
let reducerBag = useReducer(stateReducer, {
__demoMode,
menuState: __demoMode ? MenuStates.Open : MenuStates.Closed,
buttonElement: null,
itemsElement: null,
items: [],
searchQuery: '',
activeItemIndex: null,
activationTrigger: ActivationTrigger.Other,
} as StateDefinition)
let [{ menuState, itemsElement, buttonElement }, dispatch] = reducerBag
let menuRef = useSyncRefs(ref)
// Handle outside click
let outsideClickEnabled = menuState === MenuStates.Open
useOutsideClick(
outsideClickEnabled,
[buttonElement, itemsElement],
(event, target) => {
dispatch({ type: ActionTypes.CloseMenu })
if (!isFocusableElement(target, FocusableMode.Loose)) {
event.preventDefault()
buttonElement?.focus()
}
},
outsideClickScope
)
let close = useEvent(() => {
dispatch({ type: ActionTypes.CloseMenu })
})
let slot = useMemo(
() => ({ open: menuState === MenuStates.Open, close }) satisfies MenuRenderPropArg,
[menuState, close]
)
let ourProps = { ref: menuRef }
let render = useRender()
return (
<FloatingProvider>
<MenuContext.Provider value={reducerBag}>
<OpenClosedProvider
value={match(menuState, {
[MenuStates.Open]: State.Open,
[MenuStates.Closed]: State.Closed,
})}
>
{render({
ourProps,
theirProps,
slot,
defaultTag: DEFAULT_MENU_TAG,
name: 'Menu',
})}
</OpenClosedProvider>
</MenuContext.Provider>
</FloatingProvider>
)
}
// ---
let DEFAULT_BUTTON_TAG = 'button' as const
type ButtonRenderPropArg = {
open: boolean
active: boolean
hover: boolean
focus: boolean
disabled: boolean
autofocus: boolean
}
type ButtonPropsWeControl = 'aria-controls' | 'aria-expanded' | 'aria-haspopup'
export type MenuButtonProps<TTag extends ElementType = typeof DEFAULT_BUTTON_TAG> = Props<
TTag,
ButtonRenderPropArg,
ButtonPropsWeControl,
{
disabled?: boolean
autoFocus?: boolean
}
>
function ButtonFn<TTag extends ElementType = typeof DEFAULT_BUTTON_TAG>(
props: MenuButtonProps<TTag>,
ref: Ref<HTMLButtonElement>
) {
let internalId = useId()
let {
id = `headlessui-menu-button-${internalId}`,
disabled = false,
autoFocus = false,
...theirProps
} = props
let [state, dispatch] = useMenuContext('Menu.Button')
let getFloatingReferenceProps = useFloatingReferenceProps()
let buttonRef = useSyncRefs(
ref,
useFloatingReference(),
useEvent((element) => dispatch({ type: ActionTypes.SetButtonElement, element }))
)
let handleKeyDown = useEvent((event: ReactKeyboardEvent<HTMLButtonElement>) => {
switch (event.key) {
// Ref: https://www.w3.org/WAI/ARIA/apg/patterns/menubutton/#keyboard-interaction-13
case Keys.Space:
case Keys.Enter:
case Keys.ArrowDown:
event.preventDefault()
event.stopPropagation()
flushSync(() => dispatch({ type: ActionTypes.OpenMenu }))
dispatch({ type: ActionTypes.GoToItem, focus: Focus.First })
break
case Keys.ArrowUp:
event.preventDefault()
event.stopPropagation()
flushSync(() => dispatch({ type: ActionTypes.OpenMenu }))
dispatch({ type: ActionTypes.GoToItem, focus: Focus.Last })
break
}
})
let handleKeyUp = useEvent((event: ReactKeyboardEvent<HTMLButtonElement>) => {
switch (event.key) {
case Keys.Space:
// Required for firefox, event.preventDefault() in handleKeyDown for
// the Space key doesn't cancel the handleKeyUp, which in turn
// triggers a *click*.
event.preventDefault()
break
}
})
let handleClick = useEvent((event: ReactMouseEvent) => {
if (isDisabledReactIssue7711(event.currentTarget)) return event.preventDefault()
if (disabled) return
if (state.menuState === MenuStates.Open) {
flushSync(() => dispatch({ type: ActionTypes.CloseMenu }))
state.buttonElement?.focus({ preventScroll: true })
} else {
event.preventDefault()
dispatch({ type: ActionTypes.OpenMenu })
}
})
let { isFocusVisible: focus, focusProps } = useFocusRing({ autoFocus })
let { isHovered: hover, hoverProps } = useHover({ isDisabled: disabled })
let { pressed: active, pressProps } = useActivePress({ disabled })
let slot = useMemo(() => {
return {
open: state.menuState === MenuStates.Open,
active: active || state.menuState === MenuStates.Open,
disabled,
hover,
focus,
autofocus: autoFocus,
} satisfies ButtonRenderPropArg
}, [state, hover, focus, active, disabled, autoFocus])
let ourProps = mergeProps(
getFloatingReferenceProps(),
{
ref: buttonRef,
id,
type: useResolveButtonType(props, state.buttonElement),
'aria-haspopup': 'menu',
'aria-controls': state.itemsElement?.id,
'aria-expanded': state.menuState === MenuStates.Open,
disabled: disabled || undefined,
autoFocus,
onKeyDown: handleKeyDown,
onKeyUp: handleKeyUp,
onClick: handleClick,
},
focusProps,
hoverProps,
pressProps
)
let render = useRender()
return render({
ourProps,
theirProps,
slot,
defaultTag: DEFAULT_BUTTON_TAG,
name: 'Menu.Button',
})
}
// ---
let DEFAULT_ITEMS_TAG = 'div' as const
type ItemsRenderPropArg = {
open: boolean
}
type ItemsPropsWeControl = 'aria-activedescendant' | 'aria-labelledby' | 'role' | 'tabIndex'
let ItemsRenderFeatures = RenderFeatures.RenderStrategy | RenderFeatures.Static
export type MenuItemsProps<TTag extends ElementType = typeof DEFAULT_ITEMS_TAG> = Props<
TTag,
ItemsRenderPropArg,
ItemsPropsWeControl,
{
anchor?: AnchorProps
portal?: boolean
modal?: boolean
transition?: boolean
// ItemsRenderFeatures
static?: boolean
unmount?: boolean
}
>
function ItemsFn<TTag extends ElementType = typeof DEFAULT_ITEMS_TAG>(
props: MenuItemsProps<TTag>,
ref: Ref<HTMLElement>
) {
let internalId = useId()
let {
id = `headlessui-menu-items-${internalId}`,
anchor: rawAnchor,
portal = false,
modal = true,
transition = false,
...theirProps
} = props
let anchor = useResolvedAnchor(rawAnchor)
let [state, dispatch] = useMenuContext('Menu.Items')
let [floatingRef, style] = useFloatingPanel(anchor)
let getFloatingPanelProps = useFloatingPanelProps()
// To improve the correctness of transitions (timing related race conditions),
// we track the element locally to this component, instead of relying on the
// context value. This way, the component can re-render independently of the
// parent component when the `useTransition(…)` hook performs a state change.
let [localItemsElement, setLocalItemsElement] = useState<HTMLElement | null>(null)
let itemsRef = useSyncRefs(
ref,
anchor ? floatingRef : null,
useEvent((element) => dispatch({ type: ActionTypes.SetItemsElement, element })),
setLocalItemsElement
)
let portalOwnerDocument = useOwnerDocument(state.buttonElement)
let ownerDocument = useOwnerDocument(state.itemsElement)
// Always enable `portal` functionality, when `anchor` is enabled
if (anchor) {
portal = true
}
let usesOpenClosedState = useOpenClosed()
let [visible, transitionData] = useTransition(
transition,
localItemsElement,
usesOpenClosedState !== null
? (usesOpenClosedState & State.Open) === State.Open
: state.menuState === MenuStates.Open
)
// Ensure we close the menu as soon as the button becomes hidden
useOnDisappear(visible, state.buttonElement, () => {
dispatch({ type: ActionTypes.CloseMenu })
})
// Enable scroll locking when the menu is visible, and `modal` is enabled
let scrollLockEnabled = state.__demoMode ? false : modal && state.menuState === MenuStates.Open
useScrollLock(scrollLockEnabled, ownerDocument)
// Mark other elements as inert when the menu is visible, and `modal` is enabled
let inertOthersEnabled = state.__demoMode ? false : modal && state.menuState === MenuStates.Open
useInertOthers(inertOthersEnabled, {
allowed: useCallback(
() => [state.buttonElement, state.itemsElement],
[state.buttonElement, state.itemsElement]
),
})
// We keep track whether the button moved or not, we only check this when the menu state becomes
// closed. If the button moved, then we want to cancel pending transitions to prevent that the
// attached `MenuItems` is still transitioning while the button moved away.
//
// If we don't cancel these transitions then there will be a period where the `MenuItems` is
// visible and moving around because it is trying to re-position itself based on the new position.
//
// This can be solved by only transitioning the `opacity` instead of everything, but if you _do_
// want to transition the y-axis for example you will run into the same issue again.
let didButtonMoveEnabled = state.menuState !== MenuStates.Open
let didButtonMove = useDidElementMove(didButtonMoveEnabled, state.buttonElement)
// Now that we know that the button did move or not, we can either disable the panel and all of
// its transitions, or rely on the `visible` state to hide the panel whenever necessary.
let panelEnabled = didButtonMove ? false : visible
useEffect(() => {
let container = state.itemsElement
if (!container) return
if (state.menuState !== MenuStates.Open) return
if (container === ownerDocument?.activeElement) return
container.focus({ preventScroll: true })
}, [state.menuState, state.itemsElement, ownerDocument])
useTreeWalker(state.menuState === MenuStates.Open, {
container: state.itemsElement,
accept(node) {
if (node.getAttribute('role') === 'menuitem') return NodeFilter.FILTER_REJECT
if (node.hasAttribute('role')) return NodeFilter.FILTER_SKIP
return NodeFilter.FILTER_ACCEPT
},
walk(node) {
node.setAttribute('role', 'none')
},
})
let searchDisposables = useDisposables()
let handleKeyDown = useEvent((event: ReactKeyboardEvent<HTMLElement>) => {
searchDisposables.dispose()
switch (event.key) {
// Ref: https://www.w3.org/WAI/ARIA/apg/patterns/menu/#keyboard-interaction-12
// @ts-expect-error Fallthrough is expected here
case Keys.Space:
if (state.searchQuery !== '') {
event.preventDefault()
event.stopPropagation()
return dispatch({ type: ActionTypes.Search, value: event.key })
}
// When in type ahead mode, fallthrough
case Keys.Enter:
event.preventDefault()
event.stopPropagation()
dispatch({ type: ActionTypes.CloseMenu })
if (state.activeItemIndex !== null) {
let { dataRef } = state.items[state.activeItemIndex]
dataRef.current?.domRef.current?.click()
}
restoreFocusIfNecessary(state.buttonElement)
break
case Keys.ArrowDown:
event.preventDefault()
event.stopPropagation()
return dispatch({ type: ActionTypes.GoToItem, focus: Focus.Next })
case Keys.ArrowUp:
event.preventDefault()
event.stopPropagation()
return dispatch({ type: ActionTypes.GoToItem, focus: Focus.Previous })
case Keys.Home:
case Keys.PageUp:
event.preventDefault()
event.stopPropagation()
return dispatch({ type: ActionTypes.GoToItem, focus: Focus.First })
case Keys.End:
case Keys.PageDown:
event.preventDefault()
event.stopPropagation()
return dispatch({ type: ActionTypes.GoToItem, focus: Focus.Last })
case Keys.Escape:
event.preventDefault()
event.stopPropagation()
flushSync(() => dispatch({ type: ActionTypes.CloseMenu }))
state.buttonElement?.focus({ preventScroll: true })
break
case Keys.Tab:
event.preventDefault()
event.stopPropagation()
flushSync(() => dispatch({ type: ActionTypes.CloseMenu }))
focusFrom(
state.buttonElement!,
event.shiftKey ? FocusManagementFocus.Previous : FocusManagementFocus.Next
)
break
default:
if (event.key.length === 1) {
dispatch({ type: ActionTypes.Search, value: event.key })
searchDisposables.setTimeout(() => dispatch({ type: ActionTypes.ClearSearch }), 350)
}
break
}
})
let handleKeyUp = useEvent((event: ReactKeyboardEvent<HTMLButtonElement>) => {
switch (event.key) {
case Keys.Space:
// Required for firefox, event.preventDefault() in handleKeyDown for
// the Space key doesn't cancel the handleKeyUp, which in turn
// triggers a *click*.
event.preventDefault()
break
}
})
let slot = useMemo(() => {
return {
open: state.menuState === MenuStates.Open,
} satisfies ItemsRenderPropArg
}, [state.menuState])
let ourProps = mergeProps(anchor ? getFloatingPanelProps() : {}, {
'aria-activedescendant':
state.activeItemIndex === null ? undefined : state.items[state.activeItemIndex]?.id,
'aria-labelledby': state.buttonElement?.id,
id,
onKeyDown: handleKeyDown,
onKeyUp: handleKeyUp,
role: 'menu',
// When the `Menu` is closed, it should not be focusable. This allows us
// to skip focusing the `MenuItems` when pressing the tab key on an
// open `Menu`, and go to the next focusable element.
tabIndex: state.menuState === MenuStates.Open ? 0 : undefined,
ref: itemsRef,
style: {
...theirProps.style,
...style,
'--button-width': useElementSize(state.buttonElement, true).width,
} as CSSProperties,
...transitionDataAttributes(transitionData),
})
let render = useRender()
return (
<Portal enabled={portal ? props.static || visible : false} ownerDocument={portalOwnerDocument}>
{render({
ourProps,
theirProps,
slot,
defaultTag: DEFAULT_ITEMS_TAG,
features: ItemsRenderFeatures,
visible: panelEnabled,
name: 'Menu.Items',
})}
</Portal>
)
}
// ---
let DEFAULT_ITEM_TAG = Fragment
type ItemRenderPropArg = {
/** @deprecated use `focus` instead */
active: boolean
focus: boolean
disabled: boolean
close: () => void
}
type ItemPropsWeControl =
| 'aria-describedby'
| 'aria-disabled'
| 'aria-labelledby'
| 'role'
| 'tabIndex'
export type MenuItemProps<TTag extends ElementType = typeof DEFAULT_ITEM_TAG> = Props<
TTag,
ItemRenderPropArg,
ItemPropsWeControl,
{
disabled?: boolean
}
>
function ItemFn<TTag extends ElementType = typeof DEFAULT_ITEM_TAG>(
props: MenuItemProps<TTag>,
ref: Ref<HTMLElement>
) {
let internalId = useId()
let { id = `headlessui-menu-item-${internalId}`, disabled = false, ...theirProps } = props
let [state, dispatch] = useMenuContext('Menu.Item')
let active = state.activeItemIndex !== null ? state.items[state.activeItemIndex].id === id : false
let internalItemRef = useRef<HTMLElement | null>(null)
let itemRef = useSyncRefs(ref, internalItemRef)
useIsoMorphicEffect(() => {
if (state.__demoMode) return
if (state.menuState !== MenuStates.Open) return
if (!active) return
if (state.activationTrigger === ActivationTrigger.Pointer) return
return disposables().requestAnimationFrame(() => {
internalItemRef.current?.scrollIntoView?.({ block: 'nearest' })
})
}, [
state.__demoMode,
internalItemRef,
active,
state.menuState,
state.activationTrigger,
/* We also want to trigger this when the position of the active item changes so that we can re-trigger the scrollIntoView */ state.activeItemIndex,
])
let getTextValue = useTextValue(internalItemRef)
let bag = useRef<MenuItemDataRef['current']>({
disabled,
domRef: internalItemRef,
get textValue() {
return getTextValue()
},
})
useIsoMorphicEffect(() => {
bag.current.disabled = disabled
}, [bag, disabled])
useIsoMorphicEffect(() => {
dispatch({ type: ActionTypes.RegisterItem, id, dataRef: bag })
return () => dispatch({ type: ActionTypes.UnregisterItem, id })
}, [bag, id])
let close = useEvent(() => {
dispatch({ type: ActionTypes.CloseMenu })
})
let handleClick = useEvent((event: MouseEvent) => {
if (disabled) return event.preventDefault()
dispatch({ type: ActionTypes.CloseMenu })
restoreFocusIfNecessary(state.buttonElement)
})
let handleFocus = useEvent(() => {
if (disabled) return dispatch({ type: ActionTypes.GoToItem, focus: Focus.Nothing })
dispatch({ type: ActionTypes.GoToItem, focus: Focus.Specific, id })
})
let pointer = useTrackedPointer()
let handleEnter = useEvent((evt) => {
pointer.update(evt)
if (disabled) return
if (active) return
dispatch({
type: ActionTypes.GoToItem,
focus: Focus.Specific,
id,
trigger: ActivationTrigger.Pointer,
})
})
let handleMove = useEvent((evt) => {
if (!pointer.wasMoved(evt)) return
if (disabled) return
if (active) return
dispatch({
type: ActionTypes.GoToItem,
focus: Focus.Specific,
id,
trigger: ActivationTrigger.Pointer,
})
})
let handleLeave = useEvent((evt) => {
if (!pointer.wasMoved(evt)) return
if (disabled) return
if (!active) return
dispatch({ type: ActionTypes.GoToItem, focus: Focus.Nothing })
})
let [labelledby, LabelProvider] = useLabels()
let [describedby, DescriptionProvider] = useDescriptions()
let slot = useMemo(
() => ({ active, focus: active, disabled, close }) satisfies ItemRenderPropArg,
[active, disabled, close]
)
let ourProps = {
id,
ref: itemRef,
role: 'menuitem',
tabIndex: disabled === true ? undefined : -1,
'aria-disabled': disabled === true ? true : undefined,
'aria-labelledby': labelledby,
'aria-describedby': describedby,
disabled: undefined, // Never forward the `disabled` prop
onClick: handleClick,
onFocus: handleFocus,
onPointerEnter: handleEnter,
onMouseEnter: handleEnter,
onPointerMove: handleMove,
onMouseMove: handleMove,
onPointerLeave: handleLeave,
onMouseLeave: handleLeave,
}
let render = useRender()
return (
<LabelProvider>
<DescriptionProvider>
{render({