-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathDropdownMenuItem.tsx
More file actions
59 lines (53 loc) · 1.76 KB
/
DropdownMenuItem.tsx
File metadata and controls
59 lines (53 loc) · 1.76 KB
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
/** @jsxImportSource @emotion/react */
import { useMemo, useRef, useState } from 'react';
import { DropdownSubContext } from '../context';
import * as Style from '../style';
import { NOT_DISABLED_DROPDOWN_MENU_QUERY } from '../constants';
import { selectItem } from '../utils/selectItem';
import { keyboardHandler } from '../utils/keyboardHandler';
import type { DropdownMenuItemProps } from '../types';
export const MenuItem = (props: DropdownMenuItemProps) => {
const menuItemRef = useRef<HTMLLIElement>(null);
const { children, hasSub, onClick, disabled, ...restProps } = props;
const [subOpen, setSubOpen] = useState<boolean>(false);
const toggleSubOpen = () => {
if (hasSub && !disabled) {
setSubOpen(prev => !prev);
}
};
const onKeyDown = (event: React.KeyboardEvent<HTMLElement>) => {
if (!menuItemRef.current) return;
if (event.key !== 'Tab') {
setSubOpen(false);
}
keyboardHandler({
event,
parentScope: '.menu',
selectorOfList: NOT_DISABLED_DROPDOWN_MENU_QUERY,
setState: setSubOpen,
onClick
});
};
const providerValue = useMemo(() => ({ subOpen, setSubOpen }), [subOpen]);
return (
<DropdownSubContext.Provider value={providerValue}>
<li
ref={menuItemRef}
role="menuitem"
tabIndex={disabled ? -1 : 0}
className="menu_item"
aria-disabled={!!disabled}
css={{ ...Style.createDropdownItem(!!disabled) }}
onMouseOver={toggleSubOpen}
onMouseLeave={toggleSubOpen}
onKeyDown={e => onKeyDown(e)}
onClick={e => selectItem(e, onClick)}
onFocus={toggleSubOpen}
{...restProps}
>
{children}
</li>
</DropdownSubContext.Provider>
);
};
MenuItem.displayName = 'DropdownMenuItem';