Repository navigation
Expand file tree
/
Copy pathSelect.ts
More file actions
914 lines (788 loc) · 32.8 KB
/
Copy pathSelect.ts
File metadata and controls
914 lines (788 loc) · 32.8 KB
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
/*
* This file belongs to Hoist, an application development toolkit
* developed by Extremely Heavy Industries (www.xh.io | info@xh.io)
*
* Copyright © 2026 Extremely Heavy Industries Inc.
*/
import type {HoistInputProps} from '@xh/hoist/cmp/input';
import {HoistInputModel, useHoistInputModel} from '@xh/hoist/cmp/input';
import {box, div, fragment, hbox, span} from '@xh/hoist/cmp/layout';
import type {Awaitable, HoistProps, LayoutProps, PlainObject, SelectOption} from '@xh/hoist/core';
import {createElement, hoistCmp, XH} from '@xh/hoist/core';
import '@xh/hoist/desktop/register';
import {Icon} from '@xh/hoist/icon';
import {tooltip} from '@xh/hoist/kit/blueprint';
import {
reactAsyncCreatableSelect,
reactAsyncSelect,
reactCreatableSelect,
reactSelect
} from '@xh/hoist/kit/react-select';
import {action, observable, bindableRef} from '@xh/hoist/mobx';
import {debouncePromise, wait, waitFor} from '@xh/hoist/promise';
import {elemWithin, getTestId, mergeDeep, TEST_ID, throwIf, withDefault} from '@xh/hoist/utils/js';
import {createObservableRef, getLayoutProps} from '@xh/hoist/utils/react';
import classNames from 'classnames';
import {castArray, escapeRegExp, isEmpty, isEqual, isNil, isPlainObject, noop} from 'lodash';
import type {ReactElement, ReactNode} from 'react';
import {components} from 'react-select';
import {calcWindowedMenuWidth} from './impl/CalcWindowedMenuWidth';
import {countOptions, WindowedMenuList, WINDOWED_OPTION_THRESHOLD} from './impl/WindowedMenuList';
import './Select.scss';
export const MENU_PORTAL_ID = 'xh-select-input-portal';
export interface SelectProps extends HoistProps, HoistInputProps, LayoutProps {
/** True to focus the control on render. */
autoFocus?: boolean;
/**
* Function to return a "create a new option" string prompt. Requires `enableCreate` true.
* Passed current query input.
*/
createMessageFn?: (query: string) => string;
/** True (default) to close the menu after each selection. */
closeMenuOnSelect?: boolean;
/**
* Value to use when the input is empty (default `null`).
* Recommended usage is `[]` when `enableMulti` is true to ensure value is always an array.
*/
emptyValue?: any;
/** True to show a "clear" button at the right of the control. */
enableClear?: boolean;
/** True to accept and commit input values not present in options or returned by a query. */
enableCreate?: boolean;
/**
* True (default) to enable type-to-search keyboard input. False to disable keyboard input,
* showing the dropdown menu on click.
*/
enableFilter?: boolean;
/** True to allow entry/selection of multiple values - "tag picker" style. */
enableMulti?: boolean;
/**
* True to enable tooltips on selected values. Enable when the space available to the
* component might not support showing the value's full text.
*/
enableTooltips?: boolean;
/**
* True to render only the visible options of a large option list, for improved performance.
* Takes effect once the list has 100 or more options - a shorter list renders as usual. The
* menu is sized to its widest option, as a windowed menu cannot auto-size via CSS.
*
* Currently only supported when the enableCreate and queryFn props are not specified.
*
* Applications should use this option with care.
*/
enableWindowed?: boolean;
/**
* True to constrain the value to the current `options` - any selected value not found there is
* removed whenever the value or the list changes. Enforced only once `options` is non-null, so
* pass null (not `[]`) while options load - `[]` means "no valid choices" and clears the value.
* Throws if combined with `enableCreate` or `queryFn`.
*/
enforceValueInOptions?: boolean;
/**
* Function called to filter available options for a given query string input.
* Used for filtering of options provided by `options` prop when `enableFilter` is true.
* Not to be confused with `queryFn` prop, used in asynchronous mode.
*
* Provided function should take an option and a query value and return a boolean.
* Defaults to a case-insensitive match on word starts.
*/
filterFn?: (opt: SelectOption, inputVal: string) => boolean;
/**
* True to hide the dropdown indicator, i.e. the down-facing arrow at the right of the Select.
* Defaults to true on tablets, false on desktop.
*/
hideDropdownIndicator?: boolean;
/** True to suppress the default check icon rendered for the currently selected option. */
hideSelectedOptionCheck?: boolean;
/**
* True to hide options in the drop-down menu if they have been selected.
* Defaults to same as enableMulti.
*/
hideSelectedOptions?: boolean;
/** Field on provided options for sourcing each option's display text (default `label`). */
labelField?: string;
/** Icon to display inline on the left side of the input. */
leftIcon?: ReactElement;
/** Function to return loading message during an async query. Passed current query input. */
loadingMessageFn?: (query: string) => ReactNode;
/** Maximum height of the menu before scrolling. Defaults to 300px. */
maxMenuHeight?: number;
/** Placement of the dropdown menu relative to the input control. */
menuPlacement?: 'auto' | 'top' | 'bottom';
/** Width in pixels for the dropdown menu - if unspecified, defaults to control width. */
menuWidth?: number;
/** Function to return message indicating no options loaded. Passed current query input. */
noOptionsMessageFn?: (query: string) => ReactNode;
/** True to auto-open the dropdown menu on input focus. */
openMenuOnFocus?: boolean;
/**
* Function to render options in the dropdown list. Called for each option object (which
* will contain at minimum a value and label field, as well as any other fields present in
* the source objects).
*/
optionRenderer?: (opt: SelectOption) => ReactNode;
/**
* Renderer for the selected value within the control itself, called with the option matching
* the current value. Defaults to displaying the option's `label`.
*/
valueRenderer?: (opt: SelectOption) => ReactNode;
/**
* Preset list of options for selection. Elements can be either a primitive or an object.
* Primitives will be displayed via toString().
* Objects must have either:
* + A `label` property for display and a `value` property
* + A `label` property and an `options` property containing an array of sub-options
* to be grouped beneath the option. These sub-options must be either primitives or
* `label`:`value` pairs. Deeper nesting is unsupported.
*
* See also `queryFn` to supply options via an async query (i.e. from the server) instead
* of up-front in this prop.
*/
options?: Array<SelectOption | any>;
/** Text to display when control is empty. */
placeholder?: string;
/**
* Delay (in ms) to buffer calls to the async queryFn. Defaults to 300.
*/
queryBuffer?: number;
/**
* Async function to return a list of options for a given query string input.
* Replaces the `options` prop - use one or the other.
*
* For providing external (e.g. server-side) options based on user inputs. Not to be
* confused with `filterFn`, which should be used to filter through local options when
* not in async mode.
*/
queryFn?: (query: string) => Awaitable<Array<SelectOption | any>>;
/**
* Escape-hatch props passed directly to react-select. Use with care - not all props
* in the react-select API are guaranteed to be supported by this Hoist component,
* and providing them directly can interfere with the implementation of this class.
*/
rsOptions?: PlainObject;
/** True to select contents when control receives focus. */
selectOnFocus?: boolean;
/** Field on provided options for sourcing each option's value (default `value`). */
valueField?: string;
/**
* Fallback function to look up the `SelectOption` for a (non-null) selected value that is not
* present in the current options. Return null to accept the default value-as-label behavior.
*
* Intended for values that already exist but whose option is simply out of view - e.g. an
* initial value on a `queryFn`-based select, where the control is bound to the value alone and
* no query has yet run to supply its label. Useful where value-as-label would never be
* meaningful to the user, such as an object select that should always render the object's name
* rather than its id value.
*
* Note this is not capable of "creating" new values via `enableCreate`.
*/
generateOptionFn?: (value: any) => SelectOption;
}
/**
* A combobox for choosing one or more values from a dropdown list of options, with type-ahead
* filtering.
*
* Supports advanced options such as:
* + Asynchronous queries
* + Multiple selection
* + Custom dropdown option renderers
* + User-created ad-hoc entries
* + Windowed rendering of large option lists, for improved performance.
*
* Built on {@link https://react-select.com|react-select}.
*/
export const [Select, select] = hoistCmp.withFactory<SelectProps>({
displayName: 'Select',
className: 'xh-select',
render(props, ref) {
return useHoistInputModel(cmp, props, ref, SelectInputModel);
}
});
(Select as any).hasLayoutSupport = true;
//-----------------------
// Implementation
//-----------------------
class SelectInputModel extends HoistInputModel {
override xhImpl = true;
// Normalized collection of selectable options. Passed directly to synchronous select.
// Maintained for (but not passed to) async select to resolve value string <> option objects.
@bindableRef accessor internalOptions = [];
@observable accessor windowedMenuWidth: number = null;
// Prop-backed convenience getters
get asyncMode(): boolean {
return !!this.componentProps.queryFn;
}
get creatableMode(): boolean {
return !!this.componentProps.enableCreate;
}
get windowedMode(): boolean {
return !!this.componentProps.enableWindowed;
}
get multiMode(): boolean {
return !!this.componentProps.enableMulti;
}
get emptyValue(): any {
return this.componentProps.emptyValue ?? null;
}
get filterMode(): boolean {
return this.componentProps.enableFilter ?? true;
}
get selectOnFocus(): boolean {
return (
this.componentProps.selectOnFocus ??
(!this.multiMode && (this.filterMode || this.creatableMode))
);
}
get hideDropdownIndicator(): boolean {
return this.componentProps.hideDropdownIndicator ?? XH.isTablet;
}
get hideSelectedOptions(): boolean {
return this.componentProps.hideSelectedOptions ?? this.multiMode;
}
get hideSelectedOptionCheck(): boolean {
return this.componentProps.hideSelectedOptionCheck || this.hideSelectedOptions;
}
// Managed value for underlying text input under certain conditions
// This is a workaround for rs-select issue described in hoist-react #880
@observable accessor inputValue: string = null;
inputValueChangedSinceSelect = false;
get manageInputValue(): boolean {
return this.filterMode && !this.multiMode;
}
override onLinked() {
const queryBuffer = withDefault(this.componentProps.queryBuffer, 300);
if (queryBuffer) this.doQueryAsync = debouncePromise(this.doQueryAsync, queryBuffer);
this.addReaction({
track: () => this.componentProps.options,
run: opts => {
opts = this.normalizeOptions(opts);
this.internalOptions = opts;
if (this.windowedMode) {
this.windowedMenuWidth = calcWindowedMenuWidth(
opts,
o => this.formatOptionLabel(o, {context: 'menu'}),
this.getOrCreatePortalDiv()
);
}
},
fireImmediately: true
});
if (this.componentProps.enforceValueInOptions) {
throwIf(
this.creatableMode || this.asyncMode,
'`enforceValueInOptions` is not supported with `enableCreate` or `queryFn`.'
);
this.addReaction({
track: () => [this.externalValue, this.internalOptions],
run: () => this.pruneValueToOptions(),
fireImmediately: true
});
}
}
reactSelectRef = createObservableRef<any>();
get reactSelect() {
return this.reactSelectRef.current;
}
override blur() {
this.reactSelect?.blur();
}
override focus() {
this.reactSelect?.focus();
}
override select() {
this.selectText();
}
getSelectFactory() {
const {creatableMode, asyncMode, windowedMode} = this;
if (windowedMode) {
throwIf(creatableMode, 'Windowed mode not available when enableCreate is true');
throwIf(asyncMode, 'Windowed mode not available when queryFn is set');
return reactSelect;
}
return asyncMode
? creatableMode
? reactAsyncCreatableSelect
: reactAsyncSelect
: creatableMode
? reactCreatableSelect
: reactSelect;
}
@action
onSelectChange = opt => {
if (this.manageInputValue) {
this.inputValue = opt ? opt.label : null;
this.inputValueChangedSinceSelect = false;
}
this.noteValueChange(opt);
};
// Scroll selected option into view on open - react-select's own does not fire for portalled
// menus. Poll from the next tick (menuIsOpen not yet committed), stop if menu closes/unmounts.
onMenuOpen = () => {
let selected: Element;
wait()
.then(() =>
waitFor(() => {
if (this.isDestroyed || !this.reactSelect?.props.menuIsOpen) return true;
selected = document.getElementsByClassName('xh-select__option--is-selected')[0];
return !!selected;
})
)
.then(() => selected?.scrollIntoView({block: 'end'}))
.catch(noop);
};
//-------------------------
// Text input handling
//-------------------------
@action
onInputChange = (value, {action}) => {
if (this.manageInputValue) {
if (action === 'input-change') {
this.inputValue = value;
this.inputValueChangedSinceSelect = true;
} else if (action === 'input-blur') {
this.inputValue = null;
this.inputValueChangedSinceSelect = false;
}
}
};
@action
override noteFocused() {
if (this.manageInputValue) {
const {renderValue} = this;
this.inputValue = renderValue ? renderValue.label : null;
}
if (this.selectOnFocus) {
wait().then(() => {
// Delay to allow re-render. For safety, only select if still focused!
this.selectText();
});
}
super.noteFocused();
}
/**
* Enter text into the search input and open the menu, as if typed by the user.
* Ignored if the select is not searchable.
*/
enterSearchText(text: string) {
// Delay to run after the text selection scheduled by `noteFocused()`.
wait().then(() => {
const selectComp = this.innerSelect;
if (!this.hasFocus || !selectComp?.props.isSearchable) return;
selectComp.props.onInputChange(text, {
action: 'input-change',
prevInputValue: selectComp.props.inputValue ?? ''
});
selectComp.openMenu('first');
});
}
// Unwrap the HOCs added by AsyncSelect / Creatable (each exposes the inner Select via
// `.select`) to reach the underlying Select that owns the inputRef.
private get innerSelect() {
let selectComp = this.reactSelect;
while (selectComp && !selectComp.inputRef) {
selectComp = selectComp.select;
}
return selectComp;
}
private selectText() {
const inputElem = this.innerSelect?.inputRef;
if (this.hasFocus && inputElem && document.activeElement === inputElem) {
inputElem.select();
}
}
@action
override setInternalValue(val) {
const changed = !isEqual(val, this.internalValue);
super.setInternalValue(val);
if (changed && this.manageInputValue && this.hasFocus) {
const {renderValue} = this;
this.inputValue = renderValue ? renderValue.label : null;
}
}
//-------------------------
// Options / value handling
//-------------------------
filterOption = (opt, inputVal) => {
const {componentProps, asyncMode, inputValue, inputValueChangedSinceSelect} = this;
// 1) show all options if input has not changed since last select (i.e. user has not typed)
// or if in async mode (i.e. queryFn specified).
if (
(this.manageInputValue && (!inputValue || !inputValueChangedSinceSelect)) ||
asyncMode
) {
return true;
}
// 2) Use function provided by app
const {filterFn} = componentProps;
if (filterFn) {
return filterFn(opt, inputVal);
}
// 3) ...or use default word start search
const searchTerm = escapeRegExp(inputVal);
if (!searchTerm) return true;
if (!opt.label) return false;
const regex = new RegExp(`(^|\\W)${searchTerm}`, 'i');
return regex.test(opt.label);
};
// Convert external value (which may be a primitive string or number) into option object(s).
override toInternal(external) {
if (this.multiMode) {
if (external == null || isEqual(external, this.emptyValue)) external = []; // avoid [null]
return castArray(external).map(it => this.findOption(it, !isNil(it)));
}
return this.findOption(external, !isNil(external) && !isEqual(external, this.emptyValue));
}
private findOption(value, createIfNotFound, options = this.internalOptions) {
// Do a depth-first search of options
for (const option of options) {
if (option.options) {
const ret = this.findOption(value, false, option.options);
if (ret) return ret;
} else {
if (isEqual(option.value, value)) return option;
}
}
if (!createIfNotFound) return null;
return (
this.selectedOptions.find(it => isEqual(it.value, value)) ??
this.componentProps.generateOptionFn?.(value) ??
this.valueToOption(value)
);
}
// Enforce `enforceValueInOptions` - drop any current value not present in internalOptions.
// Null options signal that they have yet to load, and are not yet enforced against.
private pruneValueToOptions() {
const {externalValue, multiMode, emptyValue} = this;
if (isNil(this.componentProps.options)) return;
if (isNil(externalValue) || isEqual(externalValue, emptyValue)) return;
if (multiMode) {
const curr = castArray(externalValue),
keptOpts = curr.map(v => this.findOption(v, false)).filter(Boolean);
if (keptOpts.length !== curr.length) this.noteValueChange(keptOpts);
} else if (!this.findOption(externalValue, false)) {
this.noteValueChange(null);
}
}
override toExternal(internal) {
if (isNil(internal)) return this.emptyValue;
if (this.multiMode) {
if (isEmpty(internal)) return this.emptyValue;
return castArray(internal).map(it => it.value);
}
return internal.value;
}
private normalizeOptions(options, depth = 0) {
throwIf(depth > 1, 'Grouped select options support only one-deep nesting.');
options = options || [];
return options.map(it => this.toOption(it, depth));
}
// Normalize / clone a single source value into a normalized option object. Supports Strings
// and Objects. Objects are validated/defaulted to ensure a label+value or label+options sublist,
// with other fields brought along to support Selects emitting value objects with ad hoc properties.
private toOption(src, depth): SelectOption {
return isPlainObject(src) ? this.objectToOption(src, depth) : this.valueToOption(src);
}
private objectToOption(src, depth): SelectOption {
const {componentProps} = this,
labelField = withDefault(componentProps.labelField, 'label'),
valueField = withDefault(componentProps.valueField, 'value');
throwIf(
!src.hasOwnProperty(valueField) && !src.hasOwnProperty('options'),
`Select options provided as Objects must define a '${valueField}' property or a sublist of options.`
);
return src.hasOwnProperty('options')
? {
...src,
label: src[labelField],
options: this.normalizeOptions(src.options, depth + 1)
}
: {
...src,
label: withDefault(src[labelField], src[valueField]),
value: src[valueField]
};
}
private valueToOption(src): SelectOption {
return {label: src != null ? src.toString() : '-null-', value: src};
}
//------------------------
// Async
//------------------------
doQueryAsync = async query => {
const rawOpts = await this.componentProps.queryFn(query);
return this.normalizeOptions(rawOpts);
};
// Option(s) backing the current selection, as produced by toInternal() above.
private get selectedOptions(): SelectOption[] {
const {internalValue} = this;
return isNil(internalValue) ? [] : castArray(internalValue).filter(it => !isNil(it));
}
loadingMessageFn = params => {
const {loadingMessageFn} = this.componentProps,
q = params.inputValue;
return loadingMessageFn ? loadingMessageFn(q) : 'Loading...';
};
//----------------------
// Option Rendering
//----------------------
formatOptionLabel = (opt, params) => {
// Display the standard label string in the value container (context == 'value').
if (params.context !== 'menu') {
const {valueRenderer} = this.componentProps;
return valueRenderer ? valueRenderer(opt) : opt.label;
}
// For rendering dropdown menu items, use an optionRenderer if provided - or use the
// implementation here to render a checkmark next to the active selection.
const optionRenderer = this.componentProps.optionRenderer || this.optionRenderer;
return optionRenderer(opt);
};
private optionRenderer = opt => {
if (this.hideSelectedOptionCheck) {
return div(opt.label);
}
return castArray(this.externalValue).some(v => isEqual(v, opt.value))
? hbox({
children: [
div({
style: {minWidth: 25, textAlign: 'center'},
children: Icon.check({size: 'sm'})
}),
span(opt.label)
],
paddingLeft: 0
})
: div({children: opt.label, style: {paddingLeft: 25}});
};
//------------------------
// Other Implementation
//------------------------
// Cache to avoid re-renders and focus issues. Reads leftIcon from react-select's
// `selectProps` at render time, so the icon can change without replacing the component.
_valueContainerCmp = null;
getValueContainerCmp() {
if (!this._valueContainerCmp) {
this._valueContainerCmp = props => {
const {leftIcon} = props.selectProps,
valueContainer = createElement(components.ValueContainer, props);
return leftIcon
? fragment(
span({className: 'xh-select__control__left-icon', children: leftIcon}),
valueContainer
)
: valueContainer;
};
}
return this._valueContainerCmp;
}
// Let Home/End move the caret when there's text to navigate. See #3930.
_inputCmp = null;
getInputCmp() {
if (!this._inputCmp) {
this._inputCmp = props =>
createElement(components.Input, {
...props,
onKeyDown: e => {
if (
(e.key === 'Home' || e.key === 'End') &&
(e.currentTarget as HTMLInputElement).value
) {
e.stopPropagation();
}
}
});
}
return this._inputCmp;
}
_menuCmp = null;
getMenuCmp() {
if (!this._menuCmp) {
const testId = getTestId(this.componentProps, 'menu');
this._menuCmp = testId
? props =>
createElement(components.Menu, {
...props,
innerProps: {[TEST_ID]: testId, ...props.innerProps}
})
: components.Menu;
}
return this._menuCmp;
}
getDropdownIndicatorCmp() {
return this.hideDropdownIndicator
? () => null
: () => Icon.selectDropdown({className: 'xh-select__indicator'});
}
// As per example @ https://react-select.com/components#replaceable-components
getClearIndicatorCmp() {
return props => {
const {ref, ...restInnerProps} = props.innerProps;
return div({
...restInnerProps,
ref,
[TEST_ID]: getTestId(this.componentProps, 'clear-btn'),
children: Icon.x({className: 'xh-select__indicator'})
});
};
}
getThemeConfig() {
return base => {
return {
...base,
spacing: {...base.spacing, menuGutter: 3},
borderRadius: 3
};
};
}
getMultiValueLabelCmp() {
return this.componentProps.enableTooltips
? props => {
props = this.withTooltip(props, 'xh-select__tooltip__target');
return createElement(components.MultiValueLabel, props);
}
: components.MultiValueLabel;
}
// Windowed mode virtualizes the menu only once the list is long enough to need it.
getMenuListCmp() {
const windowed =
this.windowedMode && countOptions(this.internalOptions) >= WINDOWED_OPTION_THRESHOLD;
return windowed ? WindowedMenuList : components.MenuList;
}
getSingleValueCmp() {
return this.componentProps.enableTooltips
? props => {
props = this.withTooltip(props, 'xh-select__tooltip__target');
return createElement(components.SingleValue, props);
}
: components.SingleValue;
}
noOptionsMessageFn = params => {
const {noOptionsMessageFn} = this.componentProps,
q = params.inputValue;
if (noOptionsMessageFn) return noOptionsMessageFn(q);
if (q) return 'No matches found.';
return this.asyncMode ? 'Type to search...' : '';
};
createMessageFn = q => {
const {createMessageFn} = this.componentProps;
return createMessageFn ? createMessageFn(q) : `Create "${q}"`;
};
getOrCreatePortalDiv() {
const id = MENU_PORTAL_ID;
let portal = document.getElementById(id);
if (!portal) {
portal = document.createElement('div');
portal.id = id;
document.body.appendChild(portal);
}
return portal;
}
private withTooltip(props: PlainObject, className: string): PlainObject {
return {
...props,
children: tooltip({
className,
content: props.children,
children: props.children
})
};
}
}
const cmp = hoistCmp.factory<SelectInputModel>(({model, className, ...props}, ref) => {
const {width, height, ...layoutProps} = getLayoutProps(props),
rsProps: PlainObject = {
value: model.renderValue,
autoFocus: props.autoFocus,
formatOptionLabel: model.formatOptionLabel,
isDisabled: props.disabled,
isMulti: props.enableMulti,
closeMenuOnSelect: props.closeMenuOnSelect,
hideSelectedOptions: model.hideSelectedOptions,
maxMenuHeight: props.maxMenuHeight,
// Explicit false ensures consistent default for single and multi-value instances.
isClearable: withDefault(props.enableClear, false),
menuPlacement: withDefault(props.menuPlacement, 'auto'),
noOptionsMessage: model.noOptionsMessageFn,
openMenuOnFocus: props.openMenuOnFocus,
placeholder: withDefault(props.placeholder, 'Select...'),
tabIndex: props.tabIndex,
// Not a react-select prop - read by our custom ValueContainer via `selectProps`.
leftIcon: props.leftIcon,
// Minimize (or hide) bulky dropdown
components: {
DropdownIndicator: model.getDropdownIndicatorCmp(),
ClearIndicator: model.getClearIndicatorCmp(),
Input: model.getInputCmp(),
Menu: model.getMenuCmp(),
IndicatorSeparator: () => null,
ValueContainer: model.getValueContainerCmp(),
MultiValueLabel: model.getMultiValueLabelCmp(),
SingleValue: model.getSingleValueCmp(),
MenuList: model.getMenuListCmp()
},
// A shared div is created lazily here as needed, appended to the body, and assigned
// a high z-index to ensure options menus render over dialogs or other modals.
menuPortalTarget: model.getOrCreatePortalDiv(),
inputId: props.id,
classNamePrefix: 'xh-select',
theme: model.getThemeConfig(),
onBlur: model.onBlur,
onChange: model.onSelectChange,
onFocus: model.onFocus,
filterOption: model.filterOption,
ref: model.reactSelectRef
};
if (model.manageInputValue) {
rsProps.inputValue = model.inputValue || '';
rsProps.onInputChange = model.onInputChange;
rsProps.controlShouldRenderValue = !model.hasFocus;
}
if (!model.multiMode && model.renderValue) {
rsProps.onMenuOpen = model.onMenuOpen;
}
if (model.asyncMode) {
rsProps.loadOptions = model.doQueryAsync;
rsProps.loadingMessage = model.loadingMessageFn;
if (model.renderValue) rsProps.defaultOptions = [model.renderValue];
} else {
rsProps.options = model.internalOptions;
rsProps.isSearchable = model.filterMode;
}
if (model.creatableMode) {
rsProps.formatCreateLabel = model.createMessageFn;
}
const menuWidth = props.menuWidth ?? (model.windowedMode ? model.windowedMenuWidth : null);
if (menuWidth != null) {
rsProps.styles = {
menu: provided => ({...provided, width: menuWidth, minWidth: '100%'}),
...props.rsOptions?.styles
};
}
const factory = model.getSelectFactory();
mergeDeep(rsProps, props.rsOptions);
return box({
children: factory(rsProps),
className: classNames(className, height ? 'xh-select--has-height' : null),
onKeyDown: e => {
// Esc. and Enter can be listened for by parents -- stop the keydown event
// propagation only if react-select already likely to have used for menu management.
if (model.reactSelect?.props?.menuIsOpen && (e.key === 'Escape' || e.key === 'Enter')) {
e.stopPropagation();
}
},
onMouseDown: e => {
// Some internal elements, like the dropdown indicator and the rendered single value,
// fire 'mousedown' events. These can bubble and inadvertently close Popovers that
// contain Selects.
const target = e?.target as HTMLElement;
if (target && elemWithin(target, 'bp6-popover')) {
e.stopPropagation();
}
},
testId: props.testId,
domAttrs: props.domAttrs,
...layoutProps,
width: withDefault(width, 200),
height: height,
ref
});
});