Blame view

src/components/select/select.vue 31 KB
e355dd49   梁灏   add Select Component
1
  <template>
2fbe636b   梁灏   Select support a ...
2
      <div
2fbe636b   梁灏   Select support a ...
3
          :class="classes"
c9b86944   Sergio Crisostomo   Refactor Select!
4
          v-click-outside.capture="onClickOutside"
4a9974f6   Graham Fairweather   Normalise v-ckick...
5
          v-click-outside:mousedown.capture="onClickOutside"
c9b86944   Sergio Crisostomo   Refactor Select!
6
      >
e355dd49   梁灏   add Select Component
7
          <div
4aec6a66   梁灏   support Select
8
              ref="reference"
c9b86944   Sergio Crisostomo   Refactor Select!
9
10
11
12
13
14
15
16
17
18
  
              :class="selectionCls"
              :tabindex="selectTabindex"
  
              @blur="toggleHeaderFocus"
              @focus="toggleHeaderFocus"
  
              @click="toggleMenu"
              @keydown.esc="handleKeydown"
              @keydown.enter="handleKeydown"
66f807ed   梁灏   update Select
19
20
              @keydown.up.prevent="handleKeydown"
              @keydown.down.prevent="handleKeydown"
c9b86944   Sergio Crisostomo   Refactor Select!
21
22
23
24
25
26
27
28
              @keydown.tab="handleKeydown"
              @keydown.delete="handleKeydown"
  
  
              @mouseenter="hasMouseHoverHead = true"
              @mouseleave="hasMouseHoverHead = false"
  
          >
fed3e09d   梁灏   add AutoComplete ...
29
              <slot name="input">
c9b86944   Sergio Crisostomo   Refactor Select!
30
31
32
33
34
35
                  <input type="hidden" :name="name" :value="publicValue">
                  <select-head
                      :filterable="filterable"
                      :multiple="multiple"
                      :values="values"
                      :clearable="canBeCleared"
fed3e09d   梁灏   add AutoComplete ...
36
                      :disabled="disabled"
c9b86944   Sergio Crisostomo   Refactor Select!
37
38
39
40
41
42
43
44
45
                      :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"
7dbde804   Sergio Crisostomo   add on-clear event
46
                      @on-clear="clearSingleSelect"
47f03c54   梁灏   fix #4273
47
48
  
                      @on-keydown="handleFilterInputKeyDown"
c9b86944   Sergio Crisostomo   Refactor Select!
49
                  />
fed3e09d   梁灏   add AutoComplete ...
50
              </slot>
e355dd49   梁灏   add Select Component
51
          </div>
e09b07b7   huanghong   解决drop弹出动画异常
52
          <transition name="transition-drop">
595cfa72   梁灏   fixed #1187 #844 ...
53
              <Drop
ecaf8d51   梁灏   Date add transfer...
54
                  :class="dropdownCls"
595cfa72   梁灏   fixed #1187 #844 ...
55
56
57
58
                  v-show="dropVisible"
                  :placement="placement"
                  ref="dropdown"
                  :data-transfer="transfer"
7bafe9d9   梁灏   fixes #4453 #4480...
59
                  :transfer="transfer"
c9b86944   Sergio Crisostomo   Refactor Select!
60
61
62
63
                  v-transfer-dom
              >
                  <ul v-show="showNotFoundLabel" :class="[prefixCls + '-not-found']"><li>{{ localeNotFoundText }}</li></ul>
                  <ul :class="prefixCls + '-dropdown-list'">
220161f5   Sergio Crisostomo   Clean up empty/nu...
64
65
66
67
68
69
                      <functional-options
                          v-if="(!remote) || (remote && !loading)"
                          :options="selectOptions"
                          :slot-update-hook="updateSlotOptions"
                          :slot-options="slotOptions"
                      ></functional-options>
c9b86944   Sergio Crisostomo   Refactor Select!
70
                  </ul>
01b54e30   梁灏   Select support re...
71
                  <ul v-show="loading" :class="[prefixCls + '-loading']">{{ localeLoadingText }}</ul>
4aec6a66   梁灏   support Select
72
73
              </Drop>
          </transition>
e355dd49   梁灏   add Select Component
74
75
76
      </div>
  </template>
  <script>
4aec6a66   梁灏   support Select
77
      import Drop from './dropdown.vue';
26369639   Graham Fairweather   Update v-click-ou...
78
      import {directive as clickOutside} from 'v-click-outside-x';
595cfa72   梁灏   fixed #1187 #844 ...
79
      import TransferDom from '../../directives/transfer-dom';
c9b86944   Sergio Crisostomo   Refactor Select!
80
      import { oneOf } from '../../utils/assist';
4aec6a66   梁灏   support Select
81
      import Emitter from '../../mixins/emitter';
e5337c81   梁灏   fixed some compon...
82
      import Locale from '../../mixins/locale';
c9b86944   Sergio Crisostomo   Refactor Select!
83
84
      import SelectHead from './select-head.vue';
      import FunctionalOptions from './functional-options.vue';
e355dd49   梁灏   add Select Component
85
86
  
      const prefixCls = 'ivu-select';
9366c9a7   Sergio Crisostomo   Select improvemen...
87
      const optionRegexp = /^i-option$|^Option$/i;
523e2c81   Sergio Crisostomo   correct match log...
88
      const optionGroupRegexp = /option-?group/i;
c9b86944   Sergio Crisostomo   Refactor Select!
89
90
91
92
93
94
95
96
97
98
  
      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;
          }
      };
e355dd49   梁灏   add Select Component
99
  
