-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathlistbox-button.tsx
316 lines (294 loc) · 12.1 KB
/
listbox-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
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
import React, {
Children, cloneElement, useEffect, useRef, useState,
ComponentProps, FC, KeyboardEvent, ReactElement, useCallback
} from 'react'
import classNames from 'classnames'
import { EbayIcon } from '../ebay-icon'
import { EbayChangeEventHandler, Key } from '../common/event-utils/types'
import { filterByType } from '../common/component-utils'
import EbayListboxButtonOption from './listbox-button-option'
export type ChangeEventProps = {
index: number;
selected: string[];
wasClicked: boolean;
}
export type EbayListboxButtonProps = Omit<ComponentProps<'button'>, 'onChange'> & {
selected?: number;
borderless?: boolean;
fluid?: boolean;
maxHeight?: string;
prefixId?: string;
prefixLabel?: string;
floatingLabel?: string;
unselectedText?: string;
onChange?: EbayChangeEventHandler<HTMLButtonElement, ChangeEventProps>;
onCollapse?: () => void;
onExpand?: () => void;
}
const ListboxButton: FC<EbayListboxButtonProps> = ({
children,
name,
value,
selected,
borderless,
fluid,
className,
maxHeight,
prefixId,
prefixLabel,
floatingLabel,
unselectedText = '-',
onChange = () => {},
onCollapse = () => {},
onExpand = () => {},
...rest
}) => {
const optionsContainerRef = useRef<HTMLDivElement>(null)
const optionsParentContainerRef = useRef<HTMLDivElement>()
const optionsByIndexRef = useRef(new Map())
const buttonRef = useRef<HTMLButtonElement>()
const listBoxButtonOptions = filterByType(children, EbayListboxButtonOption)
if (!listBoxButtonOptions.length) {
throw new Error(`EbayListboxButton: Please use a
EbayListboxButtonOption that defines the options of the listbox`)
}
const getInitialSelectedOption = (): { option: any, index: number } => {
const selectedIndex = selected !== undefined ? selected : listBoxButtonOptions.findIndex(({ props }) =>
value !== undefined && props.value === value)
const index = selectedIndex > -1 || floatingLabel ? selectedIndex : undefined
return {
option: listBoxButtonOptions[index],
index
}
}
// Get the default Selected value and set it in the state
const {
option: selectedOptionFromValue,
index: initialSelectedOptionIndex
} = getInitialSelectedOption()
// Update the selected option to the state
const [selectedOption, setSelectedOption] = useState(selectedOptionFromValue)
const [selectedIndex, setSelectedIndex] = useState(initialSelectedOptionIndex)
// Update the expanded status to the state
const [expanded, setExpanded] = useState<boolean|undefined>()
// Additional flag to avoid multiple re-render when users tries to open and close
const [optionsOpened, setOptionsOpened] = useState(false)
const [wasClicked, setWasClicked] = useState<boolean>()
useEffect(() => {
setSelectedOption(selectedOptionFromValue)
}, [value])
const childrenArray = Children.toArray(children) as ReactElement[]
const getSelectedValueByIndex = (index: number) => childrenArray[index].props.value
const getIndexByValue = useCallback((selectedValue) =>
childrenArray.findIndex(({ props }) => props.value === selectedValue), [childrenArray])
const getSelectedOption = (currentIndex: number) => optionsByIndexRef.current.get(currentIndex)
const collapseListbox = () => {
setExpanded(false)
onCollapse()
}
const expandListbox = () => {
setExpanded(true)
onExpand()
}
const toggleListbox = () => {
if (expanded) {
collapseListbox()
} else {
expandListbox()
}
}
const onOptionsSelect = (e, index) => {
// OnSelect set the selectedValue to the state and expanded to false to close the list box
setSelectedOption(childrenArray[index])
setSelectedIndex(index)
collapseListbox()
buttonRef.current.focus()
onChange(e, { index, selected: [getSelectedValueByIndex(index)], wasClicked })
setWasClicked(false)
}
const reset = () => {
collapseListbox()
setSelectedOption(childrenArray[initialSelectedOptionIndex])
}
const makeOptionActive = (index: number) => {
const optionEle = optionsContainerRef.current.children[index]
optionEle.setAttribute(`aria-selected`, 'true')
optionEle.classList.add(`listbox-button__option--active`)
}
const makeOptionInActive = (index: number) => {
const optionEle = optionsContainerRef.current.children[index]
optionEle.setAttribute(`aria-selected`, 'false')
optionEle.classList.remove(`listbox-button__option--active`)
}
// Followed the implementation from W3
// https://www.w3.org/TR/wai-aria-practices/examples/listbox/listbox-collapsible.html
const scrollOptions = (index: number) => {
const listboxOptionsContainerNode = optionsParentContainerRef.current
const currentTarget = getSelectedOption(index)
if (listboxOptionsContainerNode.scrollHeight > listboxOptionsContainerNode.clientHeight) {
const scrollBottom = listboxOptionsContainerNode.clientHeight + listboxOptionsContainerNode.scrollTop
const elementBottom = currentTarget.offsetTop + currentTarget.offsetHeight
if (elementBottom > scrollBottom) {
listboxOptionsContainerNode.scrollTop = elementBottom - listboxOptionsContainerNode.clientHeight
} else if (currentTarget.offsetTop < listboxOptionsContainerNode.scrollTop) {
listboxOptionsContainerNode.scrollTop = currentTarget.offsetTop
}
}
}
const makeSelections = (updatedIndex) => {
makeOptionActive(selectedIndex === undefined || updatedIndex === -1 ? 0 : updatedIndex)
makeOptionInActive(selectedIndex === undefined || selectedIndex === -1 ? 0 : selectedIndex)
scrollOptions(updatedIndex)
setSelectedIndex(updatedIndex)
setSelectedOption(childrenArray[updatedIndex])
}
const focusOptionsContainer = (focusOptions?: FocusOptions) =>
setTimeout(() => optionsContainerRef?.current?.focus(focusOptions), 0)
const onButtonClick = () => {
toggleListbox()
focusOptionsContainer({ preventScroll: true })
}
const onButtonKeyup = (e: KeyboardEvent<HTMLButtonElement>) => {
switch (e.key as Key) {
case 'Escape':
collapseListbox()
break
case 'Enter':
focusOptionsContainer()
break
default:
break
}
}
const onOptionContainerKeydown = (e: KeyboardEvent): void => {
switch (e.key as Key) {
case ' ':
case 'PageUp':
case 'PageDown':
case 'Home':
case 'End':
e.preventDefault()
break
case 'Down':
case 'ArrowDown':
e.preventDefault()
if (selectedIndex !== listBoxButtonOptions.length - 1) {
makeSelections(selectedIndex < listBoxButtonOptions.length - 1 ? selectedIndex + 1 : 0)
}
break
case 'Up':
case 'ArrowUp':
e.preventDefault()
if (selectedIndex !== 0) {
makeSelections(selectedIndex > 0 ? selectedIndex - 1 : listBoxButtonOptions.length - 1)
}
break
case 'Enter':
collapseListbox()
setTimeout(() => setSelectedOption(childrenArray[selectedIndex]))
setTimeout(() => buttonRef.current.focus(), 0)
onChange(e as any, {
index: selectedIndex,
selected: [getSelectedValueByIndex(selectedIndex)],
wasClicked
})
break
case 'Esc':
case 'Escape':
reset()
break
default:
break
}
}
// We want to mimic the select box behavior, so we take the onSelect that passed
// at the parent level and use it for the OnClick on the list box since it is a fake dropdown
const updateListBoxButtonOptions = listBoxButtonOptions
.map((child, index) => cloneElement(child, {
index,
key: index,
selected: selectedOption && child.props.value === selectedOption.props.value,
id: child.props.id || `listbox_btn_${child.props.value}_${index}`,
onClick: (e) => onOptionsSelect(e, index),
innerRef: optionNode => !optionNode
? optionsByIndexRef.current.delete(index)
: optionsByIndexRef.current.set(index, optionNode)
}))
const wrapperClassName = classNames('listbox-button', className, { 'listbox-button--fluid': fluid })
const buttonClassName = classNames('btn', {
'btn--form': !borderless,
'btn--borderless': borderless,
'btn--floating-label': floatingLabel && selectedOption
})
const expandBtnTextId = prefixId && 'expand-btn-text'
const buttonLabel = (
<>
{floatingLabel && <span className="btn__floating-label">{floatingLabel}</span>}
{prefixLabel && <span className="btn__label">{prefixLabel}</span>}
<span className="btn__text" id={expandBtnTextId}>
{selectedOption?.props.children || unselectedText}
</span>
</>
)
return (
<span className={wrapperClassName}>
<button
{...rest}
onFocus={() => setOptionsOpened(true)}
type="button"
className={buttonClassName}
aria-expanded={!!expanded}
aria-haspopup="listbox"
aria-labelledby={prefixId && `${prefixId} ${expandBtnTextId}`}
onClick={onButtonClick}
// https://stackoverflow.com/questions/17769005/onclick-and-onblur-ordering-issue
onMouseDown={(e) => e.preventDefault()}
onKeyUp={onButtonKeyup}
ref={buttonRef}
>
<span className="btn__cell">
{buttonLabel}
<EbayIcon name="chevronDown12" />
</span>
</button>
{(expanded || optionsOpened) &&
<div
className="listbox-button__listbox"
ref={optionsParentContainerRef}
style={{ maxHeight: maxHeight }}>
<div
className="listbox-button__options"
role="listbox"
tabIndex={expanded ? 0 : -1}
ref={optionsContainerRef}
aria-activedescendant={updateListBoxButtonOptions[selectedIndex]?.props.id}
onKeyDown={(e) => onOptionContainerKeydown(e)}
// adding onMouseDown preventDefault b/c on IE the onClick event is not being fired on each
// option https://stackoverflow.com/questions/17769005/onclick-and-onblur-ordering-issue
onMouseDown={(e) => {
e.preventDefault()
setWasClicked(true)
}}
onBlur={() => {
collapseListbox()
setTimeout(() => buttonRef.current.focus(), 0)
}}
>
{updateListBoxButtonOptions}
</div>
</div>}
<select
hidden
className="listbox-button__native"
name={name}
onChange={(e) => onOptionsSelect(e, getIndexByValue(e.target.value))}
value={selectedOption ? selectedOption?.props.value : ''}>
{
updateListBoxButtonOptions.map((option, i) =>
<option value={option.props.value} key={i} />)
}
</select>
</span>
)
}
export default ListboxButton