Repository navigation
Expand file tree
/
Copy pathMenuItem.tsx
More file actions
301 lines (273 loc) · 9.65 KB
/
Copy pathMenuItem.tsx
File metadata and controls
301 lines (273 loc) · 9.65 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
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
import * as React from 'react';
import {
isCursor,
isElementDisabled,
useListItemRegister,
useListItemRovingFocus,
useListItemSelect,
} from '@workday/canvas-kit-react/collection';
import {
changeFocus,
composeHooks,
cornerShapeStencil,
createComponent,
createElemPropsHook,
createSubcomponent,
useLocalRef,
} from '@workday/canvas-kit-react/common';
import {SystemIcon, SystemIconProps, systemIconStencil} from '@workday/canvas-kit-react/icon';
import {mergeStyles} from '@workday/canvas-kit-react/layout';
import {OverflowTooltip} from '@workday/canvas-kit-react/tooltip';
import {CSProps, createStencil, handleCsProp, px2rem} from '@workday/canvas-kit-styling';
import {system} from '@workday/canvas-tokens-web';
import {useMenuModel} from './useMenuModel';
export interface MenuItemProps extends CSProps {
/**
* Optionally pass index to menu item. This should be done if `Menu.Item` components were created
* via a `Array::map` function. This index will ensure keyboard navigation works even if items are
* inserted out of order.
*/
index?: number;
/**
* The label text of the MenuItem.
*/
children?: React.ReactNode;
/**
* The name of the menu item. This name will be used in the `onSelect` callback in the model. If
* this property is not provided, it will default to a string representation of the the zero-based
* index of the Tab when it was initialized.
*/
'data-id'?: string;
/**
* `aria-disabled` is used for keyboard and screen reader users to discover disabled content with
* the keyboard or screen reader caret tool. For more information, see
* https://www.w3.org/WAI/ARIA/apg/practices/keyboard-interface/#kbd_disabled_controls
*/
'aria-disabled'?: boolean;
/**
* If true, set the StyledMenuItem to the disabled state so it is not clickable.
* @default false
* @deprecated Use `aria-disabled` instead
*/
isDisabled?: boolean;
}
export const menuItemStencil = createStencil({
extends: cornerShapeStencil,
parts: {
text: 'menu-item-text',
icon: 'menu-item-icon',
selected: 'menu-item-selected',
},
base: ({textPart, iconPart, selectedPart}) => ({
fontFamily: system.fontFamily.default,
fontWeight: system.fontWeight.normal,
fontSize: system.legacy.fontSize.subtext.lg,
lineHeight: system.legacy.lineHeight.subtext.lg,
letterSpacing: system.legacy.letterSpacing.subtext.lg,
display: 'flex',
alignItems: 'center',
width: '100%',
gap: system.legacy.gap.sm,
padding: `${system.legacy.padding.xs} ${system.legacy.padding.xs} ${system.legacy.padding.xs} ${system.legacy.padding.sm}`,
boxSizing: 'border-box',
cursor: 'pointer',
color: system.color.fg.strong,
borderWidth: 0,
[cornerShapeStencil.vars.shape]: system.legacy.shape.lg,
textAlign: 'start',
transition: 'background-color 80ms, color 80ms',
backgroundColor: 'inherit',
minHeight: system.legacy.size.md,
overflowWrap: 'anywhere',
// We want the icon colors to be the same as the text color
[systemIconStencil.vars.color]: 'currentColor',
// selected checkmark
[`& :where(${selectedPart})`]: {
transition: 'opacity 80ms linear',
opacity: system.opacity.zero,
},
// if the menu item has children we need it to be displayed in flex
'&:where(:has(span))': {
display: 'flex',
},
// Selected styles
'&[aria-selected=true]': {
color: system.legacy.color.brand.fg.selected,
backgroundColor: system.legacy.color.brand.surface.selected,
[`& :where(${selectedPart})`]: {
opacity: system.opacity.full,
},
'&:where(.focus, :focus-visible)': {
outline: `${px2rem(2)} solid ${system.legacy.color.brand.border.primary}`,
outlineOffset: `-${px2rem(2)}`,
},
},
// Hover styles
'&:is(.hover, :hover)': {
backgroundColor: system.legacy.color.surface.overlay.hover.default,
},
// Active styles
'&:is(.active, :active)': {
backgroundColor: system.legacy.color.surface.overlay.pressed.default,
},
// Focus styles
'&:is(.focus, :focus-visible)': {
outline: `${px2rem(2)} solid ${system.legacy.color.brand.border.primary}`,
outlineOffset: `-${px2rem(2)}`,
},
// Focus + Expanded Submenu
// When a `Submenu.TargetItem`'s submenu is open, real focus has moved into the submenu, so we
// de-emphasize this item's focus ring and show selected styling instead to indicate it's part
// of the open ancestor trail rather than the actively focused item.
'&[aria-expanded="true"]:is(.focus, :focus-visible)': {
color: system.legacy.color.brand.fg.selected,
backgroundColor: system.legacy.color.brand.surface.selected,
outline: 'none',
},
// Disabled styles
'&:is(:disabled, [aria-disabled=true])': {
cursor: 'default',
opacity: system.opacity.disabled,
'&:where(.hover, :hover)': {
background: 'none',
},
// Focus + Disabled
'&:where(.focus, :focus-visible)': {
color: system.legacy.color.brand.fg.selected,
backgroundColor: system.legacy.color.brand.surface.selected,
opacity: system.opacity.disabled,
},
},
[`& :where(${textPart})`]: {
flexGrow: 1,
alignSelf: 'center',
},
}),
});
const MenuItemIcon = (elemProps: SystemIconProps) => {
return <SystemIcon size="md" {...menuItemStencil.parts.icon} {...elemProps} />;
};
const MenuItemText = createComponent('span')({
Component: ({...elemProps}: CSProps, ref, Element) => {
return <Element ref={ref} {...menuItemStencil.parts.text} {...handleCsProp(elemProps)} />;
},
});
export const StyledMenuItem = createComponent('button')({
displayName: 'MenuItem',
Component: ({children, isDisabled, ...elemProps}: MenuItemProps, ref, Element) => {
return (
<Element
ref={ref}
aria-disabled={isDisabled}
{...mergeStyles(elemProps, menuItemStencil({}))}
>
{typeof children === 'string' ? <MenuItemText>{children}</MenuItemText> : children}
</Element>
);
},
});
export const useMenuItemArrowReturn = createElemPropsHook(useMenuModel)(model => {
return {
onKeyDown(event: React.KeyboardEvent) {
const styles = getComputedStyle(event.currentTarget);
if (event.key === 'ArrowLeft' && styles.direction === 'ltr' && model.UNSTABLE_parentModel) {
event.preventDefault();
const target = model.state.targetRef.current as HTMLElement | null;
model.events.hide(event);
requestAnimationFrame(() => {
changeFocus(target);
});
}
},
};
});
export const useMenuItemFocus = createElemPropsHook(useMenuModel)((
model,
ref,
elemProps: {'data-id': string} = {'data-id': ''}
) => {
const {localRef, elementRef} = useLocalRef(ref as React.Ref<HTMLElement>);
const id = elemProps['data-id'];
// A menu keeps its cursor between openings, so reopening would restore focus to a disabled item.
// Items remount whenever the menu opens, which distinguishes reopening from navigating onto a
// disabled item while the menu is already open. Clearing the cursor lets the roving focus
// fallback in `useListItemRovingFocus` move focus to the first item. The check waits for the
// first render where `id` is known, since items without an explicit `data-id` register it later.
const hasCheckedDisabledCursor = React.useRef(false);
React.useLayoutEffect(() => {
if (hasCheckedDisabledCursor.current || !id) {
return;
}
hasCheckedDisabledCursor.current = true;
const isItemDisabled = isElementDisabled(localRef.current);
if (model.state.mode === 'single' && isCursor(model.state, id) && isItemDisabled) {
model.events.goToFirst();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [id]);
// focus on the item with the cursor
React.useLayoutEffect(() => {
if (model.state.mode === 'single') {
if (isCursor(model.state, id)) {
// delay focus changes to allow PopperJS to position
requestAnimationFrame(() => {
localRef.current?.focus();
});
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [id, localRef, model.state.cursorId, model.state.mode]);
return {
ref: elementRef,
className: isCursor(model.state, elemProps['data-id']) ? 'focus' : undefined,
};
});
function hideParent(model: ReturnType<typeof useMenuModel>) {
if (model.UNSTABLE_parentModel) {
(model.UNSTABLE_parentModel as any).events.hide();
hideParent(model.UNSTABLE_parentModel as any);
}
}
export const useMenuItem = composeHooks(
createElemPropsHook(useMenuModel)(model => {
return {
role: 'menuitem',
onMouseDown(event: React.MouseEvent) {
model.events.goTo({id: event.currentTarget.getAttribute('data-id')!});
},
onClick:
model.state.mode === 'single'
? (event: React.SyntheticEvent) => {
if (isElementDisabled(event.currentTarget as Element)) {
return null;
}
model.events.hide(event);
hideParent(model);
return undefined;
}
: undefined,
};
}),
useMenuItemFocus,
useMenuItemArrowReturn,
useListItemSelect,
useListItemRovingFocus,
useListItemRegister
);
export const MenuItem = createSubcomponent('button')({
displayName: 'Menu.Item',
modelHook: useMenuModel,
elemPropsHook: useMenuItem,
subComponents: {
Icon: MenuItemIcon,
Text: MenuItemText,
},
})<MenuItemProps>(({children, ...elemProps}, Element) => {
return (
<OverflowTooltip placement="left">
<StyledMenuItem as={Element} {...elemProps}>
{children}
</StyledMenuItem>
</OverflowTooltip>
);
});