06a74f9e   Sergio Crisostomo   Allow select to n...
100
101
      const findOptionsInVNode = (node) => {
          const opts = node.componentOptions;
523e2c81   Sergio Crisostomo   correct match log...
102
          if (opts && opts.tag.match(optionRegexp)) return [node];
7d14e70c   Sergio Crisostomo   Include both node...
103
          if (!node.children && (!opts || !opts.children)) return [];
9366c9a7   Sergio Crisostomo   Select improvemen...
104
          const children = [...(node.children || []), ...(opts && opts.children || [])];
7d14e70c   Sergio Crisostomo   Include both node...
105
          const options = children.reduce(
06a74f9e   Sergio Crisostomo   Allow select to n...
106
107
108
109
110
111
112
113
114
              (arr, el) => [...arr, ...findOptionsInVNode(el)], []
          ).filter(Boolean);
          return options.length > 0 ? options : [];
      };
  
      const extractOptions = (options) => options.reduce((options, slotEntry) => {
          return options.concat(findOptionsInVNode(slotEntry));
      }, []);
  
aa21cdf9   Sergio Crisostomo   Process also shal...
115
116
117
118
119
120
121
122
123
124
125
126
127
      const applyProp = (node, propName, value) => {
          return {
              ...node,
              componentOptions: {
                  ...node.componentOptions,
                  propsData: {
                      ...node.componentOptions.propsData,
                      [propName]: value,
                  }
              }
          };
      };
  
9366c9a7   Sergio Crisostomo   Select improvemen...
128
129
130
131
132
133
      const getNestedProperty = (obj, path) => {
          const keys = path.split('.');
          return keys.reduce((o, key) => o && o[key] || null, obj);
      };
  
      const getOptionLabel = option => {
1b39f569   Sergio Crisostomo   Use label first i...
134
          if (option.componentOptions.propsData.label) return option.componentOptions.propsData.label;
9366c9a7   Sergio Crisostomo   Select improvemen...
135
136
          const textContent = (option.componentOptions.children || []).reduce((str, child) => str + (child.text || ''), '');
          const innerHTML = getNestedProperty(option, 'data.domProps.innerHTML');
1b39f569   Sergio Crisostomo   Use label first i...
137
          return textContent || (typeof innerHTML === 'string' ? innerHTML : '');
9366c9a7   Sergio Crisostomo   Select improvemen...
138
139
      };
  
cd8f1be8   任珽   fixed bug #4466 #...
140
141
142
143
144
145
146
147
148
      const checkValuesNotEqual = (value,publicValue,values) => {
          const strValue = JSON.stringify(value);
          const strPublic = JSON.stringify(publicValue);
          const strValues = JSON.stringify(values.map( item => {
              return item.value;
          }));
          return strValue !== strPublic || strValue !== strValues || strValues !== strPublic;
      };
  
9366c9a7   Sergio Crisostomo   Select improvemen...
149
  
31788df3   Sergio Crisostomo   Normalise behavio...
150
151
      const ANIMATION_TIMEOUT = 300;
  
