Debian Codegraph @

inst/www/shared/selectize/js/selectize.js

raw symbols SCIP
1 /**
2 * Selectize (v0.15.2)
3 * https://selectize.dev
4 *
5 * Copyright (c) 2013-2015 Brian Reavis & contributors
6 * Copyright (c) 2020-2023 Selectize Team & contributors
7 *
8 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
9 * file except in compliance with the License. You may obtain a copy of the License at:
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software distributed under
13 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
14 * ANY KIND, either express or implied. See the License for the specific language
15 * governing permissions and limitations under the License.
16 *
17 * @author Brian Reavis <[email protected]>
18 * @author Ris Adams <[email protected]>
19 */
20 (function (root, factory) {
21 if (typeof define === 'function' && define.amd) {
22 define(['jquery'], factory);
23 } else if (typeof module === 'object' && typeof module.exports === 'object') {
24 module.exports = factory(require('jquery'));
25 } else {
26 root.Selectize = factory(root.jQuery);
27 }
28 }(this, function ($) {
29 'use strict';
30 var highlight = function ($element, pattern) {
31 if (typeof pattern === 'string' && !pattern.length) return;
32 var regex = (typeof pattern === 'string') ? new RegExp(pattern, 'i') : pattern;
33
34 var highlight = function (node) {
35 var skip = 0;
36 if (node.nodeType === 3) {
37 var pos = node.data.search(regex);
38 if (pos >= 0 && node.data.length > 0) {
39 var match = node.data.match(regex);
40 var spannode = document.createElement('span');
41 spannode.className = 'highlight';
42 var middlebit = node.splitText(pos);
43 var endbit = middlebit.splitText(match[0].length);
44 var middleclone = middlebit.cloneNode(true);
45 spannode.appendChild(middleclone);
46 middlebit.parentNode.replaceChild(spannode, middlebit);
47 skip = 1;
48 }
49 }
50 else if (node.nodeType === 1 && node.childNodes && !/(script|style)/i.test(node.tagName) && (node.className !== 'highlight' || node.tagName !== 'SPAN')) {
51 for (var i = 0; i < node.childNodes.length; ++i) {
52 i += highlight(node.childNodes[i]);
53 }
54 }
55 return skip;
56 };
57
58 return $element.each(function () {
59 highlight(this);
60 });
61 };
62
63 $.fn.removeHighlight = function () {
64 return this.find("span.highlight").each(function () {
65 this.parentNode.firstChild.nodeName;
66 var parent = this.parentNode;
67 parent.replaceChild(this.firstChild, this);
68 parent.normalize();
69 }).end();
70 };
71
72 var MicroEvent = function () { };
73 MicroEvent.prototype = {
74 on: function (event, fct) {
75 this._events = this._events || {};
76 this._events[event] = this._events[event] || [];
77 this._events[event].push(fct);
78 },
79 off: function (event, fct) {
80 var n = arguments.length;
81 if (n === 0) return delete this._events;
82 if (n === 1) return delete this._events[event];
83
84 this._events = this._events || {};
85 if (event in this._events === false) return;
86 this._events[event].splice(this._events[event].indexOf(fct), 1);
87 },
88 trigger: function (event ) {
89 const events = this._events = this._events || {};
90 if (event in events === false) return;
91 for (var i = 0; i < events[event].length; i++) {
92 events[event][i].apply(this, Array.prototype.slice.call(arguments, 1));
93 }
94 }
95 };
96
97 MicroEvent.mixin = function (destObject) {
98 var props = ['on', 'off', 'trigger'];
99 for (var i = 0; i < props.length; i++) {
100 destObject.prototype[props[i]] = MicroEvent.prototype[props[i]];
101 }
102 };
103
104 var MicroPlugin = {};
105 MicroPlugin.mixin = function (Interface) {
106
107 Interface.plugins = {};
108
109 Interface.prototype.initializePlugins = function (plugins) {
110 var i, n, key;
111 var self = this;
112 var queue = [];
113
114 self.plugins = {
115 names: [],
116 settings: {},
117 requested: {},
118 loaded: {}
119 };
120
121 if (isArray(plugins)) {
122 for (i = 0, n = plugins.length; i < n; i++) {
123 if (typeof plugins[i] === 'string') {
124 queue.push(plugins[i]);
125 } else {
126 self.plugins.settings[plugins[i].name] = plugins[i].options;
127 queue.push(plugins[i].name);
128 }
129 }
130 } else if (plugins) {
131 for (key in plugins) {
132 if (plugins.hasOwnProperty(key)) {
133 self.plugins.settings[key] = plugins[key];
134 queue.push(key);
135 }
136 }
137 }
138
139 while (queue.length) {
140 self.require(queue.shift());
141 }
142 };
143
144
145 Interface.prototype.loadPlugin = function (name) {
146 var self = this;
147 var plugins = self.plugins;
148 var plugin = Interface.plugins[name];
149
150 if (!Interface.plugins.hasOwnProperty(name)) {
151 throw new Error('Unable to find "' + name + '" plugin');
152 }
153
154 plugins.requested[name] = true;
155 plugins.loaded[name] = plugin.fn.apply(self, [self.plugins.settings[name] || {}]);
156 plugins.names.push(name);
157 };
158
159 Interface.prototype.require = function (name) {
160 var self = this;
161 var plugins = self.plugins;
162
163 if (!self.plugins.loaded.hasOwnProperty(name)) {
164 if (plugins.requested[name]) {
165 throw new Error('Plugin has circular dependency ("' + name + '")');
166 }
167 self.loadPlugin(name);
168 }
169
170 return plugins.loaded[name];
171 };
172
173 Interface.define = function (name, fn) {
174 Interface.plugins[name] = {
175 'name': name,
176 'fn': fn
177 };
178 };
179 };
180
181 const nanoid = (t = 21) => crypto.getRandomValues(new Uint8Array(t))
182 .reduce(((t, e) =>
183 t += (e &= 63) < 36 ? e.toString(36) :
184 e < 62 ? (e - 26).toString(36).toUpperCase()
185 : e > 62 ? "-" : "_"), "");
186
187
188 var Sifter = function (items, settings) {
189 this.items = items;
190 this.settings = settings || { diacritics: true };
191 };
192
193 Sifter.prototype.tokenize = function (query, respect_word_boundaries) {
194 query = trim(String(query || '').toLowerCase());
195 if (!query || !query.length) return [];
196
197 var i, n, regex, letter;
198 var tokens = [];
199 var words = query.split(/ +/);
200
201 for (i = 0, n = words.length; i < n; i++) {
202 regex = escape_regex(words[i]);
203 if (this.settings.diacritics) {
204 for (letter in DIACRITICS) {
205 if (DIACRITICS.hasOwnProperty(letter)) {
206 regex = regex.replace(new RegExp(letter, 'g'), DIACRITICS[letter]);
207 }
208 }
209 }
210 if (respect_word_boundaries) regex = "\\b" + regex
211 tokens.push({
212 string: words[i],
213 regex: new RegExp(regex, 'i')
214 });
215 }
216
217 return tokens;
218 };
219
220 Sifter.prototype.iterator = function (object, callback) {
221 var iterator;
222 if (is_array(object)) {
223 iterator = Array.prototype.forEach || function (callback) {
224 for (var i = 0, n = this.length; i < n; i++) {
225 callback(this[i], i, this);
226 }
227 };
228 } else {
229 iterator = function (callback) {
230 for (var key in this) {
231 if (this.hasOwnProperty(key)) {
232 callback(this[key], key, this);
233 }
234 }
235 };
236 }
237
238 iterator.apply(object, [callback]);
239 };
240
241 Sifter.prototype.getScoreFunction = function (search, options) {
242 var self, fields, tokens, token_count, nesting;
243
244 self = this;
245 search = self.prepareSearch(search, options);
246 tokens = search.tokens;
247 fields = search.options.fields;
248 token_count = tokens.length;
249 nesting = search.options.nesting;
250
251 var scoreValue = function (value, token) {
252 var score, pos;
253
254 if (!value) return 0;
255 value = String(value || '');
256 pos = value.search(token.regex);
257 if (pos === -1) return 0;
258 score = token.string.length / value.length;
259 if (pos === 0) score += 0.5;
260 return score;
261 };
262
263 var scoreObject = (function () {
264 var field_count = fields.length;
265 if (!field_count) {
266 return function () { return 0; };
267 }
268 if (field_count === 1) {
269 return function (token, data) {
270 return scoreValue(getattr(data, fields[0], nesting), token);
271 };
272 }
273 return function (token, data) {
274 for (var i = 0, sum = 0; i < field_count; i++) {
275 sum += scoreValue(getattr(data, fields[i], nesting), token);
276 }
277 return sum / field_count;
278 };
279 })();
280
281 if (!token_count) {
282 return function () { return 0; };
283 }
284 if (token_count === 1) {
285 return function (data) {
286 return scoreObject(tokens[0], data);
287 };
288 }
289
290 if (search.options.conjunction === 'and') {
291 return function (data) {
292 var score;
293 for (var i = 0, sum = 0; i < token_count; i++) {
294 score = scoreObject(tokens[i], data);
295 if (score <= 0) return 0;
296 sum += score;
297 }
298 return sum / token_count;
299 };
300 } else {
301 return function (data) {
302 for (var i = 0, sum = 0; i < token_count; i++) {
303 sum += scoreObject(tokens[i], data);
304 }
305 return sum / token_count;
306 };
307 }
308 };
309
310 Sifter.prototype.getSortFunction = function (search, options) {
311 var i, n, self, field, fields, fields_count, multiplier, multipliers, get_field, implicit_score, sort;
312
313 self = this;
314 search = self.prepareSearch(search, options);
315 sort = (!search.query && options.sort_empty) || options.sort;
316
317 get_field = function (name, result) {
318 if (name === '$score') return result.score;
319 return getattr(self.items[result.id], name, options.nesting);
320 };
321
322 fields = [];
323 if (sort) {
324 for (i = 0, n = sort.length; i < n; i++) {
325 if (search.query || sort[i].field !== '$score') {
326 fields.push(sort[i]);
327 }
328 }
329 }
330
331 if (search.query) {
332 implicit_score = true;
333 for (i = 0, n = fields.length; i < n; i++) {
334 if (fields[i].field === '$score') {
335 implicit_score = false;
336 break;
337 }
338 }
339 if (implicit_score) {
340 fields.unshift({ field: '$score', direction: 'desc' });
341 }
342 } else {
343 for (i = 0, n = fields.length; i < n; i++) {
344 if (fields[i].field === '$score') {
345 fields.splice(i, 1);
346 break;
347 }
348 }
349 }
350
351 multipliers = [];
352 for (i = 0, n = fields.length; i < n; i++) {
353 multipliers.push(fields[i].direction === 'desc' ? -1 : 1);
354 }
355
356 fields_count = fields.length;
357 if (!fields_count) {
358 return null;
359 } else if (fields_count === 1) {
360 field = fields[0].field;
361 multiplier = multipliers[0];
362 return function (a, b) {
363 return multiplier * cmp(
364 get_field(field, a),
365 get_field(field, b)
366 );
367 };
368 } else {
369 return function (a, b) {
370 var i, result, a_value, b_value, field;
371 for (i = 0; i < fields_count; i++) {
372 field = fields[i].field;
373 result = multipliers[i] * cmp(
374 get_field(field, a),
375 get_field(field, b)
376 );
377 if (result) return result;
378 }
379 return 0;
380 };
381 }
382 };
383
384 Sifter.prototype.prepareSearch = function (query, options) {
385 if (typeof query === 'object') return query;
386
387 options = extend({}, options);
388
389 var option_fields = options.fields;
390 var option_sort = options.sort;
391 var option_sort_empty = options.sort_empty;
392
393 if (option_fields && !is_array(option_fields)) options.fields = [option_fields];
394 if (option_sort && !is_array(option_sort)) options.sort = [option_sort];
395 if (option_sort_empty && !is_array(option_sort_empty)) options.sort_empty = [option_sort_empty];
396
397 return {
398 options: options,
399 query: String(query || '').toLowerCase(),
400 tokens: this.tokenize(query, options.respect_word_boundaries),
401 total: 0,
402 items: []
403 };
404 };
405
406 Sifter.prototype.search = function (query, options) {
407 var self = this, value, score, search, calculateScore;
408 var fn_sort;
409 var fn_score;
410
411 search = this.prepareSearch(query, options);
412 options = search.options;
413 query = search.query;
414
415 fn_score = options.score || self.getScoreFunction(search);
416
417 if (query.length) {
418 self.iterator(self.items, function (item, id) {
419 score = fn_score(item);
420 if (options.filter === false || score > 0) {
421 search.items.push({ 'score': score, 'id': id });
422 }
423 });
424 } else {
425 self.iterator(self.items, function (item, id) {
426 search.items.push({ 'score': 1, 'id': id });
427 });
428 }
429
430 fn_sort = self.getSortFunction(search, options);
431 if (fn_sort) search.items.sort(fn_sort);
432
433 search.total = search.items.length;
434 if (typeof options.limit === 'number') {
435 search.items = search.items.slice(0, options.limit);
436 }
437
438 return search;
439 };
440
441 var cmp = function (a, b) {
442 if (typeof a === 'number' && typeof b === 'number') {
443 return a > b ? 1 : (a < b ? -1 : 0);
444 }
445 a = asciifold(String(a || ''));
446 b = asciifold(String(b || ''));
447 if (a > b) return 1;
448 if (b > a) return -1;
449 return 0;
450 };
451
452 var extend = function (a, b) {
453 var i, n, k, object;
454 for (i = 1, n = arguments.length; i < n; i++) {
455 object = arguments[i];
456 if (!object) continue;
457 for (k in object) {
458 if (object.hasOwnProperty(k)) {
459 a[k] = object[k];
460 }
461 }
462 }
463 return a;
464 };
465
466 var getattr = function (obj, name, nesting) {
467 if (!obj || !name) return;
468 if (!nesting) return obj[name];
469 var names = name.split(".");
470 while (names.length && (obj = obj[names.shift()]));
471 return obj;
472 };
473
474 var trim = function (str) {
475 return (str + '').replace(/^\s+|\s+$|/g, '');
476 };
477
478 var escape_regex = function (str) {
479 return (str + '').replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
480 };
481
482 var is_array = Array.isArray || function (object) {
483 return Object.prototype.toString.call(object) === '[object Array]';
484 };
485
486 var DIACRITICS = {
487 'a': '[aḀḁĂăÂâǍǎȺⱥȦȧẠạÄäÀàÁáĀāÃãÅåąĄÃąĄ]',
488 'b': '[b␢βΒB฿𐌁ᛒ]',
489 'c': '[cĆćĈĉČčĊċC̄c̄ÇçḈḉȻȼƇƈɕᴄCc]',
490 'd': '[dĎďḊḋḐḑḌḍḒḓḎḏĐđD̦d̦ƉɖƊɗƋƌᵭᶁᶑȡᴅDdð]',
491 'e': '[eÉéÈèÊêḘḙĚěĔĕẼẽḚḛẺẻĖėËëĒēȨȩĘęᶒɆɇȄȅẾếỀềỄễỂểḜḝḖḗḔḕȆȇẸẹỆệⱸᴇEeɘǝƏƐε]',
492 'f': '[fƑƒḞḟ]',
493 'g': '[gɢ₲ǤǥĜĝĞğĢģƓɠĠġ]',
494 'h': '[hĤĥĦħḨḩẖẖḤḥḢḣɦʰǶƕ]',
495 'i': '[iÍíÌìĬĭÎîǏǐÏïḮḯĨĩĮįĪīỈỉȈȉȊȋỊịḬḭƗɨɨ̆ᵻᶖİiIıɪIi]',
496 'j': '[jȷĴĵɈɉʝɟʲ]',
497 'k': '[kƘƙꝀꝁḰḱǨǩḲḳḴḵκϰ₭]',
498 'l': '[lŁłĽľĻļĹĺḶḷḸḹḼḽḺḻĿŀȽƚⱠⱡⱢɫɬᶅɭȴʟLl]',
499 'n': '[nŃńǸǹŇňÑñṄṅŅņṆṇṊṋṈṉN̈n̈ƝɲȠƞᵰᶇɳȵɴNnŊŋ]',
500 'o': '[oØøÖöÓóÒòÔôǑǒŐőŎŏȮȯỌọƟɵƠơỎỏŌōÕõǪǫȌȍՕօ]',
501 'p': '[pṔṕṖṗⱣᵽƤƥᵱ]',
502 'q': '[qꝖꝗʠɊɋꝘꝙq̃]',
503 'r': '[rŔŕɌɍŘřŖŗṘṙȐȑȒȓṚṛⱤɽ]',
504 's': '[sŚśṠṡṢṣꞨꞩŜŝŠšŞşȘșS̈s̈]',
505 't': '[tŤťṪṫŢţṬṭƮʈȚțṰṱṮṯƬƭ]',
506 'u': '[uŬŭɄʉỤụÜüÚúÙùÛûǓǔŰűŬŭƯưỦủŪūŨũŲųȔȕ∪]',
507 'v': '[vṼṽṾṿƲʋꝞꝟⱱʋ]',
508 'w': '[wẂẃẀẁŴŵẄẅẆẇẈẉ]',
509 'x': '[xẌẍẊẋχ]',
510 'y': '[yÝýỲỳŶŷŸÿỸỹẎẏỴỵɎɏƳƴ]',
511 'z': '[zŹźẐẑŽžŻżẒẓẔẕƵƶ]'
512 };
513
514 var asciifold = (function () {
515 var i, n, k, chunk;
516 var i18nChars = '';
517 var lookup = {};
518 for (k in DIACRITICS) {
519 if (DIACRITICS.hasOwnProperty(k)) {
520 chunk = DIACRITICS[k].substring(2, DIACRITICS[k].length - 1);
521 i18nChars += chunk;
522 for (i = 0, n = chunk.length; i < n; i++) {
523 lookup[chunk.charAt(i)] = k;
524 }
525 }
526 }
527 var regexp = new RegExp('[' + i18nChars + ']', 'g');
528 return function (str) {
529 return str.replace(regexp, function (i18nChar) {
530 return lookup[i18nChar];
531 }).toLowerCase();
532 };
533 })();
534
535 var IS_MAC = uaDetect("macOS", /Mac/);
536 var KEY_A = 65;
537 var KEY_COMMA = 188;
538 var KEY_RETURN = 13;
539 var KEY_ESC = 27;
540 var KEY_LEFT = 37;
541 var KEY_UP = 38;
542 var KEY_P = 80;
543 var KEY_RIGHT = 39;
544 var KEY_DOWN = 40;
545 var KEY_N = 78;
546 var KEY_BACKSPACE = 8;
547 var KEY_DELETE = 46;
548 var KEY_SHIFT = 16;
549 var KEY_CMD = IS_MAC ? 91 : 17;
550 var KEY_CTRL = IS_MAC ? 18 : 17;
551 var KEY_TAB = 9;
552 var TAG_SELECT = 1;
553 var TAG_INPUT = 2;
554
555 var SUPPORTS_VALIDITY_API = !uaDetect("Android", /android/i) && !!document.createElement('input').validity;
556
557 var isset = function (object) {
558 return typeof object !== 'undefined';
559 };
560
561 var isArray = Array.isArray || function (vArg) {
562 return Object.prototype.toString.call(vArg) === '[object Array]';
563 }
564
565 var hash_key = function (value) {
566 if (typeof value === 'undefined' || value === null) return null;
567 if (typeof value === 'boolean') return value ? '1' : '0';
568 return value + '';
569 };
570
571 var escape_html = function (str) {
572 return (str + '')
573 .replace(/&/g, '&amp;')
574 .replace(/</g, '&lt;')
575 .replace(/>/g, '&gt;')
576 .replace(/"/g, '&quot;');
577 };
578
579 var escape_replace = function (str) {
580 return (str + '').replace(/\$/g, '$$$$');
581 };
582
583 var hook = {};
584
585 hook.before = function (self, method, fn) {
586 var original = self[method];
587 self[method] = function () {
588 fn.apply(self, arguments);
589 return original.apply(self, arguments);
590 };
591 };
592
593 hook.after = function (self, method, fn) {
594 var original = self[method];
595 self[method] = function () {
596 var result = original.apply(self, arguments);
597 fn.apply(self, arguments);
598 return result;
599 };
600 };
601
602 var once = function (fn) {
603 var called = false;
604 return function () {
605 if (called) return;
606 called = true;
607 fn.apply(this, arguments);
608 };
609 };
610
611 var debounce = function (fn, delay) {
612 var timeout;
613 return function () {
614 var self = this;
615 var args = arguments;
616 window.clearTimeout(timeout);
617 timeout = window.setTimeout(function () {
618 fn.apply(self, args);
619 }, delay);
620 };
621 };
622
623 var debounce_events = function (self, types, fn) {
624 var type;
625 var trigger = self.trigger;
626 var event_args = {};
627
628 self.trigger = function () {
629 var type = arguments[0];
630 if (types.indexOf(type) !== -1) {
631 event_args[type] = arguments;
632 } else {
633 return trigger.apply(self, arguments);
634 }
635 };
636
637 fn.apply(self, []);
638 self.trigger = trigger;
639
640 for (type in event_args) {
641 if (event_args.hasOwnProperty(type)) {
642 trigger.apply(self, event_args[type]);
643 }
644 }
645 };
646
647 var watchChildEvent = function ($parent, event, selector, fn) {
648 $parent.on(event, selector, function (e) {
649 var child = e.target;
650 while (child && child.parentNode !== $parent[0]) {
651 child = child.parentNode;
652 }
653 e.currentTarget = child;
654 return fn.apply(this, [e]);
655 });
656 };
657
658 var getInputSelection = function (input) {
659 var result = {};
660 if (input === undefined) {
661 console.warn('WARN getInputSelection cannot locate input control');
662 return result;
663 }
664 if ('selectionStart' in input) {
665 result.start = input.selectionStart;
666 result.length = input.selectionEnd - result.start;
667 } else if (document.selection) {
668 input.focus();
669 var sel = document.selection.createRange();
670 var selLen = document.selection.createRange().text.length;
671 sel.moveStart('character', -input.value.length);
672 result.start = sel.text.length - selLen;
673 result.length = selLen;
674 }
675 return result;
676 };
677
678 var transferStyles = function ($from, $to, properties) {
679 var i, n, styles = {};
680 if (properties) {
681 for (i = 0, n = properties.length; i < n; i++) {
682 styles[properties[i]] = $from.css(properties[i]);
683 }
684 } else {
685 styles = $from.css();
686 }
687 $to.css(styles);
688 };
689
690 var measureString = function (str, $parent) {
691 if (!str) {
692 return 0;
693 }
694
695 if (!Selectize.$testInput) {
696 Selectize.$testInput = $('<span />').css({
697 position: 'absolute',
698 width: 'auto',
699 padding: 0,
700 whiteSpace: 'pre'
701 });
702
703 $('<div />').css({
704 position: 'absolute',
705 width: 0,
706 height: 0,
707 overflow: 'hidden'
708 }).attr({
709 'aria-hidden': true
710 }).append(Selectize.$testInput).appendTo('body');
711 }
712
713 Selectize.$testInput.text(str);
714
715 transferStyles($parent, Selectize.$testInput, [
716 'letterSpacing',
717 'fontSize',
718 'fontFamily',
719 'fontWeight',
720 'textTransform'
721 ]);
722
723 return Selectize.$testInput.width();
724 };
725
726 var autoGrow = function ($input) {
727 var currentWidth = null;
728
729 var update = function (e, options) {
730 var value, keyCode, printable, width;
731 var placeholder, placeholderWidth;
732 var shift, character, selection;
733 e = e || window.event || {};
734 options = options || {};
735
736 if (e.metaKey || e.altKey) return;
737 if (!options.force && $input.data('grow') === false) return;
738
739 value = $input.val();
740 if (e.type && e.type.toLowerCase() === 'keydown') {
741 keyCode = e.keyCode;
742 printable = (
743 (keyCode >= 48 && keyCode <= 57) ||
744 (keyCode >= 65 && keyCode <= 90) ||
745 (keyCode >= 96 && keyCode <= 111) ||
746 (keyCode >= 186 && keyCode <= 222) ||
747 keyCode === 32
748 );
749
750 if (keyCode === KEY_DELETE || keyCode === KEY_BACKSPACE) {
751 selection = getInputSelection($input[0]);
752 if (selection.length) {
753 value = value.substring(0, selection.start) + value.substring(selection.start + selection.length);
754 } else if (keyCode === KEY_BACKSPACE && selection.start) {
755 value = value.substring(0, selection.start - 1) + value.substring(selection.start + 1);
756 } else if (keyCode === KEY_DELETE && typeof selection.start !== 'undefined') {
757 value = value.substring(0, selection.start) + value.substring(selection.start + 1);
758 }
759 } else if (printable) {
760 shift = e.shiftKey;
761 character = String.fromCharCode(e.keyCode);
762 if (shift) character = character.toUpperCase();
763 else character = character.toLowerCase();
764 value += character;
765 }
766 }
767
768 var width = $input.attr('readonly') ? 0 : 4;
769 placeholder = $input.attr('placeholder');
770 if (placeholder) {
771 placeholderWidth = measureString(placeholder, $input) + width;
772 } else {
773 placeholderWidth = 0;
774 }
775
776 width = Math.max(measureString(value, $input), placeholderWidth) + width;
777 if (width !== currentWidth) {
778 currentWidth = width;
779 $input.width(width);
780 $input.triggerHandler('resize');
781 }
782 };
783
784 $input.on('keydown keyup update blur', update);
785 update();
786 };
787
788 var domToString = function (d) {
789 var tmp = document.createElement('div');
790
791 tmp.appendChild(d.cloneNode(true));
792
793 return tmp.innerHTML;
794 };
795
796 var logError = function (message, options) {
797 if (!options) options = {};
798 var component = "Selectize";
799
800 console.error(component + ": " + message)
801
802 if (options.explanation) {
803 if (console.group) console.group();
804 console.error(options.explanation);
805 if (console.group) console.groupEnd();
806 }
807 };
808
809 var isJSON = function (data) {
810 try {
811 JSON.parse(data);
812 } catch (e) {
813 return false;
814 }
815 return true;
816 };
817
818 function uaDetect(platform, re) {
819 if (navigator.userAgentData) {
820 return platform === navigator.userAgentData.platform;
821 }
822
823 return re.test(navigator.userAgent);
824 }
825
826 var Selectize = function($input, settings) {
827 var key, i, n, dir, input, self = this;
828 input = $input[0];
829 input.selectize = self;
830
831 var computedStyle = window.getComputedStyle && window.getComputedStyle(input, null);
832 dir = computedStyle ? computedStyle.getPropertyValue('direction') : input.currentStyle && input.currentStyle.direction;
833 dir = dir || $input.parents('[dir]:first').attr('dir') || '';
834
835 self.settings = {};
836
837 // increase the count of 'active' (i.e., non-destroyed) selectize instances
838 ++Selectize.count;
839
840 $.extend(self, {
841 order : 0,
842 settings : settings,
843 $input : $input,
844 tabIndex : $input.attr('tabindex') || '',
845 tagType : input.tagName.toLowerCase() === 'select' ? TAG_SELECT : TAG_INPUT,
846 rtl : /rtl/i.test(dir),
847 // generate a unique ID for the event namespace
848 eventNS : '.selectize-' + (new Date().getTime()) + '-' + (Math.random().toString(36).substr(2, 5)),
849 highlightedValue : null,
850 isBlurring : false,
851 isOpen : false,
852 isDisabled : false,
853 isRequired : $input.is('[required]'),
854 isInvalid : false,
855 isLocked : false,
856 isFocused : false,
857 isInputHidden : false,
858 isSetup : false,
859 isShiftDown : false,
860 isCmdDown : false,
861 isCtrlDown : false,
862 ignoreFocus : false,
863 ignoreBlur : false,
864 ignoreHover : false,
865 hasOptions : false,
866 currentResults : null,
867 lastValue : '',
868 lastValidValue : '',
869 lastOpenTarget : false,
870 caretPos : 0,
871 loading : 0,
872 loadedSearches : {},
873 isDropdownClosing: false,
874
875 $activeOption : null,
876 $activeItems : [],
877
878 optgroups : {},
879 options : {},
880 userOptions : {},
881 items : [],
882 renderCache : {},
883 onSearchChange : settings.loadThrottle === null ? self.onSearchChange : debounce(self.onSearchChange, settings.loadThrottle)
884 });
885
886 self.sifter = new Sifter(this.options, {diacritics: settings.diacritics});
887
888 if (self.settings.options) {
889 for (i = 0, n = self.settings.options.length; i < n; i++) {
890 self.registerOption(self.settings.options[i]);
891 }
892 delete self.settings.options;
893 }
894
895 if (self.settings.optgroups) {
896 for (i = 0, n = self.settings.optgroups.length; i < n; i++) {
897 self.registerOptionGroup(self.settings.optgroups[i]);
898 }
899 delete self.settings.optgroups;
900 }
901
902 self.settings.mode = self.settings.mode || (self.settings.maxItems === 1 ? 'single' : 'multi');
903 if (typeof self.settings.hideSelected !== 'boolean') {
904 self.settings.hideSelected = self.settings.mode === 'multi';
905 }
906
907 self.initializePlugins(self.settings.plugins);
908 self.setupCallbacks();
909 self.setupTemplates();
910 self.setup();
911 };
912
913 MicroEvent.mixin(Selectize);
914 MicroPlugin.mixin(Selectize);
915
916 $.extend(Selectize.prototype, {
917
918 setup: function() {
919 var self = this;
920 var settings = self.settings;
921 var eventNS = self.eventNS;
922 var $window = $(window);
923 var $document = $(document);
924 var $input = self.$input;
925
926 var $wrapper;
927 var $control;
928 var $control_input;
929 var $dropdown;
930 var $dropdown_content;
931 var $dropdown_parent;
932 var inputMode;
933 var timeout_blur;
934 var timeout_focus;
935 var classes;
936 var classes_plugins;
937 var inputId;
938 var noArrowClass;
939
940 inputMode = self.settings.mode;
941 classes = $input.attr('class') || '';
942 noArrowClass = settings.showArrow ? '' : ' no-arrow';
943
944 $wrapper = $('<div>').addClass(settings.wrapperClass).addClass(classes + ' selectize-control').addClass(inputMode);
945 $control = $('<div>').addClass(settings.inputClass + noArrowClass + ' selectize-input items').appendTo($wrapper);
946 $control_input = $('<input type="text" autocomplete="new-password" autofill="no" />').appendTo($control).attr('tabindex', $input.is(':disabled') ? '-1' : self.tabIndex);
947 $dropdown_parent = $(settings.dropdownParent || $wrapper);
948 $dropdown = $('<div>').addClass(settings.dropdownClass).addClass(inputMode + ' selectize-dropdown').hide().appendTo($dropdown_parent);
949 $dropdown_content = $('<div>').addClass(settings.dropdownContentClass + ' selectize-dropdown-content').attr('tabindex', '-1').appendTo($dropdown);
950
951 if(inputId = $input.attr('id')) {
952 $control_input.attr('id', inputId + '-selectized');
953 $("label[for='"+inputId+"']").attr('for', inputId + '-selectized');
954 }
955
956 if(self.settings.copyClassesToDropdown) {
957 $dropdown.addClass(classes);
958 }
959
960 $wrapper.css({
961 width: $input[0].style.width
962 });
963
964 if (self.plugins.names.length) {
965 classes_plugins = 'plugin-' + self.plugins.names.join(' plugin-');
966 $wrapper.addClass(classes_plugins);
967 $dropdown.addClass(classes_plugins);
968 }
969
970 if ((settings.maxItems === null || settings.maxItems > 1) && self.tagType === TAG_SELECT) {
971 $input.attr('multiple', 'multiple');
972 }
973
974 if (self.settings.placeholder) {
975 $control_input.attr('placeholder', settings.placeholder);
976 }
977
978 if (!self.settings.search) {
979 $control_input.attr('readonly', true);
980 $control_input.attr('inputmode', 'none');
981 $control.css('cursor', 'pointer');
982 }
983
984 if (!self.settings.splitOn && self.settings.delimiter) {
985 var delimiterEscaped = self.settings.delimiter.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
986 self.settings.splitOn = new RegExp('\\s*' + delimiterEscaped + '+\\s*');
987 }
988
989 if ($input.attr('autocorrect')) {
990 $control_input.attr('autocorrect', $input.attr('autocorrect'));
991 }
992
993 if ($input.attr('autocapitalize')) {
994 $control_input.attr('autocapitalize', $input.attr('autocapitalize'));
995 }
996 if ($input.is('input')) {
997 $control_input[0].type = $input[0].type;
998 }
999
1000 self.$wrapper = $wrapper;
1001 self.$control = $control;
1002 self.$control_input = $control_input;
1003 self.$dropdown = $dropdown;
1004 self.$dropdown_content = $dropdown_content;
1005
1006 $dropdown.on('mouseenter mousedown mouseup click', '[data-disabled]>[data-selectable]', function(e) { e.stopImmediatePropagation(); });
1007 $dropdown.on('mouseenter', '[data-selectable]', function() { return self.onOptionHover.apply(self, arguments); });
1008 $dropdown.on('mouseup click', '[data-selectable]', function() { return self.onOptionSelect.apply(self, arguments); });
1009 watchChildEvent($control, 'mouseup', '*:not(input)', function() { return self.onItemSelect.apply(self, arguments); });
1010 autoGrow($control_input);
1011
1012 $control.on({
1013 mousedown : function() { return self.onMouseDown.apply(self, arguments); },
1014 click : function() { return self.onClick.apply(self, arguments); }
1015 });
1016
1017 $control_input.on({
1018 mousedown : function(e) {
1019 if (self.$control_input.val() !== '' || self.settings.openOnFocus) {
1020 e.stopPropagation();
1021 }
1022 },
1023 keydown : function() { return self.onKeyDown.apply(self, arguments); },
1024 keypress : function() { return self.onKeyPress.apply(self, arguments); },
1025 input : function() { return self.onInput.apply(self, arguments); },
1026 resize : function() { self.positionDropdown.apply(self, []); },
1027 blur : function() { return self.onBlur.apply(self, arguments); },
1028 focus : function() { return self.onFocus.apply(self, arguments); },
1029 paste : function() { return self.onPaste.apply(self, arguments); }
1030 });
1031
1032 $document.on('keydown' + eventNS, function(e) {
1033 self.isCmdDown = e[IS_MAC ? 'metaKey' : 'ctrlKey'];
1034 self.isCtrlDown = e[IS_MAC ? 'altKey' : 'ctrlKey'];
1035 self.isShiftDown = e.shiftKey;
1036 });
1037
1038 $document.on('keyup' + eventNS, function(e) {
1039 if (e.keyCode === KEY_CTRL) self.isCtrlDown = false;
1040 if (e.keyCode === KEY_SHIFT) self.isShiftDown = false;
1041 if (e.keyCode === KEY_CMD) self.isCmdDown = false;
1042 });
1043
1044 $document.on('mousedown' + eventNS, function(e) {
1045 if (self.isFocused) {
1046 if (
1047 e.target === self.$dropdown[0] ||
1048 self.$dropdown.has(e.target).length)
1049 {
1050 return false;
1051 }
1052 if (e.target !== self.$control[0]) {
1053 self.blur(e.target);
1054 }
1055 }
1056 });
1057
1058 $window.on(['scroll' + eventNS, 'resize' + eventNS].join(' '), function() {
1059 if (self.isOpen) {
1060 self.positionDropdown.apply(self, arguments);
1061 }
1062 });
1063 $window.on('mousemove' + eventNS, function() {
1064 self.ignoreHover = self.settings.ignoreHover;
1065 });
1066
1067 this.revertSettings = {
1068 $children : $input.children().detach(),
1069 tabindex : $input.attr('tabindex')
1070 };
1071
1072 $input.attr('tabindex', -1).hide().after(self.$wrapper);
1073
1074 if (Array.isArray(settings.items)) {
1075 self.lastValidValue = settings.items;
1076 self.setValue(settings.items);
1077 delete settings.items;
1078 }
1079
1080 if (SUPPORTS_VALIDITY_API) {
1081 $input.on('invalid' + eventNS, function(e) {
1082 e.preventDefault();
1083 self.isInvalid = true;
1084 self.refreshState();
1085 });
1086 }
1087
1088 self.updateOriginalInput();
1089 self.refreshItems();
1090 self.refreshState();
1091 self.updatePlaceholder();
1092 self.isSetup = true;
1093
1094 if ($input.is(':disabled')) {
1095 self.disable();
1096 }
1097
1098 self.on('change', this.onChange);
1099
1100 $input.data('selectize', self);
1101 $input.addClass('selectized');
1102 self.trigger('initialize');
1103
1104 if (settings.preload === true) {
1105 self.onSearchChange('');
1106 }
1107
1108 },
1109
1110 setupTemplates: function() {
1111 var self = this;
1112 var field_label = self.settings.labelField;
1113 var field_value = self.settings.valueField;
1114 var field_optgroup = self.settings.optgroupLabelField;
1115
1116 var templates = {
1117 'optgroup': function(data) {
1118 return '<div class="optgroup">' + data.html + '</div>';
1119 },
1120 'optgroup_header': function(data, escape) {
1121 return '<div class="optgroup-header">' + escape(data[field_optgroup]) + '</div>';
1122 },
1123 'option': function(data, escape) {
1124 var classes = data.classes ? ' ' + data.classes : '';
1125 classes += data[field_value] === '' ? ' selectize-dropdown-emptyoptionlabel' : '';
1126
1127 var styles = data.styles ? ' style="' + data.styles + '"': '';
1128 return '<div' + styles + ' class="option' + classes + '">' + escape(data[field_label]) + '</div>';
1129 },
1130 'item': function(data, escape) {
1131 return '<div class="item">' + escape(data[field_label]) + '</div>';
1132 },
1133 'option_create': function(data, escape) {
1134 return '<div class="create">Add <strong>' + escape(data.input) + '</strong>&#x2026;</div>';
1135 }
1136 };
1137
1138 self.settings.render = $.extend({}, templates, self.settings.render);
1139 },
1140
1141 setupCallbacks: function() {
1142 var key, fn, callbacks = {
1143 'initialize' : 'onInitialize',
1144 'change' : 'onChange',
1145 'item_add' : 'onItemAdd',
1146 'item_remove' : 'onItemRemove',
1147 'clear' : 'onClear',
1148 'option_add' : 'onOptionAdd',
1149 'option_remove' : 'onOptionRemove',
1150 'option_clear' : 'onOptionClear',
1151 'optgroup_add' : 'onOptionGroupAdd',
1152 'optgroup_remove' : 'onOptionGroupRemove',
1153 'optgroup_clear' : 'onOptionGroupClear',
1154 'dropdown_open' : 'onDropdownOpen',
1155 'dropdown_close' : 'onDropdownClose',
1156 'type' : 'onType',
1157 'load' : 'onLoad',
1158 'focus' : 'onFocus',
1159 'blur' : 'onBlur',
1160 'dropdown_item_activate' : 'onDropdownItemActivate',
1161 'dropdown_item_deactivate' : 'onDropdownItemDeactivate'
1162 };
1163
1164 for (key in callbacks) {
1165 if (callbacks.hasOwnProperty(key)) {
1166 fn = this.settings[callbacks[key]];
1167 if (fn) this.on(key, fn);
1168 }
1169 }
1170 },
1171
1172 onClick: function(e) {
1173 var self = this;
1174
1175 if (self.isDropdownClosing) {
1176 return;
1177 }
1178
1179 if (!self.isFocused || !self.isOpen) {
1180 self.focus();
1181 e.preventDefault();
1182 }
1183 },
1184
1185 onMouseDown: function(e) {
1186 var self = this;
1187 var defaultPrevented = e.isDefaultPrevented();
1188 var $target = $(e.target);
1189
1190 if (!self.isFocused) {
1191 if (!defaultPrevented) {
1192 window.setTimeout(function () {
1193 if (!self.isOpen) {
1194 self.focus();
1195 }
1196 }, 0);
1197 }
1198 }
1199 if ($target !== self.$control_input[0] || self.$control_input.val() === '') {
1200 if (self.settings.mode === 'single') {
1201 self.isOpen ? self.close() : self.open();
1202 } else {
1203 if (!defaultPrevented) {
1204 self.setActiveItem(null);
1205 }
1206 if (!self.settings.openOnFocus) {
1207 if (self.isOpen && $target === self.lastOpenTarget) {
1208 self.close();
1209 self.lastOpenTarget = false;
1210 } else if (!self.isOpen) {
1211 self.refreshOptions();
1212 self.open();
1213 self.lastOpenTarget = $target;
1214 } else {
1215 self.lastOpenTarget = $target;
1216 }
1217 }
1218 }
1219 return false;
1220 }
1221 },
1222
1223 onChange: function() {
1224 var self = this;
1225 if (self.getValue() !== "") {
1226 self.lastValidValue = self.getValue();
1227 }
1228 this.$input.trigger('input');
1229 this.$input.trigger('change');
1230 },
1231
1232 onPaste: function(e) {
1233 var self = this;
1234
1235 if (self.isFull() || self.isInputHidden || self.isLocked) {
1236 e.preventDefault();
1237 return;
1238 }
1239
1240 if (self.settings.splitOn) {
1241
1242 setTimeout(function() {
1243 var pastedText = self.$control_input.val();
1244 if(!pastedText.match(self.settings.splitOn)){ return }
1245
1246 var splitInput = pastedText
1247 .trim()
1248 .split(self.settings.splitOn);
1249 for (var i = 0, n = splitInput.length; i < n; i++) {
1250 self.createItem(splitInput[i]);
1251 }
1252 }, 0);
1253 }
1254 },
1255
1256 onKeyPress: function(e) {
1257 if (this.isLocked) return e && e.preventDefault();
1258 var character = String.fromCharCode(e.keyCode || e.which);
1259 if (this.settings.create && this.settings.mode === 'multi' && character === this.settings.delimiter) {
1260 this.createItem();
1261 e.preventDefault();
1262 return false;
1263 }
1264 },
1265
1266 onKeyDown: function(e) {
1267 var isInput = e.target === this.$control_input[0];
1268 var self = this;
1269
1270 if (self.isLocked) {
1271 if (e.keyCode !== KEY_TAB) {
1272 e.preventDefault();
1273 }
1274 return;
1275 }
1276
1277 switch (e.keyCode) {
1278 case KEY_A:
1279 if (self.isCmdDown) {
1280 self.selectAll();
1281 return;
1282 }
1283 break;
1284 case KEY_ESC:
1285 if (self.isOpen) {
1286 e.preventDefault();
1287 e.stopPropagation();
1288 self.close();
1289 }
1290 return;
1291 case KEY_N:
1292 if (!e.ctrlKey || e.altKey) break;
1293 case KEY_DOWN:
1294 if (!self.isOpen && self.hasOptions) {
1295 self.open();
1296 } else if (self.$activeOption) {
1297 self.ignoreHover = true;
1298 var $next = self.getAdjacentOption(self.$activeOption, 1);
1299 if ($next.length) self.setActiveOption($next, true, true);
1300 }
1301 e.preventDefault();
1302 return;
1303 case KEY_P:
1304 if (!e.ctrlKey || e.altKey) break;
1305 case KEY_UP:
1306 if (self.$activeOption) {
1307 self.ignoreHover = true;
1308 var $prev = self.getAdjacentOption(self.$activeOption, -1);
1309 if ($prev.length) self.setActiveOption($prev, true, true);
1310 }
1311 e.preventDefault();
1312 return;
1313 case KEY_RETURN:
1314 if (self.isOpen && self.$activeOption) {
1315 self.onOptionSelect({currentTarget: self.$activeOption});
1316 e.preventDefault();
1317 }
1318 return;
1319 case KEY_LEFT:
1320 self.advanceSelection(-1, e);
1321 return;
1322 case KEY_RIGHT:
1323 self.advanceSelection(1, e);
1324 return;
1325 case KEY_TAB:
1326 if (self.settings.selectOnTab && self.isOpen && self.$activeOption) {
1327 self.onOptionSelect({currentTarget: self.$activeOption});
1328
1329 if (!self.isFull()) {
1330 e.preventDefault();
1331 }
1332 }
1333 if (self.settings.create && self.createItem() && self.settings.showAddOptionOnCreate) {
1334 e.preventDefault();
1335 }
1336 return;
1337 case KEY_BACKSPACE:
1338 case KEY_DELETE:
1339 self.deleteSelection(e);
1340 return;
1341 }
1342
1343 if ((self.isFull() || self.isInputHidden) && !(IS_MAC ? e.metaKey : e.ctrlKey)) {
1344 e.preventDefault();
1345 return;
1346 }
1347 },
1348
1349 onInput: function(e) {
1350 var self = this;
1351
1352 var value = self.$control_input.val() || '';
1353 if (self.lastValue !== value) {
1354 self.lastValue = value;
1355 self.onSearchChange(value);
1356 self.refreshOptions();
1357 self.trigger('type', value);
1358 }
1359 },
1360
1361 onSearchChange: function(value) {
1362 var self = this;
1363 var fn = self.settings.load;
1364 if (!fn) return;
1365 if (self.loadedSearches.hasOwnProperty(value)) return;
1366 self.loadedSearches[value] = true;
1367 self.load(function(callback) {
1368 fn.apply(self, [value, callback]);
1369 });
1370 },
1371
1372 onFocus: function(e) {
1373 var self = this;
1374 var wasFocused = self.isFocused;
1375
1376 if (self.isDisabled) {
1377 self.blur();
1378 e && e.preventDefault();
1379 return false;
1380 }
1381
1382 if (self.ignoreFocus) return;
1383 self.isFocused = true;
1384 if (self.settings.preload === 'focus') self.onSearchChange('');
1385
1386 if (!wasFocused) self.trigger('focus');
1387
1388 if (!self.$activeItems.length) {
1389 self.showInput();
1390 self.setActiveItem(null);
1391 self.refreshOptions(!!self.settings.openOnFocus);
1392 }
1393
1394 self.refreshState();
1395 },
1396
1397 onBlur: function(e, dest) {
1398 var self = this;
1399
1400 if (!self.isFocused) return;
1401 self.isFocused = false;
1402
1403 if (self.ignoreFocus) {
1404 return;
1405 }
1406
1407 var deactivate = function() {
1408 self.close();
1409 self.setTextboxValue('');
1410 self.setActiveItem(null);
1411 self.setActiveOption(null);
1412 self.setCaret(self.items.length);
1413 self.refreshState();
1414
1415 dest && dest.focus && dest.focus();
1416
1417 self.isBlurring = false;
1418 self.ignoreFocus = false;
1419 self.trigger('blur');
1420 };
1421
1422 self.isBlurring = true;
1423 self.ignoreFocus = true;
1424 if (self.settings.create && self.settings.createOnBlur) {
1425 self.createItem(null, false, deactivate);
1426 } else {
1427 deactivate();
1428 }
1429 },
1430
1431 onOptionHover: function(e) {
1432 if (this.ignoreHover) return;
1433 this.setActiveOption(e.currentTarget, false);
1434 },
1435
1436 onOptionSelect: function(e) {
1437 var value, $target, $option, self = this;
1438
1439 if (e.preventDefault) {
1440 e.preventDefault();
1441 e.stopPropagation();
1442 }
1443
1444 $target = $(e.currentTarget);
1445 if ($target.hasClass('create')) {
1446 self.createItem(null, function() {
1447 if (self.settings.closeAfterSelect) {
1448 self.close();
1449 }
1450 });
1451 } else {
1452 value = $target.attr('data-value');
1453 if (typeof value !== 'undefined') {
1454 self.lastQuery = null;
1455 self.setTextboxValue('');
1456 self.addItem(value);
1457 if (self.settings.closeAfterSelect) {
1458 self.close();
1459 } else if (!self.settings.hideSelected && e.type && /mouse/.test(e.type)) {
1460 self.setActiveOption(self.getOption(value));
1461 }
1462 }
1463 }
1464 },
1465
1466 onItemSelect: function(e) {
1467 var self = this;
1468
1469 if (self.isLocked) return;
1470 if (self.settings.mode === 'multi') {
1471 e.preventDefault();
1472 self.setActiveItem(e.currentTarget, e);
1473 }
1474 },
1475
1476 load: function(fn) {
1477 var self = this;
1478 var $wrapper = self.$wrapper.addClass(self.settings.loadingClass);
1479
1480 self.loading++;
1481 fn.apply(self, [function(results) {
1482 self.loading = Math.max(self.loading - 1, 0);
1483 if (results && results.length) {
1484 self.addOption(results);
1485 self.refreshOptions(self.isFocused && !self.isInputHidden);
1486 }
1487 if (!self.loading) {
1488 $wrapper.removeClass(self.settings.loadingClass);
1489 }
1490 self.trigger('load', results);
1491 }]);
1492 },
1493
1494 getTextboxValue: function() {
1495 var $input = this.$control_input;
1496 return $input.val();
1497 },
1498
1499 setTextboxValue: function(value) {
1500 var $input = this.$control_input;
1501 var changed = $input.val() !== value;
1502 if (changed) {
1503 $input.val(value).triggerHandler('update');
1504 this.lastValue = value;
1505 }
1506 },
1507
1508 getValue: function() {
1509 if (this.tagType === TAG_SELECT && this.$input.attr('multiple')) {
1510 return this.items;
1511 } else {
1512 return this.items.join(this.settings.delimiter);
1513 }
1514 },
1515
1516 setValue: function(value, silent) {
1517 const items = Array.isArray(value) ? value : [value];
1518 if (items.join('') === this.items.join('')) {
1519 return;
1520 }
1521
1522 var events = silent ? [] : ['change'];
1523
1524 debounce_events(this, events, function() {
1525 this.clear(silent);
1526 this.addItems(value, silent);
1527 });
1528 },
1529
1530 setMaxItems: function(value){
1531 if(value === 0) value = null;
1532 this.settings.maxItems = value;
1533 this.settings.mode = this.settings.mode || (this.settings.maxItems === 1 ? 'single' : 'multi');
1534 this.refreshState();
1535 },
1536
1537 setActiveItem: function($item, e) {
1538 var self = this;
1539 var eventName;
1540 var i, idx, begin, end, item, swap;
1541 var $last;
1542
1543 if (self.settings.mode === 'single') return;
1544 $item = $($item);
1545
1546 if (!$item.length) {
1547 $(self.$activeItems).removeClass('active');
1548 self.$activeItems = [];
1549 if (self.isFocused) {
1550 self.showInput();
1551 }
1552 return;
1553 }
1554
1555 eventName = e && e.type.toLowerCase();
1556
1557 if (eventName === 'mousedown' && self.isShiftDown && self.$activeItems.length) {
1558 $last = self.$control.children('.active:last');
1559 begin = Array.prototype.indexOf.apply(self.$control[0].childNodes, [$last[0]]);
1560 end = Array.prototype.indexOf.apply(self.$control[0].childNodes, [$item[0]]);
1561 if (begin > end) {
1562 swap = begin;
1563 begin = end;
1564 end = swap;
1565 }
1566 for (i = begin; i <= end; i++) {
1567 item = self.$control[0].childNodes[i];
1568 if (self.$activeItems.indexOf(item) === -1) {
1569 $(item).addClass('active');
1570 self.$activeItems.push(item);
1571 }
1572 }
1573 e.preventDefault();
1574 } else if ((eventName === 'mousedown' && self.isCtrlDown) || (eventName === 'keydown' && this.isShiftDown)) {
1575 if ($item.hasClass('active')) {
1576 idx = self.$activeItems.indexOf($item[0]);
1577 self.$activeItems.splice(idx, 1);
1578 $item.removeClass('active');
1579 } else {
1580 self.$activeItems.push($item.addClass('active')[0]);
1581 }
1582 } else {
1583 $(self.$activeItems).removeClass('active');
1584 self.$activeItems = [$item.addClass('active')[0]];
1585 }
1586
1587 self.hideInput();
1588 if (!this.isFocused) {
1589 self.focus();
1590 }
1591 },
1592
1593 setActiveOption: function($option, scroll, animate) {
1594 var height_menu, height_item, y;
1595 var scroll_top, scroll_bottom;
1596 var self = this;
1597
1598 if (self.$activeOption) {
1599 self.$activeOption.removeClass('active');
1600 self.trigger('dropdown_item_deactivate', self.$activeOption.attr('data-value'));
1601 }
1602 self.$activeOption = null;
1603
1604 $option = $($option);
1605 if (!$option.length) return;
1606
1607 self.$activeOption = $option.addClass('active');
1608 if (self.isOpen) self.trigger('dropdown_item_activate', self.$activeOption.attr('data-value'));
1609
1610 if (scroll || !isset(scroll)) {
1611
1612 height_menu = self.$dropdown_content.height();
1613 height_item = self.$activeOption.outerHeight(true);
1614 scroll = self.$dropdown_content.scrollTop() || 0;
1615 y = self.$activeOption.offset().top - self.$dropdown_content.offset().top + scroll;
1616 scroll_top = y;
1617 scroll_bottom = y - height_menu + height_item;
1618
1619 if (y + height_item > height_menu + scroll) {
1620 self.$dropdown_content.stop().animate({scrollTop: scroll_bottom}, animate ? self.settings.scrollDuration : 0);
1621 } else if (y < scroll) {
1622 self.$dropdown_content.stop().animate({scrollTop: scroll_top}, animate ? self.settings.scrollDuration : 0);
1623 }
1624
1625 }
1626 },
1627
1628 selectAll: function() {
1629 var self = this;
1630 if (self.settings.mode === 'single') return;
1631
1632 self.$activeItems = Array.prototype.slice.apply(self.$control.children(':not(input)').addClass('active'));
1633 if (self.$activeItems.length) {
1634 self.hideInput();
1635 self.close();
1636 }
1637 self.focus();
1638 },
1639
1640 hideInput: function() {
1641 var self = this;
1642
1643 self.setTextboxValue('');
1644 self.$control_input.css({opacity: 0, position: 'absolute', left: self.rtl ? 10000 : 0});
1645 self.isInputHidden = true;
1646 },
1647
1648 showInput: function() {
1649 this.$control_input.css({opacity: 1, position: 'relative', left: 0});
1650 this.isInputHidden = false;
1651 },
1652
1653 focus: function() {
1654 var self = this;
1655 if (self.isDisabled) return self;
1656
1657 self.ignoreFocus = true;
1658 self.$control_input[0].focus();
1659 window.setTimeout(function() {
1660 self.ignoreFocus = false;
1661 self.onFocus();
1662 }, 0);
1663 return self;
1664 },
1665
1666 blur: function(dest) {
1667 this.$control_input[0].blur();
1668 this.onBlur(null, dest);
1669 return this;
1670 },
1671
1672 getScoreFunction: function(query) {
1673 return this.sifter.getScoreFunction(query, this.getSearchOptions());
1674 },
1675
1676 getSearchOptions: function() {
1677 var settings = this.settings;
1678 var sort = settings.sortField;
1679 if (typeof sort === 'string') {
1680 sort = [{field: sort}];
1681 }
1682
1683 return {
1684 fields : settings.searchField,
1685 conjunction : settings.searchConjunction,
1686 sort : sort,
1687 nesting : settings.nesting,
1688 filter : settings.filter,
1689 respect_word_boundaries : settings.respect_word_boundaries
1690 };
1691 },
1692
1693 search: function(query) {
1694 var i, value, score, result, calculateScore;
1695 var self = this;
1696 var settings = self.settings;
1697 var options = this.getSearchOptions();
1698
1699 if (settings.score) {
1700 calculateScore = self.settings.score.apply(this, [query]);
1701 if (typeof calculateScore !== 'function') {
1702 throw new Error('Selectize "score" setting must be a function that returns a function');
1703 }
1704 }
1705
1706 if (query !== self.lastQuery) {
1707 if (settings.normalize) query = query.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
1708 self.lastQuery = query;
1709 result = self.sifter.search(query, $.extend(options, {score: calculateScore}));
1710 self.currentResults = result;
1711 } else {
1712 result = $.extend(true, {}, self.currentResults);
1713 }
1714
1715 if (settings.hideSelected) {
1716 for (i = result.items.length - 1; i >= 0; i--) {
1717 if (self.items.indexOf(hash_key(result.items[i].id)) !== -1) {
1718 result.items.splice(i, 1);
1719 }
1720 }
1721 }
1722
1723 return result;
1724 },
1725
1726 refreshOptions: function(triggerDropdown) {
1727 var i, j, k, n, groups, groups_order, option, option_html, optgroup, optgroups, html, html_children, has_create_option;
1728 var $active, $active_before, $create;
1729
1730 if (typeof triggerDropdown === 'undefined') {
1731 triggerDropdown = true;
1732 }
1733
1734 var self = this;
1735 var query = (self.$control_input.val()).trim();
1736 var results = self.search(query);
1737 var $dropdown_content = self.$dropdown_content;
1738 var active_before = self.$activeOption && hash_key(self.$activeOption.attr('data-value'));
1739
1740 n = results.items.length;
1741 if (typeof self.settings.maxOptions === 'number') {
1742 n = Math.min(n, self.settings.maxOptions);
1743 }
1744
1745 groups = {};
1746 groups_order = [];
1747
1748 for (i = 0; i < n; i++) {
1749 option = self.options[results.items[i].id];
1750 option_html = self.render('option', option);
1751 optgroup = option[self.settings.optgroupField] || '';
1752 optgroups = Array.isArray(optgroup) ? optgroup : [optgroup];
1753
1754 for (j = 0, k = optgroups && optgroups.length; j < k; j++) {
1755 optgroup = optgroups[j];
1756 if (!self.optgroups.hasOwnProperty(optgroup) && typeof self.settings.optionGroupRegister === 'function') {
1757 var regGroup;
1758 if (regGroup = self.settings.optionGroupRegister.apply(self, [optgroup])) {
1759 self.registerOptionGroup(regGroup);
1760 }
1761 }
1762 if (!self.optgroups.hasOwnProperty(optgroup)) {
1763 optgroup = '';
1764 }
1765 if (!groups.hasOwnProperty(optgroup)) {
1766 groups[optgroup] = document.createDocumentFragment();
1767 groups_order.push(optgroup);
1768 }
1769 groups[optgroup].appendChild(option_html);
1770 }
1771 }
1772
1773 if (this.settings.lockOptgroupOrder) {
1774 groups_order.sort(function(a, b) {
1775 var a_order = self.optgroups[a] && self.optgroups[a].$order || 0;
1776 var b_order = self.optgroups[b] && self.optgroups[b].$order || 0;
1777 return a_order - b_order;
1778 });
1779 }
1780
1781 html = document.createDocumentFragment();
1782 for (i = 0, n = groups_order.length; i < n; i++) {
1783 optgroup = groups_order[i];
1784 if (self.optgroups.hasOwnProperty(optgroup) && groups[optgroup].childNodes.length) {
1785 html_children = document.createDocumentFragment();
1786 html_children.appendChild(self.render('optgroup_header', self.optgroups[optgroup]));
1787 html_children.appendChild(groups[optgroup]);
1788
1789 html.appendChild(self.render('optgroup', $.extend({}, self.optgroups[optgroup], {
1790 html: domToString(html_children),
1791 dom: html_children
1792 })));
1793 } else {
1794 html.appendChild(groups[optgroup]);
1795 }
1796 }
1797
1798 $dropdown_content.html(html);
1799
1800 if (self.settings.highlight) {
1801 $dropdown_content.removeHighlight();
1802 if (results.query.length && results.tokens.length) {
1803 for (i = 0, n = results.tokens.length; i < n; i++) {
1804 highlight($dropdown_content, results.tokens[i].regex);
1805 }
1806 }
1807 }
1808
1809 if (!self.settings.hideSelected) {
1810 self.$dropdown.find('.selected').removeClass('selected');
1811
1812 for (i = 0, n = self.items.length; i < n; i++) {
1813 self.getOption(self.items[i]).addClass('selected');
1814 }
1815 }
1816
1817 if (self.settings.dropdownSize.sizeType !== 'auto' && self.isOpen) {
1818 self.setupDropdownHeight();
1819 }
1820
1821 self.positionDropdown();
1822
1823 has_create_option = self.canCreate(query);
1824 if (has_create_option) {
1825 if(self.settings.showAddOptionOnCreate) {
1826 $dropdown_content.prepend(self.render('option_create', {input: query}));
1827 $create = $($dropdown_content[0].childNodes[0]);
1828 }
1829 }
1830
1831 self.hasOptions = results.items.length > 0 || ( has_create_option && self.settings.showAddOptionOnCreate ) || self.settings.setFirstOptionActive;
1832
1833 if (self.hasOptions) {
1834 if (results.items.length > 0) {
1835 $active_before = active_before && self.getOption(active_before);
1836 if (results.query !== "" && self.settings.setFirstOptionActive) {
1837 $active = $dropdown_content.find('[data-selectable]:first')
1838 } else if (results.query !== "" && $active_before && $active_before.length) {
1839 $active = $active_before;
1840 } else if (self.settings.mode === 'single' && self.items.length) {
1841 $active = self.getOption(self.items[0]);
1842 }
1843 if (!$active || !$active.length) {
1844 if ($create && !self.settings.addPrecedence) {
1845 $active = self.getAdjacentOption($create, 1);
1846 } else {
1847 $active = $dropdown_content.find('[data-selectable]:first');
1848 }
1849 }
1850 } else {
1851 $active = $create;
1852 }
1853 self.setActiveOption($active);
1854 if (triggerDropdown && !self.isOpen) { self.open(); }
1855 } else {
1856 self.setActiveOption(null);
1857 if (triggerDropdown && self.isOpen) { self.close(); }
1858 }
1859 },
1860
1861 addOption: function(data) {
1862 var i, n, value, self = this;
1863
1864 if (Array.isArray(data)) {
1865 for (i = 0, n = data.length; i < n; i++) {
1866 self.addOption(data[i]);
1867 }
1868 return;
1869 }
1870
1871 if (value = self.registerOption(data)) {
1872 self.userOptions[value] = true;
1873 self.lastQuery = null;
1874 self.trigger('option_add', value, data);
1875 }
1876 },
1877
1878 registerOption: function(data) {
1879 var key = hash_key(data[this.settings.valueField]);
1880 if (typeof key === 'undefined' || key === null || this.options.hasOwnProperty(key)) return false;
1881 data.$order = data.$order || ++this.order;
1882 this.options[key] = data;
1883 return key;
1884 },
1885
1886 registerOptionGroup: function(data) {
1887 var key = hash_key(data[this.settings.optgroupValueField]);
1888 if (!key) return false;
1889
1890 data.$order = data.$order || ++this.order;
1891 this.optgroups[key] = data;
1892 return key;
1893 },
1894
1895 addOptionGroup: function(id, data) {
1896 data[this.settings.optgroupValueField] = id;
1897 if (id = this.registerOptionGroup(data)) {
1898 this.trigger('optgroup_add', id, data);
1899 }
1900 },
1901
1902 removeOptionGroup: function(id) {
1903 if (this.optgroups.hasOwnProperty(id)) {
1904 delete this.optgroups[id];
1905 this.renderCache = {};
1906 this.trigger('optgroup_remove', id);
1907 }
1908 },
1909
1910 clearOptionGroups: function() {
1911 this.optgroups = {};
1912 this.renderCache = {};
1913 this.trigger('optgroup_clear');
1914 },
1915
1916 updateOption: function(value, data) {
1917 var self = this;
1918 var $item, $item_new;
1919 var value_new, index_item, cache_items, cache_options, order_old;
1920
1921 value = hash_key(value);
1922 value_new = hash_key(data[self.settings.valueField]);
1923
1924 if (value === null) return;
1925 if (!self.options.hasOwnProperty(value)) return;
1926 if (typeof value_new !== 'string') throw new Error('Value must be set in option data');
1927
1928 order_old = self.options[value].$order;
1929
1930 if (value_new !== value) {
1931 delete self.options[value];
1932 index_item = self.items.indexOf(value);
1933 if (index_item !== -1) {
1934 self.items.splice(index_item, 1, value_new);
1935 }
1936 }
1937 data.$order = data.$order || order_old;
1938 self.options[value_new] = data;
1939
1940 cache_items = self.renderCache['item'];
1941 cache_options = self.renderCache['option'];
1942
1943 if (cache_items) {
1944 delete cache_items[value];
1945 delete cache_items[value_new];
1946 }
1947 if (cache_options) {
1948 delete cache_options[value];
1949 delete cache_options[value_new];
1950 }
1951
1952 if (self.items.indexOf(value_new) !== -1) {
1953 $item = self.getItem(value);
1954 $item_new = $(self.render('item', data));
1955 if ($item.hasClass('active')) $item_new.addClass('active');
1956 $item.replaceWith($item_new);
1957 }
1958
1959 self.lastQuery = null;
1960
1961 if (self.isOpen) {
1962 self.refreshOptions(false);
1963 }
1964 },
1965
1966 removeOption: function(value, silent) {
1967 var self = this;
1968 value = hash_key(value);
1969
1970 var cache_items = self.renderCache['item'];
1971 var cache_options = self.renderCache['option'];
1972 if (cache_items) delete cache_items[value];
1973 if (cache_options) delete cache_options[value];
1974
1975 delete self.userOptions[value];
1976 delete self.options[value];
1977 self.lastQuery = null;
1978 self.trigger('option_remove', value);
1979 self.removeItem(value, silent);
1980 },
1981
1982 clearOptions: function(silent) {
1983 var self = this;
1984
1985 self.loadedSearches = {};
1986 self.userOptions = {};
1987 self.renderCache = {};
1988 var options = self.options;
1989 $.each(self.options, function(key, value) {
1990 if(self.items.indexOf(key) == -1) {
1991 delete options[key];
1992 }
1993 });
1994 self.options = self.sifter.items = options;
1995 self.lastQuery = null;
1996 self.trigger('option_clear');
1997 self.clear(silent);
1998 },
1999
2000 getOption: function(value) {
2001 return this.getElementWithValue(value, this.$dropdown_content.find('[data-selectable]'));
2002 },
2003
2004 getFirstOption: function() {
2005 var $options = this.$dropdown.find('[data-selectable]');
2006 return $options.length > 0 ? $options.eq(0) : $();
2007 },
2008
2009 getAdjacentOption: function($option, direction) {
2010 var $options = this.$dropdown.find('[data-selectable]');
2011 var index = $options.index($option) + direction;
2012
2013 return index >= 0 && index < $options.length ? $options.eq(index) : $();
2014 },
2015
2016 getElementWithValue: function(value, $els) {
2017 value = hash_key(value);
2018
2019 if (typeof value !== 'undefined' && value !== null) {
2020 for (var i = 0, n = $els.length; i < n; i++) {
2021 if ($els[i].getAttribute('data-value') === value) {
2022 return $($els[i]);
2023 }
2024 }
2025 }
2026
2027 return $();
2028 },
2029
2030 getElementWithTextContent: function(textContent, ignoreCase ,$els) {
2031 textContent = hash_key(textContent);
2032
2033 if (typeof textContent !== 'undefined' && textContent !== null) {
2034 for (var i = 0, n = $els.length; i < n; i++) {
2035 var eleTextContent = $els[i].textContent
2036 if (ignoreCase == true) {
2037 eleTextContent = (eleTextContent !== null) ? eleTextContent.toLowerCase() : null;
2038 textContent = textContent.toLowerCase();
2039 }
2040 if (eleTextContent === textContent) {
2041 return $($els[i]);
2042 }
2043 }
2044 }
2045
2046 return $();
2047 },
2048
2049 getItem: function(value) {
2050 return this.getElementWithValue(value, this.$control.children());
2051 },
2052
2053 getFirstItemMatchedByTextContent: function(textContent, ignoreCase) {
2054 ignoreCase = (ignoreCase !== null && ignoreCase === true) ? true : false;
2055 return this.getElementWithTextContent(textContent, ignoreCase, this.$dropdown_content.find('[data-selectable]'));
2056 },
2057
2058 addItems: function(values, silent) {
2059 this.buffer = document.createDocumentFragment();
2060
2061 var childNodes = this.$control[0].childNodes;
2062 for (var i = 0; i < childNodes.length; i++) {
2063 this.buffer.appendChild(childNodes[i]);
2064 }
2065
2066 var items = Array.isArray(values) ? values : [values];
2067 for (var i = 0, n = items.length; i < n; i++) {
2068 this.isPending = (i < n - 1);
2069 this.addItem(items[i], silent);
2070 }
2071
2072 var control = this.$control[0];
2073 control.insertBefore(this.buffer, control.firstChild);
2074
2075 this.buffer = null;
2076 },
2077
2078 addItem: function(value, silent) {
2079 var events = silent ? [] : ['change'];
2080
2081 debounce_events(this, events, function() {
2082 var $item, $option, $options;
2083 var self = this;
2084 var inputMode = self.settings.mode;
2085 var i, active, value_next, wasFull;
2086 value = hash_key(value);
2087
2088 if (self.items.indexOf(value) !== -1) {
2089 if (inputMode === 'single') self.close();
2090 return;
2091 }
2092
2093 if (!self.options.hasOwnProperty(value)) return;
2094 if (inputMode === 'single') self.clear(silent);
2095 if (inputMode === 'multi' && self.isFull()) return;
2096
2097 $item = $(self.render('item', self.options[value]));
2098 wasFull = self.isFull();
2099 self.items.splice(self.caretPos, 0, value);
2100 self.insertAtCaret($item);
2101 if (!self.isPending || (!wasFull && self.isFull())) {
2102 self.refreshState();
2103 }
2104
2105 if (self.isSetup) {
2106 $options = self.$dropdown_content.find('[data-selectable]');
2107
2108 if (!self.isPending) {
2109 $option = self.getOption(value);
2110 value_next = self.getAdjacentOption($option, 1).attr('data-value');
2111 self.refreshOptions(self.isFocused && inputMode !== 'single');
2112 if (value_next) {
2113 self.setActiveOption(self.getOption(value_next));
2114 }
2115 }
2116
2117 if (!$options.length || self.isFull()) {
2118 self.close();
2119 } else if (!self.isPending) {
2120 self.positionDropdown();
2121 }
2122
2123 self.updatePlaceholder();
2124 self.trigger('item_add', value, $item);
2125
2126 if (!self.isPending) {
2127 self.updateOriginalInput({silent: silent});
2128 }
2129 }
2130 });
2131 },
2132
2133 removeItem: function(value, silent) {
2134 var self = this;
2135 var $item, i, idx;
2136
2137 $item = (value instanceof $) ? value : self.getItem(value);
2138 value = hash_key($item.attr('data-value'));
2139 i = self.items.indexOf(value);
2140
2141 if (i !== -1) {
2142 self.trigger('item_before_remove', value, $item);
2143 $item.remove();
2144 if ($item.hasClass('active')) {
2145 $item.removeClass('active');
2146 idx = self.$activeItems.indexOf($item[0]);
2147 self.$activeItems.splice(idx, 1);
2148 $item.removeClass('active');
2149 }
2150
2151 self.items.splice(i, 1);
2152 self.lastQuery = null;
2153 if (!self.settings.persist && self.userOptions.hasOwnProperty(value)) {
2154 self.removeOption(value, silent);
2155 }
2156
2157 if (i < self.caretPos) {
2158 self.setCaret(self.caretPos - 1);
2159 }
2160
2161 self.refreshState();
2162 self.updatePlaceholder();
2163 self.updateOriginalInput({silent: silent});
2164 self.positionDropdown();
2165 self.trigger('item_remove', value, $item);
2166 }
2167 },
2168
2169 createItem: function(input, triggerDropdown) {
2170 var self = this;
2171 var caret = self.caretPos;
2172 input = input || (self.$control_input.val() || '').trim();
2173
2174 var callback = arguments[arguments.length - 1];
2175 if (typeof callback !== 'function') callback = function() {};
2176
2177 if (typeof triggerDropdown !== 'boolean') {
2178 triggerDropdown = true;
2179 }
2180
2181 if (!self.canCreate(input)) {
2182 callback();
2183 return false;
2184 }
2185
2186 self.lock();
2187
2188 var setup = (typeof self.settings.create === 'function') ? this.settings.create : function(input) {
2189 var data = {};
2190 data[self.settings.labelField] = input;
2191 var key = input;
2192 if ( self.settings.formatValueToKey && typeof self.settings.formatValueToKey === 'function' ) {
2193 key = self.settings.formatValueToKey.apply(this, [key]);
2194 if (key === null || typeof key === 'undefined' || typeof key === 'object' || typeof key === 'function') {
2195 throw new Error('Selectize "formatValueToKey" setting must be a function that returns a value other than object or function.');
2196 }
2197 }
2198 data[self.settings.valueField] = key;
2199 return data;
2200 };
2201
2202 var create = once(function(data) {
2203 self.unlock();
2204
2205 if (!data || typeof data !== 'object') return callback();
2206 var value = hash_key(data[self.settings.valueField]);
2207 if (typeof value !== 'string') return callback();
2208
2209 self.setTextboxValue('');
2210 self.addOption(data);
2211 self.setCaret(caret);
2212 self.addItem(value);
2213 self.refreshOptions(triggerDropdown && self.settings.mode !== 'single');
2214 callback(data);
2215 });
2216
2217 var output = setup.apply(this, [input, create]);
2218 if (typeof output !== 'undefined') {
2219 create(output);
2220 }
2221
2222 return true;
2223 },
2224
2225 refreshItems: function(silent) {
2226 this.lastQuery = null;
2227
2228 if (this.isSetup) {
2229 this.addItem(this.items, silent);
2230 }
2231
2232 this.refreshState();
2233 this.updateOriginalInput({silent: silent});
2234 },
2235
2236 refreshState: function() {
2237 this.refreshValidityState();
2238 this.refreshClasses();
2239 },
2240
2241 refreshValidityState: function() {
2242 if (!this.isRequired) return false;
2243
2244 var invalid = !this.items.length;
2245
2246 this.isInvalid = invalid;
2247 this.$control_input.prop('required', invalid);
2248 this.$input.prop('required', !invalid);
2249 },
2250
2251 refreshClasses: function() {
2252 var self = this;
2253 var isFull = self.isFull();
2254 var isLocked = self.isLocked;
2255
2256 self.$wrapper
2257 .toggleClass('rtl', self.rtl);
2258
2259 self.$control
2260 .toggleClass('focus', self.isFocused)
2261 .toggleClass('disabled', self.isDisabled)
2262 .toggleClass('required', self.isRequired)
2263 .toggleClass('invalid', self.isInvalid)
2264 .toggleClass('locked', isLocked)
2265 .toggleClass('full', isFull).toggleClass('not-full', !isFull)
2266 .toggleClass('input-active', self.isFocused && !self.isInputHidden)
2267 .toggleClass('dropdown-active', self.isOpen)
2268 .toggleClass('has-options', !$.isEmptyObject(self.options))
2269 .toggleClass('has-items', self.items.length > 0);
2270
2271 self.$control_input.data('grow', !isFull && !isLocked);
2272 },
2273
2274 isFull: function() {
2275 return this.settings.maxItems !== null && this.items.length >= this.settings.maxItems;
2276 },
2277
2278 updateOriginalInput: function(opts) {
2279 var i, n, existing, fresh, old, $options, label, value, values, self = this;
2280 opts = opts || {};
2281
2282 if (self.tagType === TAG_SELECT) {
2283 $options = self.$input.find('option');
2284 existing = [];
2285 fresh = [];
2286 old = [];
2287 values = [];
2288
2289 $options.get().forEach(function(option) {
2290 existing.push(option.value);
2291 });
2292
2293 self.items.forEach(function(item) {
2294 label = self.options[item][self.settings.labelField] || '';
2295
2296 values.push(item);
2297
2298 if (existing.indexOf(item) != -1) {
2299 return;
2300 }
2301
2302 fresh.push('<option value="' + escape_html(item) + '" selected="selected">' + escape_html(label) + '</option>');
2303 });
2304
2305 old = existing.filter(function(value) {
2306 return values.indexOf(value) < 0;
2307 }).map(function(value) {
2308 return 'option[value="' + escape_html(value) + '"]';
2309 });
2310
2311 if (existing.length - old.length + fresh.length === 0 && !self.$input.attr('multiple')) {
2312 fresh.push('<option value="" selected="selected"></option>');
2313 }
2314
2315 self.$input.find(old.join(', ')).remove();
2316 self.$input.append(fresh.join(''));
2317 } else {
2318 self.$input.val(self.getValue());
2319 self.$input.attr('value',self.$input.val());
2320 }
2321
2322 if (self.isSetup) {
2323 if (!opts.silent) {
2324 self.trigger('change', self.$input.val());
2325 }
2326 }
2327 },
2328
2329 updatePlaceholder: function() {
2330 if (!this.settings.placeholder) return;
2331 var $input = this.$control_input;
2332
2333 if (this.items.length) {
2334 $input.removeAttr('placeholder');
2335 } else {
2336 $input.attr('placeholder', this.settings.placeholder);
2337 }
2338 $input.triggerHandler('update', {force: true});
2339 },
2340
2341 open: function() {
2342 var self = this;
2343
2344 if (
2345 self.isLocked ||
2346 self.isOpen ||
2347 (self.settings.mode === "multi" && self.isFull())
2348 )
2349 return;
2350 self.focus();
2351 self.isOpen = true;
2352 self.refreshState();
2353 self.$dropdown.css({ visibility: 'hidden', display: 'block' });
2354 self.setupDropdownHeight();
2355 self.positionDropdown();
2356 self.$dropdown.css({visibility: 'visible'});
2357 self.trigger('dropdown_open', self.$dropdown);
2358 },
2359
2360 close: function() {
2361 var self = this;
2362 var trigger = self.isOpen;
2363
2364 if (self.settings.mode === 'single' && self.items.length) {
2365 self.hideInput();
2366
2367 if (self.isBlurring) {
2368 self.$control_input[0].blur();
2369 }
2370 }
2371
2372 self.isOpen = false;
2373 self.$dropdown.hide();
2374 self.setActiveOption(null);
2375 self.refreshState();
2376
2377 if (trigger) self.trigger('dropdown_close', self.$dropdown);
2378 },
2379
2380 positionDropdown: function() {
2381 var $control = this.$control;
2382 var offset = this.settings.dropdownParent === 'body' ? $control.offset() : $control.position();
2383 offset.top += $control.outerHeight(true);
2384 var w = this.$wrapper[0].style.width !== 'fit-content' ? this.settings.dropdownParent === 'body' ? 'max-content' : '100%' : 'max-content';
2385 if (this.settings.minWidth && this.settings.minWidth > w)
2386 {
2387 w = this.settings.minWidth;
2388 }
2389
2390 if (this.settings.dropdownParent !== 'body' && w === 'max-content' && $control.outerWidth(true) >= this.$dropdown.outerWidth(true)) {
2391 w = '100%';
2392 }
2393
2394 this.$dropdown.css({
2395 width : w,
2396 minWidth : $control.outerWidth(true),
2397 top : offset.top,
2398 left : offset.left
2399 });
2400 },
2401
2402 setupDropdownHeight: function () {
2403 if (typeof this.settings.dropdownSize === 'object' && this.settings.dropdownSize.sizeType !== 'auto') {
2404 var height = this.settings.dropdownSize.sizeValue;
2405
2406 if (this.settings.dropdownSize.sizeType === 'numberItems') {
2407 var $items = this.$dropdown_content.find('*').not('.optgroup, .highlight').not(this.settings.ignoreOnDropwdownHeight);
2408 var totalHeight = 0;
2409 var marginTop = 0;
2410 var marginBottom = 0;
2411 var separatorHeight = 0;
2412
2413
2414 for (var i = 0; i < height; i++) {
2415 var $item = $($items[i]);
2416
2417 if ($item.length === 0) {
2418 break;
2419 }
2420
2421 totalHeight += $item.outerHeight(true);
2422 if (typeof $item.data('selectable') == 'undefined') {
2423 if ($item.hasClass('optgroup-header')) {
2424 var styles = window.getComputedStyle($item.parent()[0], ':before');
2425
2426 if (styles) {
2427 marginTop = styles.marginTop ? Number(styles.marginTop.replace(/\W*(\w)\w*/g, '$1')) : 0;
2428 marginBottom = styles.marginBottom ? Number(styles.marginBottom.replace(/\W*(\w)\w*/g, '$1')) : 0;
2429 separatorHeight = styles.borderTopWidth ? Number(styles.borderTopWidth.replace(/\W*(\w)\w*/g, '$1')) : 0;
2430 }
2431 }
2432 height++;
2433 }
2434
2435 }
2436
2437 var paddingTop = this.$dropdown_content.css('padding-top') ? Number(this.$dropdown_content.css('padding-top').replace(/\W*(\w)\w*/g, '$1')) : 0;
2438 var paddingBottom = this.$dropdown_content.css('padding-bottom') ? Number(this.$dropdown_content.css('padding-bottom').replace(/\W*(\w)\w*/g, '$1')) : 0;
2439
2440 height = (totalHeight + paddingTop + paddingBottom + marginTop + marginBottom + separatorHeight) + 'px';
2441 } else if (this.settings.dropdownSize.sizeType !== 'fixedHeight') {
2442 console.warn('Selectize.js - Value of "sizeType" must be "fixedHeight" or "numberItems');
2443 return;
2444 }
2445
2446 this.$dropdown_content.css({ height: height, maxHeight: 'none' });
2447 }
2448 },
2449
2450 clear: function(silent) {
2451 var self = this;
2452
2453 if (!self.items.length) return;
2454 self.$control.children(':not(input)').remove();
2455 self.items = [];
2456 self.lastQuery = null;
2457 self.setCaret(0);
2458 self.setActiveItem(null);
2459 self.updatePlaceholder();
2460 self.updateOriginalInput({silent: silent});
2461 self.refreshState();
2462 self.showInput();
2463 self.trigger('clear');
2464 },
2465
2466 insertAtCaret: function($el) {
2467 var caret = Math.min(this.caretPos, this.items.length);
2468 var el = $el[0];
2469 var target = this.buffer || this.$control[0];
2470
2471 if (caret === 0) {
2472 target.insertBefore(el, target.firstChild);
2473 } else {
2474 target.insertBefore(el, target.childNodes[caret]);
2475 }
2476
2477 this.setCaret(caret + 1);
2478 },
2479
2480 deleteSelection: function(e) {
2481 var i, n, direction, selection, values, caret, option_select, $option_select, $tail;
2482 var self = this;
2483
2484 direction = (e && e.keyCode === KEY_BACKSPACE) ? -1 : 1;
2485 selection = getInputSelection(self.$control_input[0]);
2486
2487 if (self.$activeOption && !self.settings.hideSelected) {
2488 if (typeof self.settings.deselectBehavior === 'string' && self.settings.deselectBehavior === 'top') {
2489 option_select = self.getFirstOption().attr('data-value');
2490 } else {
2491 option_select = self.getAdjacentOption(self.$activeOption, -1).attr('data-value');
2492 }
2493 }
2494
2495 values = [];
2496
2497 if (self.$activeItems.length) {
2498 $tail = self.$control.children('.active:' + (direction > 0 ? 'last' : 'first'));
2499 caret = self.$control.children(':not(input)').index($tail);
2500 if (direction > 0) { caret++; }
2501
2502 for (i = 0, n = self.$activeItems.length; i < n; i++) {
2503 values.push($(self.$activeItems[i]).attr('data-value'));
2504 }
2505 if (e) {
2506 e.preventDefault();
2507 e.stopPropagation();
2508 }
2509 } else if ((self.isFocused || self.settings.mode === 'single') && self.items.length) {
2510 if (direction < 0 && selection.start === 0 && selection.length === 0) {
2511 values.push(self.items[self.caretPos - 1]);
2512 } else if (direction > 0 && selection.start === self.$control_input.val().length) {
2513 values.push(self.items[self.caretPos]);
2514 }
2515 }
2516
2517 if (!values.length || (typeof self.settings.onDelete === 'function' && self.settings.onDelete.apply(self, [values]) === false)) {
2518 return false;
2519 }
2520
2521 if (typeof caret !== 'undefined') {
2522 self.setCaret(caret);
2523 }
2524 while (values.length) {
2525 self.removeItem(values.pop());
2526 }
2527
2528 self.showInput();
2529 self.positionDropdown();
2530 self.refreshOptions(true);
2531
2532 if (option_select) {
2533 $option_select = self.getOption(option_select);
2534 if ($option_select.length) {
2535 self.setActiveOption($option_select);
2536 }
2537 }
2538
2539 return true;
2540 },
2541
2542 advanceSelection: function(direction, e) {
2543 var tail, selection, idx, valueLength, cursorAtEdge, $tail;
2544 var self = this;
2545
2546 if (direction === 0) return;
2547 if (self.rtl) direction *= -1;
2548
2549 tail = direction > 0 ? 'last' : 'first';
2550 selection = getInputSelection(self.$control_input[0]);
2551
2552 if (self.isFocused && !self.isInputHidden) {
2553 valueLength = self.$control_input.val().length;
2554 cursorAtEdge = direction < 0
2555 ? selection.start === 0 && selection.length === 0
2556 : selection.start === valueLength;
2557
2558 if (cursorAtEdge && !valueLength) {
2559 self.advanceCaret(direction, e);
2560 }
2561 } else {
2562 $tail = self.$control.children('.active:' + tail);
2563 if ($tail.length) {
2564 idx = self.$control.children(':not(input)').index($tail);
2565 self.setActiveItem(null);
2566 self.setCaret(direction > 0 ? idx + 1 : idx);
2567 }
2568 }
2569 },
2570
2571 advanceCaret: function(direction, e) {
2572 var self = this, fn, $adj;
2573
2574 if (direction === 0) return;
2575
2576 fn = direction > 0 ? 'next' : 'prev';
2577 if (self.isShiftDown) {
2578 $adj = self.$control_input[fn]();
2579 if ($adj.length) {
2580 self.hideInput();
2581 self.setActiveItem($adj);
2582 e && e.preventDefault();
2583 }
2584 } else {
2585 self.setCaret(self.caretPos + direction);
2586 }
2587 },
2588
2589 setCaret: function(i) {
2590 var self = this;
2591
2592 if (self.settings.mode === 'single') {
2593 i = self.items.length;
2594 } else {
2595 i = Math.max(0, Math.min(self.items.length, i));
2596 }
2597
2598 if(!self.isPending) {
2599 var j, n, fn, $children, $child;
2600 $children = self.$control.children(':not(input)');
2601 for (j = 0, n = $children.length; j < n; j++) {
2602 $child = $($children[j]).detach();
2603 if (j < i) {
2604 self.$control_input.before($child);
2605 } else {
2606 self.$control.append($child);
2607 }
2608 }
2609 }
2610
2611 self.caretPos = i;
2612 },
2613
2614 lock: function() {
2615 this.close();
2616 this.isLocked = true;
2617 this.refreshState();
2618 },
2619
2620 unlock: function() {
2621 this.isLocked = false;
2622 this.refreshState();
2623 },
2624
2625 disable: function() {
2626 var self = this;
2627 self.$input.prop('disabled', true);
2628 self.$control_input.prop('disabled', true).prop('tabindex', -1);
2629 self.isDisabled = true;
2630 self.lock();
2631 },
2632
2633 enable: function() {
2634 var self = this;
2635 self.$input.prop('disabled', false);
2636 self.$control_input.prop('disabled', false).prop('tabindex', self.tabIndex);
2637 self.isDisabled = false;
2638 self.unlock();
2639 },
2640
2641 destroy: function() {
2642 var self = this;
2643 var eventNS = self.eventNS;
2644 var revertSettings = self.revertSettings;
2645
2646 self.trigger('destroy');
2647 self.off();
2648 self.$wrapper.remove();
2649 self.$dropdown.remove();
2650
2651 self.$input
2652 .html('')
2653 .append(revertSettings.$children)
2654 .removeAttr('tabindex')
2655 .removeClass('selectized')
2656 .attr({tabindex: revertSettings.tabindex})
2657 .show();
2658
2659 self.$control_input.removeData('grow');
2660 self.$input.removeData('selectize');
2661
2662 if (--Selectize.count == 0 && Selectize.$testInput) {
2663 Selectize.$testInput.remove();
2664 Selectize.$testInput = undefined;
2665 }
2666
2667 $(window).off(eventNS);
2668 $(document).off(eventNS);
2669 $(document.body).off(eventNS);
2670
2671 delete self.$input[0].selectize;
2672 },
2673
2674 render: function(templateName, data) {
2675 var value, id, label;
2676 var html = '';
2677 var cache = false;
2678 var self = this;
2679 var regex_tag = /^[\t \r\n]*<([a-z][a-z0-9\-_]*(?:\:[a-z][a-z0-9\-_]*)?)/i;
2680
2681 if (templateName === 'option' || templateName === 'item') {
2682 value = hash_key(data[self.settings.valueField]);
2683 cache = !!value;
2684 }
2685
2686 if (cache) {
2687 if (!isset(self.renderCache[templateName])) {
2688 self.renderCache[templateName] = {};
2689 }
2690 if (self.renderCache[templateName].hasOwnProperty(value)) {
2691 return self.renderCache[templateName][value];
2692 }
2693 }
2694
2695 html = $(self.settings.render[templateName].apply(this, [data, escape_html]));
2696
2697 if (templateName === 'option' || templateName === 'option_create') {
2698 if (!data[self.settings.disabledField]) {
2699 html.attr('data-selectable', '');
2700 }
2701 }
2702 else if (templateName === 'optgroup') {
2703 id = data[self.settings.optgroupValueField] || '';
2704 html.attr('data-group', id);
2705 if(data[self.settings.disabledField]) {
2706 html.attr('data-disabled', '');
2707 }
2708 }
2709 if (templateName === 'option' || templateName === 'item') {
2710 html.attr('data-value', value || '');
2711 }
2712
2713 if (cache) {
2714 self.renderCache[templateName][value] = html[0];
2715 }
2716
2717 return html[0];
2718 },
2719
2720 clearCache: function(templateName) {
2721 var self = this;
2722 if (typeof templateName === 'undefined') {
2723 self.renderCache = {};
2724 } else {
2725 delete self.renderCache[templateName];
2726 }
2727 },
2728
2729 canCreate: function(input) {
2730 var self = this;
2731 if (!self.settings.create) return false;
2732 var filter = self.settings.createFilter;
2733 return input.length
2734 && (typeof filter !== 'function' || filter.apply(self, [input]))
2735 && (typeof filter !== 'string' || new RegExp(filter).test(input))
2736 && (!(filter instanceof RegExp) || filter.test(input));
2737 }
2738 });
2739
2740 Selectize.count = 0;
2741 Selectize.defaults = {
2742 options: [],
2743 optgroups: [],
2744
2745 plugins: [],
2746 delimiter: ',',
2747 splitOn: null,
2748 persist: true,
2749 diacritics: true,
2750 create: false,
2751 showAddOptionOnCreate: true,
2752 createOnBlur: false,
2753 createFilter: null,
2754 highlight: true,
2755 openOnFocus: true,
2756 maxOptions: 1000,
2757 maxItems: null,
2758 hideSelected: null,
2759 addPrecedence: false,
2760 selectOnTab: false,
2761 preload: false,
2762 allowEmptyOption: false,
2763 showEmptyOptionInDropdown: false,
2764 emptyOptionLabel: '--',
2765 setFirstOptionActive: false,
2766 closeAfterSelect: false,
2767 closeDropdownThreshold: 250,
2768
2769 scrollDuration: 60,
2770 deselectBehavior: 'previous',
2771 loadThrottle: 300,
2772 loadingClass: 'loading',
2773
2774 dataAttr: 'data-data',
2775 optgroupField: 'optgroup',
2776 valueField: 'value',
2777 labelField: 'text',
2778 disabledField: 'disabled',
2779 optgroupLabelField: 'label',
2780 optgroupValueField: 'value',
2781 lockOptgroupOrder: false,
2782
2783 sortField: '$order',
2784 searchField: ['text'],
2785 searchConjunction: 'and',
2786 respect_word_boundaries: false,
2787 normalize: true,
2788
2789 mode: null,
2790 wrapperClass: '',
2791 inputClass: '',
2792 dropdownClass: '',
2793 dropdownContentClass: '',
2794
2795 dropdownParent: null,
2796
2797 copyClassesToDropdown: true,
2798 dropdownSize: {
2799 sizeType: 'auto',
2800 sizeValue: 'auto',
2801 },
2802
2803 ignoreOnDropwdownHeight: 'img, i',
2804 search: true,
2805 showArrow: true,
2806
2807 render: {
2808 }
2809 };
2810
2811 $.fn.selectize = function (settings_user) {
2812 var defaults = $.fn.selectize.defaults;
2813 var settings = $.extend({}, defaults, settings_user);
2814 var attr_data = settings.dataAttr;
2815 var field_label = settings.labelField;
2816 var field_value = settings.valueField;
2817 var field_disabled = settings.disabledField;
2818 var field_optgroup = settings.optgroupField;
2819 var field_optgroup_label = settings.optgroupLabelField;
2820 var field_optgroup_value = settings.optgroupValueField;
2821
2822 var init_textbox = function ($input, settings_element) {
2823 var i, n, values, option;
2824
2825 var data_raw = $input.attr(attr_data);
2826
2827 if (!data_raw) {
2828 var value = ($input.val() || '').trim();
2829 if (!settings.allowEmptyOption && !value.length) return;
2830 values = value.split(settings.delimiter);
2831 for (i = 0, n = values.length; i < n; i++) {
2832 option = {};
2833 option[field_label] = values[i];
2834 option[field_value] = values[i];
2835 settings_element.options.push(option);
2836 }
2837 settings_element.items = values;
2838 } else {
2839 settings_element.options = JSON.parse(data_raw);
2840 for (i = 0, n = settings_element.options.length; i < n; i++) {
2841 settings_element.items.push(settings_element.options[i][field_value]);
2842 }
2843 }
2844 };
2845
2846 var init_select = function ($input, settings_element) {
2847 var i, n, tagName, $children, order = 0;
2848 var options = settings_element.options;
2849 var optionsMap = {};
2850
2851 var readData = function ($el) {
2852 var data = attr_data && $el.attr(attr_data);
2853 var allData = $el.data();
2854 var obj = {};
2855
2856 if (typeof data === 'string' && data.length) {
2857 if (isJSON(data)) {
2858 Object.assign(obj, JSON.parse(data))
2859 } else {
2860 obj[data] = data;
2861 }
2862 }
2863
2864
2865 Object.assign(obj, allData);
2866
2867 return obj || null;
2868 };
2869
2870 var addOption = function ($option, group) {
2871 $option = $($option);
2872
2873 var value = hash_key($option.val());
2874 if (!value && !settings.allowEmptyOption) return;
2875
2876 if (optionsMap.hasOwnProperty(value)) {
2877 if (group) {
2878 var arr = optionsMap[value][field_optgroup];
2879 if (!arr) {
2880 optionsMap[value][field_optgroup] = group;
2881 } else if (!Array.isArray(arr)) {
2882 optionsMap[value][field_optgroup] = [arr, group];
2883 } else {
2884 arr.push(group);
2885 }
2886 }
2887 return;
2888 }
2889
2890 var option = readData($option) || {};
2891 option[field_label] = option[field_label] || $option.text();
2892 option[field_value] = option[field_value] || value;
2893 option[field_disabled] = option[field_disabled] || $option.prop('disabled');
2894 option[field_optgroup] = option[field_optgroup] || group;
2895 option.styles = $option.attr('style') || '';
2896 option.classes = $option.attr('class') || '';
2897
2898 optionsMap[value] = option;
2899 options.push(option);
2900
2901 if ($option.is(':selected')) {
2902 settings_element.items.push(value);
2903 }
2904 };
2905
2906 var addGroup = function ($optgroup) {
2907 var i, n, id, optgroup, $options;
2908
2909 $optgroup = $($optgroup);
2910 id = $optgroup.attr('label');
2911
2912 if (id) {
2913 optgroup = readData($optgroup) || {};
2914 optgroup[field_optgroup_label] = id;
2915 optgroup[field_optgroup_value] = id;
2916 optgroup[field_disabled] = $optgroup.prop('disabled');
2917 settings_element.optgroups.push(optgroup);
2918 }
2919
2920 $options = $('option', $optgroup);
2921 for (i = 0, n = $options.length; i < n; i++) {
2922 addOption($options[i], id);
2923 }
2924 };
2925
2926 settings_element.maxItems = $input.attr('multiple') ? null : 1;
2927
2928 $children = $input.children();
2929 for (i = 0, n = $children.length; i < n; i++) {
2930 tagName = $children[i].tagName.toLowerCase();
2931 if (tagName === 'optgroup') {
2932 addGroup($children[i]);
2933 } else if (tagName === 'option') {
2934 addOption($children[i]);
2935 }
2936 }
2937 };
2938
2939 return this.each(function () {
2940 if (this.selectize) return;
2941
2942 var instance;
2943 var $input = $(this);
2944 var tag_name = this.tagName.toLowerCase();
2945 var placeholder = $input.attr('placeholder') || $input.attr('data-placeholder');
2946 if (!placeholder && !settings.allowEmptyOption) {
2947 placeholder = $input.children('option[value=""]').text();
2948 }
2949 if (settings.allowEmptyOption && settings.showEmptyOptionInDropdown && !$input.children('option[value=""]').length) {
2950 var input_html = $input.html();
2951 var label = escape_html(settings.emptyOptionLabel || '--');
2952 $input.html('<option value="">' + label + '</option>' + input_html);
2953 }
2954
2955 var settings_element = {
2956 'placeholder': placeholder,
2957 'options': [],
2958 'optgroups': [],
2959 'items': []
2960 };
2961
2962 if (tag_name === 'select') {
2963 init_select($input, settings_element);
2964 } else {
2965 init_textbox($input, settings_element);
2966 }
2967
2968 instance = new Selectize($input, $.extend(true, {}, defaults, settings_element, settings_user));
2969 instance.settings_user = settings_user;
2970 });
2971 };
2972
2973 $.fn.selectize.defaults = Selectize.defaults;
2974 $.fn.selectize.support = {
2975 validity: SUPPORTS_VALIDITY_API
2976 };
2977
2978 Selectize.define("auto_position", function () {
2979 var self = this;
2980
2981 const POSITION = {
2982 top: 'top',
2983 bottom: 'bottom',
2984 };
2985
2986 self.positionDropdown = (function () {
2987 return function () {
2988 const $control = this.$control;
2989 const offset = this.settings.dropdownParent === 'body' ? $control.offset() : $control.position();
2990 offset.top += $control.outerHeight(true);
2991
2992 const dropdownHeight = this.$dropdown.prop('scrollHeight') + 5;
2993 const controlPosTop = this.$control.get(0).getBoundingClientRect().top;
2994 const wrapperHeight = this.$wrapper.height();
2995 const controlPosBottom = self.$control.get(0).getBoundingClientRect().bottom
2996 const position =
2997 controlPosTop + dropdownHeight + wrapperHeight > window.innerHeight &&
2998 controlPosBottom - dropdownHeight - wrapperHeight >= 0 ?
2999 POSITION.top :
3000 POSITION.bottom;
3001 let w = this.$wrapper[0].style.width !== 'fit-content' ? this.settings.dropdownParent === 'body' ? 'max-content' : '100%' : 'max-content';
3002 const styles = {
3003 width: w,
3004 minWidth : $control.outerWidth(true),
3005 left: offset.left
3006 };
3007
3008 if (position === POSITION.top) {
3009 const styleToAdd = { bottom: offset.top, top: 'unset' };
3010
3011 if (this.settings.dropdownParent === 'body') {
3012 styleToAdd.top = offset.top - this.$dropdown.outerHeight(true) - $control.outerHeight(true);
3013 styleToAdd.bottom = 'unset';
3014 }
3015 Object.assign(styles, styleToAdd);
3016 this.$dropdown.addClass('selectize-position-top');
3017 this.$control.addClass('selectize-position-top');
3018 } else {
3019 Object.assign(styles, { top: offset.top, bottom: 'unset' });
3020 this.$dropdown.removeClass('selectize-position-top');
3021 this.$control.removeClass('selectize-position-top');
3022 }
3023
3024 if (this.settings.dropdownParent !== 'body' && w === 'max-content' && $control.outerWidth(true) >= this.$dropdown.outerWidth(true)) {
3025 w = '100%';
3026 }
3027
3028 this.$dropdown.css(styles);
3029 };
3030 }());
3031 });
3032
3033 Selectize.define('auto_select_on_type', function(options) {
3034 var self = this;
3035
3036 self.onBlur = (function() {
3037 var originalBlur = self.onBlur;
3038 return function(e) {
3039 var $matchedItem = self.getFirstItemMatchedByTextContent(self.lastValue, true);
3040 if (typeof $matchedItem.attr('data-value') !== 'undefined' && self.getValue() !== $matchedItem.attr('data-value'))
3041 {
3042 self.setValue($matchedItem.attr('data-value'));
3043 }
3044 return originalBlur.apply(this, arguments);
3045 }
3046 }());
3047 });
3048
3049 Selectize.define("autofill_disable", function (options) {
3050 var self = this;
3051
3052 self.setup = (function () {
3053 var original = self.setup;
3054 return function () {
3055 original.apply(self, arguments);
3056
3057 self.$control_input.attr({ name: nanoid(21), autocomplete: nanoid(21) });
3058 };
3059 })();
3060 });
3061
3062 Selectize.define("clear_button", function (options) {
3063 var self = this;
3064
3065 options = $.extend(
3066 {
3067 title: "Clear",
3068 className: "clear",
3069 label: "×",
3070 html: function (data) {
3071 return (
3072 '<a class="' + data.className + '" title="' + data.title + '"> ' + data.label + '</a>'
3073 );
3074 },
3075 },
3076 options
3077 );
3078
3079 self.setup = (function () {
3080 var original = self.setup;
3081 return function () {
3082 original.apply(self, arguments);
3083 self.$button_clear = $(options.html(options));
3084
3085 if (self.settings.mode === "single") self.$wrapper.addClass("single");
3086
3087 self.$wrapper.append(self.$button_clear);
3088
3089 if (self.getValue() === "" || self.getValue().length === 0) {
3090 self.$wrapper.find("." + options.className).css("display", "none");
3091 }
3092
3093 self.on("change", function () {
3094 if (self.getValue() === "" || self.getValue().length === 0) {
3095 self.$wrapper.find("." + options.className).css("display", "none");
3096 } else {
3097 self.$wrapper.find("." + options.className).css("display", "");
3098 }
3099 });
3100
3101 self.$wrapper.on("click", "." + options.className, function (e) {
3102 e.preventDefault();
3103 e.stopImmediatePropagation();
3104 e.stopPropagation();
3105
3106 if (self.isLocked) return;
3107
3108 self.clear();
3109 self.$wrapper.find("." + options.className).css("display", "none");
3110 });
3111 };
3112 })();
3113 });
3114
3115 Selectize.define('drag_drop', function(options) {
3116 if (!$.fn.sortable) throw new Error('The "drag_drop" plugin requires jQuery UI "sortable".');
3117 if (this.settings.mode !== 'multi') return;
3118 var self = this;
3119
3120 self.lock = (function() {
3121 var original = self.lock;
3122 return function() {
3123 var sortable = self.$control.data('sortable');
3124 if (sortable) sortable.disable();
3125 return original.apply(self, arguments);
3126 };
3127 })();
3128
3129 self.unlock = (function() {
3130 var original = self.unlock;
3131 return function() {
3132 var sortable = self.$control.data('sortable');
3133 if (sortable) sortable.enable();
3134 return original.apply(self, arguments);
3135 };
3136 })();
3137
3138 self.setup = (function() {
3139 var original = self.setup;
3140 return function() {
3141 original.apply(this, arguments);
3142
3143 var $control = self.$control.sortable({
3144 items: '[data-value]',
3145 forcePlaceholderSize: true,
3146 disabled: self.isLocked,
3147 start: function(e, ui) {
3148 ui.placeholder.css('width', ui.helper.css('width'));
3149 $control.addClass('dragging');
3150 },
3151 stop: function() {
3152 $control.removeClass('dragging');
3153 var active = self.$activeItems ? self.$activeItems.slice() : null;
3154 var values = [];
3155 $control.children('[data-value]').each(function() {
3156 values.push($(this).attr('data-value'));
3157 });
3158 self.isFocused = false;
3159 self.setValue(values);
3160 self.isFocused = true;
3161 self.setActiveItem(active);
3162 self.positionDropdown();
3163 }
3164 });
3165 };
3166 })();
3167
3168 });
3169
3170 Selectize.define('dropdown_header', function(options) {
3171 var self = this;
3172
3173 options = $.extend({
3174 title : 'Untitled',
3175 headerClass : 'selectize-dropdown-header',
3176 titleRowClass : 'selectize-dropdown-header-title',
3177 labelClass : 'selectize-dropdown-header-label',
3178 closeClass : 'selectize-dropdown-header-close',
3179
3180 html: function(data) {
3181 return (
3182 '<div class="' + data.headerClass + '">' +
3183 '<div class="' + data.titleRowClass + '">' +
3184 '<span class="' + data.labelClass + '">' + data.title + '</span>' +
3185 '<a href="javascript:void(0)" class="' + data.closeClass + '">&#xd7;</a>' +
3186 '</div>' +
3187 '</div>'
3188 );
3189 }
3190 }, options);
3191
3192 self.setup = (function() {
3193 var original = self.setup;
3194 return function() {
3195 original.apply(self, arguments);
3196 self.$dropdown_header = $(options.html(options));
3197 self.$dropdown.prepend(self.$dropdown_header);
3198 self.$dropdown_header.find('.' + options.closeClass).on('click', function () {
3199 self.close();
3200 });
3201 };
3202 })();
3203
3204 });
3205
3206 Selectize.define('optgroup_columns', function(options) {
3207 var self = this;
3208
3209 options = $.extend({
3210 equalizeWidth : true,
3211 equalizeHeight : true
3212 }, options);
3213
3214 this.getAdjacentOption = function($option, direction) {
3215 var $options = $option.closest('[data-group]').find('[data-selectable]');
3216 var index = $options.index($option) + direction;
3217
3218 return index >= 0 && index < $options.length ? $options.eq(index) : $();
3219 };
3220
3221 this.onKeyDown = (function() {
3222 var original = self.onKeyDown;
3223 return function(e) {
3224 var index, $option, $options, $optgroup;
3225
3226 if (this.isOpen && (e.keyCode === KEY_LEFT || e.keyCode === KEY_RIGHT)) {
3227 self.ignoreHover = true;
3228 $optgroup = this.$activeOption.closest('[data-group]');
3229 index = $optgroup.find('[data-selectable]').index(this.$activeOption);
3230
3231 if(e.keyCode === KEY_LEFT) {
3232 $optgroup = $optgroup.prev('[data-group]');
3233 } else {
3234 $optgroup = $optgroup.next('[data-group]');
3235 }
3236
3237 $options = $optgroup.find('[data-selectable]');
3238 $option = $options.eq(Math.min($options.length - 1, index));
3239 if ($option.length) {
3240 this.setActiveOption($option);
3241 }
3242 return;
3243 }
3244
3245 return original.apply(this, arguments);
3246 };
3247 })();
3248
3249 var getScrollbarWidth = function() {
3250 var div;
3251 var width = getScrollbarWidth.width;
3252 var doc = document;
3253
3254 if (typeof width === 'undefined') {
3255 div = doc.createElement('div');
3256 div.innerHTML = '<div style="width:50px;height:50px;position:absolute;left:-50px;top:-50px;overflow:auto;"><div style="width:1px;height:100px;"></div></div>';
3257 div = div.firstChild;
3258 doc.body.appendChild(div);
3259 width = getScrollbarWidth.width = div.offsetWidth - div.clientWidth;
3260 doc.body.removeChild(div);
3261 }
3262 return width;
3263 };
3264
3265 var equalizeSizes = function() {
3266 var i, n, height_max, width, width_last, width_parent, $optgroups;
3267
3268 $optgroups = $('[data-group]', self.$dropdown_content);
3269 n = $optgroups.length;
3270 if (!n || !self.$dropdown_content.width()) return;
3271
3272 if (options.equalizeHeight) {
3273 height_max = 0;
3274 for (i = 0; i < n; i++) {
3275 height_max = Math.max(height_max, $optgroups.eq(i).height());
3276 }
3277 $optgroups.css({height: height_max});
3278 }
3279
3280 if (options.equalizeWidth) {
3281 width_parent = self.$dropdown_content.innerWidth() - getScrollbarWidth();
3282 width = Math.round(width_parent / n);
3283 $optgroups.css({width: width});
3284 if (n > 1) {
3285 width_last = width_parent - width * (n - 1);
3286 $optgroups.eq(n - 1).css({width: width_last});
3287 }
3288 }
3289 };
3290
3291 if (options.equalizeHeight || options.equalizeWidth) {
3292 hook.after(this, 'positionDropdown', equalizeSizes);
3293 hook.after(this, 'refreshOptions', equalizeSizes);
3294 }
3295
3296
3297 });
3298
3299 Selectize.define('read-only', function(options){
3300 var self = this;
3301 this.setup = (function() {
3302 var original = self.setup;
3303 return function() {
3304 original.apply(this, arguments);
3305 if(this.$dropdown.hasClass("read-only"))this.$control_input.attr('readonly', 'readonly');
3306 };
3307 })();
3308 this.readonly = (function() {
3309 return function(state) {
3310 if(state){
3311 this.$control_input.attr('readonly', 'readonly');
3312 this.$dropdown.addClass("read-only")
3313 }
3314 else{
3315 this.$control_input.removeAttr('readonly');
3316 this.$dropdown.removeClass("read-only")
3317 }
3318 };
3319 })();
3320 });
3321
3322 Selectize.define('remove_button', function (options) {
3323 if (this.settings.mode === 'single') return;
3324
3325 options = $.extend({
3326 label : '&#xd7;',
3327 title : 'Remove',
3328 className : 'remove',
3329 append : true
3330 }, options);
3331
3332 var multiClose = function(thisRef, options) {
3333
3334 var self = thisRef;
3335 var html = '<a href="javascript:void(0)" class="' + options.className + '" tabindex="-1" title="' + escape_html(options.title) + '">' + options.label + '</a>';
3336
3337 var append = function(html_container, html_element) {
3338 var pos = html_container.search(/(<\/[^>]+>\s*)$/);
3339 return html_container.substring(0, pos) + html_element + html_container.substring(pos);
3340 };
3341
3342 thisRef.setup = (function() {
3343 var original = self.setup;
3344 return function() {
3345 if (options.append) {
3346 var render_item = self.settings.render.item;
3347 self.settings.render.item = function(data) {
3348 return append(render_item.apply(thisRef, arguments), html);
3349 };
3350 }
3351
3352 original.apply(thisRef, arguments);
3353
3354 thisRef.$control.on('click', '.' + options.className, function(e) {
3355 e.preventDefault();
3356 if (self.isLocked) return;
3357
3358 var $item = $(e.currentTarget).parent();
3359 self.setActiveItem($item);
3360 if (self.deleteSelection()) {
3361 self.setCaret(self.items.length);
3362 }
3363 return false;
3364 });
3365
3366 };
3367 })();
3368 };
3369
3370 multiClose(this, options);
3371 });
3372
3373 Selectize.define('restore_on_backspace', function(options) {
3374 var self = this;
3375
3376 options.text = options.text || function(option) {
3377 return option[this.settings.labelField];
3378 };
3379
3380 this.onKeyDown = (function() {
3381 var original = self.onKeyDown;
3382 return function(e) {
3383 var index, option;
3384 if (e.keyCode === KEY_BACKSPACE && this.$control_input.val() === '' && !this.$activeItems.length) {
3385 index = this.caretPos - 1;
3386 if (index >= 0 && index < this.items.length) {
3387 option = this.options[this.items[index]];
3388 if (this.deleteSelection(e)) {
3389 this.setTextboxValue(options.text.apply(this, [option]));
3390 this.refreshOptions(true);
3391 }
3392 e.preventDefault();
3393 return;
3394 }
3395 }
3396 return original.apply(this, arguments);
3397 };
3398 })();
3399 });
3400
3401 Selectize.define('select_on_focus', function(options) {
3402 var self = this;
3403
3404 self.on('focus', function() {
3405 var originalFocus = self.onFocus;
3406 return function(e) {
3407 var value = self.getItem(self.getValue()).text();
3408 self.clear();
3409 self.setTextboxValue(value);
3410 self.$control_input.select();
3411 setTimeout( function () {
3412 if (self.settings.selectOnTab) {
3413 self.setActiveOption(self.getFirstItemMatchedByTextContent(value));
3414 }
3415 self.settings.score = null;
3416 },0);
3417 return originalFocus.apply(this, arguments);
3418 };
3419 }());
3420
3421 self.onBlur = (function() {
3422 var originalBlur = self.onBlur;
3423 return function(e) {
3424 if (self.getValue() === "" && self.lastValidValue !== self.getValue()) {
3425 self.setValue(self.lastValidValue);
3426 }
3427 setTimeout( function () {
3428 self.settings.score = function() {
3429 return function() {
3430 return 1;
3431 };
3432 };
3433 }, 0 );
3434 return originalBlur.apply(this, arguments);
3435 }
3436 }());
3437 self.settings.score = function() {
3438 return function() { return 1; };
3439 };
3440
3441 });
3442
3443 Selectize.define('tag_limit', function (options) {
3444 const self = this
3445 options.tagLimit = options.tagLimit
3446 this.onBlur = (function (e) {
3447 const original = self.onBlur
3448
3449 return function (e) {
3450 original.apply(this, e);
3451 if (!e)
3452 return
3453 const $control = this.$control
3454 const $items = $control.find('.item')
3455 const limit = options.tagLimit
3456 if (limit === undefined || $items.length <= limit)
3457 return
3458
3459 $items.toArray().forEach(function(item, index) {
3460 if (index < limit)
3461 return
3462 $(item).hide()
3463 });
3464
3465 $control.append('<span><b>' + ($items.length - limit) + '</b></span>')
3466 };
3467 })()
3468
3469 this.onFocus = (function (e) {
3470 const original = self.onFocus
3471
3472 return function (e) {
3473 original.apply(this, e);
3474 if (!e)
3475 return
3476 const $control = this.$control
3477 const $items = $control.find('.item')
3478 $items.show()
3479 $control.find('span').remove()
3480
3481 };
3482 })()
3483 });
3484
3485 return Selectize;
3486 }));