-
Notifications
You must be signed in to change notification settings - Fork 934
/
downshift.js
1295 lines (1159 loc) · 38.4 KB
/
downshift.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
/* eslint camelcase:0 */
import PropTypes from 'prop-types'
import {Component, cloneElement} from 'react'
import {isForwardRef} from 'react-is'
import {isPreact, isReactNative, isReactNativeWeb} from './is.macro'
import {setStatus} from './set-a11y-status'
import * as stateChangeTypes from './stateChangeTypes'
import {
handleRefs,
callAllEventHandlers,
cbToCb,
debounce,
generateId,
getA11yStatusMessage,
getElementProps,
isDOMElement,
targetWithinDownshift,
isPlainObject,
noop,
normalizeArrowKey,
pickState,
requiredProp,
scrollIntoView,
unwrapArray,
getState,
isControlledProp,
validateControlledUnchanged,
getHighlightedIndex,
getNonDisabledIndex,
} from './utils'
class Downshift extends Component {
static propTypes = {
children: PropTypes.func,
defaultHighlightedIndex: PropTypes.number,
defaultIsOpen: PropTypes.bool,
initialHighlightedIndex: PropTypes.number,
initialSelectedItem: PropTypes.any,
initialInputValue: PropTypes.string,
initialIsOpen: PropTypes.bool,
getA11yStatusMessage: PropTypes.func,
itemToString: PropTypes.func,
onChange: PropTypes.func,
onSelect: PropTypes.func,
onStateChange: PropTypes.func,
onInputValueChange: PropTypes.func,
onUserAction: PropTypes.func,
onOuterClick: PropTypes.func,
selectedItemChanged: PropTypes.func,
stateReducer: PropTypes.func,
itemCount: PropTypes.number,
id: PropTypes.string,
environment: PropTypes.shape({
addEventListener: PropTypes.func.isRequired,
removeEventListener: PropTypes.func.isRequired,
document: PropTypes.shape({
createElement: PropTypes.func.isRequired,
getElementById: PropTypes.func.isRequired,
activeElement: PropTypes.any.isRequired,
body: PropTypes.any.isRequired,
}).isRequired,
Node: PropTypes.func.isRequired,
}),
suppressRefError: PropTypes.bool,
scrollIntoView: PropTypes.func,
// things we keep in state for uncontrolled components
// but can accept as props for controlled components
/* eslint-disable react/no-unused-prop-types */
selectedItem: PropTypes.any,
isOpen: PropTypes.bool,
inputValue: PropTypes.string,
highlightedIndex: PropTypes.number,
labelId: PropTypes.string,
inputId: PropTypes.string,
menuId: PropTypes.string,
getItemId: PropTypes.func,
/* eslint-enable react/no-unused-prop-types */
}
static defaultProps = {
defaultHighlightedIndex: null,
defaultIsOpen: false,
getA11yStatusMessage,
itemToString: i => {
if (i == null) {
return ''
}
if (
process.env.NODE_ENV !== 'production' &&
isPlainObject(i) &&
!i.hasOwnProperty('toString')
) {
// eslint-disable-next-line no-console
console.warn(
'downshift: An object was passed to the default implementation of `itemToString`. You should probably provide your own `itemToString` implementation. Please refer to the `itemToString` API documentation.',
'The object that was passed:',
i,
)
}
return String(i)
},
onStateChange: noop,
onInputValueChange: noop,
onUserAction: noop,
onChange: noop,
onSelect: noop,
onOuterClick: noop,
selectedItemChanged: (prevItem, item) => prevItem !== item,
environment:
/* istanbul ignore next (ssr) */
typeof window === 'undefined' || isReactNative ? undefined : window,
stateReducer: (state, stateToSet) => stateToSet,
suppressRefError: false,
scrollIntoView,
}
static stateChangeTypes = stateChangeTypes
constructor(props) {
super(props)
// fancy destructuring + defaults + aliases
// this basically says each value of state should either be set to
// the initial value or the default value if the initial value is not provided
const {
defaultHighlightedIndex,
initialHighlightedIndex: highlightedIndex = defaultHighlightedIndex,
defaultIsOpen,
initialIsOpen: isOpen = defaultIsOpen,
initialInputValue: inputValue = '',
initialSelectedItem: selectedItem = null,
} = this.props
const state = this.getState({
highlightedIndex,
isOpen,
inputValue,
selectedItem,
})
if (
state.selectedItem != null &&
this.props.initialInputValue === undefined
) {
state.inputValue = this.props.itemToString(state.selectedItem)
}
this.state = state
}
id = this.props.id || `downshift-${generateId()}`
menuId = this.props.menuId || `${this.id}-menu`
labelId = this.props.labelId || `${this.id}-label`
inputId = this.props.inputId || `${this.id}-input`
getItemId = this.props.getItemId || (index => `${this.id}-item-${index}`)
items = []
// itemCount can be changed asynchronously
// from within downshift (so it can't come from a prop)
// this is why we store it as an instance and use
// getItemCount rather than just use items.length
// (to support windowing + async)
itemCount = null
previousResultCount = 0
timeoutIds = []
/**
* @param {Function} fn the function to call after the time
* @param {Number} time the time to wait
*/
internalSetTimeout = (fn, time) => {
const id = setTimeout(() => {
this.timeoutIds = this.timeoutIds.filter(i => i !== id)
fn()
}, time)
this.timeoutIds.push(id)
}
/**
* Clear all running timeouts
*/
internalClearTimeouts() {
this.timeoutIds.forEach(id => {
clearTimeout(id)
})
this.timeoutIds = []
}
/**
* Gets the state based on internal state or props
* If a state value is passed via props, then that
* is the value given, otherwise it's retrieved from
* stateToMerge
*
* @param {Object} stateToMerge defaults to this.state
* @return {Object} the state
*/
getState(stateToMerge = this.state) {
return getState(stateToMerge, this.props)
}
getItemCount() {
// things read better this way. They're in priority order:
// 1. `this.itemCount`
// 2. `this.props.itemCount`
// 3. `this.items.length`
let itemCount = this.items.length
if (this.itemCount != null) {
itemCount = this.itemCount
} else if (this.props.itemCount !== undefined) {
itemCount = this.props.itemCount
}
return itemCount
}
setItemCount = count => {
this.itemCount = count
}
unsetItemCount = () => {
this.itemCount = null
}
getItemNodeFromIndex(index) {
return this.props.environment
? this.props.environment.document.getElementById(this.getItemId(index))
: null
}
isItemDisabled = (_item, index) => {
const currentElementNode = this.getItemNodeFromIndex(index)
return currentElementNode && currentElementNode.hasAttribute('disabled')
}
setHighlightedIndex = (
highlightedIndex = this.props.defaultHighlightedIndex,
otherStateToSet = {},
) => {
otherStateToSet = pickState(otherStateToSet)
this.internalSetState({highlightedIndex, ...otherStateToSet})
}
scrollHighlightedItemIntoView() {
/* istanbul ignore else (react-native) */
if (!isReactNative) {
const node = this.getItemNodeFromIndex(this.getState().highlightedIndex)
this.props.scrollIntoView(node, this._menuNode)
}
}
moveHighlightedIndex(amount, otherStateToSet) {
const itemCount = this.getItemCount()
const {highlightedIndex} = this.getState()
if (itemCount > 0) {
const nextHighlightedIndex = getHighlightedIndex(
highlightedIndex,
amount,
{length: itemCount},
this.isItemDisabled,
true,
)
this.setHighlightedIndex(nextHighlightedIndex, otherStateToSet)
}
}
clearSelection = cb => {
this.internalSetState(
{
selectedItem: null,
inputValue: '',
highlightedIndex: this.props.defaultHighlightedIndex,
isOpen: this.props.defaultIsOpen,
},
cb,
)
}
selectItem = (item, otherStateToSet, cb) => {
otherStateToSet = pickState(otherStateToSet)
this.internalSetState(
{
isOpen: this.props.defaultIsOpen,
highlightedIndex: this.props.defaultHighlightedIndex,
selectedItem: item,
inputValue: this.props.itemToString(item),
...otherStateToSet,
},
cb,
)
}
selectItemAtIndex = (itemIndex, otherStateToSet, cb) => {
const item = this.items[itemIndex]
if (item == null) {
return
}
this.selectItem(item, otherStateToSet, cb)
}
selectHighlightedItem = (otherStateToSet, cb) => {
return this.selectItemAtIndex(
this.getState().highlightedIndex,
otherStateToSet,
cb,
)
}
// any piece of our state can live in two places:
// 1. Uncontrolled: it's internal (this.state)
// We will call this.setState to update that state
// 2. Controlled: it's external (this.props)
// We will call this.props.onStateChange to update that state
//
// In addition, we'll call this.props.onChange if the
// selectedItem is changed.
internalSetState = (stateToSet, cb) => {
let isItemSelected, onChangeArg
const onStateChangeArg = {}
const isStateToSetFunction = typeof stateToSet === 'function'
// we want to call `onInputValueChange` before the `setState` call
// so someone controlling the `inputValue` state gets notified of
// the input change as soon as possible. This avoids issues with
// preserving the cursor position.
// See https://github.com/downshift-js/downshift/issues/217 for more info.
if (!isStateToSetFunction && stateToSet.hasOwnProperty('inputValue')) {
this.props.onInputValueChange(stateToSet.inputValue, {
...this.getStateAndHelpers(),
...stateToSet,
})
}
return this.setState(
state => {
state = this.getState(state)
let newStateToSet = isStateToSetFunction
? stateToSet(state)
: stateToSet
// Your own function that could modify the state that will be set.
newStateToSet = this.props.stateReducer(state, newStateToSet)
// checks if an item is selected, regardless of if it's different from
// what was selected before
// used to determine if onSelect and onChange callbacks should be called
isItemSelected = newStateToSet.hasOwnProperty('selectedItem')
// this keeps track of the object we want to call with setState
const nextState = {}
// this is just used to tell whether the state changed
const nextFullState = {}
// we need to call on change if the outside world is controlling any of our state
// and we're trying to update that state. OR if the selection has changed and we're
// trying to update the selection
if (
isItemSelected &&
newStateToSet.selectedItem !== state.selectedItem
) {
onChangeArg = newStateToSet.selectedItem
}
newStateToSet.type ||= stateChangeTypes.unknown
Object.keys(newStateToSet).forEach(key => {
// onStateChangeArg should only have the state that is
// actually changing
if (state[key] !== newStateToSet[key]) {
onStateChangeArg[key] = newStateToSet[key]
}
// the type is useful for the onStateChangeArg
// but we don't actually want to set it in internal state.
// this is an undocumented feature for now... Not all internalSetState
// calls support it and I'm not certain we want them to yet.
// But it enables users controlling the isOpen state to know when
// the isOpen state changes due to mouseup events which is quite handy.
if (key === 'type') {
return
}
nextFullState[key] = newStateToSet[key]
// if it's coming from props, then we don't care to set it internally
if (!isControlledProp(this.props, key)) {
nextState[key] = newStateToSet[key]
}
})
// if stateToSet is a function, then we weren't able to call onInputValueChange
// earlier, so we'll call it now that we know what the inputValue state will be.
if (
isStateToSetFunction &&
newStateToSet.hasOwnProperty('inputValue')
) {
this.props.onInputValueChange(newStateToSet.inputValue, {
...this.getStateAndHelpers(),
...newStateToSet,
})
}
return nextState
},
() => {
// call the provided callback if it's a function
cbToCb(cb)()
// only call the onStateChange and onChange callbacks if
// we have relevant information to pass them.
const hasMoreStateThanType = Object.keys(onStateChangeArg).length > 1
if (hasMoreStateThanType) {
this.props.onStateChange(onStateChangeArg, this.getStateAndHelpers())
}
if (isItemSelected) {
this.props.onSelect(
stateToSet.selectedItem,
this.getStateAndHelpers(),
)
}
if (onChangeArg !== undefined) {
this.props.onChange(onChangeArg, this.getStateAndHelpers())
}
// this is currently undocumented and therefore subject to change
// We'll try to not break it, but just be warned.
this.props.onUserAction(onStateChangeArg, this.getStateAndHelpers())
},
)
}
getStateAndHelpers() {
const {highlightedIndex, inputValue, selectedItem, isOpen} = this.getState()
const {itemToString} = this.props
const {id} = this
const {
getRootProps,
getToggleButtonProps,
getLabelProps,
getMenuProps,
getInputProps,
getItemProps,
openMenu,
closeMenu,
toggleMenu,
selectItem,
selectItemAtIndex,
selectHighlightedItem,
setHighlightedIndex,
clearSelection,
clearItems,
reset,
setItemCount,
unsetItemCount,
internalSetState: setState,
} = this
return {
// prop getters
getRootProps,
getToggleButtonProps,
getLabelProps,
getMenuProps,
getInputProps,
getItemProps,
// actions
reset,
openMenu,
closeMenu,
toggleMenu,
selectItem,
selectItemAtIndex,
selectHighlightedItem,
setHighlightedIndex,
clearSelection,
clearItems,
setItemCount,
unsetItemCount,
setState,
// props
itemToString,
// derived
id,
// state
highlightedIndex,
inputValue,
isOpen,
selectedItem,
}
}
//////////////////////////// ROOT
rootRef = node => (this._rootNode = node)
getRootProps = (
{refKey = 'ref', ref, ...rest} = {},
{suppressRefError = false} = {},
) => {
// this is used in the render to know whether the user has called getRootProps.
// It uses that to know whether to apply the props automatically
this.getRootProps.called = true
this.getRootProps.refKey = refKey
this.getRootProps.suppressRefError = suppressRefError
const {isOpen} = this.getState()
return {
[refKey]: handleRefs(ref, this.rootRef),
role: 'combobox',
'aria-expanded': isOpen,
'aria-haspopup': 'listbox',
'aria-owns': isOpen ? this.menuId : undefined,
'aria-labelledby': this.labelId,
...rest,
}
}
//\\\\\\\\\\\\\\\\\\\\\\\\\\ ROOT
keyDownHandlers = {
ArrowDown(event) {
event.preventDefault()
if (this.getState().isOpen) {
const amount = event.shiftKey ? 5 : 1
this.moveHighlightedIndex(amount, {
type: stateChangeTypes.keyDownArrowDown,
})
} else {
this.internalSetState(
{
isOpen: true,
type: stateChangeTypes.keyDownArrowDown,
},
() => {
const itemCount = this.getItemCount()
if (itemCount > 0) {
const {highlightedIndex} = this.getState()
const nextHighlightedIndex = getHighlightedIndex(
highlightedIndex,
1,
{length: itemCount},
this.isItemDisabled,
true,
)
this.setHighlightedIndex(nextHighlightedIndex, {
type: stateChangeTypes.keyDownArrowDown,
})
}
},
)
}
},
ArrowUp(event) {
event.preventDefault()
if (this.getState().isOpen) {
const amount = event.shiftKey ? -5 : -1
this.moveHighlightedIndex(amount, {
type: stateChangeTypes.keyDownArrowUp,
})
} else {
this.internalSetState(
{
isOpen: true,
type: stateChangeTypes.keyDownArrowUp,
},
() => {
const itemCount = this.getItemCount()
if (itemCount > 0) {
const {highlightedIndex} = this.getState()
const nextHighlightedIndex = getHighlightedIndex(
highlightedIndex,
-1,
{length: itemCount},
this.isItemDisabled,
true,
)
this.setHighlightedIndex(nextHighlightedIndex, {
type: stateChangeTypes.keyDownArrowUp,
})
}
},
)
}
},
Enter(event) {
if (event.which === 229) {
return
}
const {isOpen, highlightedIndex} = this.getState()
if (isOpen && highlightedIndex != null) {
event.preventDefault()
const item = this.items[highlightedIndex]
const itemNode = this.getItemNodeFromIndex(highlightedIndex)
if (item == null || (itemNode && itemNode.hasAttribute('disabled'))) {
return
}
this.selectHighlightedItem({
type: stateChangeTypes.keyDownEnter,
})
}
},
Escape(event) {
event.preventDefault()
this.reset({
type: stateChangeTypes.keyDownEscape,
...(!this.state.isOpen && {selectedItem: null, inputValue: ''}),
})
},
}
//////////////////////////// BUTTON
buttonKeyDownHandlers = {
...this.keyDownHandlers,
' '(event) {
event.preventDefault()
this.toggleMenu({type: stateChangeTypes.keyDownSpaceButton})
},
}
inputKeyDownHandlers = {
...this.keyDownHandlers,
Home(event) {
const {isOpen} = this.getState()
if (!isOpen) {
return
}
event.preventDefault()
const itemCount = this.getItemCount()
if (itemCount <= 0 || !isOpen) {
return
}
// get next non-disabled starting downwards from 0 if that's disabled.
const newHighlightedIndex = getNonDisabledIndex(
0,
false,
{length: itemCount},
this.isItemDisabled,
)
this.setHighlightedIndex(newHighlightedIndex, {
type: stateChangeTypes.keyDownHome,
})
},
End(event) {
const {isOpen} = this.getState()
if (!isOpen) {
return
}
event.preventDefault()
const itemCount = this.getItemCount()
if (itemCount <= 0 || !isOpen) {
return
}
// get next non-disabled starting upwards from last index if that's disabled.
const newHighlightedIndex = getNonDisabledIndex(
itemCount - 1,
true,
{length: itemCount},
this.isItemDisabled,
)
this.setHighlightedIndex(newHighlightedIndex, {
type: stateChangeTypes.keyDownEnd,
})
},
}
getToggleButtonProps = ({
onClick,
onPress,
onKeyDown,
onKeyUp,
onBlur,
...rest
} = {}) => {
const {isOpen} = this.getState()
const enabledEventHandlers =
isReactNative || isReactNativeWeb
? /* istanbul ignore next (react-native) */
{
onPress: callAllEventHandlers(onPress, this.buttonHandleClick),
}
: {
onClick: callAllEventHandlers(onClick, this.buttonHandleClick),
onKeyDown: callAllEventHandlers(
onKeyDown,
this.buttonHandleKeyDown,
),
onKeyUp: callAllEventHandlers(onKeyUp, this.buttonHandleKeyUp),
onBlur: callAllEventHandlers(onBlur, this.buttonHandleBlur),
}
const eventHandlers = rest.disabled ? {} : enabledEventHandlers
return {
type: 'button',
role: 'button',
'aria-label': isOpen ? 'close menu' : 'open menu',
'aria-haspopup': true,
'data-toggle': true,
...eventHandlers,
...rest,
}
}
buttonHandleKeyUp = event => {
// Prevent click event from emitting in Firefox
event.preventDefault()
}
buttonHandleKeyDown = event => {
const key = normalizeArrowKey(event)
if (this.buttonKeyDownHandlers[key]) {
this.buttonKeyDownHandlers[key].call(this, event)
}
}
buttonHandleClick = event => {
event.preventDefault()
// handle odd case for Safari and Firefox which
// don't give the button the focus properly.
/* istanbul ignore if (can't reasonably test this) */
if (!isReactNative && this.props.environment) {
const {body, activeElement} = this.props.environment.document
if (body && body === activeElement) {
event.target.focus()
}
}
// to simplify testing components that use downshift, we'll not wrap this in a setTimeout
// if the NODE_ENV is test. With the proper build system, this should be dead code eliminated
// when building for production and should therefore have no impact on production code.
if (process.env.NODE_ENV === 'test') {
this.toggleMenu({type: stateChangeTypes.clickButton})
} else {
// Ensure that toggle of menu occurs after the potential blur event in iOS
this.internalSetTimeout(() =>
this.toggleMenu({type: stateChangeTypes.clickButton}),
)
}
}
buttonHandleBlur = event => {
const blurTarget = event.target // Save blur target for comparison with activeElement later
// Need setTimeout, so that when the user presses Tab, the activeElement is the next focused element, not body element
this.internalSetTimeout(() => {
if (this.isMouseDown || !this.props.environment) {
return
}
const {activeElement} = this.props.environment.document
if (
(activeElement == null || activeElement.id !== this.inputId) &&
activeElement !== blurTarget // Do nothing if we refocus the same element again (to solve issue in Safari on iOS)
) {
this.reset({type: stateChangeTypes.blurButton})
}
})
}
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ BUTTON
/////////////////////////////// LABEL
getLabelProps = props => {
return {htmlFor: this.inputId, id: this.labelId, ...props}
}
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ LABEL
/////////////////////////////// INPUT
getInputProps = ({
onKeyDown,
onBlur,
onChange,
onInput,
onChangeText,
...rest
} = {}) => {
let onChangeKey
let eventHandlers = {}
/* istanbul ignore next (preact) */
if (isPreact) {
onChangeKey = 'onInput'
} else {
onChangeKey = 'onChange'
}
const {inputValue, isOpen, highlightedIndex} = this.getState()
if (!rest.disabled) {
eventHandlers = {
[onChangeKey]: callAllEventHandlers(
onChange,
onInput,
this.inputHandleChange,
),
onKeyDown: callAllEventHandlers(onKeyDown, this.inputHandleKeyDown),
onBlur: callAllEventHandlers(onBlur, this.inputHandleBlur),
}
}
/* istanbul ignore if (react-native) */
if (isReactNative) {
eventHandlers = {
onChange: callAllEventHandlers(
onChange,
onInput,
this.inputHandleChange,
),
onChangeText: callAllEventHandlers(onChangeText, onInput, text =>
this.inputHandleChange({nativeEvent: {text}}),
),
onBlur: callAllEventHandlers(onBlur, this.inputHandleBlur),
}
}
return {
'aria-autocomplete': 'list',
'aria-activedescendant':
isOpen && typeof highlightedIndex === 'number' && highlightedIndex >= 0
? this.getItemId(highlightedIndex)
: undefined,
'aria-controls': isOpen ? this.menuId : undefined,
'aria-labelledby': rest && rest['aria-label'] ? undefined : this.labelId,
// https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion
// revert back since autocomplete="nope" is ignored on latest Chrome and Opera
autoComplete: 'off',
value: inputValue,
id: this.inputId,
...eventHandlers,
...rest,
}
}
inputHandleKeyDown = event => {
const key = normalizeArrowKey(event)
if (key && this.inputKeyDownHandlers[key]) {
this.inputKeyDownHandlers[key].call(this, event)
}
}
inputHandleChange = event => {
this.internalSetState({
type: stateChangeTypes.changeInput,
isOpen: true,
inputValue:
isReactNative || isReactNativeWeb
? /* istanbul ignore next (react-native) */ event.nativeEvent.text
: event.target.value,
highlightedIndex: this.props.defaultHighlightedIndex,
})
}
inputHandleBlur = () => {
// Need setTimeout, so that when the user presses Tab, the activeElement is the next focused element, not the body element
this.internalSetTimeout(() => {
if (this.isMouseDown || !this.props.environment) {
return
}
const {activeElement} = this.props.environment.document
const downshiftButtonIsActive =
activeElement?.dataset?.toggle &&
this._rootNode &&
this._rootNode.contains(activeElement)
if (!downshiftButtonIsActive) {
this.reset({type: stateChangeTypes.blurInput})
}
})
}
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ INPUT
/////////////////////////////// MENU
menuRef = node => {
this._menuNode = node
}
getMenuProps = (
{refKey = 'ref', ref, ...props} = {},
{suppressRefError = false} = {},
) => {
this.getMenuProps.called = true
this.getMenuProps.refKey = refKey
this.getMenuProps.suppressRefError = suppressRefError
return {
[refKey]: handleRefs(ref, this.menuRef),
role: 'listbox',
'aria-labelledby':
props && props['aria-label'] ? undefined : this.labelId,
id: this.menuId,
...props,
}
}
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ MENU
/////////////////////////////// ITEM
getItemProps = ({
onMouseMove,
onMouseDown,
onClick,
onPress,
index,
item = process.env.NODE_ENV === 'production'
? /* istanbul ignore next */ undefined
: requiredProp('getItemProps', 'item'),
...rest
} = {}) => {
if (index === undefined) {
this.items.push(item)
index = this.items.indexOf(item)
} else {
this.items[index] = item
}
const onSelectKey =
isReactNative || isReactNativeWeb
? /* istanbul ignore next (react-native) */ 'onPress'
: 'onClick'
const customClickHandler = isReactNative
? /* istanbul ignore next (react-native) */ onPress
: onClick
const enabledEventHandlers = {
// onMouseMove is used over onMouseEnter here. onMouseMove
// is only triggered on actual mouse movement while onMouseEnter
// can fire on DOM changes, interrupting keyboard navigation
onMouseMove: callAllEventHandlers(onMouseMove, () => {
if (index === this.getState().highlightedIndex) {
return
}
this.setHighlightedIndex(index, {
type: stateChangeTypes.itemMouseEnter,
})
// We never want to manually scroll when changing state based
// on `onMouseMove` because we will be moving the element out
// from under the user which is currently scrolling/moving the
// cursor
this.avoidScrolling = true
this.internalSetTimeout(() => (this.avoidScrolling = false), 250)
}),
onMouseDown: callAllEventHandlers(onMouseDown, event => {
// This prevents the activeElement from being changed
// to the item so it can remain with the current activeElement
// which is a more common use case.
event.preventDefault()
}),
[onSelectKey]: callAllEventHandlers(customClickHandler, () => {
this.selectItemAtIndex(index, {
type: stateChangeTypes.clickItem,
})
}),
}
// Passing down the onMouseDown handler to prevent redirect
// of the activeElement if clicking on disabled items
const eventHandlers = rest.disabled
? {onMouseDown: enabledEventHandlers.onMouseDown}
: enabledEventHandlers
return {
id: this.getItemId(index),
role: 'option',
'aria-selected': this.getState().highlightedIndex === index,
...eventHandlers,
...rest,
}
}
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ ITEM
clearItems = () => {
this.items = []
}
reset = (otherStateToSet = {}, cb) => {
otherStateToSet = pickState(otherStateToSet)
this.internalSetState(