-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Copy pathDropdown.js
1496 lines (1215 loc) · 42.5 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 EventStack from '@semantic-ui-react/event-stack'
import cx from 'clsx'
import keyboardKey from 'keyboard-key'
import _ from 'lodash'
import PropTypes from 'prop-types'
import React, { Children, cloneElement, createRef } from 'react'
import shallowEqual from 'shallowequal'
import {
ModernAutoControlledComponent as Component,
childrenUtils,
customPropTypes,
doesNodeContainClick,
getComponentType,
getUnhandledProps,
makeDebugger,
objectDiff,
setRef,
getKeyOnly,
getKeyOrValueAndKey,
} from '../../lib'
import Icon from '../../elements/Icon'
import Label from '../../elements/Label'
import Flag from '../../elements/Flag'
import Image from '../../elements/Image'
import DropdownDivider from './DropdownDivider'
import DropdownItem from './DropdownItem'
import DropdownHeader from './DropdownHeader'
import DropdownMenu from './DropdownMenu'
import DropdownSearchInput from './DropdownSearchInput'
import DropdownText from './DropdownText'
import getMenuOptions from './utils/getMenuOptions'
import getSelectedIndex from './utils/getSelectedIndex'
const debug = makeDebugger('dropdown')
const getKeyOrValue = (key, value) => (_.isNil(key) ? value : key)
const getKeyAndValues = (options) =>
options ? options.map((option) => _.pick(option, ['key', 'value'])) : options
function renderItemContent(item) {
const { flag, image, text } = item
// TODO: remove this in v3
// This maintains compatibility with Shorthand API in v1 as this might be called in "Label.create()"
if (_.isFunction(text)) {
return text
}
return {
content: (
<>
{Flag.create(flag)}
{Image.create(image)}
{text}
</>
),
}
}
/**
* A dropdown allows a user to select a value from a series of options.
* @see Form
* @see Select
* @see Menu
*/
const Dropdown = React.forwardRef((props, ref) => {
const {
additionLabel = 'Add ',
additionPosition = 'top',
closeOnBlur = true,
closeOnEscape = true,
deburr = false,
icon = 'dropdown',
minCharacters = 1,
noResultsMessage = 'No results found.',
openOnFocus = true,
renderLabel = renderItemContent,
searchInput = 'text',
selectOnBlur = true,
selectOnNavigation = true,
wrapSelection = true,
...rest
} = props
return (
<DropdownInner
additionLabel={additionLabel}
additionPosition={additionPosition}
closeOnBlur={closeOnBlur}
closeOnEscape={closeOnEscape}
deburr={deburr}
icon={icon}
minCharacters={minCharacters}
noResultsMessage={noResultsMessage}
openOnFocus={openOnFocus}
renderLabel={renderLabel}
searchInput={searchInput}
selectOnBlur={selectOnBlur}
selectOnNavigation={selectOnNavigation}
wrapSelection={wrapSelection}
{...rest}
innerRef={ref}
/>
)
})
class DropdownInner extends Component {
searchRef = createRef()
sizerRef = createRef()
ref = createRef()
handleRef = (el) => {
this.ref.current = el
setRef(this.props.innerRef, el)
}
getInitialAutoControlledState() {
return { focus: false, searchQuery: '' }
}
static getAutoControlledStateFromProps(nextProps, computedState, prevState) {
// These values are stored only for a comparison on next getAutoControlledStateFromProps()
const derivedState = { __options: nextProps.options, __value: computedState.value }
// The selected index is only dependent:
const shouldComputeSelectedIndex =
// On value change
!shallowEqual(prevState.__value, computedState.value) ||
// On option keys/values, we only check those properties to avoid recursive performance impacts.
// https://github.com/Semantic-Org/Semantic-UI-React/issues/3000
!_.isEqual(getKeyAndValues(nextProps.options), getKeyAndValues(prevState.__options))
if (shouldComputeSelectedIndex) {
derivedState.selectedIndex = getSelectedIndex({
additionLabel: nextProps.additionLabel,
additionPosition: nextProps.additionPosition,
allowAdditions: nextProps.allowAdditions,
deburr: nextProps.deburr,
multiple: nextProps.multiple,
search: nextProps.search,
selectedIndex: computedState.selectedIndex,
value: computedState.value,
options: nextProps.options,
searchQuery: computedState.searchQuery,
})
}
return derivedState
}
componentDidMount() {
debug('componentDidMount()')
const { open } = this.state
if (open) {
this.open(null, false)
}
}
shouldComponentUpdate(nextProps, nextState) {
return !shallowEqual(nextProps, this.props) || !shallowEqual(nextState, this.state)
}
componentDidUpdate(prevProps, prevState) {
// eslint-disable-line complexity
debug('componentDidUpdate()')
debug('to state:', objectDiff(prevState, this.state))
const { closeOnBlur, minCharacters, openOnFocus, search } = this.props
/* eslint-disable no-console */
if (process.env.NODE_ENV !== 'production') {
// in development, validate value type matches dropdown type
const isNextValueArray = Array.isArray(this.props.value)
const hasValue = _.has(this.props, 'value')
if (hasValue && this.props.multiple && !isNextValueArray) {
console.error(
'Dropdown `value` must be an array when `multiple` is set.' +
` Received type: \`${Object.prototype.toString.call(this.props.value)}\`.`,
)
} else if (hasValue && !this.props.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 */
// focused / blurred
if (!prevState.focus && this.state.focus) {
debug('dropdown focused')
if (!this.isMouseDown) {
const openable = !search || (search && minCharacters === 1 && !this.state.open)
debug('mouse is not down, opening')
if (openOnFocus && openable) this.open()
}
} else if (prevState.focus && !this.state.focus) {
debug('dropdown blurred')
if (!this.isMouseDown && closeOnBlur) {
debug('mouse is not down and closeOnBlur=true, closing')
this.close()
}
}
// opened / closed
if (!prevState.open && this.state.open) {
debug('dropdown opened')
this.setOpenDirection()
this.scrollSelectedItemIntoView()
} else if (prevState.open && !this.state.open) {
debug('dropdown closed')
}
if (prevState.selectedIndex !== this.state.selectedIndex) {
this.scrollSelectedItemIntoView()
}
}
// ----------------------------------------
// Document Event Handlers
// ----------------------------------------
// onChange needs to receive a value
// can't rely on props.value if we are controlled
handleChange = (e, value) => {
debug('handleChange()', value)
_.invoke(this.props, 'onChange', e, { ...this.props, value })
}
closeOnChange = (e) => {
const { closeOnChange, multiple } = this.props
const shouldClose = _.isUndefined(closeOnChange) ? !multiple : closeOnChange
if (shouldClose) {
this.close(e, _.noop)
}
}
closeOnEscape = (e) => {
if (!this.props.closeOnEscape) return
if (keyboardKey.getCode(e) !== keyboardKey.Escape) return
e.preventDefault()
debug('closeOnEscape()')
this.close(e)
}
moveSelectionOnKeyDown = (e) => {
debug('moveSelectionOnKeyDown()', keyboardKey.getKey(e))
const { multiple, selectOnNavigation } = this.props
const { open } = this.state
if (!open) {
return
}
const moves = {
[keyboardKey.ArrowDown]: 1,
[keyboardKey.ArrowUp]: -1,
}
const move = moves[keyboardKey.getCode(e)]
if (move === undefined) {
return
}
e.preventDefault()
const nextIndex = this.getSelectedIndexAfterMove(move)
if (!multiple && selectOnNavigation) {
this.makeSelectedItemActive(e, nextIndex)
}
this.setState({ selectedIndex: nextIndex })
}
openOnSpace = (e) => {
debug('openOnSpace()')
const shouldHandleEvent =
this.state.focus && !this.state.open && keyboardKey.getCode(e) === keyboardKey.Spacebar
const shouldPreventDefault =
e.target?.tagName !== 'INPUT' &&
e.target?.tagName !== 'TEXTAREA' &&
e.target?.isContentEditable !== true
if (shouldHandleEvent) {
if (shouldPreventDefault) {
e.preventDefault()
}
this.open(e)
}
}
openOnArrow = (e) => {
debug('openOnArrow()')
const { focus, open } = this.state
if (focus && !open) {
const code = keyboardKey.getCode(e)
if (code === keyboardKey.ArrowDown || code === keyboardKey.ArrowUp) {
e.preventDefault()
this.open(e)
}
}
}
makeSelectedItemActive = (e, selectedIndex) => {
const { open, value } = this.state
const { multiple } = this.props
const item = this.getSelectedItem(selectedIndex)
const selectedValue = _.get(item, 'value')
const disabled = _.get(item, 'disabled')
// prevent selecting null if there was no selected item value
// prevent selecting duplicate items when the dropdown is closed
// prevent selecting disabled items
if (_.isNil(selectedValue) || !open || disabled) {
return value
}
// state value may be undefined
const newValue = multiple ? _.union(value, [selectedValue]) : selectedValue
const valueHasChanged = multiple ? !!_.difference(newValue, value).length : newValue !== value
if (valueHasChanged) {
// notify the onChange prop that the user is trying to change value
this.setState({ value: newValue })
this.handleChange(e, newValue)
// Heads up! This event handler should be called after `onChange`
// Notify the onAddItem prop if this is a new value
if (item['data-additional']) {
_.invoke(this.props, 'onAddItem', e, { ...this.props, value: selectedValue })
}
}
return value
}
selectItemOnEnter = (e) => {
debug('selectItemOnEnter()', keyboardKey.getKey(e))
const { search } = this.props
const { open, selectedIndex } = this.state
if (!open) {
return
}
const shouldSelect =
keyboardKey.getCode(e) === keyboardKey.Enter ||
// https://github.com/Semantic-Org/Semantic-UI-React/pull/3766
(!search && keyboardKey.getCode(e) === keyboardKey.Spacebar)
if (!shouldSelect) {
return
}
e.preventDefault()
const optionSize = _.size(
getMenuOptions({
value: this.state.value,
options: this.props.options,
searchQuery: this.state.searchQuery,
additionLabel: this.props.additionLabel,
additionPosition: this.props.additionPosition,
allowAdditions: this.props.allowAdditions,
deburr: this.props.deburr,
multiple: this.props.multiple,
search: this.props.search,
}),
)
if (search && optionSize === 0) {
return
}
const nextValue = this.makeSelectedItemActive(e, selectedIndex)
// This is required as selected value may be the same
this.setState({
selectedIndex: getSelectedIndex({
additionLabel: this.props.additionLabel,
additionPosition: this.props.additionPosition,
allowAdditions: this.props.allowAdditions,
deburr: this.props.deburr,
multiple: this.props.multiple,
search: this.props.search,
selectedIndex,
value: nextValue,
options: this.props.options,
searchQuery: '',
}),
})
this.closeOnChange(e)
this.clearSearchQuery()
if (search) {
_.invoke(this.searchRef.current, 'focus')
}
}
removeItemOnBackspace = (e) => {
debug('removeItemOnBackspace()', keyboardKey.getKey(e))
const { multiple, search } = this.props
const { searchQuery, value } = this.state
if (keyboardKey.getCode(e) !== keyboardKey.Backspace) return
if (searchQuery || !search || !multiple || _.isEmpty(value)) return
e.preventDefault()
// remove most recent value
const newValue = _.dropRight(value)
this.setState({ value: newValue })
this.handleChange(e, newValue)
}
closeOnDocumentClick = (e) => {
debug('closeOnDocumentClick()')
debug(e)
if (!this.props.closeOnBlur) return
// If event happened in the dropdown, ignore it
if (this.ref.current && doesNodeContainClick(this.ref.current, e)) return
this.close()
}
// ----------------------------------------
// Component Event Handlers
// ----------------------------------------
handleMouseDown = (e) => {
debug('handleMouseDown()')
this.isMouseDown = true
_.invoke(this.props, 'onMouseDown', e, this.props)
document.addEventListener('mouseup', this.handleDocumentMouseUp)
}
handleDocumentMouseUp = () => {
debug('handleDocumentMouseUp()')
this.isMouseDown = false
document.removeEventListener('mouseup', this.handleDocumentMouseUp)
}
handleClick = (e) => {
debug('handleClick()', e)
const { minCharacters, search } = this.props
const { open, searchQuery } = this.state
_.invoke(this.props, 'onClick', e, this.props)
// prevent closeOnDocumentClick()
e.stopPropagation()
if (!search) return this.toggle(e)
if (open) {
_.invoke(this.searchRef.current, 'focus')
return
}
if (searchQuery.length >= minCharacters || minCharacters === 1) {
this.open(e)
return
}
_.invoke(this.searchRef.current, 'focus')
}
handleIconClick = (e) => {
const { clearable } = this.props
const hasValue = this.hasValue()
debug('handleIconClick()', { e, clearable, hasValue })
_.invoke(this.props, 'onClick', e, this.props)
// prevent handleClick()
e.stopPropagation()
if (clearable && hasValue) {
this.clearValue(e)
} else {
this.toggle(e)
}
}
handleItemClick = (e, item) => {
debug('handleItemClick()', item)
const { multiple, search } = this.props
const { value: currentValue } = this.state
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
}
const isAdditionItem = item['data-additional']
const newValue = multiple ? _.union(this.state.value, [value]) : value
const valueHasChanged = multiple
? !!_.difference(newValue, currentValue).length
: newValue !== currentValue
// notify the onChange prop that the user is trying to change value
if (valueHasChanged) {
this.setState({ value: newValue })
this.handleChange(e, newValue)
}
this.clearSearchQuery()
if (search) {
_.invoke(this.searchRef.current, 'focus')
} else {
_.invoke(this.ref.current, 'focus')
}
this.closeOnChange(e)
// Heads up! This event handler should be called after `onChange`
// Notify the onAddItem prop if this is a new value
if (isAdditionItem) {
_.invoke(this.props, 'onAddItem', e, { ...this.props, value })
}
}
handleFocus = (e) => {
debug('handleFocus()')
const { focus } = this.state
if (focus) return
_.invoke(this.props, 'onFocus', e, this.props)
this.setState({ focus: true })
}
handleBlur = (e) => {
debug('handleBlur()')
// Heads up! Don't remove this.
// https://github.com/Semantic-Org/Semantic-UI-React/issues/1315
const currentTarget = _.get(e, 'currentTarget')
if (currentTarget && currentTarget.contains(document.activeElement)) return
const { closeOnBlur, multiple, selectOnBlur } = this.props
// do not "blur" when the mouse is down inside of the Dropdown
if (this.isMouseDown) return
_.invoke(this.props, 'onBlur', e, this.props)
if (selectOnBlur && !multiple) {
this.makeSelectedItemActive(e, this.state.selectedIndex)
if (closeOnBlur) this.close()
}
this.setState({ focus: false })
this.clearSearchQuery()
}
handleSearchChange = (e, { value }) => {
debug('handleSearchChange()')
debug(value)
// prevent propagating to this.props.onChange()
e.stopPropagation()
const { minCharacters } = this.props
const { open } = this.state
const newQuery = value
_.invoke(this.props, 'onSearchChange', e, { ...this.props, searchQuery: newQuery })
this.setState({ searchQuery: newQuery, selectedIndex: 0 })
// open search dropdown on search query
if (!open && newQuery.length >= minCharacters) {
this.open()
return
}
// close search dropdown if search query is too small
if (open && minCharacters !== 1 && newQuery.length < minCharacters) this.close()
}
handleKeyDown = (e) => {
this.moveSelectionOnKeyDown(e)
this.openOnArrow(e)
this.openOnSpace(e)
this.selectItemOnEnter(e)
_.invoke(this.props, 'onKeyDown', e)
}
// ----------------------------------------
// Getters
// ----------------------------------------
getSelectedItem = (selectedIndex) => {
const options = getMenuOptions({
value: this.state.value,
options: this.props.options,
searchQuery: this.state.searchQuery,
additionLabel: this.props.additionLabel,
additionPosition: this.props.additionPosition,
allowAdditions: this.props.allowAdditions,
deburr: this.props.deburr,
multiple: this.props.multiple,
search: this.props.search,
})
return _.get(options, `[${selectedIndex}]`)
}
getItemByValue = (value) => {
const { options } = this.props
return _.find(options, { value })
}
getDropdownAriaOptions = () => {
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
// ----------------------------------------
clearSearchQuery = () => {
debug('clearSearchQuery()')
const { searchQuery } = this.state
if (searchQuery === undefined || searchQuery === '') return
this.setState({ searchQuery: '' })
}
handleLabelClick = (e, labelProps) => {
debug('handleLabelClick()')
// prevent focusing search input on click
e.stopPropagation()
this.setState({ selectedLabel: labelProps.value })
_.invoke(this.props, '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.setState({ value: newValue })
this.handleChange(e, newValue)
}
getSelectedIndexAfterMove = (offset, startIndex = this.state.selectedIndex) => {
debug('moveSelectionBy()')
debug(`offset: ${offset}`)
const options = getMenuOptions({
value: this.state.value,
options: this.props.options,
searchQuery: this.state.searchQuery,
additionLabel: this.props.additionLabel,
additionPosition: this.props.additionPosition,
allowAdditions: this.props.allowAdditions,
deburr: this.props.deburr,
multiple: this.props.multiple,
search: this.props.search,
})
// Prevent infinite loop
// TODO: remove left part of condition after children API will be removed
if (options === undefined || _.every(options, 'disabled')) return
const lastIndex = options.length - 1
const { wrapSelection } = this.props
// next is after last, wrap to beginning
// next is before first, wrap to end
let nextIndex = startIndex + offset
// if 'wrapSelection' is set to false and selection is after last or before first, it just does not change
if (!wrapSelection && (nextIndex > lastIndex || nextIndex < 0)) {
nextIndex = startIndex
} else if (nextIndex > lastIndex) {
nextIndex = 0
} else if (nextIndex < 0) {
nextIndex = lastIndex
}
if (options[nextIndex].disabled) {
return this.getSelectedIndexAfterMove(offset, nextIndex)
}
return nextIndex
}
// ----------------------------------------
// Overrides
// ----------------------------------------
handleIconOverrides = (predefinedProps) => {
const { clearable } = this.props
const classes = cx(clearable && this.hasValue() && 'clear', predefinedProps.className)
return {
className: classes,
onClick: (e) => {
_.invoke(predefinedProps, 'onClick', e, predefinedProps)
this.handleIconClick(e)
},
}
}
// ----------------------------------------
// Helpers
// ----------------------------------------
clearValue = (e) => {
const { multiple } = this.props
const newValue = multiple ? [] : ''
this.setState({ value: newValue })
this.handleChange(e, newValue)
}
computeSearchInputTabIndex = () => {
const { disabled, tabIndex } = this.props
if (!_.isNil(tabIndex)) return tabIndex
return disabled ? -1 : 0
}
computeSearchInputWidth = () => {
const { searchQuery } = this.state
if (this.sizerRef.current && searchQuery) {
// resize the search input, temporarily show the sizer so we can measure it
this.sizerRef.current.style.display = 'inline'
this.sizerRef.current.textContent = searchQuery
const searchWidth = Math.ceil(this.sizerRef.current.getBoundingClientRect().width)
this.sizerRef.current.style.removeProperty('display')
return searchWidth
}
}
computeTabIndex = () => {
const { disabled, search, tabIndex } = this.props
// don't set a root node tabIndex as the search input has its own tabIndex
if (search) return undefined
if (disabled) return -1
return _.isNil(tabIndex) ? 0 : tabIndex
}
handleSearchInputOverrides = (predefinedProps) => ({
onChange: (e, inputProps) => {
_.invoke(predefinedProps, 'onChange', e, inputProps)
this.handleSearchChange(e, inputProps)
},
ref: this.searchRef,
})
hasValue = () => {
const { multiple } = this.props
const { value } = this.state
return multiple ? !_.isEmpty(value) : !_.isNil(value) && value !== ''
}
// ----------------------------------------
// Behavior
// ----------------------------------------
scrollSelectedItemIntoView = () => {
debug('scrollSelectedItemIntoView()')
if (!this.ref.current) return
const menu = this.ref.current.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) {
// eslint-disable-next-line no-mixed-operators
menu.scrollTop = item.offsetTop + item.clientHeight - menu.clientHeight
}
}
setOpenDirection = () => {
if (!this.ref.current) return
const menu = this.ref.current.querySelector('.menu.visible')
if (!menu) return
const dropdownRect = this.ref.current.getBoundingClientRect()
const menuHeight = menu.clientHeight
const spaceAtTheBottom =
document.documentElement.clientHeight - dropdownRect.top - dropdownRect.height - menuHeight
const spaceAtTheTop = dropdownRect.top - menuHeight
const upward = spaceAtTheBottom < 0 && spaceAtTheTop > spaceAtTheBottom
// set state only if there's a relevant difference
if (!upward !== !this.state.upward) {
this.setState({ upward })
}
}
open = (e = null, triggerSetState = true) => {
const { disabled, search } = this.props
debug('open()', { disabled, search, open: this.state.open })
if (disabled) return
if (search) _.invoke(this.searchRef.current, 'focus')
_.invoke(this.props, 'onOpen', e, this.props)
if (triggerSetState) {
this.setState({ open: true })
}
this.scrollSelectedItemIntoView()
}
close = (e, callback = this.handleClose) => {
debug('close()', { open: this.state.open })
if (this.state.open) {
_.invoke(this.props, 'onClose', e, this.props)
this.setState({ open: false }, callback)
}
}
handleClose = () => {
debug('handleClose()')
const hasSearchFocus = document.activeElement === this.searchRef.current
// 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.current) {
this.ref.current.blur()
}
const hasDropdownFocus = document.activeElement === this.ref.current
const hasFocus = hasSearchFocus || hasDropdownFocus
// 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 })
}
toggle = (e) => (this.state.open ? this.close(e) : this.open(e))
// ----------------------------------------
// Render
// ----------------------------------------
renderText = () => {
const { multiple, placeholder, search, text } = this.props
const { searchQuery, selectedIndex, value, open } = this.state
const hasValue = this.hasValue()
const classes = cx(
placeholder && !hasValue && 'default',
'text',
search && searchQuery && 'filtered',
)
let _text = placeholder
let selectedItem
if (text) {
_text = text
} else if (open && !multiple) {
selectedItem = this.getSelectedItem(selectedIndex)
} else if (hasValue) {
selectedItem = this.getItemByValue(value)
}
return DropdownText.create(selectedItem ? renderItemContent(selectedItem) : _text, {
defaultProps: {
className: classes,
},
})
}
renderSearchInput = () => {
const { search, searchInput } = this.props
const { searchQuery } = this.state
return (
search &&
DropdownSearchInput.create(searchInput, {
defaultProps: {
style: { width: this.computeSearchInputWidth() },
tabIndex: this.computeSearchInputTabIndex(),
value: searchQuery,
},
overrideProps: this.handleSearchInputOverrides,
})
)
}
renderSearchSizer = () => {
const { search, multiple } = this.props
return search && multiple && <span className='sizer' ref={this.sizerRef} />
}
renderLabels = () => {
debug('renderLabels()')
const { multiple, renderLabel } = this.props
const { selectedLabel, value } = this.state
if (!multiple || _.isEmpty(value)) {
return
}
const selectedItems = _.map(value, this.getItemByValue)
debug('selectedItems', selectedItems)
// if no item could be found for a given state value the selected item will be undefined
// compact the selectedItems so we only have actual objects left
return _.map(_.compact(selectedItems), (item, index) => {
const defaultProps = {
active: item.value === selectedLabel,
as: 'a',
key: getKeyOrValue(item.key, item.value),
onClick: this.handleLabelClick,
onRemove: this.handleLabelRemove,
value: item.value,
}
return Label.create(renderLabel(item, index, defaultProps), { defaultProps })
})
}
renderOptions = () => {
const { lazyLoad, multiple, search, noResultsMessage } = this.props
const { open, selectedIndex, value } = this.state
// lazy load, only render options when open
if (lazyLoad && !open) return null