-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathuseMenuList.ts
More file actions
196 lines (169 loc) · 6.71 KB
/
useMenuList.ts
File metadata and controls
196 lines (169 loc) · 6.71 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
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
'use client';
import * as React from 'react';
import {
useMergedRefs,
useEventCallback,
useControllableState,
getIntrinsicElementProps,
slot,
} from '@fluentui/react-utilities';
import { useFocusFinders, TabsterMoveFocusEventName, type TabsterMoveFocusEvent } from '@fluentui/react-tabster';
import { useFluent_unstable as useFluent } from '@fluentui/react-shared-contexts';
import { useHasParentContext } from '@fluentui/react-context-selector';
import { useMenuContext_unstable } from '../../contexts/menuContext';
import { MenuContext } from '../../contexts/menuContext';
import type { MenuListProps, MenuListState } from './MenuList.types';
import { useValidateNesting } from '../../utils/useValidateNesting';
/**
* Returns the props and state required to render the component
*/
export const useMenuList_unstable = (props: MenuListProps, ref: React.Ref<HTMLElement>): MenuListState => {
const { findAllFocusable } = useFocusFinders();
const { targetDocument } = useFluent();
const menuContext = useMenuContextSelectors();
const hasMenuContext = useHasParentContext(MenuContext);
if (usingPropsAndMenuContext(props, menuContext, hasMenuContext)) {
// TODO throw warnings in development safely
// eslint-disable-next-line no-console
console.warn('You are using both MenuList and Menu props, we recommend you to use Menu props when available');
}
const innerRef = React.useRef<HTMLElement>(null);
const validateNestingRef = useValidateNesting('MenuList');
React.useEffect(() => {
const element = innerRef.current;
if (hasMenuContext && targetDocument && element) {
const onTabsterMoveFocus = (e: TabsterMoveFocusEvent) => {
const nextElement = e.detail.next;
if (nextElement && element.contains(targetDocument.activeElement) && !element.contains(nextElement)) {
// Preventing Tabster from handling Tab press, useMenuPopover will handle it.
e.preventDefault();
}
};
targetDocument.addEventListener(TabsterMoveFocusEventName, onTabsterMoveFocus);
return () => {
targetDocument.removeEventListener(TabsterMoveFocusEventName, onTabsterMoveFocus);
};
}
}, [innerRef, targetDocument, hasMenuContext]);
const setFocusByFirstCharacter = React.useCallback(
(e: React.KeyboardEvent<HTMLElement>, itemEl: HTMLElement) => {
// TODO use some kind of children registration to reduce dependency on DOM roles
const acceptedRoles = ['menuitem', 'menuitemcheckbox', 'menuitemradio'];
if (!innerRef.current) {
return;
}
const menuItems = findAllFocusable(
innerRef.current,
(el: HTMLElement) => el.hasAttribute('role') && acceptedRoles.indexOf(el.getAttribute('role')!) !== -1,
);
let startIndex = menuItems.indexOf(itemEl) + 1;
if (startIndex === menuItems.length) {
startIndex = 0;
}
const firstChars = menuItems.map(menuItem => menuItem.textContent?.charAt(0).toLowerCase());
const char = e.key.toLowerCase();
const getIndexFirstChars = (start: number, firstChar: string) => {
for (let i = start; i < firstChars.length; i++) {
if (char === firstChars[i]) {
return i;
}
}
return -1;
};
// Check remaining slots in the menu
let index = getIndexFirstChars(startIndex, char);
// If not found in remaining slots, check from beginning
if (index === -1) {
index = getIndexFirstChars(0, char);
}
// If match was found...
if (index > -1) {
menuItems[index].focus();
}
},
[findAllFocusable],
);
const [checkedValues, setCheckedValues] = useControllableState({
state: props.checkedValues ?? (hasMenuContext ? menuContext.checkedValues : undefined),
defaultState: props.defaultCheckedValues,
initialState: {},
});
const handleCheckedValueChange =
props.onCheckedValueChange ?? (hasMenuContext ? menuContext.onCheckedValueChange : undefined);
const toggleCheckbox = useEventCallback(
(e: React.MouseEvent | React.KeyboardEvent, name: string, value: string, checked: boolean) => {
const checkedItems = checkedValues?.[name] || [];
const newCheckedItems = [...checkedItems];
if (checked) {
newCheckedItems.splice(newCheckedItems.indexOf(value), 1);
} else {
newCheckedItems.push(value);
}
handleCheckedValueChange?.(e, { name, checkedItems: newCheckedItems });
setCheckedValues(s => ({ ...s, [name]: newCheckedItems }));
},
);
const selectRadio = useEventCallback((e: React.MouseEvent | React.KeyboardEvent, name: string, value: string) => {
const newCheckedItems = [value];
setCheckedValues(s => ({ ...s, [name]: newCheckedItems }));
handleCheckedValueChange?.(e, { name, checkedItems: newCheckedItems });
});
return {
components: {
root: 'div',
},
root: slot.always(
getIntrinsicElementProps('div', {
// FIXME:
// `ref` is wrongly assigned to be `HTMLElement` instead of `HTMLDivElement`
// but since it would be a breaking change to fix it, we are casting ref to it's proper type
ref: useMergedRefs(ref, innerRef, validateNestingRef) as React.Ref<HTMLDivElement>,
role: 'menu',
'aria-labelledby': menuContext.triggerId,
focusgroup: 'menu nomemory wrap',
...props,
}),
{ elementType: 'div' },
),
hasIcons: menuContext.hasIcons || false,
hasCheckmarks: menuContext.hasCheckmarks || false,
checkedValues,
hasMenuContext,
setFocusByFirstCharacter,
selectRadio,
toggleCheckbox,
};
};
/**
* Adds some sugar to fetching multiple context selector values
*/
const useMenuContextSelectors = () => {
const checkedValues = useMenuContext_unstable(context => context.checkedValues);
const onCheckedValueChange = useMenuContext_unstable(context => context.onCheckedValueChange);
const triggerId = useMenuContext_unstable(context => context.triggerId);
const hasIcons = useMenuContext_unstable(context => context.hasIcons);
const hasCheckmarks = useMenuContext_unstable(context => context.hasCheckmarks);
return {
checkedValues,
onCheckedValueChange,
triggerId,
hasIcons,
hasCheckmarks,
};
};
/**
* Helper function to detect if props and MenuContext values are both used
*/
const usingPropsAndMenuContext = (
props: MenuListProps,
contextValue: ReturnType<typeof useMenuContextSelectors>,
hasMenuContext: boolean,
) => {
let isUsingPropsAndContext = false;
for (const val in contextValue) {
if (props[val as keyof Omit<typeof contextValue, 'hasMenuContext' | 'onCheckedValueChange' | 'triggerId'>]) {
isUsingPropsAndContext = true;
}
}
return hasMenuContext && isUsingPropsAndContext;
};