-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathmenu.tsx
More file actions
393 lines (346 loc) · 12.1 KB
/
menu.tsx
File metadata and controls
393 lines (346 loc) · 12.1 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
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
import './menu.module.css'
import * as React from 'react'
import {
Menu as AriakitMenu,
MenuButton as AriakitMenuButton,
MenuGroup as AriakitMenuGroup,
MenuItem as AriakitMenuItem,
Portal,
Role,
useMenuStore,
} from '@ariakit/react'
import classNames from 'classnames'
import type {
MenuButtonProps as AriakitMenuButtonProps,
MenuItemProps as AriakitMenuItemProps,
MenuProps as AriakitMenuProps,
MenuStore,
MenuStoreProps,
RoleProps,
} from '@ariakit/react'
import type { ObfuscatedClassName } from '../utils/common-types'
type MenuContextState = {
menuStore: MenuStore | null
handleItemSelect?: (value: string | null | undefined) => void
getAnchorRect: (() => { x: number; y: number }) | null
setAnchorRect: (rect: { x: number; y: number } | null) => void
}
const MenuContext = React.createContext<MenuContextState>({
menuStore: null,
handleItemSelect: () => undefined,
getAnchorRect: null,
setAnchorRect: () => undefined,
})
const SubMenuContext = React.createContext<{ isSubMenu: boolean }>({ isSubMenu: false })
//
// Menu
//
interface MenuProps extends Omit<MenuStoreProps, 'visible'> {
/**
* The `Menu` must contain a `MenuList` that defines the menu options. It must also contain a
* `MenuButton` that triggers the menu to be opened or closed.
*/
children: React.ReactNode
/**
* An optional callback that will be called back whenever a menu item is selected. It receives
* the `value` of the selected `MenuItem`.
*
* If you pass down this callback, it is recommended that you properly memoize it so it does not
* change on every render.
*/
onItemSelect?: (value: string | null | undefined) => void
}
/**
* Wrapper component to control a menu. It does not render anything, only providing the state
* management for the menu components inside it.
*/
function Menu({ children, onItemSelect, ...props }: MenuProps) {
const [anchorRect, setAnchorRect] = React.useState<{ x: number; y: number } | null>(null)
const getAnchorRect = React.useMemo(() => (anchorRect ? () => anchorRect : null), [anchorRect])
const menuStore = useMenuStore({ focusLoop: true, ...props })
const value: MenuContextState = React.useMemo(
() => ({ menuStore, handleItemSelect: onItemSelect, getAnchorRect, setAnchorRect }),
[menuStore, onItemSelect, getAnchorRect, setAnchorRect],
)
return <MenuContext.Provider value={value}>{children}</MenuContext.Provider>
}
//
// MenuButton
//
interface MenuButtonProps
extends Omit<AriakitMenuButtonProps, 'store' | 'className' | 'as'>,
ObfuscatedClassName {}
/**
* A button to toggle a dropdown menu open or closed.
*/
const MenuButton = React.forwardRef<HTMLButtonElement, MenuButtonProps>(function MenuButton(
{ exceptionallySetClassName, ...props },
ref,
) {
const { menuStore } = React.useContext(MenuContext)
if (!menuStore) {
throw new Error('MenuButton must be wrapped in <Menu/>')
}
return (
<AriakitMenuButton
{...props}
store={menuStore}
ref={ref}
className={classNames('reactist_menubutton', exceptionallySetClassName)}
/>
)
})
//
// ContextMenuTrigger
//
interface ContextMenuTriggerProps
extends ObfuscatedClassName,
React.HTMLAttributes<HTMLDivElement>,
Pick<RoleProps, 'render'> {}
const ContextMenuTrigger = React.forwardRef<HTMLDivElement, ContextMenuTriggerProps>(
function ContextMenuTrigger({ render, ...props }, ref) {
const { setAnchorRect, menuStore } = React.useContext(MenuContext)
if (!menuStore) {
throw new Error('ContextMenuTrigger must be wrapped in <Menu/>')
}
const handleContextMenu = React.useCallback(
function handleContextMenu(event: React.MouseEvent) {
event.preventDefault()
setAnchorRect({ x: event.clientX, y: event.clientY })
menuStore.show()
},
[setAnchorRect, menuStore],
)
const isOpen = menuStore.useState('open')
React.useEffect(() => {
if (!isOpen) setAnchorRect(null)
}, [isOpen, setAnchorRect])
return <Role.div {...props} onContextMenu={handleContextMenu} ref={ref} render={render} />
},
)
//
// MenuList
//
interface MenuListProps
extends Omit<AriakitMenuProps, 'store' | 'className'>,
ObfuscatedClassName {}
/**
* The dropdown menu itself, containing a list of menu items.
*/
const MenuList = React.forwardRef<HTMLDivElement, MenuListProps>(function MenuList(
{ exceptionallySetClassName, modal = true, flip, ...props },
ref,
) {
const { menuStore, getAnchorRect } = React.useContext(MenuContext)
if (!menuStore) {
throw new Error('MenuList must be wrapped in <Menu/>')
}
const { isSubMenu } = React.useContext(SubMenuContext)
const isOpen = menuStore.useState('open')
return isOpen ? (
<Portal preserveTabOrder>
<AriakitMenu
{...props}
store={menuStore}
gutter={8}
shift={4}
ref={ref}
className={classNames('reactist_menulist', exceptionallySetClassName)}
getAnchorRect={getAnchorRect ?? undefined}
modal={modal}
flip={flip ?? (isSubMenu ? 'left bottom' : undefined)}
/>
</Portal>
) : null
})
//
// MenuItem
//
interface MenuItemProps extends AriakitMenuItemProps, ObfuscatedClassName {
/**
* An optional value given to this menu item. It is passed on to the parent `Menu`'s
* `onItemSelect` when you provide that instead of (or alongside) providing individual
* `onSelect` callbacks to each menu item.
*/
value?: string
/**
* When `true` the menu item is disabled and won't be selectable or be part of the keyboard
* navigation across the menu options.
*
* @default true
*/
disabled?: boolean
/**
* When `true` the menu will close when the menu item is selected, in addition to performing the
* action that the menu item is set out to do.
*
* Set this to `false` to make sure that a given menu item does not auto-closes the menu when
* selected. This should be the exception and not the norm, as the default is to auto-close.
*
* @default true
*/
hideOnSelect?: boolean
/**
* The action to perform when the menu item is selected.
*
* If you return `false` from this function, the menu will not auto-close when this menu item
* is selected. Though you should use `hideOnSelect` for this purpose, this allows you to
* achieve the same effect conditionally and dynamically deciding at run time.
*/
onSelect?: () => unknown
/**
* The event handler called when the menu item is clicked.
*
* This is similar to `onSelect`, but a bit different. You can certainly use it to trigger the
* action that the menu item represents. But in general you should prefer `onSelect` for that.
*
* The main use for this handler is to get access to the click event. This can be used, for
* example, to call `event.preventDefault()`, which will effectively prevent the rest of the
* consequences of the click, including preventing `onSelect` from being called. In particular,
* this is useful in menu items that are links, and you want the click to not trigger navigation
* under some circumstances.
*/
onClick?: (event: React.MouseEvent) => void
}
/**
* A menu item inside a menu list. It can be selected by the user, triggering the `onSelect`
* callback.
*/
const MenuItem = React.forwardRef<HTMLDivElement, MenuItemProps>(function MenuItem(
{
value,
children,
onSelect,
hideOnSelect = true,
onClick,
exceptionallySetClassName,
...props
},
ref,
) {
const { handleItemSelect, menuStore } = React.useContext(MenuContext)
if (!menuStore) {
throw new Error('MenuItem must be wrapped in <Menu/>')
}
const { hide } = menuStore
const handleClick = React.useCallback(
function handleClick(event: React.MouseEvent) {
onClick?.(event)
const onSelectResult: unknown =
onSelect && !event.defaultPrevented ? onSelect() : undefined
const shouldClose = onSelectResult !== false && hideOnSelect
handleItemSelect?.(value)
if (shouldClose) hide()
},
[onSelect, onClick, handleItemSelect, hideOnSelect, hide, value],
)
return (
<AriakitMenuItem
{...props}
store={menuStore}
ref={ref}
onClick={handleClick}
className={exceptionallySetClassName}
hideOnClick={false}
>
{children}
</AriakitMenuItem>
)
})
//
// SubMenu
//
type SubMenuProps = Pick<MenuProps, 'children' | 'onItemSelect'>
/**
* This component can be rendered alongside other `MenuItem` inside a `MenuList` in order to have
* a sub-menu.
*
* Its children are expected to have the structure of a first level menu (a `MenuButton` and a
* `MenuList`).
*
* ```jsx
* <MenuItem label="Edit profile" />
* <SubMenu>
* <MenuButton>More options</MenuButton>
* <MenuList>
* <MenuItem label="Preferences" />
* <MenuItem label="Sign out" />
* </MenuList>
* </SubMenu>
* ```
*
* The `MenuButton` will become a menu item in the current menu items list, and it will lead to
* opening a sub-menu with the menu items list below it.
*/
const SubMenu = React.forwardRef<HTMLDivElement, SubMenuProps>(function SubMenu(
{ children, onItemSelect },
ref,
) {
const { handleItemSelect: parentMenuItemSelect, menuStore } = React.useContext(MenuContext)
if (!menuStore) {
throw new Error('SubMenu must be wrapped in <Menu/>')
}
const { hide: parentMenuHide } = menuStore
const handleSubItemSelect = React.useCallback(
function handleSubItemSelect(value: string | null | undefined) {
onItemSelect?.(value)
parentMenuItemSelect?.(value)
parentMenuHide()
},
[parentMenuHide, parentMenuItemSelect, onItemSelect],
)
const [button, list] = React.Children.toArray(children)
const buttonElement = button as React.ReactElement<MenuButtonProps>
const subMenuContextValue = React.useMemo(() => ({ isSubMenu: true }), [])
return (
<Menu onItemSelect={handleSubItemSelect}>
<AriakitMenuItem store={menuStore} ref={ref} hideOnClick={false} render={buttonElement}>
{buttonElement.props.children}
</AriakitMenuItem>
<SubMenuContext.Provider value={subMenuContextValue}>{list}</SubMenuContext.Provider>
</Menu>
)
})
//
// MenuGroup
//
interface MenuGroupProps
extends Omit<React.HTMLAttributes<HTMLDivElement>, 'className'>,
ObfuscatedClassName {
/**
* A label to be shown visually and also used to semantically label the group.
*/
label: string
}
/**
* A way to semantically group some menu items.
*
* This group does not add any visual separator. You can do that yourself adding `<hr />` elements
* before and/or after the group if you so wish.
*/
const MenuGroup = React.forwardRef<HTMLDivElement, MenuGroupProps>(function MenuGroup(
{ label, children, exceptionallySetClassName, ...props },
ref,
) {
const { menuStore } = React.useContext(MenuContext)
if (!menuStore) {
throw new Error('MenuGroup must be wrapped in <Menu/>')
}
return (
<AriakitMenuGroup
{...props}
ref={ref}
store={menuStore}
className={exceptionallySetClassName}
>
{label ? (
<div role="presentation" className="reactist_menugroup__label">
{label}
</div>
) : null}
{children}
</AriakitMenuGroup>
)
})
export { ContextMenuTrigger, Menu, MenuButton, MenuGroup, MenuItem, MenuList, SubMenu }
export type { MenuButtonProps, MenuGroupProps, MenuItemProps, MenuListProps }