forked from reach/reach-ui
/
index.tsx
1114 lines (1017 loc) · 31.6 KB
/
index.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
/**
* Welcome to @reach/menu-button!
*
* An accessible dropdown menu for the common dropdown menu button design
* pattern.
*
* @see Docs https://reacttraining.com/reach-ui/menu-button
* @see Source https://github.com/reach/reach-ui/tree/main/packages/menu-button
* @see WAI-ARIA https://www.w3.org/TR/wai-aria-practices-1.2/#menubutton
*
* TODO: Fix flash when opening a menu button on a screen with another open menu
*/
import React, {
forwardRef,
useCallback,
useContext,
useEffect,
useMemo,
useReducer,
useRef,
useState,
} from "react";
import PropTypes from "prop-types";
import { useId } from "@reach/auto-id";
import Popover, { Position } from "@reach/popover";
import {
createDescendantContext,
Descendant,
DescendantProvider,
useDescendant,
useDescendants,
useDescendantsInit,
useDescendantKeyDown,
} from "@reach/descendants";
import {
checkStyles,
createNamedContext,
forwardRefWithAs,
getOwnerDocument,
isFunction,
isString,
makeId,
noop,
useForkedRef,
usePrevious,
wrapEvent,
} from "@reach/utils";
////////////////////////////////////////////////////////////////////////////////
// Actions
const CLEAR_SELECTION_INDEX = "CLEAR_SELECTION_INDEX";
const CLICK_MENU_ITEM = "CLICK_MENU_ITEM";
const CLOSE_MENU = "CLOSE_MENU";
const OPEN_MENU_AT_FIRST_ITEM = "OPEN_MENU_AT_FIRST_ITEM";
const OPEN_MENU_CLEARED = "OPEN_MENU_CLEARED";
const SEARCH_FOR_ITEM = "SEARCH_FOR_ITEM";
const SELECT_ITEM_AT_INDEX = "SELECT_ITEM_AT_INDEX";
const SET_BUTTON_ID = "SET_BUTTON_ID";
const MenuDescendantContext = createDescendantContext<MenuButtonDescendant>(
"MenuDescendantContext"
);
const MenuContext = createNamedContext<InternalMenuContextValue>(
"MenuContext",
{} as InternalMenuContextValue
);
const initialState: MenuButtonState = {
// The button ID is needed for aria controls and can be set directly and
// updated for top-level use via context. Otherwise a default is set by useId.
// TODO: Consider deprecating direct ID in 1.0 in favor of id at the top level
// for passing deterministic IDs to descendent components.
buttonId: null,
// Whether or not the menu is expanded
isExpanded: false,
// When a user begins typing a character string, the selection will change if
// a matching item is found
typeaheadQuery: "",
// The index of the current selected item. When the selection is cleared a
// value of -1 is used.
selectionIndex: -1,
};
////////////////////////////////////////////////////////////////////////////////
/**
* Menu
*
* The wrapper component for the other components. No DOM element is rendered.
*
* @see Docs https://reacttraining.com/reach-ui/menu-button#menu
*/
export const Menu: React.FC<MenuProps> = ({ id, children }) => {
let buttonRef = useRef(null);
let menuRef = useRef(null);
let popoverRef = useRef(null);
let [descendants, setDescendants] = useDescendantsInit<
MenuButtonDescendant
>();
let [state, dispatch] = useReducer(reducer, initialState);
let _id = useId(id);
let menuId = id || makeId("menu", _id);
// We use an event listener attached to the window to capture outside clicks
// that close the menu. We don't want the initial button click to trigger this
// when a menu is closed, so we can track this behavior in a ref for now.
// We shouldn't need this when we rewrite with state machine logic.
let buttonClickedRef = useRef(false);
// We will put children callbacks in a ref to avoid triggering endless render
// loops when using render props if the app code doesn't useCallback
// https://github.com/reach/reach-ui/issues/523
let selectCallbacks = useRef([]);
// If the popover's position overlaps with an option when the popover
// initially opens, the mouseup event will trigger a select. To prevent that,
// we decide the menu button is only ready to make a selection if the pointer
// moves first, otherwise the user is just registering the initial button
// click rather than selecting an item. This is similar to a native select
// on most platforms, and our menu button popover works similarly.
let readyToSelect = useRef(false);
let context: InternalMenuContextValue = {
buttonRef,
dispatch,
menuId,
menuRef,
popoverRef,
buttonClickedRef,
readyToSelect,
selectCallbacks,
state,
};
// When the menu is open, focus is placed on the menu itself so that
// keyboard navigation is still possible.
useEffect(() => {
if (state.isExpanded) {
// @ts-ignore
window.__REACH_DISABLE_TOOLTIPS = true;
window.requestAnimationFrame(() => {
focus(menuRef.current);
});
} else {
// We want to ignore the immediate focus of a tooltip so it doesn't pop
// up again when the menu closes, only pops up when focus returns again
// to the tooltip (like native OS tooltips).
// @ts-ignore
window.__REACH_DISABLE_TOOLTIPS = false;
}
}, [state.isExpanded]);
useEffect(() => checkStyles("menu-button"), []);
return (
<DescendantProvider
context={MenuDescendantContext}
items={descendants}
set={setDescendants}
>
<MenuContext.Provider value={context}>
{isFunction(children)
? children({
isExpanded: state.isExpanded,
// TODO: Remove in 1.0
isOpen: state.isExpanded,
})
: children}
</MenuContext.Provider>
</DescendantProvider>
);
};
/**
* @see Docs https://reacttraining.com/reach-ui/menu-button#menu-props
*/
export interface MenuProps {
/**
* Requires two children: a `<MenuButton>` and a `<MenuList>`.
*
* @see Docs https://reacttraining.com/reach-ui/menu-button#menu-children
*/
children:
| React.ReactNode
| ((
props: MenuContextValue & {
// TODO: Remove in 1.0
isOpen: boolean;
}
) => React.ReactNode);
id?: string;
}
if (__DEV__) {
Menu.displayName = "Menu";
Menu.propTypes = {
children: PropTypes.oneOfType([PropTypes.func, PropTypes.node]),
};
}
////////////////////////////////////////////////////////////////////////////////
/**
* MenuButton
*
* Wraps a DOM `button` that toggles the opening and closing of the dropdown
* menu. Must be rendered inside of a `<Menu>`.
*
* @see Docs https://reacttraining.com/reach-ui/menu-button#menubutton
*/
export const MenuButton = forwardRefWithAs<MenuButtonProps, "button">(
function MenuButton(
{ as: Comp = "button", onKeyDown, onMouseDown, id, ...props },
forwardedRef
) {
let {
buttonRef,
buttonClickedRef,
menuId,
state: { buttonId, isExpanded },
dispatch,
} = useContext(MenuContext);
let ref = useForkedRef(buttonRef, forwardedRef);
useEffect(() => {
let newButtonId =
id != null
? id
: menuId
? makeId("menu-button", menuId)
: "menu-button";
if (buttonId !== newButtonId) {
dispatch({
type: SET_BUTTON_ID,
payload: newButtonId,
});
}
}, [buttonId, dispatch, id, menuId]);
function handleKeyDown(event: React.KeyboardEvent) {
switch (event.key) {
case "ArrowDown":
case "ArrowUp":
event.preventDefault(); // prevent scroll
dispatch({ type: OPEN_MENU_AT_FIRST_ITEM });
break;
case "Enter":
case " ":
dispatch({ type: OPEN_MENU_AT_FIRST_ITEM });
break;
default:
break;
}
}
function handleMouseDown(event: React.MouseEvent) {
if (!isExpanded) {
buttonClickedRef.current = true;
}
if (isRightClick(event.nativeEvent)) {
return;
} else if (isExpanded) {
dispatch({ type: CLOSE_MENU, payload: { buttonRef } });
} else {
dispatch({ type: OPEN_MENU_CLEARED });
}
}
return (
<Comp
// When the menu is displayed, the element with role `button` has
// `aria-expanded` set to `true`. When the menu is hidden, it is
// recommended that `aria-expanded` is not present.
// https://www.w3.org/TR/wai-aria-practices-1.2/#menubutton
aria-expanded={isExpanded ? true : undefined}
// The element with role `button` has `aria-haspopup` set to either
// `"menu"` or `true`.
// https://www.w3.org/TR/wai-aria-practices-1.2/#menubutton
aria-haspopup
// Optionally, the element with role `button` has a value specified for
// `aria-controls` that refers to the element with role `menu`.
// https://www.w3.org/TR/wai-aria-practices-1.2/#menubutton
aria-controls={menuId}
{...props}
ref={ref}
data-reach-menu-button=""
id={buttonId || undefined}
onKeyDown={wrapEvent(onKeyDown, handleKeyDown)}
onMouseDown={wrapEvent(onMouseDown, handleMouseDown)}
type="button"
/>
);
}
);
/**
* @see Docs https://reacttraining.com/reach-ui/menu-button#menubutton-props
*/
export type MenuButtonProps = React.ButtonHTMLAttributes<HTMLButtonElement> & {
/**
* Accepts any renderable content.
*
* @see Docs https://reacttraining.com/reach-ui/menu-button#menubutton-children
*/
children: React.ReactNode;
};
if (__DEV__) {
MenuButton.displayName = "MenuButton";
MenuButton.propTypes = {
children: PropTypes.node,
};
}
////////////////////////////////////////////////////////////////////////////////
/**
* MenuItemImpl
*
* MenuItem and MenuLink share most of the same functionality captured here.
*/
const MenuItemImpl = forwardRefWithAs<MenuItemImplProps, "div">(
function MenuItemImpl(
{
as: Comp,
index: indexProp,
isLink = false,
onClick,
onDragStart,
onMouseDown,
onMouseEnter,
onMouseLeave,
onMouseMove,
onMouseUp,
onSelect,
valueText: valueTextProp,
...props
},
forwardedRef
) {
let {
buttonRef,
dispatch,
readyToSelect,
selectCallbacks,
state: { selectionIndex, isExpanded },
} = useContext(MenuContext);
let ownRef = useRef<HTMLElement | null>(null);
// After the ref is mounted to the DOM node, we check to see if we have an
// explicit valueText prop before looking for the node's textContent for
// typeahead functionality.
let [valueText, setValueText] = useState(valueTextProp || "");
let setValueTextFromDom = useCallback(
(node) => {
if (node) {
ownRef.current = node;
if (
!valueTextProp ||
(node.textContent && valueText !== node.textContent)
) {
setValueText(node.textContent);
}
}
},
[valueText, valueTextProp]
);
let ref = useForkedRef(forwardedRef, setValueTextFromDom);
let mouseEventStarted = useRef(false);
let index = useDescendant(
{
element: ownRef.current!,
key: valueText,
isLink,
},
MenuDescendantContext,
indexProp
);
let isSelected = index === selectionIndex;
// Update the callback ref array on every render
selectCallbacks.current[index] = onSelect;
function select() {
focus(buttonRef.current);
onSelect && onSelect();
dispatch({ type: CLICK_MENU_ITEM });
}
function handleClick(event: React.MouseEvent) {
if (isLink && !isRightClick(event.nativeEvent)) {
select();
}
}
function handleDragStart(event: React.MouseEvent) {
// Because we don't preventDefault on mousedown for links (we need the
// native click event), clicking and holding on a link triggers a
// dragstart which we don't want.
if (isLink) {
event.preventDefault();
}
}
function handleMouseDown(event: React.MouseEvent) {
if (isRightClick(event.nativeEvent)) return;
if (isLink) {
// Signal that the mouse is down so we can react call the right function
// if the user is clicking on a link.
mouseEventStarted.current = true;
} else {
event.preventDefault();
}
}
function handleMouseEnter(event: React.MouseEvent) {
if (!isSelected && index != null) {
dispatch({ type: SELECT_ITEM_AT_INDEX, payload: { index } });
}
}
function handleMouseLeave(event: React.MouseEvent) {
// Clear out selection when mouse over a non-menu item child.
dispatch({ type: CLEAR_SELECTION_INDEX });
}
function handleMouseMove() {
readyToSelect.current = true;
if (!isSelected && index != null) {
dispatch({ type: SELECT_ITEM_AT_INDEX, payload: { index } });
}
}
function handleMouseUp(event: React.MouseEvent) {
if (!readyToSelect.current) {
readyToSelect.current = true;
return;
}
if (isRightClick(event.nativeEvent)) return;
if (isLink) {
// If a mousedown event was initiated on a menu link followed by a
// mouseup event on the same link, we do nothing; a click event will
// come next and handle selection. Otherwise, we trigger a click event.
if (mouseEventStarted.current) {
mouseEventStarted.current = false;
} else if (ownRef.current) {
ownRef.current.click();
}
} else {
select();
}
}
// When the menu closes, reset readyToSelect for the next interaction.
useEffect(() => {
if (!isExpanded) {
readyToSelect.current = false;
}
}, [isExpanded, readyToSelect]);
// Any time a mouseup event occurs anywhere in the document, we reset the
// mouseEventStarted ref so we can check it again when needed.
useEffect(() => {
let ownerDocument = getOwnerDocument(ownRef.current) || document;
let listener = () => (mouseEventStarted.current = false);
ownerDocument.addEventListener("mouseup", listener);
return () => ownerDocument.removeEventListener("mouseup", listener);
}, []);
return (
<Comp
role="menuitem"
id={useMenuItemId(index)}
tabIndex={-1}
{...props}
ref={ref}
data-reach-menu-item=""
data-selected={isSelected ? "" : undefined}
data-valuetext={valueText}
onClick={wrapEvent(onClick, handleClick)}
onDragStart={wrapEvent(onDragStart, handleDragStart)}
onMouseDown={wrapEvent(onMouseDown, handleMouseDown)}
onMouseEnter={wrapEvent(onMouseEnter, handleMouseEnter)}
onMouseLeave={wrapEvent(onMouseLeave, handleMouseLeave)}
onMouseMove={wrapEvent(onMouseMove, handleMouseMove)}
onMouseUp={wrapEvent(onMouseUp, handleMouseUp)}
/>
);
}
);
export type MenuItemImplProps = {
/**
* You can put any type of content inside of a `<MenuItem>`.
*
* @see Docs https://reacttraining.com/reach-ui/menu-button#menuitem-children
*/
children: React.ReactNode;
/**
* Callback that fires when a `MenuItem` is selected.
*
* @see Docs https://reacttraining.com/reach-ui/menu-button#menuitem-onselect
*/
onSelect(): void;
index?: number;
isLink?: boolean;
valueText?: string;
};
////////////////////////////////////////////////////////////////////////////////
/**
* MenuItem
*
* Handles menu selection. Must be a direct child of a `<MenuList>`.
*
* @see Docs https://reacttraining.com/reach-ui/menu-button#menuitem
*/
export const MenuItem = forwardRefWithAs<MenuItemProps, "div">(
function MenuItem({ as = "div", ...props }, forwardedRef) {
return <MenuItemImpl {...props} ref={forwardedRef} as={as} />;
}
);
/**
* @see Docs https://reacttraining.com/reach-ui/menu-button#menuitem-props
*/
export type MenuItemProps = Omit<MenuItemImplProps, "isLink">;
if (__DEV__) {
MenuItem.displayName = "MenuItem";
MenuItem.propTypes = {
as: PropTypes.any,
onSelect: PropTypes.func.isRequired,
};
}
////////////////////////////////////////////////////////////////////////////////
/**
* MenuItems
*
* A low-level wrapper for menu items. Compose it with `MenuPopover` for more
* control over the nested components and their rendered DOM nodes, or if you
* need to nest arbitrary components between the outer wrapper and your list.
*
* @see Docs https://reacttraining.com/reach-ui/menu-button#menuitems
*/
export const MenuItems = forwardRefWithAs<MenuItemsProps, "div">(
function MenuItems(
{ as: Comp = "div", children, id, onKeyDown, ...props },
forwardedRef
) {
const {
menuId,
dispatch,
buttonRef,
menuRef,
selectCallbacks,
state: { isExpanded, buttonId, selectionIndex, typeaheadQuery },
} = useContext(MenuContext);
const menuItems = useDescendants(MenuDescendantContext);
const ref = useForkedRef(menuRef, forwardedRef);
useEffect(() => {
// Respond to user char key input with typeahead
const match = findItemFromTypeahead(menuItems, typeaheadQuery);
if (typeaheadQuery && match != null) {
dispatch({
type: SELECT_ITEM_AT_INDEX,
payload: { index: match },
});
}
let timeout = window.setTimeout(
() =>
typeaheadQuery && dispatch({ type: SEARCH_FOR_ITEM, payload: "" }),
1000
);
return () => window.clearTimeout(timeout);
}, [dispatch, menuItems, typeaheadQuery]);
const prevMenuItemsLength = usePrevious(menuItems.length);
const prevSelected = usePrevious(menuItems[selectionIndex]);
const prevSelectionIndex = usePrevious(selectionIndex);
useEffect(() => {
if (selectionIndex > menuItems.length - 1) {
// If for some reason our selection index is larger than our possible
// index range (let's say the last item is selected and the list
// dynamically updates), we need to select the last item in the list.
dispatch({
type: SELECT_ITEM_AT_INDEX,
payload: { index: menuItems.length - 1 },
});
} else if (
// Checks if
// - menu length has changed
// - selection index has not changed BUT selected item has changed
//
// This prevents any dynamic adding/removing of menu items from actually
// changing a user's expected selection.
prevMenuItemsLength !== menuItems.length &&
selectionIndex > -1 &&
prevSelected &&
prevSelectionIndex === selectionIndex &&
menuItems[selectionIndex] !== prevSelected
) {
dispatch({
type: SELECT_ITEM_AT_INDEX,
payload: {
index: menuItems.findIndex((i) => i.key === prevSelected.key),
},
});
}
}, [
dispatch,
menuItems,
prevMenuItemsLength,
prevSelected,
prevSelectionIndex,
selectionIndex,
]);
let handleKeyDown = wrapEvent(
function handleKeyDown(event: React.KeyboardEvent) {
let { key } = event;
if (!isExpanded) {
return;
}
switch (key) {
case "Enter":
case " ":
let selected = menuItems.find(
(item) => item.index === selectionIndex
);
// For links, the Enter key will trigger a click by default, but for
// consistent behavior across menu items we'll trigger a click when
// the spacebar is pressed.
if (selected) {
if (selected.isLink && selected.element) {
selected.element.click();
} else {
event.preventDefault();
// Focus the button first by default when an item is selected.
// We fire the onSelect callback next so the app can manage
// focus if needed.
focus(buttonRef.current);
selectCallbacks.current[selected.index] &&
selectCallbacks.current[selected.index]();
dispatch({ type: CLICK_MENU_ITEM });
}
}
break;
case "Escape":
focus(buttonRef.current);
dispatch({ type: CLOSE_MENU, payload: { buttonRef } });
break;
case "Tab":
// prevent leaving
event.preventDefault();
break;
default:
// Check if a user is typing some char keys and respond by setting
// the query state.
if (isString(key) && key.length === 1) {
const query = typeaheadQuery + key.toLowerCase();
dispatch({
type: SEARCH_FOR_ITEM,
payload: query,
});
}
break;
}
},
useDescendantKeyDown(MenuDescendantContext, {
currentIndex: selectionIndex,
orientation: "vertical",
rotate: false,
callback: (index: number) => {
dispatch({
type: SELECT_ITEM_AT_INDEX,
payload: { index },
});
},
key: "index",
})
);
return (
// TODO: Should probably file a but in jsx-a11y, but this is correct
// according to https://www.w3.org/TR/wai-aria-practices-1.2/examples/menu-button/menu-button-actions-active-descendant.html
// eslint-disable-next-line jsx-a11y/aria-activedescendant-has-tabindex
<Comp
// Refers to the descendant menuitem element that is visually indicated
// as focused.
// https://www.w3.org/TR/wai-aria-practices-1.2/examples/menu-button/menu-button-actions-active-descendant.html
aria-activedescendant={useMenuItemId(selectionIndex) || undefined}
// Refers to the element that contains the accessible name for the
// `menu`. The menu is labeled by the menu button.
// https://www.w3.org/TR/wai-aria-practices-1.2/examples/menu-button/menu-button-actions-active-descendant.html
aria-labelledby={buttonId || undefined}
// The element that contains the menu items displayed by activating the
// button has role menu.
// https://www.w3.org/TR/wai-aria-practices-1.2/#menubutton
role="menu"
tabIndex={-1}
{...props}
ref={ref}
data-reach-menu-items=""
id={menuId}
onKeyDown={wrapEvent(onKeyDown, handleKeyDown)}
>
{children}
</Comp>
);
}
);
/**
* @see Docs https://reacttraining.com/reach-ui/menu-button#menuitems-props
*/
export type MenuItemsProps = {
/**
* Can contain only `MenuItem` or a `MenuLink`.
*
* @see Docs https://reacttraining.com/reach-ui/menu-button#menuitems-children
*/
children: React.ReactNode;
} & React.HTMLAttributes<HTMLDivElement>;
if (__DEV__) {
MenuItems.displayName = "MenuItems";
MenuItems.propTypes = {
children: PropTypes.node,
};
}
////////////////////////////////////////////////////////////////////////////////
/**
* MenuLink
*
* Handles linking to a different page in the menu. By default it renders `<a>`,
* but also accepts any other kind of Link as long as the `Link` uses the
* `React.forwardRef` API.
*
* Must be a direct child of a `<MenuList>`.
*
* @see Docs https://reacttraining.com/reach-ui/menu-button#menulink
*/
export const MenuLink = forwardRefWithAs<
MenuLinkProps & { component?: any },
"a"
>(function MenuLink({ as = "a", component, onSelect, ...props }, forwardedRef) {
if (component) {
console.warn(
"[@reach/menu-button]: Please use the `as` prop instead of `component`."
);
}
return (
<div role="none" tabIndex={-1}>
<MenuItemImpl
{...props}
ref={forwardedRef}
data-reach-menu-link=""
as={as}
isLink={true}
onSelect={onSelect || noop}
/>
</div>
);
});
/**
* @see Docs https://reacttraining.com/reach-ui/menu-button#menulink-props
*/
export type MenuLinkProps = Omit<MenuItemImplProps, "isLink" | "onSelect"> & {
onSelect?(): void;
};
if (__DEV__) {
MenuLink.displayName = "MenuLink";
MenuLink.propTypes = {
as: PropTypes.any,
component: PropTypes.any,
};
}
////////////////////////////////////////////////////////////////////////////////
/**
* MenuList
*
* Wraps a DOM element that renders the menu items. Must be rendered inside of
* a `<Menu>`.
*
* @see Docs https://reacttraining.com/reach-ui/menu-button#menulist
*/
export const MenuList = forwardRef<HTMLDivElement, MenuListProps>(
function MenuList({ portal = true, ...props }, forwardedRef) {
return (
<MenuPopover portal={portal}>
<MenuItems {...props} ref={forwardedRef} data-reach-menu-list="" />
</MenuPopover>
);
}
);
/**
* @see Docs https://reacttraining.com/reach-ui/menu-button#menulist-props
*/
export type MenuListProps = React.HTMLAttributes<HTMLDivElement> & {
/**
* Whether or not the popover should be rendered inside a portal. Defaults to
* `true`.
*
* @see Docs https://reacttraining.com/reach-ui/menu-button#menulist-portal
*/
portal?: boolean;
/**
* Can contain only `MenuItem` or a `MenuLink`.
*
* @see Docs https://reacttraining.com/reach-ui/menu-button#menulist-children
*/
children: React.ReactNode;
};
if (__DEV__) {
MenuList.displayName = "MenuList";
MenuList.propTypes = {
children: PropTypes.node.isRequired,
};
}
////////////////////////////////////////////////////////////////////////////////
/**
* MenuPopover
*
* A low-level wrapper for the popover that appears when a menu button is open.
* You can compose it with `MenuItems` for more control over the nested
* components and their rendered DOM nodes, or if you need to nest arbitrary
* components between the outer wrapper and your list.
*
* @see Docs https://reacttraining.com/reach-ui/menu-button#menupopover
*/
export const MenuPopover = forwardRef<any, MenuPopoverProps>(
function MenuPopover(
{ children, portal = true, position, ...props },
forwardedRef
) {
const {
buttonRef,
buttonClickedRef,
dispatch,
menuRef,
popoverRef,
state: { isExpanded },
} = useContext(MenuContext);
const ref = useForkedRef(popoverRef, forwardedRef);
useEffect(() => {
function listener(event: MouseEvent) {
if (buttonClickedRef.current) {
buttonClickedRef.current = false;
} else {
// We on want to close only if focus rests outside the menu
if (isExpanded && popoverRef.current) {
if (!popoverRef.current.contains(event.target as Element)) {
dispatch({ type: CLOSE_MENU, payload: { buttonRef } });
}
}
}
}
window.addEventListener("mousedown", listener);
return () => {
window.removeEventListener("mousedown", listener);
};
}, [
buttonClickedRef,
buttonRef,
dispatch,
isExpanded,
menuRef,
popoverRef,
]);
let commonProps = {
ref,
// TODO: remove in 1.0
"data-reach-menu": "",
"data-reach-menu-popover": "",
hidden: !isExpanded,
children,
...props,
};
return portal ? (
<Popover
{...commonProps}
targetRef={buttonRef as any}
position={position}
/>
) : (
<div {...commonProps} />
);
}
);
/**
* @see Docs https://reacttraining.com/reach-ui/menu-button#menupopover-props
*/
export type MenuPopoverProps = React.HTMLAttributes<HTMLDivElement> & {
/**
* Must contain a `MenuItems`
*
* @see Docs https://reacttraining.com/reach-ui/menu-button#menupopover-children
*/
children: React.ReactNode;
/**
* Whether or not the popover should be rendered inside a portal. Defaults to
* `true`.
*
* @see Docs https://reacttraining.com/reach-ui/menu-button#menupopover-portal
*/
portal?: boolean;
position?: Position;
};
if (__DEV__) {
MenuPopover.displayName = "MenuPopover";
MenuPopover.propTypes = {
children: PropTypes.node,
};
}
////////////////////////////////////////////////////////////////////////////////
/**
* A hook that exposes data for a given `Menu` component to its descendants.
*
* @see Docs https://reacttraining.com/reach-ui/menu-button#usemenubuttoncontext
*/
export function useMenuButtonContext(): MenuContextValue {
let {
state: { isExpanded },
} = useContext(MenuContext);
return useMemo(() => ({ isExpanded }), [isExpanded]);
}
////////////////////////////////////////////////////////////////////////////////
/**
* When a user's typed input matches the string displayed in a menu item, it is
* expected that the matching menu item is selected. This is our matching
* function.
*/
function findItemFromTypeahead(
items: Descendant<HTMLElement>[],
string: string = ""
) {
if (!string) {
return null;
}
const found = items.find(({ element }) =>
element?.dataset?.valuetext?.toLowerCase().startsWith(string)
);
return found ? items.indexOf(found) : null;
}
function useMenuItemId(index: number | null) {
let { menuId } = useContext(MenuContext);
return index != null && index > -1
? makeId(`option-${index}`, menuId)
: undefined;
}
interface MenuButtonState {
isExpanded: boolean;
selectionIndex: number;
buttonId: null | string;
typeaheadQuery: string;
}