select.vue
28 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
<template>
<div
:class="classes"
v-click-outside.capture="onClickOutside"
v-click-outside:mousedown.capture="onClickOutside"
>
<div
ref="reference"
:class="selectionCls"
:tabindex="selectTabindex"
@blur="toggleHeaderFocus"
@focus="toggleHeaderFocus"
@click="toggleMenu"
@keydown.esc="handleKeydown"
@keydown.enter="handleKeydown"
@keydown.up.prevent="handleKeydown"
@keydown.down.prevent="handleKeydown"
@keydown.tab="handleKeydown"
@keydown.delete="handleKeydown"
@mouseenter="hasMouseHoverHead = true"
@mouseleave="hasMouseHoverHead = false"
>
<slot name="input">
<input type="hidden" :name="name" :value="publicValue">
<select-head
:filterable="filterable"
:multiple="multiple"
:values="values"
:clearable="canBeCleared"
:disabled="disabled"
:remote="remote"
:input-element-id="elementId"
:initial-label="initialLabel"
:placeholder="placeholder"
:query-prop="query"
@on-query-change="onQueryChange"
@on-input-focus="isFocused = true"
@on-input-blur="isFocused = false"
@on-clear="clearSingleSelect"
/>
</slot>
</div>
<transition name="transition-drop">
<Drop
:class="dropdownCls"
v-show="dropVisible"
:placement="placement"
ref="dropdown"
:data-transfer="transfer"
v-transfer-dom
>
<ul v-show="showNotFoundLabel" :class="[prefixCls + '-not-found']"><li>{{ localeNotFoundText }}</li></ul>
<ul :class="prefixCls + '-dropdown-list'">
<functional-options
v-if="(!remote) || (remote && !loading)"
:options="selectOptions"
:slot-update-hook="updateSlotOptions"
:slot-options="slotOptions"
></functional-options>
</ul>
<ul v-show="loading" :class="[prefixCls + '-loading']">{{ localeLoadingText }}</ul>
</Drop>
</transition>
</div>
</template>
<script>
import Icon from '../icon';
import Drop from './dropdown.vue';
import vClickOutside from 'v-click-outside-x';
import TransferDom from '../../directives/transfer-dom';
import { oneOf } from '../../utils/assist';
import Emitter from '../../mixins/emitter';
import Locale from '../../mixins/locale';
import SelectHead from './select-head.vue';
import FunctionalOptions from './functional-options.vue';
const prefixCls = 'ivu-select';
const optionRegexp = /^i-option$|^Option$/;
const optionGroupRegexp = /option-?group/i;
const findChild = (instance, checkFn) => {
let match = checkFn(instance);
if (match) return instance;
for (let i = 0, l = instance.$children.length; i < l; i++){
const child = instance.$children[i];
match = findChild(child, checkFn);
if (match) return match;
}
};
const findOptionsInVNode = (node) => {
const opts = node.componentOptions;
if (opts && opts.tag.match(optionRegexp)) return [node];
if (!node.children && (!opts || !opts.children)) return [];
const children = [...(node.children || []), ...(opts && opts.children || [])];
const options = children.reduce(
(arr, el) => [...arr, ...findOptionsInVNode(el)], []
).filter(Boolean);
return options.length > 0 ? options : [];
};
const extractOptions = (options) => options.reduce((options, slotEntry) => {
return options.concat(findOptionsInVNode(slotEntry));
}, []);
const applyProp = (node, propName, value) => {
return {
...node,
componentOptions: {
...node.componentOptions,
propsData: {
...node.componentOptions.propsData,
[propName]: value,
}
}
};
};
const ANIMATION_TIMEOUT = 300;
export default {
name: 'iSelect',
mixins: [ Emitter, Locale ],
components: { FunctionalOptions, Drop, Icon, SelectHead },
directives: { clickOutside: vClickOutside.directive, TransferDom },
props: {
value: {
type: [String, Number, Array],
default: ''
},
// 使用时,也得设置 value 才行
label: {
type: [String, Number, Array],
default: ''
},
multiple: {
type: Boolean,
default: false
},
disabled: {
type: Boolean,
default: false
},
clearable: {
type: Boolean,
default: false
},
placeholder: {
type: String
},
filterable: {
type: Boolean,
default: false
},
filterMethod: {
type: Function
},
remoteMethod: {
type: Function
},
loading: {
type: Boolean,
default: false
},
loadingText: {
type: String
},
size: {
validator (value) {
return oneOf(value, ['small', 'large', 'default']);
}
},
labelInValue: {
type: Boolean,
default: false
},
notFoundText: {
type: String
},
placement: {
validator (value) {
return oneOf(value, ['top', 'bottom']);
},
default: 'bottom'
},
transfer: {
type: Boolean,
default: false
},
// Use for AutoComplete
autoComplete: {
type: Boolean,
default: false
},
name: {
type: String
},
elementId: {
type: String
}
},
mounted(){
this.$on('on-select-selected', this.onOptionClick);
// set the initial values if there are any
if (this.values.length > 0 && !this.remote && this.selectOptions.length > 0){
this.values = this.values.map(this.getOptionData).filter(Boolean);
}
if (this.values.length > 0 && this.selectOptions.length === 0){
this.hasExpectedValue = this.values;
}
},
data () {
return {
prefixCls: prefixCls,
values: this.getInitialValue(),
dropDownWidth: 0,
visible: false,
focusIndex: -1,
isFocused: false,
query: '',
initialLabel: this.label,
hasMouseHoverHead: false,
slotOptions: this.$slots.default,
caretPosition: -1,
lastRemoteQuery: '',
unchangedQuery: true,
hasExpectedValue: false,
preventRemoteCall: false,
};
},
computed: {
classes () {
return [
`${prefixCls}`,
{
[`${prefixCls}-visible`]: this.visible,
[`${prefixCls}-disabled`]: this.disabled,
[`${prefixCls}-multiple`]: this.multiple,
[`${prefixCls}-single`]: !this.multiple,
[`${prefixCls}-show-clear`]: this.showCloseIcon,
[`${prefixCls}-${this.size}`]: !!this.size
}
];
},
dropdownCls () {
return {
[prefixCls + '-dropdown-transfer']: this.transfer,
[prefixCls + '-multiple']: this.multiple && this.transfer,
['ivu-auto-complete']: this.autoComplete,
};
},
selectionCls () {
return {
[`${prefixCls}-selection`]: !this.autoComplete,
[`${prefixCls}-selection-focused`]: this.isFocused
};
},
queryStringMatchesSelectedOption(){
const selectedOptions = this.values[0];
if (!selectedOptions) return false;
const [query, label] = [this.query, selectedOptions.label].map(str => (str || '').trim());
return !this.multiple && this.unchangedQuery && query === label;
},
localeNotFoundText () {
if (typeof this.notFoundText === 'undefined') {
return this.t('i.select.noMatch');
} else {
return this.notFoundText;
}
},
localeLoadingText () {
if (typeof this.loadingText === 'undefined') {
return this.t('i.select.loading');
} else {
return this.loadingText;
}
},
transitionName () {
return this.placement === 'bottom' ? 'slide-up' : 'slide-down';
},
dropVisible () {
let status = true;
const noOptions = !this.selectOptions || this.selectOptions.length === 0;
if (!this.loading && this.remote && this.query === '' && noOptions) status = false;
if (this.autoComplete && noOptions) status = false;
return this.visible && status;
},
showNotFoundLabel () {
const {loading, remote, selectOptions} = this;
return selectOptions && selectOptions.length === 0 && (!remote || (remote && !loading));
},
publicValue(){
if (this.labelInValue){
return this.multiple ? this.values : this.values[0];
} else {
return this.multiple ? this.values.map(option => option.value) : (this.values[0] || {}).value;
}
},
canBeCleared(){
const uiStateMatch = this.hasMouseHoverHead || this.active;
const qualifiesForClear = !this.multiple && this.clearable;
return uiStateMatch && qualifiesForClear && this.reset; // we return a function
},
selectOptions() {
const selectOptions = [];
const slotOptions = (this.slotOptions || []);
let optionCounter = -1;
const currentIndex = this.focusIndex;
const selectedValues = this.values.filter(Boolean).map(({value}) => value);
if (this.autoComplete) {
const copyChildren = (node, fn) => {
return {
...node,
children: (node.children || []).map(fn).map(child => copyChildren(child, fn))
};
};
const autoCompleteOptions = extractOptions(slotOptions);
const selectedSlotOption = autoCompleteOptions[currentIndex];
return slotOptions.map(node => {
if (node === selectedSlotOption) return applyProp(node, 'isFocused', true);
return copyChildren(node, (child) => {
if (child !== selectedSlotOption) return child;
return applyProp(child, 'isFocused', true);
});
});
}
for (let option of slotOptions) {
const cOptions = option.componentOptions;
if (!cOptions) continue;
if (cOptions.tag.match(optionGroupRegexp)){
let children = cOptions.children;
// remove filtered children
if (this.filterable){
children = children.filter(
({componentOptions}) => this.validateOption(componentOptions)
);
}
cOptions.children = children.map(opt => {
optionCounter = optionCounter + 1;
return this.processOption(opt, selectedValues, optionCounter === currentIndex);
});
// keep the group if it still has children
if (cOptions.children.length > 0) selectOptions.push({...option});
} else {
// ignore option if not passing filter
const optionPassesFilter = this.filterable ? this.validateOption(cOptions) : option;
if (!optionPassesFilter) continue;
optionCounter = optionCounter + 1;
selectOptions.push(this.processOption(option, selectedValues, optionCounter === currentIndex));
}
}
return selectOptions;
},
flatOptions(){
return extractOptions(this.selectOptions);
},
selectTabindex(){
return this.disabled || this.filterable ? -1 : 0;
},
remote(){
return typeof this.remoteMethod === 'function';
}
},
methods: {
setQuery(query){ // PUBLIC API
if (query) {
this.onQueryChange(query);
return;
}
if (query === null) {
this.onQueryChange('');
this.values = [];
}
},
clearSingleSelect(){ // PUBLIC API
this.$emit('on-clear');
this.hideMenu();
if (this.clearable) this.values = [];
},
getOptionData(value){
const option = this.flatOptions.find(({componentOptions}) => componentOptions.propsData.value === value);
if (!option) return null;
const textContent = option.componentOptions.children.reduce((str, child) => str + (child.text || ''), '');
const label = option.componentOptions.propsData.label || textContent || '';
return {
value: value,
label: label,
};
},
getInitialValue(){
const {multiple, value} = this;
let initialValue = Array.isArray(value) ? value : [value];
if (!multiple && (typeof initialValue[0] === 'undefined' || String(initialValue[0]).trim() === '')) initialValue = [];
return initialValue.filter(Boolean);
},
processOption(option, values, isFocused){
if (!option.componentOptions) return option;
const optionValue = option.componentOptions.propsData.value;
const disabled = option.componentOptions.propsData.disabled;
const isSelected = values.includes(optionValue);
const propsData = {
...option.componentOptions.propsData,
selected: isSelected,
isFocused: isFocused,
disabled: typeof disabled === 'undefined' ? false : disabled !== false,
};
return {
...option,
componentOptions: {
...option.componentOptions,
propsData: propsData
}
};
},
validateOption({children, elm, propsData}){
if (this.queryStringMatchesSelectedOption) return true;
const value = propsData.value;
const label = propsData.label || '';
const textContent = (elm && elm.textContent) || (children || []).reduce((str, node) => {
const nodeText = node.elm ? node.elm.textContent : node.text;
return `${str} ${nodeText}`;
}, '') || '';
const stringValues = JSON.stringify([value, label, textContent]);
const query = this.query.toLowerCase().trim();
return stringValues.toLowerCase().includes(query);
},
toggleMenu (e, force) {
if (this.disabled || this.autoComplete) {
return false;
}
this.visible = typeof force !== 'undefined' ? force : !this.visible;
if (this.visible){
this.dropDownWidth = this.$el.getBoundingClientRect().width;
this.broadcast('Drop', 'on-update-popper');
}
},
hideMenu () {
this.toggleMenu(null, false);
setTimeout(() => this.unchangedQuery = true, ANIMATION_TIMEOUT);
},
onClickOutside(event){
if (this.visible) {
if (event.type === 'mousedown') {
event.preventDefault();
return;
}
if (this.filterable) {
const input = this.$el.querySelector('input[type="text"]');
this.caretPosition = input.selectionStart;
this.$nextTick(() => {
const caretPosition = this.caretPosition === -1 ? input.value.length : this.caretPosition;
input.setSelectionRange(caretPosition, caretPosition);
});
}
if (!this.autoComplete) event.stopPropagation();
event.preventDefault();
this.hideMenu();
this.isFocused = true;
} else {
this.caretPosition = -1;
this.isFocused = false;
}
},
reset(){
this.unchangedQuery = true;
this.values = [];
},
handleKeydown (e) {
if (e.key === 'Backspace'){
return; // so we don't call preventDefault
}
if (this.visible) {
e.preventDefault();
if (e.key === 'Tab'){
e.stopPropagation();
}
// Esc slide-up
if (e.key === 'Escape') {
e.stopPropagation();
this.hideMenu();
}
// next
if (e.key === 'ArrowUp') {
this.navigateOptions(-1);
}
// prev
if (e.key === 'ArrowDown') {
this.navigateOptions(1);
}
// enter
if (e.key === 'Enter') {
if (this.focusIndex === -1) return this.hideMenu();
const optionComponent = this.flatOptions[this.focusIndex];
const option = this.getOptionData(optionComponent.componentOptions.propsData.value);
this.onOptionClick(option);
}
} else {
const keysThatCanOpenSelect = ['ArrowUp', 'ArrowDown'];
if (keysThatCanOpenSelect.includes(e.key)) this.toggleMenu(null, true);
}
},
navigateOptions(direction){
const optionsLength = this.flatOptions.length - 1;
let index = this.focusIndex + direction;
if (index < 0) index = optionsLength;
if (index > optionsLength) index = 0;
// find nearest option in case of disabled options in between
if (direction > 0){
let nearestActiveOption = -1;
for (let i = 0; i < this.flatOptions.length; i++){
const optionIsActive = !this.flatOptions[i].componentOptions.propsData.disabled;
if (optionIsActive) nearestActiveOption = i;
if (nearestActiveOption >= index) break;
}
index = nearestActiveOption;
} else {
let nearestActiveOption = this.flatOptions.length;
for (let i = optionsLength; i >= 0; i--){
const optionIsActive = !this.flatOptions[i].componentOptions.propsData.disabled;
if (optionIsActive) nearestActiveOption = i;
if (nearestActiveOption <= index) break;
}
index = nearestActiveOption;
}
this.focusIndex = index;
},
onOptionClick(option) {
if (this.multiple){
// keep the query for remote select
if (this.remote) this.lastRemoteQuery = this.lastRemoteQuery || this.query;
else this.lastRemoteQuery = '';
const valueIsSelected = this.values.find(({value}) => value === option.value);
if (valueIsSelected){
this.values = this.values.filter(({value}) => value !== option.value);
} else {
this.values = this.values.concat(option);
}
this.isFocused = true; // so we put back focus after clicking with mouse on option elements
} else {
this.query = String(option.label).trim();
this.values = [option];
this.lastRemoteQuery = '';
this.hideMenu();
}
this.focusIndex = this.flatOptions.findIndex((opt) => {
if (!opt || !opt.componentOptions) return false;
return opt.componentOptions.propsData.value === option.value;
});
if (this.filterable){
const inputField = this.$el.querySelector('input[type="text"]');
if (!this.autoComplete) this.$nextTick(() => inputField.focus());
}
this.broadcast('Drop', 'on-update-popper');
},
onQueryChange(query) {
if (query.length > 0 && query !== this.query) this.visible = true;
this.query = query;
this.unchangedQuery = this.visible;
},
toggleHeaderFocus({type}){
if (this.disabled) {
return;
}
this.isFocused = type === 'focus';
},
updateSlotOptions(){
this.slotOptions = this.$slots.default;
}
},
watch: {
value(value){
const {getInitialValue, getOptionData, publicValue} = this;
if (value === '') this.values = [];
else if (JSON.stringify(value) !== JSON.stringify(publicValue)) {
this.$nextTick(() => this.values = getInitialValue().map(getOptionData).filter(Boolean));
}
},
values(now, before){
const newValue = JSON.stringify(now);
const oldValue = JSON.stringify(before);
const shouldEmitInput = newValue !== oldValue;
if (shouldEmitInput) {
// v-model is always just the value, event with labelInValue === true
const vModelValue = this.labelInValue ?
(this.multiple ? this.publicValue.map(({value}) => value)
:
this.publicValue.value) : this.publicValue;
this.$emit('input', vModelValue); // to update v-model
this.$emit('on-change', this.publicValue);
this.dispatch('FormItem', 'on-form-change', this.publicValue);
}
},
query (query) {
this.$emit('on-query-change', query);
const {remoteMethod, lastRemoteQuery} = this;
const hasValidQuery = query !== '' && (query !== lastRemoteQuery || !lastRemoteQuery);
const shouldCallRemoteMethod = remoteMethod && hasValidQuery && !this.preventRemoteCall;
this.preventRemoteCall = false; // remove the flag
if (shouldCallRemoteMethod){
this.focusIndex = -1;
const promise = this.remoteMethod(query);
this.initialLabel = '';
if (promise && promise.then){
promise.then(options => {
if (options) this.options = options;
});
}
}
if (query !== '' && this.remote) this.lastRemoteQuery = query;
},
loading(state){
if (state === false){
this.updateSlotOptions();
}
},
isFocused(focused){
const el = this.filterable ? this.$el.querySelector('input[type="text"]') : this.$el;
el[this.isFocused ? 'focus' : 'blur']();
// restore query value in filterable single selects
const [selectedOption] = this.values;
if (selectedOption && this.filterable && !this.multiple && !focused){
const selectedLabel = String(selectedOption.label || selectedOption.value).trim();
if (selectedLabel && this.query !== selectedLabel) {
this.preventRemoteCall = true;
this.query = selectedLabel;
}
}
},
focusIndex(index){
if (index < 0 || this.autoComplete) return;
// update scroll
const optionValue = this.flatOptions[index].componentOptions.propsData.value;
const optionInstance = findChild(this, ({$options}) => {
return $options.componentName === 'select-item' && $options.propsData.value === optionValue;
});
let bottomOverflowDistance = optionInstance.$el.getBoundingClientRect().bottom - this.$refs.dropdown.$el.getBoundingClientRect().bottom;
let topOverflowDistance = optionInstance.$el.getBoundingClientRect().top - this.$refs.dropdown.$el.getBoundingClientRect().top;
if (bottomOverflowDistance > 0) {
this.$refs.dropdown.$el.scrollTop += bottomOverflowDistance;
}
if (topOverflowDistance < 0) {
this.$refs.dropdown.$el.scrollTop += topOverflowDistance;
}
},
dropVisible(open){
this.broadcast('Drop', open ? 'on-update-popper' : 'on-destroy-popper');
},
selectOptions(){
if (this.hasExpectedValue){
this.values = this.values.map(this.getOptionData).filter(Boolean);
this.hasExpectedValue = false;
}
if (this.slotOptions && this.slotOptions.length === 0){
this.query = '';
}
},
visible(state){
this.$emit('on-open-change', state);
}
}
};
</script>