-
Notifications
You must be signed in to change notification settings - Fork 268
/
index.js
378 lines (337 loc) · 11.4 KB
/
index.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
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
/*!
* React Dropdown Tree Select
* A lightweight, fast and highly customizable tree select component.
* Hrusikesh Panda <hrusikesh.panda@dowjones.com>
* Copyright (c) 2017 Dow Jones, Inc. <support@dowjones.com> (http://dowjones.com)
* license MIT
* see https://github.com/dowjones/react-dropdown-tree-select
*/
import PropTypes from 'prop-types'
import React, { Component } from 'react'
import { isOutsideClick, clientIdGenerator } from './utils'
import Input from './input'
import Tags from './tags'
import Trigger from './trigger'
import Tree from './tree'
import TreeManager from './tree-manager'
import keyboardNavigation from './tree-manager/keyboardNavigation'
import './index.css'
import { getAriaLabel } from './a11y'
class DropdownTreeSelect extends Component {
static propTypes = {
data: PropTypes.oneOfType([PropTypes.object, PropTypes.array]).isRequired,
clearSearchOnChange: PropTypes.bool,
keepTreeOnSearch: PropTypes.bool,
keepChildrenOnSearch: PropTypes.bool,
keepOpenOnSelect: PropTypes.bool,
texts: PropTypes.shape({
placeholder: PropTypes.string,
inlineSearchPlaceholder: PropTypes.string,
noMatches: PropTypes.string,
label: PropTypes.string,
labelRemove: PropTypes.string,
}),
showDropdown: PropTypes.oneOf(['default', 'initial', 'always']),
className: PropTypes.string,
onChange: PropTypes.func,
onAction: PropTypes.func,
onNodeToggle: PropTypes.func,
onFocus: PropTypes.func,
onBlur: PropTypes.func,
mode: PropTypes.oneOf(['multiSelect', 'simpleSelect', 'radioSelect', 'hierarchical']),
showPartiallySelected: PropTypes.bool,
disabled: PropTypes.bool,
readOnly: PropTypes.bool,
id: PropTypes.string,
searchPredicate: PropTypes.func,
inlineSearchInput: PropTypes.bool,
tabIndex: PropTypes.number,
disablePoppingOnBackspace: PropTypes.bool,
}
static defaultProps = {
onAction: () => {},
onFocus: () => {},
onBlur: () => {},
onChange: () => {},
texts: {},
showDropdown: 'default',
inlineSearchInput: false,
tabIndex: 0,
disablePoppingOnBackspace: false,
}
constructor(props) {
super(props)
this.state = {
searchModeOn: false,
currentFocus: undefined,
}
this.clientId = props.id || clientIdGenerator.get(this)
}
initNewProps = ({ data, mode, showDropdown, showPartiallySelected, searchPredicate }) => {
this.treeManager = new TreeManager({
data,
mode,
showPartiallySelected,
rootPrefixId: this.clientId,
searchPredicate,
})
this.setState(prevState => {
const currentFocusNode = prevState.currentFocus && this.treeManager.getNodeById(prevState.currentFocus)
if (currentFocusNode) {
currentFocusNode._focused = true
}
return {
showDropdown: /initial|always/.test(showDropdown) || prevState.showDropdown === true,
...this.treeManager.getTreeAndTags(),
}
})
}
resetSearchState = () => {
// clear the search criteria and avoid react controlled/uncontrolled warning
if (this.searchInput) {
this.searchInput.value = ''
}
return {
tree: this.treeManager.restoreNodes(), // restore the tree to its pre-search state
searchModeOn: false,
allNodesHidden: false,
}
}
UNSAFE_componentWillMount() {
this.initNewProps(this.props)
}
componentWillUnmount() {
document.removeEventListener('click', this.handleOutsideClick, false)
}
UNSAFE_componentWillReceiveProps(nextProps) {
this.initNewProps(nextProps)
}
handleClick = (e, callback) => {
this.setState(prevState => {
// keep dropdown active when typing in search box
const showDropdown = this.props.showDropdown === 'always' || this.keepDropdownActive || !prevState.showDropdown
// register event listeners only if there is a state change
if (showDropdown !== prevState.showDropdown) {
if (showDropdown) {
document.addEventListener('click', this.handleOutsideClick, false)
} else {
document.removeEventListener('click', this.handleOutsideClick, false)
}
}
if (showDropdown) this.props.onFocus()
else this.props.onBlur()
return !showDropdown ? { showDropdown, ...this.resetSearchState() } : { showDropdown }
}, callback)
}
handleOutsideClick = e => {
if (this.props.showDropdown === 'always' || !isOutsideClick(e, this.node)) {
return
}
this.handleClick()
}
onInputChange = value => {
const searchModeOn = value.length > 0
if (!searchModeOn) {
this.setState(this.resetSearchState())
} else {
const { allNodesHidden, tree } = this.treeManager.filterTree(
value,
this.props.keepTreeOnSearch,
this.props.keepChildrenOnSearch
)
this.setState({
tree,
searchModeOn,
allNodesHidden,
})
}
}
onTagRemove = (id, isKeyboardEvent) => {
const { tags: prevTags } = this.state
this.onCheckboxChange(id, false, tags => {
if (!isKeyboardEvent) return
keyboardNavigation.getNextFocusAfterTagDelete(id, prevTags, tags, this.searchInput).focus()
})
}
onNodeToggle = id => {
this.treeManager.toggleNodeExpandState(id)
const tree = this.state.searchModeOn ? this.treeManager.matchTree : this.treeManager.tree
this.setState({ tree })
typeof this.props.onNodeToggle === 'function' && this.props.onNodeToggle(this.treeManager.getNodeById(id))
}
onCheckboxChange = (id, checked, callback) => {
const { mode, keepOpenOnSelect, clearSearchOnChange } = this.props
const { currentFocus, searchModeOn } = this.state
this.treeManager.setNodeCheckedState(id, checked)
let tags = this.treeManager.tags
const isSingleSelect = ['simpleSelect', 'radioSelect'].indexOf(mode) > -1
const showDropdown = isSingleSelect && !keepOpenOnSelect ? false : this.state.showDropdown
const currentFocusNode = currentFocus && this.treeManager.getNodeById(currentFocus)
const node = this.treeManager.getNodeById(id)
if (!tags.length) {
this.treeManager.restoreDefaultValues()
tags = this.treeManager.tags
}
const tree = searchModeOn ? this.treeManager.matchTree : this.treeManager.tree
const nextState = {
tree,
tags,
showDropdown,
currentFocus: id,
}
if ((isSingleSelect && !showDropdown) || clearSearchOnChange) {
Object.assign(nextState, this.resetSearchState())
}
if (isSingleSelect && !showDropdown) {
document.removeEventListener('click', this.handleOutsideClick, false)
}
keyboardNavigation.adjustFocusedProps(currentFocusNode, node)
this.setState(nextState, () => {
callback && callback(tags)
})
this.props.onChange(node, tags)
}
onAction = (nodeId, action) => {
this.props.onAction(this.treeManager.getNodeById(nodeId), action)
}
onInputFocus = () => {
this.keepDropdownActive = true
}
onInputBlur = () => {
this.keepDropdownActive = false
}
onTrigger = e => {
this.handleClick(e, () => {
// If the dropdown is shown after key press, focus the input
if (this.state.showDropdown) {
this.searchInput.focus()
}
})
}
onKeyboardKeyDown = e => {
const { readOnly, mode, disablePoppingOnBackspace } = this.props
const { showDropdown, tags, searchModeOn, currentFocus } = this.state
const tm = this.treeManager
const tree = searchModeOn ? tm.matchTree : tm.tree
if (!showDropdown && (keyboardNavigation.isValidKey(e.key, false) || /^\w$/i.test(e.key))) {
// Triggers open of dropdown and retriggers event
e.persist()
this.handleClick(null, () => this.onKeyboardKeyDown(e))
if (/\w/i.test(e.key)) return
} else if (showDropdown && keyboardNavigation.isValidKey(e.key, true)) {
const newFocus = tm.handleNavigationKey(
currentFocus,
tree,
e.key,
readOnly,
!searchModeOn,
this.onCheckboxChange,
this.onNodeToggle
)
if (newFocus !== currentFocus) {
this.setState({ currentFocus: newFocus }, () => {
const ele = document && document.getElementById(`${newFocus}_li`)
ele && ele.scrollIntoView()
})
}
} else if (showDropdown && ['Escape', 'Tab'].indexOf(e.key) > -1) {
if (mode === 'simpleSelect' && tree.has(currentFocus)) {
this.onCheckboxChange(currentFocus, true)
} else {
// Triggers close
this.keepDropdownActive = false
this.handleClick()
}
return
} else if (
!disablePoppingOnBackspace &&
e.key === 'Backspace' &&
tags.length &&
this.searchInput.value.length === 0
) {
const lastTag = tags.pop()
this.onCheckboxChange(lastTag._id, false)
} else {
return
}
e.preventDefault()
}
getAriaAttributes = () => {
const { mode, texts } = this.props
if (mode !== 'radioSelect') return {}
return {
role: 'radiogroup',
...getAriaLabel(texts.label),
}
}
render() {
const { disabled, readOnly, mode, texts, inlineSearchInput, tabIndex } = this.props
const { showDropdown, currentFocus, tags } = this.state
const activeDescendant = currentFocus ? `${currentFocus}_li` : undefined
const commonProps = { disabled, readOnly, activeDescendant, texts, mode, clientId: this.clientId }
const searchInput = (
<Input
inputRef={el => {
this.searchInput = el
}}
onInputChange={this.onInputChange}
onFocus={this.onInputFocus}
onBlur={this.onInputBlur}
onKeyDown={this.onKeyboardKeyDown}
{...commonProps}
inlineSearchInput={inlineSearchInput}
/>
)
return (
<div
id={this.clientId}
className={[this.props.className && this.props.className, 'react-dropdown-tree-select']
.filter(Boolean)
.join(' ')}
ref={node => {
this.node = node
}}
>
<div
className={['dropdown', mode === 'simpleSelect' && 'simple-select', mode === 'radioSelect' && 'radio-select']
.filter(Boolean)
.join(' ')}
>
<Trigger
onTrigger={this.onTrigger}
showDropdown={showDropdown}
{...commonProps}
tags={tags}
tabIndex={tabIndex}
>
<Tags tags={tags} onTagRemove={this.onTagRemove} {...commonProps}>
{!inlineSearchInput && searchInput}
</Tags>
</Trigger>
{showDropdown && (
<div className="dropdown-content" {...this.getAriaAttributes()}>
{inlineSearchInput && searchInput}
{this.state.allNodesHidden ? (
<span className="no-matches">{texts.noMatches || 'No matches found'}</span>
) : (
<Tree
data={this.state.tree}
keepTreeOnSearch={this.props.keepTreeOnSearch}
keepChildrenOnSearch={this.props.keepChildrenOnSearch}
searchModeOn={this.state.searchModeOn}
onAction={this.onAction}
onCheckboxChange={this.onCheckboxChange}
onNodeToggle={this.onNodeToggle}
mode={mode}
showPartiallySelected={this.props.showPartiallySelected}
{...commonProps}
/>
)}
</div>
)}
</div>
</div>
)
}
}
export default DropdownTreeSelect