-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Copy pathDropdown.js
1285 lines (1075 loc) · 37.3 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
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import cx from 'classnames'
import _ from 'lodash'
import PropTypes from 'prop-types'
import React, { Children, cloneElement } from 'react'
import {
AutoControlledComponent as Component,
customPropTypes,
getElementType,
getUnhandledProps,
isBrowser,
keyboardKey,
makeDebugger,
META,
objectDiff,
useKeyOnly,
useKeyOrValueAndKey,
} from '../../lib'
import Icon from '../../elements/Icon'
import Label from '../../elements/Label'
import DropdownDivider from './DropdownDivider'
import DropdownItem from './DropdownItem'
import DropdownHeader from './DropdownHeader'
import DropdownMenu from './DropdownMenu'
const debug = makeDebugger('dropdown')
/**
* A dropdown allows a user to select a value from a series of options.
* @see Form
* @see Select
* @see Menu
*/
export default class Dropdown extends Component {
static propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** Label prefixed to an option added by a user. */
additionLabel: PropTypes.oneOfType([
PropTypes.element,
PropTypes.string,
]),
/** Position of the `Add: ...` option in the dropdown list ('top' or 'bottom'). */
additionPosition: PropTypes.oneOf(['top', 'bottom']),
/**
* Allow user additions to the list of options (boolean).
* Requires the use of `selection`, `options` and `search`.
*/
allowAdditions: customPropTypes.every([
customPropTypes.demand(['options', 'selection', 'search']),
PropTypes.bool,
]),
/** A Dropdown can reduce its complexity. */
basic: PropTypes.bool,
/** Format the Dropdown to appear as a button. */
button: PropTypes.bool,
/** Primary content. */
children: customPropTypes.every([
customPropTypes.disallow(['options', 'selection']),
customPropTypes.givenProps(
{ children: PropTypes.any.isRequired },
PropTypes.element.isRequired,
),
]),
/** Additional classes. */
className: PropTypes.string,
/** Whether or not the menu should close when the dropdown is blurred. */
closeOnBlur: PropTypes.bool,
/**
* Whether or not the menu should close when a value is selected from the dropdown.
* By default, multiple selection dropdowns will remain open on change, while single
* selection dropdowns will close on change.
*/
closeOnChange: PropTypes.bool,
/** A compact dropdown has no minimum width. */
compact: PropTypes.bool,
/** Initial value of open. */
defaultOpen: PropTypes.bool,
/** Currently selected label in multi-select. */
defaultSelectedLabel: customPropTypes.every([
customPropTypes.demand(['multiple']),
PropTypes.oneOfType([
PropTypes.number,
PropTypes.string,
]),
]),
/** Initial value or value array if multiple. */
defaultValue: PropTypes.oneOfType([
PropTypes.number,
PropTypes.string,
PropTypes.arrayOf(PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
])),
]),
/** A disabled dropdown menu or item does not allow user interaction. */
disabled: PropTypes.bool,
/** An errored dropdown can alert a user to a problem. */
error: PropTypes.bool,
/** A dropdown menu can contain floated content. */
floating: PropTypes.bool,
/** A dropdown can take the full width of its parent */
fluid: PropTypes.bool,
/** A dropdown menu can contain a header. */
header: PropTypes.node,
/** Shorthand for Icon. */
icon: PropTypes.oneOfType([
PropTypes.node,
PropTypes.object,
]),
/** A dropdown can be formatted to appear inline in other content. */
inline: PropTypes.bool,
/** A dropdown can be formatted as a Menu item. */
item: PropTypes.bool,
/** A dropdown can be labeled. */
labeled: PropTypes.bool,
/** A dropdown can show that it is currently loading data. */
loading: PropTypes.bool,
/** A selection dropdown can allow multiple selections. */
multiple: PropTypes.bool,
/** Name of the hidden input which holds the value. */
name: PropTypes.string,
/** Message to display when there are no results. */
noResultsMessage: PropTypes.string,
/**
* Called when a user adds a new item. Use this to update the options list.
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All props and the new item's value.
*/
onAddItem: PropTypes.func,
/**
* Called on blur.
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All props.
*/
onBlur: PropTypes.func,
/**
* Called when the user attempts to change the value.
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All props and proposed value.
*/
onChange: PropTypes.func,
/**
* Called on click.
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All props.
*/
onClick: PropTypes.func,
/**
* Called when a close event happens.
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All props.
*/
onClose: PropTypes.func,
/**
* Called on focus.
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All props.
*/
onFocus: PropTypes.func,
/**
* Called when a multi-select label is clicked.
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All label props.
*/
onLabelClick: PropTypes.func,
/**
* Called on mousedown.
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All props.
*/
onMouseDown: PropTypes.func,
/**
* Called when an open event happens.
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All props.
*/
onOpen: PropTypes.func,
/**
* Called on search input change.
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {string} value - Current value of search input.
*/
onSearchChange: PropTypes.func,
/** Controls whether or not the dropdown menu is displayed. */
open: PropTypes.bool,
/** Whether or not the menu should open when the dropdown is focused. */
openOnFocus: PropTypes.bool,
/** Array of Dropdown.Item props e.g. `{ text: '', value: '' }` */
options: customPropTypes.every([
customPropTypes.disallow(['children']),
PropTypes.arrayOf(PropTypes.shape(DropdownItem.propTypes)),
]),
/** Placeholder text. */
placeholder: PropTypes.string,
/** A dropdown can be formatted so that its menu is pointing. */
pointing: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.oneOf(['left', 'right', 'top', 'top left', 'top right', 'bottom', 'bottom left', 'bottom right']),
]),
/**
* Mapped over the active items and returns shorthand for the active item Labels.
* Only applies to `multiple` Dropdowns.
*
* @param {object} item - A currently active dropdown item.
* @param {number} index - The current index.
* @param {object} defaultLabelProps - The default props for an active item Label.
* @returns {*} Shorthand for a Label.
*/
renderLabel: PropTypes.func,
/** A dropdown can have its menu scroll. */
scrolling: PropTypes.bool,
/**
* A selection dropdown can allow a user to search through a large list of choices.
* Pass a function here to replace the default search.
*/
search: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.func,
]),
// TODO 'searchInMenu' or 'search='in menu' or ??? How to handle this markup and functionality?
/** Define whether the highlighted item should be selected on blur. */
selectOnBlur: PropTypes.bool,
/** Currently selected label in multi-select. */
selectedLabel: customPropTypes.every([
customPropTypes.demand(['multiple']),
PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
]),
]),
/** A dropdown can be used to select between choices in a form. */
selection: customPropTypes.every([
customPropTypes.disallow(['children']),
customPropTypes.demand(['options']),
PropTypes.bool,
]),
/** A simple dropdown can open without Javascript. */
simple: PropTypes.bool,
/** A dropdown can receive focus. */
tabIndex: PropTypes.oneOfType([
PropTypes.number,
PropTypes.string,
]),
/** The text displayed in the dropdown, usually for the active item. */
text: PropTypes.string,
/** Custom element to trigger the menu to become visible. Takes place of 'text'. */
trigger: customPropTypes.every([
customPropTypes.disallow(['selection', 'text']),
PropTypes.node,
]),
/** Current value or value array if multiple. Creates a controlled component. */
value: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
PropTypes.arrayOf(PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
])),
]),
/** A dropdown can open upward. */
upward: PropTypes.bool,
}
static defaultProps = {
additionLabel: 'Add ',
additionPosition: 'top',
icon: 'dropdown',
noResultsMessage: 'No results found.',
renderLabel: ({ text }) => text,
selectOnBlur: true,
openOnFocus: true,
closeOnBlur: true,
}
static autoControlledProps = [
'open',
'value',
'selectedLabel',
]
static _meta = {
name: 'Dropdown',
type: META.TYPES.MODULE,
}
static Divider = DropdownDivider
static Header = DropdownHeader
static Item = DropdownItem
static Menu = DropdownMenu
componentWillMount() {
if (super.componentWillMount) super.componentWillMount()
debug('componentWillMount()')
const { open, value } = this.state
this.setValue(value)
if (open) this.open()
}
shouldComponentUpdate(nextProps, nextState) {
return !_.isEqual(nextProps, this.props) || !_.isEqual(nextState, this.state)
}
componentWillReceiveProps(nextProps) {
super.componentWillReceiveProps(nextProps)
debug('componentWillReceiveProps()')
// TODO objectDiff still runs in prod, stop it
debug('to props:', objectDiff(this.props, nextProps))
/* eslint-disable no-console */
if (process.env.NODE_ENV !== 'production') {
// in development, validate value type matches dropdown type
const isNextValueArray = Array.isArray(nextProps.value)
const hasValue = _.has(nextProps, 'value')
if (hasValue && nextProps.multiple && !isNextValueArray) {
console.error(
'Dropdown `value` must be an array when `multiple` is set.' +
` Received type: \`${Object.prototype.toString.call(nextProps.value)}\`.`,
)
} else if (hasValue && !nextProps.multiple && isNextValueArray) {
console.error(
'Dropdown `value` must not be an array when `multiple` is not set.' +
' Either set `multiple={true}` or use a string or number value.'
)
}
}
/* eslint-enable no-console */
if (!_.isEqual(nextProps.value, this.props.value)) {
debug('value changed, setting', nextProps.value)
this.setValue(nextProps.value)
}
if (!_.isEqual(nextProps.options, this.props.options)) {
this.setSelectedIndex(undefined, nextProps.options)
}
}
componentDidUpdate(prevProps, prevState) { // eslint-disable-line complexity
debug('componentDidUpdate()')
// TODO objectDiff still runs in prod, stop it
debug('to state:', objectDiff(prevState, this.state))
// Do not access document when server side rendering
if (!isBrowser) return
// focused / blurred
if (!prevState.focus && this.state.focus) {
debug('dropdown focused')
if (!this.isMouseDown) {
const { openOnFocus } = this.props
debug('mouse is not down, opening')
if (openOnFocus) this.open()
}
if (!this.state.open) {
document.addEventListener('keydown', this.openOnArrow)
document.addEventListener('keydown', this.openOnSpace)
} else {
document.addEventListener('keydown', this.moveSelectionOnKeyDown)
document.addEventListener('keydown', this.selectItemOnEnter)
}
document.addEventListener('keydown', this.removeItemOnBackspace)
} else if (prevState.focus && !this.state.focus) {
debug('dropdown blurred')
const { closeOnBlur } = this.props
if (!this.isMouseDown && closeOnBlur) {
debug('mouse is not down and closeOnBlur=true, closing')
this.close()
}
document.removeEventListener('keydown', this.openOnArrow)
document.removeEventListener('keydown', this.openOnSpace)
document.removeEventListener('keydown', this.moveSelectionOnKeyDown)
document.removeEventListener('keydown', this.selectItemOnEnter)
document.removeEventListener('keydown', this.removeItemOnBackspace)
}
// opened / closed
if (!prevState.open && this.state.open) {
debug('dropdown opened')
document.addEventListener('keydown', this.closeOnEscape)
document.addEventListener('keydown', this.moveSelectionOnKeyDown)
document.addEventListener('keydown', this.selectItemOnEnter)
document.addEventListener('keydown', this.removeItemOnBackspace)
document.addEventListener('click', this.closeOnDocumentClick)
document.removeEventListener('keydown', this.openOnArrow)
document.removeEventListener('keydown', this.openOnSpace)
this.scrollSelectedItemIntoView()
} else if (prevState.open && !this.state.open) {
debug('dropdown closed')
this.handleClose()
document.removeEventListener('keydown', this.closeOnEscape)
document.removeEventListener('keydown', this.moveSelectionOnKeyDown)
document.removeEventListener('keydown', this.selectItemOnEnter)
document.removeEventListener('click', this.closeOnDocumentClick)
if (!this.state.focus) {
document.removeEventListener('keydown', this.removeItemOnBackspace)
}
}
}
componentWillUnmount() {
debug('componentWillUnmount()')
// Do not access document when server side rendering
if (!isBrowser) return
document.removeEventListener('keydown', this.openOnArrow)
document.removeEventListener('keydown', this.openOnSpace)
document.removeEventListener('keydown', this.moveSelectionOnKeyDown)
document.removeEventListener('keydown', this.selectItemOnEnter)
document.removeEventListener('keydown', this.removeItemOnBackspace)
document.removeEventListener('keydown', this.closeOnEscape)
document.removeEventListener('click', this.closeOnDocumentClick)
}
// ----------------------------------------
// Document Event Handlers
// ----------------------------------------
// onChange needs to receive a value
// can't rely on props.value if we are controlled
handleChange = (e, value) => {
debug('handleChange()')
debug(value)
const { onChange } = this.props
if (onChange) onChange(e, { ...this.props, value })
}
closeOnChange = (e) => {
const { closeOnChange, multiple } = this.props
const shouldClose = _.isUndefined(closeOnChange)
? !multiple
: closeOnChange
if (shouldClose) this.close(e)
}
closeOnEscape = (e) => {
if (keyboardKey.getCode(e) !== keyboardKey.Escape) return
e.preventDefault()
this.close()
}
moveSelectionOnKeyDown = (e) => {
debug('moveSelectionOnKeyDown()')
debug(keyboardKey.getName(e))
switch (keyboardKey.getCode(e)) {
case keyboardKey.ArrowDown:
e.preventDefault()
this.moveSelectionBy(1)
break
case keyboardKey.ArrowUp:
e.preventDefault()
this.moveSelectionBy(-1)
break
default:
break
}
}
openOnSpace = (e) => {
debug('openOnSpace()')
if (keyboardKey.getCode(e) !== keyboardKey.Spacebar) return
if (this.state.open) return
e.preventDefault()
this.open(e)
}
openOnArrow = (e) => {
debug('openOnArrow()')
const code = keyboardKey.getCode(e)
if (!_.includes([keyboardKey.ArrowDown, keyboardKey.ArrowUp], code)) return
if (this.state.open) return
e.preventDefault()
this.open(e)
}
makeSelectedItemActive = (e) => {
const { open } = this.state
const { multiple, onAddItem } = this.props
const item = this.getSelectedItem()
const value = _.get(item, 'value')
// prevent selecting null if there was no selected item value
// prevent selecting duplicate items when the dropdown is closed
if (!value || !open) return
// notify the onAddItem prop if this is a new value
if (onAddItem && item['data-additional']) {
onAddItem(e, { ...this.props, value })
}
// notify the onChange prop that the user is trying to change value
if (multiple) {
// state value may be undefined
const newValue = _.union(this.state.value, [value])
this.setValue(newValue)
this.handleChange(e, newValue)
} else {
this.setValue(value)
this.handleChange(e, value)
}
}
selectItemOnEnter = (e) => {
debug('selectItemOnEnter()')
debug(keyboardKey.getName(e))
if (keyboardKey.getCode(e) !== keyboardKey.Enter) return
e.preventDefault()
this.makeSelectedItemActive(e)
this.closeOnChange(e)
}
removeItemOnBackspace = (e) => {
debug('removeItemOnBackspace()')
debug(keyboardKey.getName(e))
if (keyboardKey.getCode(e) !== keyboardKey.Backspace) return
const { multiple, search } = this.props
const { searchQuery, value } = this.state
if (searchQuery || !search || !multiple || _.isEmpty(value)) return
e.preventDefault()
// remove most recent value
const newValue = _.dropRight(value)
this.setValue(newValue)
this.handleChange(e, newValue)
}
closeOnDocumentClick = (e) => {
debug('closeOnDocumentClick()')
debug(e)
// If event happened in the dropdown, ignore it
if (this.ref && _.isFunction(this.ref.contains) && this.ref.contains(e.target)) return
this.close()
}
// ----------------------------------------
// Component Event Handlers
// ----------------------------------------
handleMouseDown = (e) => {
debug('handleMouseDown()')
const { onMouseDown } = this.props
if (onMouseDown) onMouseDown(e, this.props)
this.isMouseDown = true
// Do not access document when server side rendering
if (!isBrowser) return
document.addEventListener('mouseup', this.handleDocumentMouseUp)
}
handleDocumentMouseUp = () => {
debug('handleDocumentMouseUp()')
this.isMouseDown = false
// Do not access document when server side rendering
if (!isBrowser) return
document.removeEventListener('mouseup', this.handleDocumentMouseUp)
}
handleClick = (e) => {
debug('handleClick()', e)
const { onClick } = this.props
if (onClick) onClick(e, this.props)
// prevent closeOnDocumentClick()
e.stopPropagation()
this.toggle(e)
}
handleItemClick = (e, item) => {
debug('handleItemClick()')
debug(item)
const { multiple, onAddItem } = this.props
const { value } = item
// prevent toggle() in handleClick()
e.stopPropagation()
// prevent closeOnDocumentClick() if multiple or item is disabled
if (multiple || item.disabled) {
e.nativeEvent.stopImmediatePropagation()
}
if (item.disabled) return
// notify the onAddItem prop if this is a new value
if (onAddItem && item['data-additional']) {
onAddItem(e, { ...this.props, value })
}
// notify the onChange prop that the user is trying to change value
if (multiple) {
const newValue = _.union(this.state.value, [value])
this.setValue(newValue)
this.handleChange(e, newValue)
} else {
this.setValue(value)
this.handleChange(e, value)
}
this.closeOnChange(e)
}
handleFocus = (e) => {
debug('handleFocus()')
const { onFocus } = this.props
const { focus } = this.state
if (focus) return
if (onFocus) onFocus(e, this.props)
this.setState({ focus: true })
}
handleBlur = (e) => {
debug('handleBlur()')
const { closeOnBlur, multiple, onBlur, selectOnBlur } = this.props
// do not "blur" when the mouse is down inside of the Dropdown
if (this.isMouseDown) return
if (onBlur) onBlur(e, this.props)
if (selectOnBlur && !multiple) {
this.makeSelectedItemActive(e)
if (closeOnBlur) this.close()
}
this.setState({ focus: false, searchQuery: '' })
}
handleSearchChange = (e) => {
debug('handleSearchChange()')
debug(e.target.value)
// prevent propagating to this.props.onChange()
e.stopPropagation()
const { search, onSearchChange } = this.props
const { open } = this.state
const newQuery = e.target.value
if (onSearchChange) onSearchChange(e, newQuery)
// open search dropdown on search query
if (search && newQuery && !open) this.open()
this.setState({
selectedIndex: 0,
searchQuery: newQuery,
})
}
// ----------------------------------------
// Getters
// ----------------------------------------
// There are times when we need to calculate the options based on a value
// that hasn't yet been persisted to state.
getMenuOptions = (value = this.state.value, options = this.props.options) => {
const { multiple, search, allowAdditions, additionPosition, additionLabel } = this.props
const { searchQuery } = this.state
let filteredOptions = options
// filter out active options
if (multiple) {
filteredOptions = _.filter(filteredOptions, opt => !_.includes(value, opt.value))
}
// filter by search query
if (search && searchQuery) {
if (_.isFunction(search)) {
filteredOptions = search(filteredOptions, searchQuery)
} else {
const re = new RegExp(_.escapeRegExp(searchQuery), 'i')
filteredOptions = _.filter(filteredOptions, (opt) => re.test(opt.text))
}
}
// insert the "add" item
if (allowAdditions && search && searchQuery && !_.some(filteredOptions, { text: searchQuery })) {
const additionLabelElement = React.isValidElement(additionLabel)
? React.cloneElement(additionLabel, { key: 'label' })
: additionLabel || ''
const addItem = {
// by using an array, we can pass multiple elements, but when doing so
// we must specify a `key` for React to know which one is which
text: [
additionLabelElement,
<b key='addition'>{searchQuery}</b>,
],
value: searchQuery,
className: 'addition',
'data-additional': true,
}
if (additionPosition === 'top') filteredOptions.unshift(addItem)
else filteredOptions.push(addItem)
}
return filteredOptions
}
getSelectedItem = () => {
const { selectedIndex } = this.state
const options = this.getMenuOptions()
return _.get(options, `[${selectedIndex}]`)
}
getEnabledIndices = (givenOptions) => {
const options = givenOptions || this.getMenuOptions()
return _.reduce(options, (memo, item, index) => {
if (!item.disabled) memo.push(index)
return memo
}, [])
}
getItemByValue = (value) => {
const { options } = this.props
return _.find(options, { value })
}
getMenuItemIndexByValue = (value, givenOptions) => {
const options = givenOptions || this.getMenuOptions()
return _.findIndex(options, ['value', value])
}
getDropdownAriaOptions = (ElementType) => {
const { loading, disabled, search, multiple } = this.props
const { open } = this.state
const ariaOptions = {
role: search ? 'combobox' : 'listbox',
'aria-busy': loading,
'aria-disabled': disabled,
'aria-expanded': !!open,
}
if (ariaOptions.role === 'listbox') {
ariaOptions['aria-multiselectable'] = multiple
}
return ariaOptions
}
getDropdownMenuAriaOptions() {
const { search, multiple } = this.props
const ariaOptions = {}
if (search) {
ariaOptions['aria-multiselectable'] = multiple
ariaOptions.role = 'listbox'
}
return ariaOptions
}
// ----------------------------------------
// Setters
// ----------------------------------------
setValue = (value) => {
debug('setValue()')
debug('value', value)
const newState = {
searchQuery: '',
}
const { multiple, search } = this.props
if (multiple && search && this.searchRef) this.searchRef.focus()
this.trySetState({ value }, newState)
this.setSelectedIndex(value)
}
setSelectedIndex = (value = this.state.value, optionsProps = this.props.options) => {
const { multiple } = this.props
const { selectedIndex } = this.state
const options = this.getMenuOptions(value, optionsProps)
const enabledIndicies = this.getEnabledIndices(options)
let newSelectedIndex
// update the selected index
if (!selectedIndex || selectedIndex < 0) {
const firstIndex = enabledIndicies[0]
// Select the currently active item, if none, use the first item.
// Multiple selects remove active items from the list,
// their initial selected index should be 0.
newSelectedIndex = multiple
? firstIndex
: this.getMenuItemIndexByValue(value, options) || enabledIndicies[0]
} else if (multiple) {
// multiple selects remove options from the menu as they are made active
// keep the selected index within range of the remaining items
if (selectedIndex >= options.length - 1) {
newSelectedIndex = enabledIndicies[enabledIndicies.length - 1]
}
} else {
const activeIndex = this.getMenuItemIndexByValue(value, options)
// regular selects can only have one active item
// set the selected index to the currently active item
newSelectedIndex = _.includes(enabledIndicies, activeIndex) ? activeIndex : undefined
}
if (!newSelectedIndex || newSelectedIndex < 0) {
newSelectedIndex = enabledIndicies[0]
}
this.setState({ selectedIndex: newSelectedIndex })
}
handleLabelClick = (e, labelProps) => {
debug('handleLabelClick()')
// prevent focusing search input on click
e.stopPropagation()
this.setState({ selectedLabel: labelProps.value })
const { onLabelClick } = this.props
if (onLabelClick) onLabelClick(e, labelProps)
}
handleLabelRemove = (e, labelProps) => {
debug('handleLabelRemove()')
// prevent focusing search input on click
e.stopPropagation()
const { value } = this.state
const newValue = _.without(value, labelProps.value)
debug('label props:', labelProps)
debug('current value:', value)
debug('remove value:', labelProps.value)
debug('new value:', newValue)
this.setValue(newValue)
this.handleChange(e, newValue)
}
moveSelectionBy = (offset, startIndex = this.state.selectedIndex) => {
debug('moveSelectionBy()')
debug(`offset: ${offset}`)
const options = this.getMenuOptions()
const lastIndex = options.length - 1
// Prevent infinite loop
if (_.every(options, 'disabled')) return
// next is after last, wrap to beginning
// next is before first, wrap to end
let nextIndex = startIndex + offset
if (nextIndex > lastIndex) nextIndex = 0
else if (nextIndex < 0) nextIndex = lastIndex
if (options[nextIndex].disabled) return this.moveSelectionBy(offset, nextIndex)
this.setState({ selectedIndex: nextIndex })
this.scrollSelectedItemIntoView()
}
// ----------------------------------------
// Refs
// ----------------------------------------
handleSearchRef = c => (this.searchRef = c)
handleSizerRef = c => (this.sizerRef = c)
handleRef = c => (this.ref = c)
// ----------------------------------------
// Behavior
// ----------------------------------------
scrollSelectedItemIntoView = () => {
debug('scrollSelectedItemIntoView()')
if (!this.ref) return
const menu = this.ref.querySelector('.menu.visible')
if (!menu) return
const item = menu.querySelector('.item.selected')
if (!item) return
debug(`menu: ${menu}`)
debug(`item: ${item}`)
const isOutOfUpperView = item.offsetTop < menu.scrollTop
const isOutOfLowerView = (item.offsetTop + item.clientHeight) > menu.scrollTop + menu.clientHeight
if (isOutOfUpperView) {
menu.scrollTop = item.offsetTop
} else if (isOutOfLowerView) {
menu.scrollTop = item.offsetTop + item.clientHeight - menu.clientHeight
}
}
open = (e) => {
debug('open()')
const { disabled, onOpen, search } = this.props
if (disabled) return
if (search && this.searchRef) this.searchRef.focus()
if (onOpen) onOpen(e, this.props)
this.trySetState({ open: true })
this.scrollSelectedItemIntoView()
}
close = (e) => {
debug('close()')
const { onClose } = this.props
if (onClose) onClose(e, this.props)
this.trySetState({ open: false })
}
handleClose = () => {
debug('handleClose()')
const hasSearchFocus = document.activeElement === this.searchRef
const hasDropdownFocus = document.activeElement === this.ref
const hasFocus = hasSearchFocus || hasDropdownFocus
// https://github.com/Semantic-Org/Semantic-UI-React/issues/627
// Blur the Dropdown on close so it is blurred after selecting an item.
// This is to prevent it from re-opening when switching tabs after selecting an item.
if (!hasSearchFocus) {
this.ref.blur()
}
// We need to keep the virtual model in sync with the browser focus change
// https://github.com/Semantic-Org/Semantic-UI-React/issues/692
this.setState({ focus: hasFocus })
}