/
Dropdown.js
302 lines (265 loc) · 8.81 KB
/
Dropdown.js
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
/* eslint react/no-find-dom-node: 0 */
// https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-find-dom-node.md
import React from 'react';
import PropTypes from 'prop-types';
import { Manager } from 'react-popper';
import classNames from 'classnames';
import { DropdownContext } from './DropdownContext';
import { mapToCssModules, omit, keyCodes, tagPropType } from './utils';
const propTypes = {
a11y: PropTypes.bool,
disabled: PropTypes.bool,
direction: PropTypes.oneOf(['up', 'down', 'start', 'end']),
group: PropTypes.bool,
isOpen: PropTypes.bool,
nav: PropTypes.bool,
active: PropTypes.bool,
size: PropTypes.string,
tag: tagPropType,
toggle: PropTypes.func,
children: PropTypes.node,
className: PropTypes.string,
cssModule: PropTypes.object,
inNavbar: PropTypes.bool,
setActiveFromChild: PropTypes.bool,
menuRole: PropTypes.oneOf(['listbox', 'menu'])
};
const defaultProps = {
a11y: true,
isOpen: false,
direction: 'down',
nav: false,
active: false,
inNavbar: false,
setActiveFromChild: false
};
const preventDefaultKeys = [
keyCodes.space,
keyCodes.enter,
keyCodes.up,
keyCodes.down,
keyCodes.end,
keyCodes.home
]
class Dropdown extends React.Component {
constructor(props) {
super(props);
this.addEvents = this.addEvents.bind(this);
this.handleDocumentClick = this.handleDocumentClick.bind(this);
this.handleKeyDown = this.handleKeyDown.bind(this);
this.removeEvents = this.removeEvents.bind(this);
this.toggle = this.toggle.bind(this);
this.handleMenuRef = this.handleMenuRef.bind(this);
this.containerRef = React.createRef();
this.menuRef = React.createRef();
}
handleMenuRef(menuRef) {
this.menuRef.current = menuRef;
}
getContextValue() {
return {
toggle: this.toggle,
isOpen: this.props.isOpen,
direction: (this.props.direction === 'down' && this.props.dropup) ? 'up' : this.props.direction,
inNavbar: this.props.inNavbar,
disabled: this.props.disabled,
// Callback that should be called by DropdownMenu to provide a ref to
// a HTML tag that's used for the DropdownMenu
onMenuRef: this.handleMenuRef,
menuRole: this.props.menuRole
};
}
componentDidMount() {
this.handleProps();
}
componentDidUpdate(prevProps) {
if (this.props.isOpen !== prevProps.isOpen) {
this.handleProps();
}
}
componentWillUnmount() {
this.removeEvents();
}
getContainer() {
return this.containerRef.current;
}
getMenu() {
return this.menuRef.current;
}
getMenuCtrl() {
if (this._$menuCtrl) return this._$menuCtrl;
this._$menuCtrl = this.getContainer().querySelector('[aria-expanded]');
return this._$menuCtrl;
}
getItemType() {
if(this.context.menuRole === 'listbox') {
return 'option'
}
return 'menuitem'
}
getMenuItems() {
// In a real menu with a child DropdownMenu, `this.getMenu()` should never
// be null, but it is sometimes null in tests. To mitigate that, we just
// use `this.getContainer()` as the fallback `menuContainer`.
const menuContainer = this.getMenu() || this.getContainer();
return [].slice.call(menuContainer.querySelectorAll(`[role="${this.getItemType()}"]`));
}
addEvents() {
['click', 'touchstart', 'keyup'].forEach(event =>
document.addEventListener(event, this.handleDocumentClick, true)
);
}
removeEvents() {
['click', 'touchstart', 'keyup'].forEach(event =>
document.removeEventListener(event, this.handleDocumentClick, true)
);
}
handleDocumentClick(e) {
if (e && (e.which === 3 || (e.type === 'keyup' && e.which !== keyCodes.tab))) return;
const container = this.getContainer();
const menu = this.getMenu();
const clickIsInContainer = container.contains(e.target) && container !== e.target;
const clickIsInInput = container.classList.contains('input-group') && container.classList.contains('dropdown') && e.target.tagName === 'INPUT';
const clickIsInMenu = menu && menu.contains(e.target) && menu !== e.target;
if (((clickIsInContainer && !clickIsInInput) || clickIsInMenu) && (e.type !== 'keyup' || e.which === keyCodes.tab)) {
return;
}
this.toggle(e);
}
handleKeyDown(e) {
const isTargetMenuItem = e.target.getAttribute('role') === 'menuitem' || e.target.getAttribute('role') === 'option';
const isTargetMenuCtrl = this.getMenuCtrl() === e.target;
const isTab = keyCodes.tab === e.which;
if (
/input|textarea/i.test(e.target.tagName)
|| (isTab && !this.props.a11y)
|| (isTab && !(isTargetMenuItem || isTargetMenuCtrl))
) {
return;
}
if (preventDefaultKeys.indexOf(e.which) !== -1 || ((e.which >= 48) && (e.which <= 90))) {
e.preventDefault();
}
if (this.props.disabled) return;
if (isTargetMenuCtrl) {
if ([keyCodes.space, keyCodes.enter, keyCodes.up, keyCodes.down].indexOf(e.which) > -1) {
// Open the menu (if not open) and focus the first menu item
if (!this.props.isOpen) {
this.toggle(e);
}
setTimeout(() => this.getMenuItems()[0].focus());
} else if (this.props.isOpen && isTab) {
// Focus the first menu item if tabbing from an open menu. We need this
// for cases where the DropdownMenu sets a custom container, which may
// not be the natural next item to tab to from the DropdownToggle.
e.preventDefault();
this.getMenuItems()[0].focus();
} else if (this.props.isOpen && e.which === keyCodes.esc) {
this.toggle(e);
}
}
if (this.props.isOpen && isTargetMenuItem) {
if ([keyCodes.tab, keyCodes.esc].indexOf(e.which) > -1) {
this.toggle(e);
this.getMenuCtrl().focus();
} else if ([keyCodes.space, keyCodes.enter].indexOf(e.which) > -1) {
e.target.click();
this.getMenuCtrl().focus();
} else if (
[keyCodes.down, keyCodes.up].indexOf(e.which) > -1
|| ([keyCodes.n, keyCodes.p].indexOf(e.which) > -1 && e.ctrlKey)
) {
const $menuitems = this.getMenuItems();
let index = $menuitems.indexOf(e.target);
if (keyCodes.up === e.which || (keyCodes.p === e.which && e.ctrlKey)) {
index = index !== 0 ? index - 1 : $menuitems.length - 1;
} else if (keyCodes.down === e.which || (keyCodes.n === e.which && e.ctrlKey)) {
index = index === $menuitems.length - 1 ? 0 : index + 1;
}
$menuitems[index].focus();
} else if (keyCodes.end === e.which) {
const $menuitems = this.getMenuItems();
$menuitems[$menuitems.length - 1].focus();
} else if (keyCodes.home === e.which) {
const $menuitems = this.getMenuItems();
$menuitems[0].focus();
} else if ((e.which >= 48) && (e.which <= 90)) {
const $menuitems = this.getMenuItems();
const charPressed = String.fromCharCode(e.which).toLowerCase();
for (let i = 0; i < $menuitems.length; i += 1) {
const firstLetter = $menuitems[i].textContent && $menuitems[i].textContent[0].toLowerCase();
if (firstLetter === charPressed) {
$menuitems[i].focus();
break;
}
}
}
}
}
handleProps() {
if (this.props.isOpen) {
this.addEvents();
} else {
this.removeEvents();
}
}
toggle(e) {
if (this.props.disabled) {
return e && e.preventDefault();
}
return this.props.toggle(e);
}
render() {
const {
className,
cssModule,
direction,
isOpen,
group,
size,
nav,
setActiveFromChild,
active,
tag,
menuRole,
...attrs
} = omit(this.props, ['toggle', 'disabled', 'inNavbar', 'a11y']);
const Tag = tag || (nav ? 'li' : 'div');
let subItemIsActive = false;
if (setActiveFromChild) {
React.Children.map(this.props.children[1].props.children,
(dropdownItem) => {
if (dropdownItem && dropdownItem.props.active) subItemIsActive = true;
}
);
}
const classes = mapToCssModules(classNames(
className,
direction !== 'down' && `drop${direction}`,
nav && active ? 'active' : false,
setActiveFromChild && subItemIsActive ? 'active' : false,
{
'btn-group': group,
[`btn-group-${size}`]: !!size,
dropdown: !group,
show: isOpen,
'nav-item': nav
}
), cssModule);
return (
<DropdownContext.Provider value={this.getContextValue()}>
<Manager>
<Tag
{...attrs}
{...{ [typeof Tag === 'string' ? 'ref' : 'innerRef']: this.containerRef }}
onKeyDown={this.handleKeyDown}
className={classes}
/>
</Manager>
</DropdownContext.Provider>
);
}
}
Dropdown.propTypes = propTypes;
Dropdown.defaultProps = defaultProps;
export default Dropdown;