-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathmenu-button.tsx
177 lines (159 loc) · 6.53 KB
/
menu-button.tsx
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
import React, { cloneElement, ComponentProps, FC, useEffect, useState } from 'react'
import classnames from 'classnames'
import { filterByType, findComponent } from '../common/component-utils'
import { EbayMenu, EbayMenuChangeEventHandler } from '../ebay-menu'
import { EbayButton, EbayButtonProps } from '../ebay-button'
import { EbayIconButton } from '../ebay-icon-button'
import { EbayIcon } from '../ebay-icon'
import { EbayMenuButtonItem, EbayMenuButtonLabel, EbayMenuButtonSeparator, LabelProps, MenuButtonProps } from './index'
import { randomId } from '../common/random-id'
import { handleEscapeKeydown } from '../common/event-utils'
import { useFloatingDropdown } from '../common/dropdown'
type ButtonProps = Omit<EbayButtonProps, 'variant' | 'onKeyDown' | 'onMouseDown'> &
Omit<ComponentProps<'button'>, 'onKeyDown' | 'onMouseDown' | 'onSelect'> &
Omit<ComponentProps<'a'>, 'onKeyDown' | 'onMouseDown' | 'onSelect'>
const EbayMenuButton: FC<MenuButtonProps> = ({
type,
variant = 'button',
className,
text = '',
fixWidth,
reverse,
expanded: defaultExpanded,
noToggleIcon,
checked,
collapseOnSelect,
a11yText,
prefixId,
prefixLabel,
onClick = () => {},
onExpand = () => {},
onCollapse = () => {},
onChange = () => {},
onSelect = () => {},
children,
...rest
}) => {
const [expanded, setExpanded] = useState(defaultExpanded)
const [menuId, setMenuId] = useState<string | undefined>()
const { overlayStyles, refs } = useFloatingDropdown({
open: expanded,
options: { reverse }
})
const buttonRef = refs.host as React.MutableRefObject<HTMLButtonElement>
const menuRef = refs.overlay
const menuItems = filterByType(children, [EbayMenuButtonItem, EbayMenuButtonSeparator])
const defaultIndexes = menuItems.map((item) => Boolean(item.props.checked))
const [checkedIndexes, setCheckedIndexes] = useState<boolean[]>(defaultIndexes)
const menuButtonLabel = findComponent(children, EbayMenuButtonLabel)
const icon = findComponent(children, EbayIcon)
const label = labelWithPrefixAndIcon({ text, prefixId, prefixLabel, menuButtonLabel, icon })
const wrapperClasses = classnames('menu-button', className)
const menuClasses = classnames('menu-button__menu', {
'menu-button__menu--fix-width': fixWidth,
'menu-button__menu--reverse': reverse
})
useEffect(() => {
const handleBackgroundClick = (e: React.MouseEvent) => {
const menuEl = menuRef.current as HTMLDivElement
const menuClicked = menuEl && menuEl.contains(e.target as Node)
if (collapseOnSelect || !menuClicked) {
setExpanded(false)
}
}
if (expanded) {
onExpand()
// On React 18 useEffect hooks runs synchronous instead of asynchronous as React 17 or prior
// causing the event listener to be attached to the document at the same time that the dialog
// opens. Adding a timeout so the event is attached after the click event that opened the modal
// is finished.
setTimeout(() => {
document.addEventListener('click', handleBackgroundClick as any, false)
})
} else if (expanded === false) {
onCollapse()
}
return () => document.removeEventListener('click', handleBackgroundClick as any, false)
}, [expanded])
useEffect(() => {
setMenuId(randomId())
}, [])
const handleMenuKeydown = (e) => {
handleEscapeKeydown(e, () => {
setExpanded(false)
buttonRef.current?.focus()
})
}
const buttonProps: Omit<ButtonProps, 'type' | 'ref'> = {
ref: refs.setHost,
className: 'menu-button__button',
'aria-expanded': !!expanded,
'aria-haspopup': true,
'aria-label': a11yText,
'aria-controls': menuId,
'aria-labelledby': prefixId,
onClick: e => {
setExpanded(!expanded)
onClick(e)
},
...rest
}
const handleOnChange: EbayMenuChangeEventHandler = (e, eventProps) => {
if (type === 'radio' || type === 'checkbox') {
const newCheckedIndexes = checkedIndexes.map((_, i) => eventProps.indexes.includes(i))
setCheckedIndexes(newCheckedIndexes)
}
onChange(e, eventProps)
}
const checkedIndex = () => {
const index = checkedIndexes.findIndex(Boolean)
return index > -1 ? index : checked
}
return (
<span className={wrapperClasses}>
{variant === 'overflow' ?
<EbayIconButton icon="overflowVertical16" {...buttonProps} /> :
<EbayButton
variant={variant === 'form' ? 'form' : undefined}
{...buttonProps}
>
{label}
{!noToggleIcon ? <EbayIcon name="chevronDown12" /> : null}
</EbayButton>
}
{expanded &&
<EbayMenu
baseEl="div"
ref={refs.setOverlay as any /* TODO: Update @types/react version to fix the type */}
type={type}
className={menuClasses}
tabIndex={-1}
id={menuId}
autofocus
checked={checkedIndex()}
onKeyDown={handleMenuKeydown}
onChange={handleOnChange}
onSelect={onSelect}
style={overlayStyles}
>
{menuItems.map((item, i) =>
cloneElement(item, {
...item.props,
className: classnames(item.props.className, 'menu-button__item'),
key: i,
checked: checkedIndexes[i]
})
)}
</EbayMenu>
}
</span>
)
}
function labelWithPrefixAndIcon({ text, prefixId, prefixLabel, menuButtonLabel, icon }: LabelProps) {
const textLabelElement = text.length ? <span>{text}</span> : null
const prefixLabelElement = !prefixId && prefixLabel &&
<><span className="menu-button-prefix-label" key="prefix-label">{prefixLabel}</span> </>
const labelArray = [icon, prefixLabelElement, menuButtonLabel || textLabelElement].filter(Boolean) as JSX.Element[]
return labelArray.map((item, i) => cloneElement(item, { ...item.props, key: i }))
}
export default EbayMenuButton