UNPKG

1.47 kBJavaScriptView Raw
1import _extends from "@babel/runtime/helpers/esm/extends";
2import { ListActionTypes, listReducer } from '../useList';
3export function menuReducer(state, action) {
4 if (action.type === ListActionTypes.itemHover) {
5 return _extends({}, state, {
6 highlightedValue: action.item
7 });
8 }
9 const newState = listReducer(state, action);
10
11 // make sure an item is always highlighted
12 if (newState.highlightedValue === null && action.context.items.length > 0) {
13 return _extends({}, newState, {
14 highlightedValue: action.context.items[0]
15 });
16 }
17 if (action.type === ListActionTypes.keyDown) {
18 if (action.event.key === 'Escape') {
19 return _extends({}, newState, {
20 open: false
21 });
22 }
23 }
24 if (action.type === ListActionTypes.blur) {
25 if (!action.context.listboxRef.current?.contains(action.event.relatedTarget)) {
26 // To prevent the menu from closing when the focus leaves the menu to the button.
27 // For more details, see https://github.com/mui/material-ui/pull/36917#issuecomment-1566992698
28 const listboxId = action.context.listboxRef.current?.getAttribute('id');
29 const controlledBy = action.event.relatedTarget?.getAttribute('aria-controls');
30 if (listboxId && controlledBy && listboxId === controlledBy) {
31 return newState;
32 }
33 return _extends({}, newState, {
34 open: false,
35 highlightedValue: action.context.items[0]
36 });
37 }
38 }
39 return newState;
40}
\No newline at end of file