-
Notifications
You must be signed in to change notification settings - Fork 0
/
autocomplete.js
3809 lines (3228 loc) · 120 KB
/
autocomplete.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/dist/";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 186);
/******/ })
/************************************************************************/
/******/ ({
/***/ 0:
/***/ (function(module, exports) {
/* globals __VUE_SSR_CONTEXT__ */
// IMPORTANT: Do NOT use ES2015 features in this file.
// This module is a runtime utility for cleaner component module output and will
// be included in the final webpack user bundle.
module.exports = function normalizeComponent (
rawScriptExports,
compiledTemplate,
functionalTemplate,
injectStyles,
scopeId,
moduleIdentifier /* server only */
) {
var esModule
var scriptExports = rawScriptExports = rawScriptExports || {}
// ES6 modules interop
var type = typeof rawScriptExports.default
if (type === 'object' || type === 'function') {
esModule = rawScriptExports
scriptExports = rawScriptExports.default
}
// Vue.extend constructor export interop
var options = typeof scriptExports === 'function'
? scriptExports.options
: scriptExports
// render functions
if (compiledTemplate) {
options.render = compiledTemplate.render
options.staticRenderFns = compiledTemplate.staticRenderFns
options._compiled = true
}
// functional template
if (functionalTemplate) {
options.functional = true
}
// scopedId
if (scopeId) {
options._scopeId = scopeId
}
var hook
if (moduleIdentifier) { // server build
hook = function (context) {
// 2.3 injection
context =
context || // cached call
(this.$vnode && this.$vnode.ssrContext) || // stateful
(this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext) // functional
// 2.2 with runInNewContext: true
if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {
context = __VUE_SSR_CONTEXT__
}
// inject component styles
if (injectStyles) {
injectStyles.call(this, context)
}
// register component module identifier for async chunk inferrence
if (context && context._registeredComponents) {
context._registeredComponents.add(moduleIdentifier)
}
}
// used by ssr in case component is cached and beforeCreate
// never gets called
options._ssrRegister = hook
} else if (injectStyles) {
hook = injectStyles
}
if (hook) {
var functional = options.functional
var existing = functional
? options.render
: options.beforeCreate
if (!functional) {
// inject component registration as beforeCreate hook
options.beforeCreate = existing
? [].concat(existing, hook)
: [hook]
} else {
// for template-only hot-reload because in that case the render fn doesn't
// go through the normalizer
options._injectStyles = hook
// register for functioal component in vue file
options.render = function renderWithStyleInjection (h, context) {
hook.call(context)
return existing(h, context)
}
}
}
return {
esModule: esModule,
exports: scriptExports,
options: options
}
}
/***/ }),
/***/ 1:
/***/ (function(module, exports) {
module.exports = require("vue");
/***/ }),
/***/ 10:
/***/ (function(module, exports) {
module.exports = require("elvant/lib/utils/popup");
/***/ }),
/***/ 102:
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _debounce = __webpack_require__(24);
var _debounce2 = _interopRequireDefault(_debounce);
var _input = __webpack_require__(12);
var _input2 = _interopRequireDefault(_input);
var _clickoutside = __webpack_require__(21);
var _clickoutside2 = _interopRequireDefault(_clickoutside);
var _autocompleteSuggestions = __webpack_require__(188);
var _autocompleteSuggestions2 = _interopRequireDefault(_autocompleteSuggestions);
var _emitter = __webpack_require__(2);
var _emitter2 = _interopRequireDefault(_emitter);
var _migrating = __webpack_require__(5);
var _migrating2 = _interopRequireDefault(_migrating);
var _util = __webpack_require__(4);
var _focus = __webpack_require__(41);
var _focus2 = _interopRequireDefault(_focus);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
exports.default = {
name: 'ElAutocomplete',
mixins: [_emitter2.default, (0, _focus2.default)('input'), _migrating2.default],
inheritAttrs: false,
componentName: 'ElAutocomplete',
components: {
ElInput: _input2.default,
ElAutocompleteSuggestions: _autocompleteSuggestions2.default
},
directives: { Clickoutside: _clickoutside2.default },
props: {
valueKey: {
type: String,
default: 'value'
},
popperClass: String,
popperOptions: Object,
placeholder: String,
disabled: Boolean,
name: String,
size: String,
value: String,
maxlength: Number,
minlength: Number,
autofocus: Boolean,
fetchSuggestions: Function,
triggerOnFocus: {
type: Boolean,
default: true
},
customItem: String,
selectWhenUnmatched: {
type: Boolean,
default: false
},
prefixIcon: String,
suffixIcon: String,
label: String,
debounce: {
type: Number,
default: 300
},
placement: {
type: String,
default: 'bottom-start'
},
hideLoading: Boolean,
popperAppendToBody: {
type: Boolean,
default: true
}
},
data: function data() {
return {
activated: false,
suggestions: [],
loading: false,
highlightedIndex: -1,
suggestionDisabled: false
};
},
computed: {
suggestionVisible: function suggestionVisible() {
var suggestions = this.suggestions;
var isValidData = Array.isArray(suggestions) && suggestions.length > 0;
return (isValidData || this.loading) && this.activated;
},
id: function id() {
return 'el-autocomplete-' + (0, _util.generateId)();
}
},
watch: {
suggestionVisible: function suggestionVisible(val) {
this.broadcast('ElAutocompleteSuggestions', 'visible', [val, this.$refs.input.$refs.input.offsetWidth]);
}
},
methods: {
getMigratingConfig: function getMigratingConfig() {
return {
props: {
'custom-item': 'custom-item is removed, use scoped slot instead.',
'props': 'props is removed, use value-key instead.'
}
};
},
getData: function getData(queryString) {
var _this = this;
if (this.suggestionDisabled) {
return;
}
this.loading = true;
this.fetchSuggestions(queryString, function (suggestions) {
_this.loading = false;
if (_this.suggestionDisabled) {
return;
}
if (Array.isArray(suggestions)) {
_this.suggestions = suggestions;
} else {
console.error('[Element Error][Autocomplete]autocomplete suggestions must be an array');
}
});
},
handleChange: function handleChange(value) {
this.$emit('input', value);
this.suggestionDisabled = false;
if (!this.triggerOnFocus && !value) {
this.suggestionDisabled = true;
this.suggestions = [];
return;
}
this.debouncedGetData(value);
},
handleFocus: function handleFocus(event) {
this.activated = true;
this.$emit('focus', event);
if (this.triggerOnFocus) {
this.debouncedGetData(this.value);
}
},
handleBlur: function handleBlur(event) {
this.$emit('blur', event);
},
close: function close(e) {
this.activated = false;
},
handleKeyEnter: function handleKeyEnter(e) {
var _this2 = this;
if (this.suggestionVisible && this.highlightedIndex >= 0 && this.highlightedIndex < this.suggestions.length) {
e.preventDefault();
this.select(this.suggestions[this.highlightedIndex]);
} else if (this.selectWhenUnmatched) {
this.$emit('select', { value: this.value });
this.$nextTick(function (_) {
_this2.suggestions = [];
_this2.highlightedIndex = -1;
});
}
},
select: function select(item) {
var _this3 = this;
this.$emit('input', item[this.valueKey]);
this.$emit('select', item);
this.$nextTick(function (_) {
_this3.suggestions = [];
_this3.highlightedIndex = -1;
});
},
highlight: function highlight(index) {
if (!this.suggestionVisible || this.loading) {
return;
}
if (index < 0) {
this.highlightedIndex = -1;
return;
}
if (index >= this.suggestions.length) {
index = this.suggestions.length - 1;
}
var suggestion = this.$refs.suggestions.$el.querySelector('.el-autocomplete-suggestion__wrap');
var suggestionList = suggestion.querySelectorAll('.el-autocomplete-suggestion__list li');
var highlightItem = suggestionList[index];
var scrollTop = suggestion.scrollTop;
var offsetTop = highlightItem.offsetTop;
if (offsetTop + highlightItem.scrollHeight > scrollTop + suggestion.clientHeight) {
suggestion.scrollTop += highlightItem.scrollHeight;
}
if (offsetTop < scrollTop) {
suggestion.scrollTop -= highlightItem.scrollHeight;
}
this.highlightedIndex = index;
this.$el.querySelector('.el-input__inner').setAttribute('aria-activedescendant', this.id + '-item-' + this.highlightedIndex);
}
},
mounted: function mounted() {
var _this4 = this;
this.debouncedGetData = (0, _debounce2.default)(this.debounce, this.getData);
this.$on('item-click', function (item) {
_this4.select(item);
});
var $input = this.$el.querySelector('.el-input__inner');
$input.setAttribute('role', 'textbox');
$input.setAttribute('aria-autocomplete', 'list');
$input.setAttribute('aria-controls', 'id');
$input.setAttribute('aria-activedescendant', this.id + '-item-' + this.highlightedIndex);
},
beforeDestroy: function beforeDestroy() {
this.$refs.suggestions.$destroy();
}
};
/***/ }),
/***/ 103:
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _vuePopper = __webpack_require__(9);
var _vuePopper2 = _interopRequireDefault(_vuePopper);
var _emitter = __webpack_require__(2);
var _emitter2 = _interopRequireDefault(_emitter);
var _scrollbar = __webpack_require__(33);
var _scrollbar2 = _interopRequireDefault(_scrollbar);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = {
components: { ElScrollbar: _scrollbar2.default },
mixins: [_vuePopper2.default, _emitter2.default],
componentName: 'ElAutocompleteSuggestions',
data: function data() {
return {
parent: this.$parent,
dropdownWidth: ''
};
},
props: {
options: {
default: function _default() {
return {
gpuAcceleration: false
};
}
},
id: String
},
methods: {
select: function select(item) {
this.dispatch('ElAutocomplete', 'item-click', item);
}
},
updated: function updated() {
var _this = this;
this.$nextTick(function (_) {
_this.popperJS && _this.updatePopper();
});
},
mounted: function mounted() {
this.$parent.popperElm = this.popperElm = this.$el;
this.referenceElm = this.$parent.$refs.input.$refs.input;
this.referenceList = this.$el.querySelector('.el-autocomplete-suggestion__list');
this.referenceList.setAttribute('role', 'listbox');
this.referenceList.setAttribute('id', this.id);
},
created: function created() {
var _this2 = this;
this.$on('visible', function (val, inputWidth) {
_this2.dropdownWidth = inputWidth + 'px';
_this2.showPopper = val;
});
}
}; //
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
/***/ }),
/***/ 11:
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/**
* @fileOverview Kickass library to create and place poppers near their reference elements.
* @version {{version}}
* @license
* Copyright (c) 2016 Federico Zivolo and contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
//
// Cross module loader
// Supported: Node, AMD, Browser globals
//
;(function (root, factory) {
if (true) {
// AMD. Register as an anonymous module.
!(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) :
__WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if (typeof module === 'object' && module.exports) {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory();
} else {
// Browser globals (root is window)
root.Popper = factory();
}
}(this, function () {
'use strict';
var root = window;
// default options
var DEFAULTS = {
// placement of the popper
placement: 'bottom',
gpuAcceleration: true,
// shift popper from its origin by the given amount of pixels (can be negative)
offset: 0,
// the element which will act as boundary of the popper
boundariesElement: 'viewport',
// amount of pixel used to define a minimum distance between the boundaries and the popper
boundariesPadding: 5,
// popper will try to prevent overflow following this order,
// by default, then, it could overflow on the left and on top of the boundariesElement
preventOverflowOrder: ['left', 'right', 'top', 'bottom'],
// the behavior used by flip to change the placement of the popper
flipBehavior: 'flip',
arrowElement: '[x-arrow]',
arrowOffset: 0,
// list of functions used to modify the offsets before they are applied to the popper
modifiers: [ 'shift', 'offset', 'preventOverflow', 'keepTogether', 'arrow', 'flip', 'applyStyle'],
modifiersIgnored: [],
forceAbsolute: false
};
/**
* Create a new Popper.js instance
* @constructor Popper
* @param {HTMLElement} reference - The reference element used to position the popper
* @param {HTMLElement|Object} popper
* The HTML element used as popper, or a configuration used to generate the popper.
* @param {String} [popper.tagName='div'] The tag name of the generated popper.
* @param {Array} [popper.classNames=['popper']] Array of classes to apply to the generated popper.
* @param {Array} [popper.attributes] Array of attributes to apply, specify `attr:value` to assign a value to it.
* @param {HTMLElement|String} [popper.parent=window.document.body] The parent element, given as HTMLElement or as query string.
* @param {String} [popper.content=''] The content of the popper, it can be text, html, or node; if it is not text, set `contentType` to `html` or `node`.
* @param {String} [popper.contentType='text'] If `html`, the `content` will be parsed as HTML. If `node`, it will be appended as-is.
* @param {String} [popper.arrowTagName='div'] Same as `popper.tagName` but for the arrow element.
* @param {Array} [popper.arrowClassNames='popper__arrow'] Same as `popper.classNames` but for the arrow element.
* @param {String} [popper.arrowAttributes=['x-arrow']] Same as `popper.attributes` but for the arrow element.
* @param {Object} options
* @param {String} [options.placement=bottom]
* Placement of the popper accepted values: `top(-start, -end), right(-start, -end), bottom(-start, -right),
* left(-start, -end)`
*
* @param {HTMLElement|String} [options.arrowElement='[x-arrow]']
* The DOM Node used as arrow for the popper, or a CSS selector used to get the DOM node. It must be child of
* its parent Popper. Popper.js will apply to the given element the style required to align the arrow with its
* reference element.
* By default, it will look for a child node of the popper with the `x-arrow` attribute.
*
* @param {Boolean} [options.gpuAcceleration=true]
* When this property is set to true, the popper position will be applied using CSS3 translate3d, allowing the
* browser to use the GPU to accelerate the rendering.
* If set to false, the popper will be placed using `top` and `left` properties, not using the GPU.
*
* @param {Number} [options.offset=0]
* Amount of pixels the popper will be shifted (can be negative).
*
* @param {String|Element} [options.boundariesElement='viewport']
* The element which will define the boundaries of the popper position, the popper will never be placed outside
* of the defined boundaries (except if `keepTogether` is enabled)
*
* @param {Number} [options.boundariesPadding=5]
* Additional padding for the boundaries
*
* @param {Array} [options.preventOverflowOrder=['left', 'right', 'top', 'bottom']]
* Order used when Popper.js tries to avoid overflows from the boundaries, they will be checked in order,
* this means that the last ones will never overflow
*
* @param {String|Array} [options.flipBehavior='flip']
* The behavior used by the `flip` modifier to change the placement of the popper when the latter is trying to
* overlap its reference element. Defining `flip` as value, the placement will be flipped on
* its axis (`right - left`, `top - bottom`).
* You can even pass an array of placements (eg: `['right', 'left', 'top']` ) to manually specify
* how alter the placement when a flip is needed. (eg. in the above example, it would first flip from right to left,
* then, if even in its new placement, the popper is overlapping its reference element, it will be moved to top)
*
* @param {Array} [options.modifiers=[ 'shift', 'offset', 'preventOverflow', 'keepTogether', 'arrow', 'flip', 'applyStyle']]
* List of functions used to modify the data before they are applied to the popper, add your custom functions
* to this array to edit the offsets and placement.
* The function should reflect the @params and @returns of preventOverflow
*
* @param {Array} [options.modifiersIgnored=[]]
* Put here any built-in modifier name you want to exclude from the modifiers list
* The function should reflect the @params and @returns of preventOverflow
*
* @param {Boolean} [options.removeOnDestroy=false]
* Set to true if you want to automatically remove the popper when you call the `destroy` method.
*/
function Popper(reference, popper, options) {
this._reference = reference.jquery ? reference[0] : reference;
this.state = {};
// if the popper variable is a configuration object, parse it to generate an HTMLElement
// generate a default popper if is not defined
var isNotDefined = typeof popper === 'undefined' || popper === null;
var isConfig = popper && Object.prototype.toString.call(popper) === '[object Object]';
if (isNotDefined || isConfig) {
this._popper = this.parse(isConfig ? popper : {});
}
// otherwise, use the given HTMLElement as popper
else {
this._popper = popper.jquery ? popper[0] : popper;
}
// with {} we create a new object with the options inside it
this._options = Object.assign({}, DEFAULTS, options);
// refactoring modifiers' list
this._options.modifiers = this._options.modifiers.map(function(modifier){
// remove ignored modifiers
if (this._options.modifiersIgnored.indexOf(modifier) !== -1) return;
// set the x-placement attribute before everything else because it could be used to add margins to the popper
// margins needs to be calculated to get the correct popper offsets
if (modifier === 'applyStyle') {
this._popper.setAttribute('x-placement', this._options.placement);
}
// return predefined modifier identified by string or keep the custom one
return this.modifiers[modifier] || modifier;
}.bind(this));
// make sure to apply the popper position before any computation
this.state.position = this._getPosition(this._popper, this._reference);
setStyle(this._popper, { position: this.state.position, top: 0 });
// fire the first update to position the popper in the right place
this.update();
// setup event listeners, they will take care of update the position in specific situations
this._setupEventListeners();
return this;
}
//
// Methods
//
/**
* Destroy the popper
* @method
* @memberof Popper
*/
Popper.prototype.destroy = function() {
this._popper.removeAttribute('x-placement');
this._popper.style.left = '';
this._popper.style.position = '';
this._popper.style.top = '';
this._popper.style[getSupportedPropertyName('transform')] = '';
this._removeEventListeners();
// remove the popper if user explicity asked for the deletion on destroy
if (this._options.removeOnDestroy) {
this._popper.remove();
}
return this;
};
/**
* Updates the position of the popper, computing the new offsets and applying the new style
* @method
* @memberof Popper
*/
Popper.prototype.update = function() {
var data = { instance: this, styles: {} };
// store placement inside the data object, modifiers will be able to edit `placement` if needed
// and refer to _originalPlacement to know the original value
data.placement = this._options.placement;
data._originalPlacement = this._options.placement;
// compute the popper and reference offsets and put them inside data.offsets
data.offsets = this._getOffsets(this._popper, this._reference, data.placement);
// get boundaries
data.boundaries = this._getBoundaries(data, this._options.boundariesPadding, this._options.boundariesElement);
data = this.runModifiers(data, this._options.modifiers);
if (typeof this.state.updateCallback === 'function') {
this.state.updateCallback(data);
}
};
/**
* If a function is passed, it will be executed after the initialization of popper with as first argument the Popper instance.
* @method
* @memberof Popper
* @param {Function} callback
*/
Popper.prototype.onCreate = function(callback) {
// the createCallbacks return as first argument the popper instance
callback(this);
return this;
};
/**
* If a function is passed, it will be executed after each update of popper with as first argument the set of coordinates and informations
* used to style popper and its arrow.
* NOTE: it doesn't get fired on the first call of the `Popper.update()` method inside the `Popper` constructor!
* @method
* @memberof Popper
* @param {Function} callback
*/
Popper.prototype.onUpdate = function(callback) {
this.state.updateCallback = callback;
return this;
};
/**
* Helper used to generate poppers from a configuration file
* @method
* @memberof Popper
* @param config {Object} configuration
* @returns {HTMLElement} popper
*/
Popper.prototype.parse = function(config) {
var defaultConfig = {
tagName: 'div',
classNames: [ 'popper' ],
attributes: [],
parent: root.document.body,
content: '',
contentType: 'text',
arrowTagName: 'div',
arrowClassNames: [ 'popper__arrow' ],
arrowAttributes: [ 'x-arrow']
};
config = Object.assign({}, defaultConfig, config);
var d = root.document;
var popper = d.createElement(config.tagName);
addClassNames(popper, config.classNames);
addAttributes(popper, config.attributes);
if (config.contentType === 'node') {
popper.appendChild(config.content.jquery ? config.content[0] : config.content);
}else if (config.contentType === 'html') {
popper.innerHTML = config.content;
} else {
popper.textContent = config.content;
}
if (config.arrowTagName) {
var arrow = d.createElement(config.arrowTagName);
addClassNames(arrow, config.arrowClassNames);
addAttributes(arrow, config.arrowAttributes);
popper.appendChild(arrow);
}
var parent = config.parent.jquery ? config.parent[0] : config.parent;
// if the given parent is a string, use it to match an element
// if more than one element is matched, the first one will be used as parent
// if no elements are matched, the script will throw an error
if (typeof parent === 'string') {
parent = d.querySelectorAll(config.parent);
if (parent.length > 1) {
console.warn('WARNING: the given `parent` query(' + config.parent + ') matched more than one element, the first one will be used');
}
if (parent.length === 0) {
throw 'ERROR: the given `parent` doesn\'t exists!';
}
parent = parent[0];
}
// if the given parent is a DOM nodes list or an array of nodes with more than one element,
// the first one will be used as parent
if (parent.length > 1 && parent instanceof Element === false) {
console.warn('WARNING: you have passed as parent a list of elements, the first one will be used');
parent = parent[0];
}
// append the generated popper to its parent
parent.appendChild(popper);
return popper;
/**
* Adds class names to the given element
* @function
* @ignore
* @param {HTMLElement} target
* @param {Array} classes
*/
function addClassNames(element, classNames) {
classNames.forEach(function(className) {
element.classList.add(className);
});
}
/**
* Adds attributes to the given element
* @function
* @ignore
* @param {HTMLElement} target
* @param {Array} attributes
* @example
* addAttributes(element, [ 'data-info:foobar' ]);
*/
function addAttributes(element, attributes) {
attributes.forEach(function(attribute) {
element.setAttribute(attribute.split(':')[0], attribute.split(':')[1] || '');
});
}
};
/**
* Helper used to get the position which will be applied to the popper
* @method
* @memberof Popper
* @param config {HTMLElement} popper element
* @param reference {HTMLElement} reference element
* @returns {String} position
*/
Popper.prototype._getPosition = function(popper, reference) {
var container = getOffsetParent(reference);
if (this._options.forceAbsolute) {
return 'absolute';
}
// Decide if the popper will be fixed
// If the reference element is inside a fixed context, the popper will be fixed as well to allow them to scroll together
var isParentFixed = isFixed(reference, container);
return isParentFixed ? 'fixed' : 'absolute';
};
/**
* Get offsets to the popper
* @method
* @memberof Popper
* @access private
* @param {Element} popper - the popper element
* @param {Element} reference - the reference element (the popper will be relative to this)
* @returns {Object} An object containing the offsets which will be applied to the popper
*/
Popper.prototype._getOffsets = function(popper, reference, placement) {
placement = placement.split('-')[0];
var popperOffsets = {};