e355dd49   梁灏   add Select Component
152
      export default {
8f5b1686   梁灏   fixed #196
153
          name: 'iSelect',
e5337c81   梁灏   fixed some compon...
154
          mixins: [ Emitter, Locale ],
9eba26fe   梁灏   update Select Icons
155
          components: { FunctionalOptions, Drop, SelectHead },
26369639   Graham Fairweather   Update v-click-ou...
156
          directives: { clickOutside, TransferDom },
e355dd49   梁灏   add Select Component
157
          props: {
4aec6a66   梁灏   support Select
158
              value: {
e355dd49   梁灏   add Select Component
159
160
161
                  type: [String, Number, Array],
                  default: ''
              },
98bf25b3   梁灏   fixed #1286
162
              // 使用时,也得设置 value 才行
ddc35c9a   梁灏   fixed #952
163
164
165
166
              label: {
                  type: [String, Number, Array],
                  default: ''
              },
e355dd49   梁灏   add Select Component
167
168
169
170
171
172
173
174
175
176
177
178
179
              multiple: {
                  type: Boolean,
                  default: false
              },
              disabled: {
                  type: Boolean,
                  default: false
              },
              clearable: {
                  type: Boolean,
                  default: false
              },
              placeholder: {
e5337c81   梁灏   fixed some compon...
180
                  type: String
e355dd49   梁灏   add Select Component
181
182
183
184
185
186
187
188
              },
              filterable: {
                  type: Boolean,
                  default: false
              },
              filterMethod: {
                  type: Function
              },
01b54e30   梁灏   Select support re...
189
190
191
192
193
194
195
196
197
198
              remoteMethod: {
                  type: Function
              },
              loading: {
                  type: Boolean,
                  default: false
              },
              loadingText: {
                  type: String
              },
e355dd49   梁灏   add Select Component
199
200
              size: {
                  validator (value) {
6932b4d7   梁灏   update Page compo...
201
                      return oneOf(value, ['small', 'large', 'default']);
be2c3198   梁灏   Select support gl...
202
203
                  },
                  default () {
fe5ffd7f   梁灏   fixed #4196 #4165
204
                      return !this.$IVIEW || this.$IVIEW.size === '' ? 'default' : this.$IVIEW.size;
e355dd49   梁灏   add Select Component
205
206
207
208
209
                  }
              },
              labelInValue: {
                  type: Boolean,
                  default: false
294e2412   梁灏   update Select com...
210
211
              },
              notFoundText: {
e5337c81   梁灏   fixed some compon...
212
                  type: String
f89dd9c2   梁灏   Paeg、Select add p...
213
214
215
              },
              placement: {
                  validator (value) {
74ef0a6a   梁灏   fixed #4194
216
                      return oneOf(value, ['top', 'bottom', 'top-start', 'bottom-start', 'top-end', 'bottom-end']);
f89dd9c2   梁灏   Paeg、Select add p...
217
                  },
74ef0a6a   梁灏   fixed #4194
218
                  default: 'bottom-start'
595cfa72   梁灏   fixed #1187 #844 ...
219
220
221
              },
              transfer: {
                  type: Boolean,
517917a2   梁灏   add global settin...
222
                  default () {
fe5ffd7f   梁灏   fixed #4196 #4165
223
                      return !this.$IVIEW || this.$IVIEW.transfer === '' ? false : this.$IVIEW.transfer;
517917a2   梁灏   add global settin...
224
                  }
fed3e09d   梁灏   add AutoComplete ...
225
226
227
228
229
              },
              // Use for AutoComplete
              autoComplete: {
                  type: Boolean,
                  default: false
0460a1e8   梁灏   fixed #812
230
231
232
              },
              name: {
                  type: String
acb79ba3   梁灏   fixed #433
233
234
235
              },
              elementId: {
                  type: String
e355dd49   梁灏   add Select Component
236
237
              }
          },
c9b86944   Sergio Crisostomo   Refactor Select!
238
239
240
241
          mounted(){
              this.$on('on-select-selected', this.onOptionClick);
  
              // set the initial values if there are any
9366c9a7   Sergio Crisostomo   Select improvemen...
242
243
244
245
246
              if (!this.remote && this.selectOptions.length > 0){
                  this.values = this.getInitialValue().map(value => {
                      if (typeof value !== 'number' && !value) return null;
                      return this.getOptionData(value);
                  }).filter(Boolean);
c9b86944   Sergio Crisostomo   Refactor Select!
247
              }
7f63e58c   Sergio Crisostomo   Make possible for...
248
  
73b01ee0   郑敏   fixed #3722 that ...
249
              this.checkUpdateStatus();
c9b86944   Sergio Crisostomo   Refactor Select!
250
          },
e355dd49   梁灏   add Select Component
251
          data () {
c9b86944   Sergio Crisostomo   Refactor Select!
252
  
e355dd49   梁灏   add Select Component
253
254
              return {
                  prefixCls: prefixCls,
9366c9a7   Sergio Crisostomo   Select improvemen...
255
                  values: [],
c9b86944   Sergio Crisostomo   Refactor Select!
256
                  dropDownWidth: 0,
e355dd49   梁灏   add Select Component
257
                  visible: false,
c9b86944   Sergio Crisostomo   Refactor Select!
258
259
                  focusIndex: -1,
                  isFocused: false,
e355dd49   梁灏   add Select Component
260
                  query: '',
c9b86944   Sergio Crisostomo   Refactor Select!
261
262
263
264
265
                  initialLabel: this.label,
                  hasMouseHoverHead: false,
                  slotOptions: this.$slots.default,
                  caretPosition: -1,
                  lastRemoteQuery: '',
31788df3   Sergio Crisostomo   Normalise behavio...
266
                  unchangedQuery: true,
7f63e58c   Sergio Crisostomo   Make possible for...
267
                  hasExpectedValue: false,
45bcc14d   Sergio Crisostomo   prevent calling r...
268
                  preventRemoteCall: false,
47f03c54   梁灏   fix #4273
269
                  filterQueryKeyDown: false,  // #4273
b0893113   jingsam   :art: add eslint
270
              };
e355dd49   梁灏   add Select Component
271
272
273
274
          },
          computed: {
              classes () {
                  return [
4b7138b9   梁灏   fixed some bugs
275
                      `${prefixCls}`,
e355dd49   梁灏   add Select Component
276
                      {
4b7138b9   梁灏   fixed some bugs
277
278
279
280
281
282
                          [`${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
e355dd49   梁灏   add Select Component
283
                      }
b0893113   jingsam   :art: add eslint
284
                  ];
e355dd49   梁灏   add Select Component
285
              },
ecaf8d51   梁灏   Date add transfer...
286
287
288
              dropdownCls () {
                  return {
                      [prefixCls + '-dropdown-transfer']: this.transfer,
fed3e09d   梁灏   add AutoComplete ...
289
290
291
292
293
294
                      [prefixCls + '-multiple']: this.multiple && this.transfer,
                      ['ivu-auto-complete']: this.autoComplete,
                  };
              },
              selectionCls () {
                  return {
c9b86944   Sergio Crisostomo   Refactor Select!
295
296
                      [`${prefixCls}-selection`]: !this.autoComplete,
                      [`${prefixCls}-selection-focused`]: this.isFocused
ecaf8d51   梁灏   Date add transfer...
297
298
                  };
              },
31788df3   Sergio Crisostomo   Normalise behavio...
299
300
              queryStringMatchesSelectedOption(){
                  const selectedOptions = this.values[0];
5266c905   Sergio Crisostomo   Trim label so we ...
301
302
303
                  if (!selectedOptions) return false;
                  const [query, label] = [this.query, selectedOptions.label].map(str => (str || '').trim());
                  return !this.multiple && this.unchangedQuery && query === label;
31788df3   Sergio Crisostomo   Normalise behavio...
304
              },
e5337c81   梁灏   fixed some compon...
305
              localeNotFoundText () {
c9b86944   Sergio Crisostomo   Refactor Select!
306
                  if (typeof this.notFoundText === 'undefined') {
e5337c81   梁灏   fixed some compon...
307
308
309
310
                      return this.t('i.select.noMatch');
                  } else {
                      return this.notFoundText;
                  }
f89dd9c2   梁灏   Paeg、Select add p...
311
              },
01b54e30   梁灏   Select support re...
312
              localeLoadingText () {
c9b86944   Sergio Crisostomo   Refactor Select!
313
                  if (typeof this.loadingText === 'undefined') {
01b54e30   梁灏   Select support re...
314
315
316
317
318
                      return this.t('i.select.loading');
                  } else {
                      return this.loadingText;
                  }
              },
f89dd9c2   梁灏   Paeg、Select add p...
319
320
              transitionName () {
                  return this.placement === 'bottom' ? 'slide-up' : 'slide-down';
ec98f3c3   梁灏   update Select
321
322
323
              },
              dropVisible () {
                  let status = true;
bc348e7e   Sergio Crisostomo   adapt to auto-com...
324
325
                  const noOptions = !this.selectOptions || this.selectOptions.length === 0;
                  if (!this.loading && this.remote && this.query === '' && noOptions) status = false;
fed3e09d   梁灏   add AutoComplete ...
326
  
bc348e7e   Sergio Crisostomo   adapt to auto-com...
327
                  if (this.autoComplete && noOptions) status = false;
fed3e09d   梁灏   add AutoComplete ...
328
  
ec98f3c3   梁灏   update Select
329
                  return this.visible && status;
29264399   梁灏   update Select
330
              },
c9b86944   Sergio Crisostomo   Refactor Select!
331
332
              showNotFoundLabel () {
                  const {loading, remote, selectOptions} = this;
bc348e7e   Sergio Crisostomo   adapt to auto-com...
333
                  return selectOptions && selectOptions.length === 0 && (!remote || (remote && !loading));
e355dd49   梁灏   add Select Component
334
              },
c9b86944   Sergio Crisostomo   Refactor Select!
335
336
337
              publicValue(){
                  if (this.labelInValue){
                      return this.multiple ? this.values : this.values[0];
e355dd49   梁灏   add Select Component
338
                  } else {
c9b86944   Sergio Crisostomo   Refactor Select!
339
                      return this.multiple ? this.values.map(option => option.value) : (this.values[0] || {}).value;
e355dd49   梁灏   add Select Component
340
341
                  }
              },
c9b86944   Sergio Crisostomo   Refactor Select!
342
343
              canBeCleared(){
                  const uiStateMatch = this.hasMouseHoverHead || this.active;
9050e61c   Emilio Losada   fix(select): don'...
344
                  const qualifiesForClear = !this.multiple && !this.disabled && this.clearable;
c9b86944   Sergio Crisostomo   Refactor Select!
345
346
347
348
                  return uiStateMatch && qualifiesForClear && this.reset; // we return a function
              },
              selectOptions() {
                  const selectOptions = [];
06a74f9e   Sergio Crisostomo   Allow select to n...
349
                  const slotOptions = (this.slotOptions || []);
c9b86944   Sergio Crisostomo   Refactor Select!
350
351
                  let optionCounter = -1;
                  const currentIndex = this.focusIndex;
220161f5   Sergio Crisostomo   Clean up empty/nu...
352
                  const selectedValues = this.values.filter(Boolean).map(({value}) => value);
06a74f9e   Sergio Crisostomo   Allow select to n...
353
354
355
356
357
358
359
360
361
362
                  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];
  
aa21cdf9   Sergio Crisostomo   Process also shal...
363
                      return slotOptions.map(node => {
f8620d9a   Sergio Crisostomo   Fix autocomplete ...
364
                          if (node === selectedSlotOption || getNestedProperty(node, 'componentOptions.propsData.value') === this.value) return applyProp(node, 'isFocused', true);
aa21cdf9   Sergio Crisostomo   Process also shal...
365
366
367
368
369
                          return copyChildren(node, (child) => {
                              if (child !== selectedSlotOption) return child;
                              return applyProp(child, 'isFocused', true);
                          });
                      });
06a74f9e   Sergio Crisostomo   Allow select to n...
370
                  }
e27b704a   梁灏   fixed #4273
371
372
373
                  /**
                   * Not sure why use hasDefaultSelected #4273
                   * */
bef01c91   梁灏   it will make a ne...
374
                  let hasDefaultSelected = slotOptions.some(option => this.query === option.key);
06a74f9e   Sergio Crisostomo   Allow select to n...
375
                  for (let option of slotOptions) {
e355dd49   梁灏   add Select Component
376
  
b6c069ca   Sergio Crisostomo   reset query if op...
377
378
                      const cOptions = option.componentOptions;
                      if (!cOptions) continue;
b6c069ca   Sergio Crisostomo   reset query if op...
379
380
                      if (cOptions.tag.match(optionGroupRegexp)){
                          let children = cOptions.children;
20719945   Aresn   Revert "Fix select"
381
  
c9b86944   Sergio Crisostomo   Refactor Select!
382
383
384
385
386
387
                          // remove filtered children
                          if (this.filterable){
                              children = children.filter(
                                  ({componentOptions}) => this.validateOption(componentOptions)
                              );
                          }
e355dd49   梁灏   add Select Component
388
  
b6c069ca   Sergio Crisostomo   reset query if op...
389
                          cOptions.children = children.map(opt => {
c9b86944   Sergio Crisostomo   Refactor Select!
390
391
392
                              optionCounter = optionCounter + 1;
                              return this.processOption(opt, selectedValues, optionCounter === currentIndex);
                          });
3e855e34   梁灏   fixed #46
393
  
c9b86944   Sergio Crisostomo   Refactor Select!
394
                          // keep the group if it still has children
b6c069ca   Sergio Crisostomo   reset query if op...
395
                          if (cOptions.children.length > 0) selectOptions.push({...option});
c9b86944   Sergio Crisostomo   Refactor Select!
396
397
                      } else {
                          // ignore option if not passing filter
47f03c54   梁灏   fix #4273
398
                          if (!hasDefaultSelected || this.filterQueryKeyDown) {
bef01c91   梁灏   it will make a ne...
399
400
401
                              const optionPassesFilter = this.filterable ? this.validateOption(cOptions) : option;
                              if (!optionPassesFilter) continue;
                          }
20719945   Aresn   Revert "Fix select"
402
  
c9b86944   Sergio Crisostomo   Refactor Select!
403
                          optionCounter = optionCounter + 1;
fdc71ffe   郑敏   reset the focus i...
404
                          selectOptions.push(this.processOption(option, selectedValues, optionCounter === currentIndex));
3e855e34   梁灏   fixed #46
405
                      }
e355dd49   梁灏   add Select Component
406
407
                  }
  
47f03c54   梁灏   fix #4273
408
409
                  this.filterQueryKeyDown = false;
  
c9b86944   Sergio Crisostomo   Refactor Select!
410
                  return selectOptions;
e355dd49   梁灏   add Select Component
411
              },
c9b86944   Sergio Crisostomo   Refactor Select!
412
              flatOptions(){
06a74f9e   Sergio Crisostomo   Allow select to n...
413
                  return extractOptions(this.selectOptions);
c9b86944   Sergio Crisostomo   Refactor Select!
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
              },
              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 = [];
e355dd49   梁灏   add Select Component
431
432
                  }
              },
c9b86944   Sergio Crisostomo   Refactor Select!
433
              clearSingleSelect(){ // PUBLIC API
7dbde804   Sergio Crisostomo   add on-clear event
434
                  this.$emit('on-clear');
c3304bce   Sergio Crisostomo   correct unchanged...
435
                  this.hideMenu();
743f6e06   Sergio Crisostomo   Be more hard on t...
436
                  if (this.clearable) this.reset();
c9b86944   Sergio Crisostomo   Refactor Select!
437
438
439
              },
              getOptionData(value){
                  const option = this.flatOptions.find(({componentOptions}) => componentOptions.propsData.value === value);
7f63e58c   Sergio Crisostomo   Make possible for...
440
                  if (!option) return null;
9366c9a7   Sergio Crisostomo   Select improvemen...
441
                  const label = getOptionLabel(option);
c9b86944   Sergio Crisostomo   Refactor Select!
442
443
444
445
446
447
                  return {
                      value: value,
                      label: label,
                  };
              },
              getInitialValue(){
c741fa2f   Sergio Crisostomo   Use label as query
448
                  const {multiple, remote, value} = this;
c9b86944   Sergio Crisostomo   Refactor Select!
449
                  let initialValue = Array.isArray(value) ? value : [value];
31e4380d   luffyzhao   还是要保留multiple判断
450
                  if (!multiple && (typeof initialValue[0] === 'undefined' || (String(initialValue[0]).trim() === '' && !Number.isFinite(initialValue[0])))) initialValue = [];
c741fa2f   Sergio Crisostomo   Use label as query
451
452
453
454
                  if (remote && !multiple && value) {
                      const data = this.getOptionData(value);
                      this.query = data ? data.label : String(value);
                  }
b4138675   luffyzhao   select-binding-0
455
                  return initialValue.filter((item) => {
5c846d28   Sergio Crisostomo   Correct event pro...
456
                      return Boolean(item) || item === 0;
b4138675   luffyzhao   select-binding-0
457
                  });
c9b86944   Sergio Crisostomo   Refactor Select!
458
459
460
461
462
463
464
465
466
467
468
469
470
              },
              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,
                  };
e355dd49   梁灏   add Select Component
471
  
c9b86944   Sergio Crisostomo   Refactor Select!
472
473
474
475
476
                  return {
                      ...option,
                      componentOptions: {
                          ...option.componentOptions,
                          propsData: propsData
e355dd49   梁灏   add Select Component
477
                      }
c9b86944   Sergio Crisostomo   Refactor Select!
478
479
                  };
              },
e355dd49   梁灏   add Select Component
480
  
db5110c2   Sergio Crisostomo   Allow wider searc...
481
              validateOption({children, elm, propsData}){
31788df3   Sergio Crisostomo   Normalise behavio...
482
                  if (this.queryStringMatchesSelectedOption) return true;
db5110c2   Sergio Crisostomo   Allow wider searc...
483
  
c9b86944   Sergio Crisostomo   Refactor Select!
484
485
                  const value = propsData.value;
                  const label = propsData.label || '';
db5110c2   Sergio Crisostomo   Allow wider searc...
486
487
488
489
                  const textContent = (elm && elm.textContent) || (children || []).reduce((str, node) => {
                      const nodeText = node.elm ? node.elm.textContent : node.text;
                      return `${str} ${nodeText}`;
                  }, '') || '';
c9b86944   Sergio Crisostomo   Refactor Select!
490
                  const stringValues = JSON.stringify([value, label, textContent]);
5266c905   Sergio Crisostomo   Trim label so we ...
491
                  const query = this.query.toLowerCase().trim();
c3304bce   Sergio Crisostomo   correct unchanged...
492
                  return stringValues.toLowerCase().includes(query);
e355dd49   梁灏   add Select Component
493
              },
d87ce40a   梁灏   update Select
494
  
c9b86944   Sergio Crisostomo   Refactor Select!
495
              toggleMenu (e, force) {
f8620d9a   Sergio Crisostomo   Fix autocomplete ...
496
                  if (this.disabled) {
c9b86944   Sergio Crisostomo   Refactor Select!
497
                      return false;
d87ce40a   梁灏   update Select
498
                  }
d87ce40a   梁灏   update Select
499
  
c9b86944   Sergio Crisostomo   Refactor Select!
500
501
502
                  this.visible = typeof force !== 'undefined' ? force : !this.visible;
                  if (this.visible){
                      this.dropDownWidth = this.$el.getBoundingClientRect().width;
cf753854   Sergio Crisostomo   Corrections after...
503
                      this.broadcast('Drop', 'on-update-popper');
e4ce9917   梁灏   update Select com...
504
                  }
e355dd49   梁灏   add Select Component
505
              },
c9b86944   Sergio Crisostomo   Refactor Select!
506
507
              hideMenu () {
                  this.toggleMenu(null, false);
31788df3   Sergio Crisostomo   Normalise behavio...
508
                  setTimeout(() => this.unchangedQuery = true, ANIMATION_TIMEOUT);
e355dd49   梁灏   add Select Component
509
              },
c9b86944   Sergio Crisostomo   Refactor Select!
510
511
              onClickOutside(event){
                  if (this.visible) {
4a9974f6   Graham Fairweather   Normalise v-ckick...
512
513
514
515
                      if (event.type === 'mousedown') {
                          event.preventDefault();
                          return;
                      }
c9b86944   Sergio Crisostomo   Refactor Select!
516
  
5c846d28   Sergio Crisostomo   Correct event pro...
517
518
519
520
521
522
523
524
                      if (this.transfer) {
                          const {$el} = this.$refs.dropdown;
                          if ($el === event.target || $el.contains(event.target)) {
                              return;
                          }
                      }
  
  
c9b86944   Sergio Crisostomo   Refactor Select!
525
                      if (this.filterable) {
ae7579e9   Sergio Crisostomo   Fix input getters...
526
                          const input = this.$el.querySelector('input[type="text"]');
c9b86944   Sergio Crisostomo   Refactor Select!
527
528
529
530
                          this.caretPosition = input.selectionStart;
                          this.$nextTick(() => {
                              const caretPosition = this.caretPosition === -1 ? input.value.length : this.caretPosition;
                              input.setSelectionRange(caretPosition, caretPosition);
e355dd49   梁灏   add Select Component
531
532
533
                          });
                      }
  
ae7579e9   Sergio Crisostomo   Fix input getters...
534
                      if (!this.autoComplete) event.stopPropagation();
c9b86944   Sergio Crisostomo   Refactor Select!
535
536
537
538
539
540
                      event.preventDefault();
                      this.hideMenu();
                      this.isFocused = true;
                  } else {
                      this.caretPosition = -1;
                      this.isFocused = false;
e355dd49   梁灏   add Select Component
541
542
                  }
              },
c9b86944   Sergio Crisostomo   Refactor Select!
543
              reset(){
743f6e06   Sergio Crisostomo   Be more hard on t...
544
545
                  this.query = '';
                  this.focusIndex = -1;
31788df3   Sergio Crisostomo   Normalise behavio...
546
                  this.unchangedQuery = true;
c9b86944   Sergio Crisostomo   Refactor Select!
547
                  this.values = [];
e355dd49   梁灏   add Select Component
548
549
              },
              handleKeydown (e) {
c9b86944   Sergio Crisostomo   Refactor Select!
550
551
552
553
                  if (e.key === 'Backspace'){
                      return; // so we don't call preventDefault
                  }
  
e355dd49   梁灏   add Select Component
554
                  if (this.visible) {
c9b86944   Sergio Crisostomo   Refactor Select!
555
556
557
558
559
                      e.preventDefault();
                      if (e.key === 'Tab'){
                          e.stopPropagation();
                      }
  
e355dd49   梁灏   add Select Component
560
                      // Esc slide-up
c9b86944   Sergio Crisostomo   Refactor Select!
561
                      if (e.key === 'Escape') {
16fc6361   Sergio Crisostomo   stop propagation ...
562
                          e.stopPropagation();
e355dd49   梁灏   add Select Component
563
564
565
                          this.hideMenu();
                      }
                      // next
c9b86944   Sergio Crisostomo   Refactor Select!
566
567
                      if (e.key === 'ArrowUp') {
                          this.navigateOptions(-1);
e355dd49   梁灏   add Select Component
568
569
                      }
                      // prev
c9b86944   Sergio Crisostomo   Refactor Select!
570
571
                      if (e.key === 'ArrowDown') {
                          this.navigateOptions(1);
e355dd49   梁灏   add Select Component
572
573
                      }
                      // enter
7e3fc4a5   Sergio Crisostomo   close the menu if...
574
575
                      if (e.key === 'Enter') {
                          if (this.focusIndex === -1) return this.hideMenu();
c9b86944   Sergio Crisostomo   Refactor Select!
576
577
578
                          const optionComponent = this.flatOptions[this.focusIndex];
                          const option = this.getOptionData(optionComponent.componentOptions.propsData.value);
                          this.onOptionClick(option);
e355dd49   梁灏   add Select Component
579
                      }
c9b86944   Sergio Crisostomo   Refactor Select!
580
581
582
                  } else {
                      const keysThatCanOpenSelect = ['ArrowUp', 'ArrowDown'];
                      if (keysThatCanOpenSelect.includes(e.key)) this.toggleMenu(null, true);
e355dd49   梁灏   add Select Component
583
584
                  }
  
e355dd49   梁灏   add Select Component
585
  
c9b86944   Sergio Crisostomo   Refactor Select!
586
587
588
              },
              navigateOptions(direction){
                  const optionsLength = this.flatOptions.length - 1;
e4ebd304   梁灏   update Select com...
589
  
c9b86944   Sergio Crisostomo   Refactor Select!
590
591
592
                  let index = this.focusIndex + direction;
                  if (index < 0) index = optionsLength;
                  if (index > optionsLength) index = 0;
e355dd49   梁灏   add Select Component
593
  
c9b86944   Sergio Crisostomo   Refactor Select!
594
595
596
597
598
599
600
                  // 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;
e355dd49   梁灏   add Select Component
601
                      }
c9b86944   Sergio Crisostomo   Refactor Select!
602
603
604
605
606
607
608
                      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;
e4ebd304   梁灏   update Select com...
609
                      }
c9b86944   Sergio Crisostomo   Refactor Select!
610
                      index = nearestActiveOption;
e355dd49   梁灏   add Select Component
611
                  }
e355dd49   梁灏   add Select Component
612
  
c9b86944   Sergio Crisostomo   Refactor Select!
613
                  this.focusIndex = index;
e4ebd304   梁灏   update Select com...
614
              },
c9b86944   Sergio Crisostomo   Refactor Select!
615
616
617
618
619
620
              onOptionClick(option) {
                  if (this.multiple){
  
                      // keep the query for remote select
                      if (this.remote) this.lastRemoteQuery = this.lastRemoteQuery || this.query;
                      else this.lastRemoteQuery = '';
e4ebd304   梁灏   update Select com...
621
  
c9b86944   Sergio Crisostomo   Refactor Select!
622
623
624
                      const valueIsSelected = this.values.find(({value}) => value === option.value);
                      if (valueIsSelected){
                          this.values = this.values.filter(({value}) => value !== option.value);
e4ebd304   梁灏   update Select com...
625
                      } else {
c9b86944   Sergio Crisostomo   Refactor Select!
626
                          this.values = this.values.concat(option);
e4ebd304   梁灏   update Select com...
627
                      }
c9b86944   Sergio Crisostomo   Refactor Select!
628
629
630
  
                      this.isFocused = true; // so we put back focus after clicking with mouse on option elements
                  } else {
5266c905   Sergio Crisostomo   Trim label so we ...
631
                      this.query = String(option.label).trim();
c9b86944   Sergio Crisostomo   Refactor Select!
632
633
634
635
636
                      this.values = [option];
                      this.lastRemoteQuery = '';
                      this.hideMenu();
                  }
  
52cfcd66   Sergio Crisostomo   Keep last selecte...
637
638
639
640
641
                  this.focusIndex = this.flatOptions.findIndex((opt) => {
                      if (!opt || !opt.componentOptions) return false;
                      return opt.componentOptions.propsData.value === option.value;
                  });
  
c9b86944   Sergio Crisostomo   Refactor Select!
642
                  if (this.filterable){
ae7579e9   Sergio Crisostomo   Fix input getters...
643
644
                      const inputField = this.$el.querySelector('input[type="text"]');
                      if (!this.autoComplete) this.$nextTick(() => inputField.focus());
e4ce9917   梁灏   update Select com...
645
                  }
88ef37f5   Aresn   fixed in multiple...
646
                  this.broadcast('Drop', 'on-update-popper');
3e855e34   梁灏   fixed #46
647
              },
c9b86944   Sergio Crisostomo   Refactor Select!
648
              onQueryChange(query) {
c3304bce   Sergio Crisostomo   correct unchanged...
649
                  if (query.length > 0 && query !== this.query) this.visible = true;
2f0b086d   梁灏   fixed #116
650
                  this.query = query;
c3304bce   Sergio Crisostomo   correct unchanged...
651
                  this.unchangedQuery = this.visible;
9c3a3e7d   YikaJ   更新 Select 组件
652
              },
c9b86944   Sergio Crisostomo   Refactor Select!
653
654
655
              toggleHeaderFocus({type}){
                  if (this.disabled) {
                      return;
15b72d31   梁灏   fixed #566
656
                  }
c9b86944   Sergio Crisostomo   Refactor Select!
657
                  this.isFocused = type === 'focus';
98bf25b3   梁灏   fixed #1286
658
              },
c9b86944   Sergio Crisostomo   Refactor Select!
659
660
              updateSlotOptions(){
                  this.slotOptions = this.$slots.default;
73b01ee0   郑敏   fixed #3722 that ...
661
662
663
664
665
              },
              checkUpdateStatus() {
                  if (this.getInitialValue().length > 0 && this.selectOptions.length === 0) {
                      this.hasExpectedValue = true;
                  }
47f03c54   梁灏   fix #4273
666
667
668
669
670
671
672
673
              },
              /**
               * 下面的方法,当 filterable 时,输入内容时,标记,用于区分和直接选择而引起的 bug
               * #4273
               * */
              handleFilterInputKeyDown () {
                  this.filterQueryKeyDown = true;
              },
e355dd49   梁灏   add Select Component
674
          },
e355dd49   梁灏   add Select Component
675
          watch: {
c9b86944   Sergio Crisostomo   Refactor Select!
676
              value(value){
cd8f1be8   任珽   fixed bug #4466 #...
677
                  const {getInitialValue, getOptionData, publicValue, values} = this;
c9b86944   Sergio Crisostomo   Refactor Select!
678
  
73b01ee0   郑敏   fixed #3722 that ...
679
                  this.checkUpdateStatus();
9ccd8196   郑敏   fixed #3722
680
  
c9b86944   Sergio Crisostomo   Refactor Select!
681
                  if (value === '') this.values = [];
cd8f1be8   任珽   fixed bug #4466 #...
682
                  else if (checkValuesNotEqual(value,publicValue,values)) {
220161f5   Sergio Crisostomo   Clean up empty/nu...
683
                      this.$nextTick(() => this.values = getInitialValue().map(getOptionData).filter(Boolean));
e355dd49   梁灏   add Select Component
684
                  }
c9b86944   Sergio Crisostomo   Refactor Select!
685
686
687
688
              },
              values(now, before){
                  const newValue = JSON.stringify(now);
                  const oldValue = JSON.stringify(before);
9366c9a7   Sergio Crisostomo   Select improvemen...
689
690
691
692
693
                  // v-model is always just the value, event with labelInValue === true
                  const vModelValue = (this.publicValue && this.labelInValue) ?
                      (this.multiple ? this.publicValue.map(({value}) => value) : this.publicValue.value) :
                      this.publicValue;
                  const shouldEmitInput = newValue !== oldValue && vModelValue !== this.value;
c9b86944   Sergio Crisostomo   Refactor Select!
694
                  if (shouldEmitInput) {
c9b86944   Sergio Crisostomo   Refactor Select!
695
696
697
                      this.$emit('input', vModelValue); // to update v-model
                      this.$emit('on-change', this.publicValue);
                      this.dispatch('FormItem', 'on-form-change', this.publicValue);
219e5c92   梁灏   fixed #957
698
                  }
e355dd49   梁灏   add Select Component
699
              },
c9b86944   Sergio Crisostomo   Refactor Select!
700
701
702
703
              query (query) {
                  this.$emit('on-query-change', query);
                  const {remoteMethod, lastRemoteQuery} = this;
                  const hasValidQuery = query !== '' && (query !== lastRemoteQuery || !lastRemoteQuery);
45bcc14d   Sergio Crisostomo   prevent calling r...
704
705
                  const shouldCallRemoteMethod = remoteMethod && hasValidQuery && !this.preventRemoteCall;
                  this.preventRemoteCall = false; // remove the flag
c9b86944   Sergio Crisostomo   Refactor Select!
706
707
708
709
710
711
712
713
714
  
                  if (shouldCallRemoteMethod){
                      this.focusIndex = -1;
                      const promise = this.remoteMethod(query);
                      this.initialLabel = '';
                      if (promise && promise.then){
                          promise.then(options => {
                              if (options) this.options = options;
                          });
b7cf983e   梁灏   update Select com...
715
                      }
e355dd49   梁灏   add Select Component
716
                  }
c9b86944   Sergio Crisostomo   Refactor Select!
717
                  if (query !== '' && this.remote) this.lastRemoteQuery = query;
e4ebd304   梁灏   update Select com...
718
              },
c9b86944   Sergio Crisostomo   Refactor Select!
719
720
721
722
723
724
              loading(state){
                  if (state === false){
                      this.updateSlotOptions();
                  }
              },
              isFocused(focused){
ae7579e9   Sergio Crisostomo   Fix input getters...
725
                  const el = this.filterable ? this.$el.querySelector('input[type="text"]') : this.$el;
c9b86944   Sergio Crisostomo   Refactor Select!
726
                  el[this.isFocused ? 'focus' : 'blur']();
d8bb1771   windywany   let select compon...
727
  
c9b86944   Sergio Crisostomo   Refactor Select!
728
729
730
                  // restore query value in filterable single selects
                  const [selectedOption] = this.values;
                  if (selectedOption && this.filterable && !this.multiple && !focused){
5266c905   Sergio Crisostomo   Trim label so we ...
731
                      const selectedLabel = String(selectedOption.label || selectedOption.value).trim();
9ca6671c   Sergio Crisostomo   Check for selecte...
732
                      if (selectedLabel && this.query !== selectedLabel) {
45bcc14d   Sergio Crisostomo   prevent calling r...
733
734
735
                          this.preventRemoteCall = true;
                          this.query = selectedLabel;
                      }
c9b86944   Sergio Crisostomo   Refactor Select!
736
737
738
                  }
              },
              focusIndex(index){
06a74f9e   Sergio Crisostomo   Allow select to n...
739
                  if (index < 0 || this.autoComplete) return;
c9b86944   Sergio Crisostomo   Refactor Select!
740
741
742
743
744
                  // update scroll
                  const optionValue = this.flatOptions[index].componentOptions.propsData.value;
                  const optionInstance = findChild(this, ({$options}) => {
                      return $options.componentName === 'select-item' && $options.propsData.value === optionValue;
                  });
e4ce9917   梁灏   update Select com...
745
  
c9b86944   Sergio Crisostomo   Refactor Select!
746
747
748
749
750
751
752
                  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;
01b54e30   梁灏   Select support re...
753
                  }
cf753854   Sergio Crisostomo   Corrections after...
754
755
756
              },
              dropVisible(open){
                  this.broadcast('Drop', open ? 'on-update-popper' : 'on-destroy-popper');
7f63e58c   Sergio Crisostomo   Make possible for...
757
              },
f7f65c84   Sergio Crisostomo   reset query only ...
758
              selectOptions(){
0fb9d645   郑敏   fix bug #3795
759
760
761
762
                  if (this.hasExpectedValue && this.selectOptions.length > 0){
                      if (this.values.length === 0) {
                          this.values = this.getInitialValue();
                      }
220161f5   Sergio Crisostomo   Clean up empty/nu...
763
                      this.values = this.values.map(this.getOptionData).filter(Boolean);
7f63e58c   Sergio Crisostomo   Make possible for...
764
765
                      this.hasExpectedValue = false;
                  }
b6c069ca   Sergio Crisostomo   reset query if op...
766
  
f7f65c84   Sergio Crisostomo   reset query only ...
767
                  if (this.slotOptions && this.slotOptions.length === 0){
b6c069ca   Sergio Crisostomo   reset query if op...
768
769
                      this.query = '';
                  }
1376a01a   Sergio Crisostomo   Emit on-open-chan...
770
771
772
              },
              visible(state){
                  this.$emit('on-open-change', state);
e355dd49   梁灏   add Select Component
773
774
              }
          }
b0893113   jingsam   :art: add eslint
775
      };
d6342fe1   jingsam   fixed ie bug
776
  </script>