PluginProbe
Groups – Memberships and Access Control / 1.10.1
Groups – Memberships and Access Control v1.10.1
4.7.1 4.7.0 4.6.0 4.5.0 4.4.0 4.3.0 trunk 1.0.0-beta-1 1.0.0-beta-2 1.0.0-beta-3 1.0.0-beta-3b 1.0.0-beta-3c 1.0.0-beta-3d 1.1.4 1.1.5 1.10.0 1.10.1 1.10.2 1.10.3 1.11.0 1.11.1 1.11.2 1.11.3 1.12.0 1.13.0 All 131 releases
groups / js / selectize / selectize.js

selectize.js in Groups – Memberships and Access Control 1.10.1, at js/selectize/selectize.js

3,669 lines 96.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 /**
2 * sifter.js
3 * Copyright (c) 2013 Brian Reavis & contributors
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
6 * file except in compliance with the License. You may obtain a copy of the License at:
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software distributed under
10 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11 * ANY KIND, either express or implied. See the License for the specific language
12 * governing permissions and limitations under the License.
13 *
14 * @author Brian Reavis <brian@thirdroute.com>
15 */
16
17 (function(root, factory) {
18 if (typeof define === 'function' && define.amd) {
19 define('sifter', factory);
20 } else if (typeof exports === 'object') {
21 module.exports = factory();
22 } else {
23 root.Sifter = factory();
24 }
25 }(this, function() {
26
27 /**
28 * Textually searches arrays and hashes of objects
29 * by property (or multiple properties). Designed
30 * specifically for autocomplete.
31 *
32 * @constructor
33 * @param {array|object} items
34 * @param {object} items
35 */
36 var Sifter = function(items, settings) {
37 this.items = items;
38 this.settings = settings || {diacritics: true};
39 };
40
41 /**
42 * Splits a search string into an array of individual
43 * regexps to be used to match results.
44 *
45 * @param {string} query
46 * @returns {array}
47 */
48 Sifter.prototype.tokenize = function(query) {
49 query = trim(String(query || '').toLowerCase());
50 if (!query || !query.length) return [];
51
52 var i, n, regex, letter;
53 var tokens = [];
54 var words = query.split(/ +/);
55
56 for (i = 0, n = words.length; i < n; i++) {
57 regex = escape_regex(words[i]);
58 if (this.settings.diacritics) {
59 for (letter in DIACRITICS) {
60 if (DIACRITICS.hasOwnProperty(letter)) {
61 regex = regex.replace(new RegExp(letter, 'g'), DIACRITICS[letter]);
62 }
63 }
64 }
65 tokens.push({
66 string : words[i],
67 regex : new RegExp(regex, 'i')
68 });
69 }
70
71 return tokens;
72 };
73
74 /**
75 * Iterates over arrays and hashes.
76 *
77 * ```
78 * this.iterator(this.items, function(item, id) {
79 * // invoked for each item
80 * });
81 * ```
82 *
83 * @param {array|object} object
84 */
85 Sifter.prototype.iterator = function(object, callback) {
86 var iterator;
87 if (is_array(object)) {
88 iterator = Array.prototype.forEach || function(callback) {
89 for (var i = 0, n = this.length; i < n; i++) {
90 callback(this[i], i, this);
91 }
92 };
93 } else {
94 iterator = function(callback) {
95 for (var key in this) {
96 if (this.hasOwnProperty(key)) {
97 callback(this[key], key, this);
98 }
99 }
100 };
101 }
102
103 iterator.apply(object, [callback]);
104 };
105
106 /**
107 * Returns a function to be used to score individual results.
108 *
109 * Good matches will have a higher score than poor matches.
110 * If an item is not a match, 0 will be returned by the function.
111 *
112 * @param {object|string} search
113 * @param {object} options (optional)
114 * @returns {function}
115 */
116 Sifter.prototype.getScoreFunction = function(search, options) {
117 var self, fields, tokens, token_count;
118
119 self = this;
120 search = self.prepareSearch(search, options);
121 tokens = search.tokens;
122 fields = search.options.fields;
123 token_count = tokens.length;
124
125 /**
126 * Calculates how close of a match the
127 * given value is against a search token.
128 *
129 * @param {mixed} value
130 * @param {object} token
131 * @return {number}
132 */
133 var scoreValue = function(value, token) {
134 var score, pos;
135
136 if (!value) return 0;
137 value = String(value || '');
138 pos = value.search(token.regex);
139 if (pos === -1) return 0;
140 score = token.string.length / value.length;
141 if (pos === 0) score += 0.5;
142 return score;
143 };
144
145 /**
146 * Calculates the score of an object
147 * against the search query.
148 *
149 * @param {object} token
150 * @param {object} data
151 * @return {number}
152 */
153 var scoreObject = (function() {
154 var field_count = fields.length;
155 if (!field_count) {
156 return function() { return 0; };
157 }
158 if (field_count === 1) {
159 return function(token, data) {
160 return scoreValue(data[fields[0]], token);
161 };
162 }
163 return function(token, data) {
164 for (var i = 0, sum = 0; i < field_count; i++) {
165 sum += scoreValue(data[fields[i]], token);
166 }
167 return sum / field_count;
168 };
169 })();
170
171 if (!token_count) {
172 return function() { return 0; };
173 }
174 if (token_count === 1) {
175 return function(data) {
176 return scoreObject(tokens[0], data);
177 };
178 }
179
180 if (search.options.conjunction === 'and') {
181 return function(data) {
182 var score;
183 for (var i = 0, sum = 0; i < token_count; i++) {
184 score = scoreObject(tokens[i], data);
185 if (score <= 0) return 0;
186 sum += score;
187 }
188 return sum / token_count;
189 };
190 } else {
191 return function(data) {
192 for (var i = 0, sum = 0; i < token_count; i++) {
193 sum += scoreObject(tokens[i], data);
194 }
195 return sum / token_count;
196 };
197 }
198 };
199
200 /**
201 * Returns a function that can be used to compare two
202 * results, for sorting purposes. If no sorting should
203 * be performed, `null` will be returned.
204 *
205 * @param {string|object} search
206 * @param {object} options
207 * @return function(a,b)
208 */
209 Sifter.prototype.getSortFunction = function(search, options) {
210 var i, n, self, field, fields, fields_count, multiplier, multipliers, get_field, implicit_score, sort;
211
212 self = this;
213 search = self.prepareSearch(search, options);
214 sort = (!search.query && options.sort_empty) || options.sort;
215
216 /**
217 * Fetches the specified sort field value
218 * from a search result item.
219 *
220 * @param {string} name
221 * @param {object} result
222 * @return {mixed}
223 */
224 get_field = function(name, result) {
225 if (name === '$score') return result.score;
226 return self.items[result.id][name];
227 };
228
229 // parse options
230 fields = [];
231 if (sort) {
232 for (i = 0, n = sort.length; i < n; i++) {
233 if (search.query || sort[i].field !== '$score') {
234 fields.push(sort[i]);
235 }
236 }
237 }
238
239 // the "$score" field is implied to be the primary
240 // sort field, unless it's manually specified
241 if (search.query) {
242 implicit_score = true;
243 for (i = 0, n = fields.length; i < n; i++) {
244 if (fields[i].field === '$score') {
245 implicit_score = false;
246 break;
247 }
248 }
249 if (implicit_score) {
250 fields.unshift({field: '$score', direction: 'desc'});
251 }
252 } else {
253 for (i = 0, n = fields.length; i < n; i++) {
254 if (fields[i].field === '$score') {
255 fields.splice(i, 1);
256 break;
257 }
258 }
259 }
260
261 multipliers = [];
262 for (i = 0, n = fields.length; i < n; i++) {
263 multipliers.push(fields[i].direction === 'desc' ? -1 : 1);
264 }
265
266 // build function
267 fields_count = fields.length;
268 if (!fields_count) {
269 return null;
270 } else if (fields_count === 1) {
271 field = fields[0].field;
272 multiplier = multipliers[0];
273 return function(a, b) {
274 return multiplier * cmp(
275 get_field(field, a),
276 get_field(field, b)
277 );
278 };
279 } else {
280 return function(a, b) {
281 var i, result, a_value, b_value, field;
282 for (i = 0; i < fields_count; i++) {
283 field = fields[i].field;
284 result = multipliers[i] * cmp(
285 get_field(field, a),
286 get_field(field, b)
287 );
288 if (result) return result;
289 }
290 return 0;
291 };
292 }
293 };
294
295 /**
296 * Parses a search query and returns an object
297 * with tokens and fields ready to be populated
298 * with results.
299 *
300 * @param {string} query
301 * @param {object} options
302 * @returns {object}
303 */
304 Sifter.prototype.prepareSearch = function(query, options) {
305 if (typeof query === 'object') return query;
306
307 options = extend({}, options);
308
309 var option_fields = options.fields;
310 var option_sort = options.sort;
311 var option_sort_empty = options.sort_empty;
312
313 if (option_fields && !is_array(option_fields)) options.fields = [option_fields];
314 if (option_sort && !is_array(option_sort)) options.sort = [option_sort];
315 if (option_sort_empty && !is_array(option_sort_empty)) options.sort_empty = [option_sort_empty];
316
317 return {
318 options : options,
319 query : String(query || '').toLowerCase(),
320 tokens : this.tokenize(query),
321 total : 0,
322 items : []
323 };
324 };
325
326 /**
327 * Searches through all items and returns a sorted array of matches.
328 *
329 * The `options` parameter can contain:
330 *
331 * - fields {string|array}
332 * - sort {array}
333 * - score {function}
334 * - filter {bool}
335 * - limit {integer}
336 *
337 * Returns an object containing:
338 *
339 * - options {object}
340 * - query {string}
341 * - tokens {array}
342 * - total {int}
343 * - items {array}
344 *
345 * @param {string} query
346 * @param {object} options
347 * @returns {object}
348 */
349 Sifter.prototype.search = function(query, options) {
350 var self = this, value, score, search, calculateScore;
351 var fn_sort;
352 var fn_score;
353
354 search = this.prepareSearch(query, options);
355 options = search.options;
356 query = search.query;
357
358 // generate result scoring function
359 fn_score = options.score || self.getScoreFunction(search);
360
361 // perform search and sort
362 if (query.length) {
363 self.iterator(self.items, function(item, id) {
364 score = fn_score(item);
365 if (options.filter === false || score > 0) {
366 search.items.push({'score': score, 'id': id});
367 }
368 });
369 } else {
370 self.iterator(self.items, function(item, id) {
371 search.items.push({'score': 1, 'id': id});
372 });
373 }
374
375 fn_sort = self.getSortFunction(search, options);
376 if (fn_sort) search.items.sort(fn_sort);
377
378 // apply limits
379 search.total = search.items.length;
380 if (typeof options.limit === 'number') {
381 search.items = search.items.slice(0, options.limit);
382 }
383
384 return search;
385 };
386
387 // utilities
388 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
389
390 var cmp = function(a, b) {
391 if (typeof a === 'number' && typeof b === 'number') {
392 return a > b ? 1 : (a < b ? -1 : 0);
393 }
394 a = asciifold(String(a || ''));
395 b = asciifold(String(b || ''));
396 if (a > b) return 1;
397 if (b > a) return -1;
398 return 0;
399 };
400
401 var extend = function(a, b) {
402 var i, n, k, object;
403 for (i = 1, n = arguments.length; i < n; i++) {
404 object = arguments[i];
405 if (!object) continue;
406 for (k in object) {
407 if (object.hasOwnProperty(k)) {
408 a[k] = object[k];
409 }
410 }
411 }
412 return a;
413 };
414
415 var trim = function(str) {
416 return (str + '').replace(/^\s+|\s+$|/g, '');
417 };
418
419 var escape_regex = function(str) {
420 return (str + '').replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
421 };
422
423 var is_array = Array.isArray || ($ && $.isArray) || function(object) {
424 return Object.prototype.toString.call(object) === '[object Array]';
425 };
426
427 var DIACRITICS = {
428 'a': '[aÀÁÂÃÄ�
429 àáâãäåĀā�
430 Ą]',
431 'c': '[cÇçćĆčČ]',
432 'd': '[dđĐďĎ]',
433 'e': '[eÈÉÊËèéêëěĚĒēęĘ]',
434 'i': '[iÌÍÎÏìíîïĪī]',
435 'l': '[lłŁ]',
436 'n': '[nÑñňŇńŃ]',
437 'o': '[oÒÓÔÕÕÖØòóôõöøŌō]',
438 'r': '[rřŘ]',
439 's': '[sŠšśŚ]',
440 't': '[tťŤ]',
441 'u': '[uÙÚÛÜùúûüůŮŪū]',
442 'y': '[yŸÿýÝ]',
443 'z': '[zŽžżŻźŹ]'
444 };
445
446 var asciifold = (function() {
447 var i, n, k, chunk;
448 var foreignletters = '';
449 var lookup = {};
450 for (k in DIACRITICS) {
451 if (DIACRITICS.hasOwnProperty(k)) {
452 chunk = DIACRITICS[k].substring(2, DIACRITICS[k].length - 1);
453 foreignletters += chunk;
454 for (i = 0, n = chunk.length; i < n; i++) {
455 lookup[chunk.charAt(i)] = k;
456 }
457 }
458 }
459 var regexp = new RegExp('[' + foreignletters + ']', 'g');
460 return function(str) {
461 return str.replace(regexp, function(foreignletter) {
462 return lookup[foreignletter];
463 }).toLowerCase();
464 };
465 })();
466
467
468 // export
469 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
470
471 return Sifter;
472 }));
473
474
475
476 /**
477 * microplugin.js
478 * Copyright (c) 2013 Brian Reavis & contributors
479 *
480 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
481 * file except in compliance with the License. You may obtain a copy of the License at:
482 * http://www.apache.org/licenses/LICENSE-2.0
483 *
484 * Unless required by applicable law or agreed to in writing, software distributed under
485 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
486 * ANY KIND, either express or implied. See the License for the specific language
487 * governing permissions and limitations under the License.
488 *
489 * @author Brian Reavis <brian@thirdroute.com>
490 */
491
492 (function(root, factory) {
493 if (typeof define === 'function' && define.amd) {
494 define('microplugin', factory);
495 } else if (typeof exports === 'object') {
496 module.exports = factory();
497 } else {
498 root.MicroPlugin = factory();
499 }
500 }(this, function() {
501 var MicroPlugin = {};
502
503 MicroPlugin.mixin = function(Interface) {
504 Interface.plugins = {};
505
506 /**
507 * Initializes the listed plugins (with options).
508 * Acceptable formats:
509 *
510 * List (without options):
511 * ['a', 'b', 'c']
512 *
513 * List (with options):
514 * [{'name': 'a', options: {}}, {'name': 'b', options: {}}]
515 *
516 * Hash (with options):
517 * {'a': { ... }, 'b': { ... }, 'c': { ... }}
518 *
519 * @param {mixed} plugins
520 */
521 Interface.prototype.initializePlugins = function(plugins) {
522 var i, n, key;
523 var self = this;
524 var queue = [];
525
526 self.plugins = {
527 names : [],
528 settings : {},
529 requested : {},
530 loaded : {}
531 };
532
533 if (utils.isArray(plugins)) {
534 for (i = 0, n = plugins.length; i < n; i++) {
535 if (typeof plugins[i] === 'string') {
536 queue.push(plugins[i]);
537 } else {
538 self.plugins.settings[plugins[i].name] = plugins[i].options;
539 queue.push(plugins[i].name);
540 }
541 }
542 } else if (plugins) {
543 for (key in plugins) {
544 if (plugins.hasOwnProperty(key)) {
545 self.plugins.settings[key] = plugins[key];
546 queue.push(key);
547 }
548 }
549 }
550
551 while (queue.length) {
552 self.require(queue.shift());
553 }
554 };
555
556 Interface.prototype.loadPlugin = function(name) {
557 var self = this;
558 var plugins = self.plugins;
559 var plugin = Interface.plugins[name];
560
561 if (!Interface.plugins.hasOwnProperty(name)) {
562 throw new Error('Unable to find "' + name + '" plugin');
563 }
564
565 plugins.requested[name] = true;
566 plugins.loaded[name] = plugin.fn.apply(self, [self.plugins.settings[name] || {}]);
567 plugins.names.push(name);
568 };
569
570 /**
571 * Initializes a plugin.
572 *
573 * @param {string} name
574 */
575 Interface.prototype.require = function(name) {
576 var self = this;
577 var plugins = self.plugins;
578
579 if (!self.plugins.loaded.hasOwnProperty(name)) {
580 if (plugins.requested[name]) {
581 throw new Error('Plugin has circular dependency ("' + name + '")');
582 }
583 self.loadPlugin(name);
584 }
585
586 return plugins.loaded[name];
587 };
588
589 /**
590 * Registers a plugin.
591 *
592 * @param {string} name
593 * @param {function} fn
594 */
595 Interface.define = function(name, fn) {
596 Interface.plugins[name] = {
597 'name' : name,
598 'fn' : fn
599 };
600 };
601 };
602
603 var utils = {
604 isArray: Array.isArray || function(vArg) {
605 return Object.prototype.toString.call(vArg) === '[object Array]';
606 }
607 };
608
609 return MicroPlugin;
610 }));
611
612 /**
613 * selectize.js (v0.12.1)
614 * Copyright (c) 2013–2015 Brian Reavis & contributors
615 *
616 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
617 * file except in compliance with the License. You may obtain a copy of the License at:
618 * http://www.apache.org/licenses/LICENSE-2.0
619 *
620 * Unless required by applicable law or agreed to in writing, software distributed under
621 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
622 * ANY KIND, either express or implied. See the License for the specific language
623 * governing permissions and limitations under the License.
624 *
625 * @author Brian Reavis <brian@thirdroute.com>
626 */
627
628 /*jshint curly:false */
629 /*jshint browser:true */
630
631 (function(root, factory) {
632 if (typeof define === 'function' && define.amd) {
633 define('selectize', ['jquery','sifter','microplugin'], factory);
634 } else if (typeof exports === 'object') {
635 module.exports = factory(require('jquery'), require('sifter'), require('microplugin'));
636 } else {
637 root.Selectize = factory(root.jQuery, root.Sifter, root.MicroPlugin);
638 }
639 }(this, function($, Sifter, MicroPlugin) {
640 'use strict';
641
642 var highlight = function($element, pattern) {
643 if (typeof pattern === 'string' && !pattern.length) return;
644 var regex = (typeof pattern === 'string') ? new RegExp(pattern, 'i') : pattern;
645
646 var highlight = function(node) {
647 var skip = 0;
648 if (node.nodeType === 3) {
649 var pos = node.data.search(regex);
650 if (pos >= 0 && node.data.length > 0) {
651 var match = node.data.match(regex);
652 var spannode = document.createElement('span');
653 spannode.className = 'highlight';
654 var middlebit = node.splitText(pos);
655 var endbit = middlebit.splitText(match[0].length);
656 var middleclone = middlebit.cloneNode(true);
657 spannode.appendChild(middleclone);
658 middlebit.parentNode.replaceChild(spannode, middlebit);
659 skip = 1;
660 }
661 } else if (node.nodeType === 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
662 for (var i = 0; i < node.childNodes.length; ++i) {
663 i += highlight(node.childNodes[i]);
664 }
665 }
666 return skip;
667 };
668
669 return $element.each(function() {
670 highlight(this);
671 });
672 };
673
674 var MicroEvent = function() {};
675 MicroEvent.prototype = {
676 on: function(event, fct){
677 this._events = this._events || {};
678 this._events[event] = this._events[event] || [];
679 this._events[event].push(fct);
680 },
681 off: function(event, fct){
682 var n = arguments.length;
683 if (n === 0) return delete this._events;
684 if (n === 1) return delete this._events[event];
685
686 this._events = this._events || {};
687 if (event in this._events === false) return;
688 this._events[event].splice(this._events[event].indexOf(fct), 1);
689 },
690 trigger: function(event /* , args... */){
691 this._events = this._events || {};
692 if (event in this._events === false) return;
693 for (var i = 0; i < this._events[event].length; i++){
694 this._events[event][i].apply(this, Array.prototype.slice.call(arguments, 1));
695 }
696 }
697 };
698
699 /**
700 * Mixin will delegate all MicroEvent.js function in the destination object.
701 *
702 * - MicroEvent.mixin(Foobar) will make Foobar able to use MicroEvent
703 *
704 * @param {object} the object which will support MicroEvent
705 */
706 MicroEvent.mixin = function(destObject){
707 var props = ['on', 'off', 'trigger'];
708 for (var i = 0; i < props.length; i++){
709 destObject.prototype[props[i]] = MicroEvent.prototype[props[i]];
710 }
711 };
712
713 var IS_MAC = /Mac/.test(navigator.userAgent);
714
715 var KEY_A = 65;
716 var KEY_COMMA = 188;
717 var KEY_RETURN = 13;
718 var KEY_ESC = 27;
719 var KEY_LEFT = 37;
720 var KEY_UP = 38;
721 var KEY_P = 80;
722 var KEY_RIGHT = 39;
723 var KEY_DOWN = 40;
724 var KEY_N = 78;
725 var KEY_BACKSPACE = 8;
726 var KEY_DELETE = 46;
727 var KEY_SHIFT = 16;
728 var KEY_CMD = IS_MAC ? 91 : 17;
729 var KEY_CTRL = IS_MAC ? 18 : 17;
730 var KEY_TAB = 9;
731
732 var TAG_SELECT = 1;
733 var TAG_INPUT = 2;
734
735 // for now, android support in general is too spotty to support validity
736 var SUPPORTS_VALIDITY_API = !/android/i.test(window.navigator.userAgent) && !!document.createElement('form').validity;
737
738 var isset = function(object) {
739 return typeof object !== 'undefined';
740 };
741
742 /**
743 * Converts a scalar to its best string representation
744 * for hash keys and HTML attribute values.
745 *
746 * Transformations:
747 * 'str' -> 'str'
748 * null -> ''
749 * undefined -> ''
750 * true -> '1'
751 * false -> '0'
752 * 0 -> '0'
753 * 1 -> '1'
754 *
755 * @param {string} value
756 * @returns {string|null}
757 */
758 var hash_key = function(value) {
759 if (typeof value === 'undefined' || value === null) return null;
760 if (typeof value === 'boolean') return value ? '1' : '0';
761 return value + '';
762 };
763
764 /**
765 * Escapes a string for use within HTML.
766 *
767 * @param {string} str
768 * @returns {string}
769 */
770 var escape_html = function(str) {
771 return (str + '')
772 .replace(/&/g, '&amp;')
773 .replace(/</g, '&lt;')
774 .replace(/>/g, '&gt;')
775 .replace(/"/g, '&quot;');
776 };
777
778 /**
779 * Escapes "$" characters in replacement strings.
780 *
781 * @param {string} str
782 * @returns {string}
783 */
784 var escape_replace = function(str) {
785 return (str + '').replace(/\$/g, '$$$$');
786 };
787
788 var hook = {};
789
790 /**
791 * Wraps `method` on `self` so that `fn`
792 * is invoked before the original method.
793 *
794 * @param {object} self
795 * @param {string} method
796 * @param {function} fn
797 */
798 hook.before = function(self, method, fn) {
799 var original = self[method];
800 self[method] = function() {
801 fn.apply(self, arguments);
802 return original.apply(self, arguments);
803 };
804 };
805
806 /**
807 * Wraps `method` on `self` so that `fn`
808 * is invoked after the original method.
809 *
810 * @param {object} self
811 * @param {string} method
812 * @param {function} fn
813 */
814 hook.after = function(self, method, fn) {
815 var original = self[method];
816 self[method] = function() {
817 var result = original.apply(self, arguments);
818 fn.apply(self, arguments);
819 return result;
820 };
821 };
822
823 /**
824 * Wraps `fn` so that it can only be invoked once.
825 *
826 * @param {function} fn
827 * @returns {function}
828 */
829 var once = function(fn) {
830 var called = false;
831 return function() {
832 if (called) return;
833 called = true;
834 fn.apply(this, arguments);
835 };
836 };
837
838 /**
839 * Wraps `fn` so that it can only be called once
840 * every `delay` milliseconds (invoked on the falling edge).
841 *
842 * @param {function} fn
843 * @param {int} delay
844 * @returns {function}
845 */
846 var debounce = function(fn, delay) {
847 var timeout;
848 return function() {
849 var self = this;
850 var args = arguments;
851 window.clearTimeout(timeout);
852 timeout = window.setTimeout(function() {
853 fn.apply(self, args);
854 }, delay);
855 };
856 };
857
858 /**
859 * Debounce all fired events types listed in `types`
860 * while executing the provided `fn`.
861 *
862 * @param {object} self
863 * @param {array} types
864 * @param {function} fn
865 */
866 var debounce_events = function(self, types, fn) {
867 var type;
868 var trigger = self.trigger;
869 var event_args = {};
870
871 // override trigger method
872 self.trigger = function() {
873 var type = arguments[0];
874 if (types.indexOf(type) !== -1) {
875 event_args[type] = arguments;
876 } else {
877 return trigger.apply(self, arguments);
878 }
879 };
880
881 // invoke provided function
882 fn.apply(self, []);
883 self.trigger = trigger;
884
885 // trigger queued events
886 for (type in event_args) {
887 if (event_args.hasOwnProperty(type)) {
888 trigger.apply(self, event_args[type]);
889 }
890 }
891 };
892
893 /**
894 * A workaround for http://bugs.jquery.com/ticket/6696
895 *
896 * @param {object} $parent - Parent element to listen on.
897 * @param {string} event - Event name.
898 * @param {string} selector - Descendant selector to filter by.
899 * @param {function} fn - Event handler.
900 */
901 var watchChildEvent = function($parent, event, selector, fn) {
902 $parent.on(event, selector, function(e) {
903 var child = e.target;
904 while (child && child.parentNode !== $parent[0]) {
905 child = child.parentNode;
906 }
907 e.currentTarget = child;
908 return fn.apply(this, [e]);
909 });
910 };
911
912 /**
913 * Determines the current selection within a text input control.
914 * Returns an object containing:
915 * - start
916 * - length
917 *
918 * @param {object} input
919 * @returns {object}
920 */
921 var getSelection = function(input) {
922 var result = {};
923 if ('selectionStart' in input) {
924 result.start = input.selectionStart;
925 result.length = input.selectionEnd - result.start;
926 } else if (document.selection) {
927 input.focus();
928 var sel = document.selection.createRange();
929 var selLen = document.selection.createRange().text.length;
930 sel.moveStart('character', -input.value.length);
931 result.start = sel.text.length - selLen;
932 result.length = selLen;
933 }
934 return result;
935 };
936
937 /**
938 * Copies CSS properties from one element to another.
939 *
940 * @param {object} $from
941 * @param {object} $to
942 * @param {array} properties
943 */
944 var transferStyles = function($from, $to, properties) {
945 var i, n, styles = {};
946 if (properties) {
947 for (i = 0, n = properties.length; i < n; i++) {
948 styles[properties[i]] = $from.css(properties[i]);
949 }
950 } else {
951 styles = $from.css();
952 }
953 $to.css(styles);
954 };
955
956 /**
957 * Measures the width of a string within a
958 * parent element (in pixels).
959 *
960 * @param {string} str
961 * @param {object} $parent
962 * @returns {int}
963 */
964 var measureString = function(str, $parent) {
965 if (!str) {
966 return 0;
967 }
968
969 var $test = $('<test>').css({
970 position: 'absolute',
971 top: -99999,
972 left: -99999,
973 width: 'auto',
974 padding: 0,
975 whiteSpace: 'pre'
976 }).text(str).appendTo('body');
977
978 transferStyles($parent, $test, [
979 'letterSpacing',
980 'fontSize',
981 'fontFamily',
982 'fontWeight',
983 'textTransform'
984 ]);
985
986 var width = $test.width();
987 $test.remove();
988
989 return width;
990 };
991
992 /**
993 * Sets up an input to grow horizontally as the user
994 * types. If the value is changed manually, you can
995 * trigger the "update" handler to resize:
996 *
997 * $input.trigger('update');
998 *
999 * @param {object} $input
1000 */
1001 var autoGrow = function($input) {
1002 var currentWidth = null;
1003
1004 var update = function(e, options) {
1005 var value, keyCode, printable, placeholder, width;
1006 var shift, character, selection;
1007 e = e || window.event || {};
1008 options = options || {};
1009
1010 if (e.metaKey || e.altKey) return;
1011 if (!options.force && $input.data('grow') === false) return;
1012
1013 value = $input.val();
1014 if (e.type && e.type.toLowerCase() === 'keydown') {
1015 keyCode = e.keyCode;
1016 printable = (
1017 (keyCode >= 97 && keyCode <= 122) || // a-z
1018 (keyCode >= 65 && keyCode <= 90) || // A-Z
1019 (keyCode >= 48 && keyCode <= 57) || // 0-9
1020 keyCode === 32 // space
1021 );
1022
1023 if (keyCode === KEY_DELETE || keyCode === KEY_BACKSPACE) {
1024 selection = getSelection($input[0]);
1025 if (selection.length) {
1026 value = value.substring(0, selection.start) + value.substring(selection.start + selection.length);
1027 } else if (keyCode === KEY_BACKSPACE && selection.start) {
1028 value = value.substring(0, selection.start - 1) + value.substring(selection.start + 1);
1029 } else if (keyCode === KEY_DELETE && typeof selection.start !== 'undefined') {
1030 value = value.substring(0, selection.start) + value.substring(selection.start + 1);
1031 }
1032 } else if (printable) {
1033 shift = e.shiftKey;
1034 character = String.fromCharCode(e.keyCode);
1035 if (shift) character = character.toUpperCase();
1036 else character = character.toLowerCase();
1037 value += character;
1038 }
1039 }
1040
1041 placeholder = $input.attr('placeholder');
1042 if (!value && placeholder) {
1043 value = placeholder;
1044 }
1045
1046 width = measureString(value, $input) + 4;
1047 if (width !== currentWidth) {
1048 currentWidth = width;
1049 $input.width(width);
1050 $input.triggerHandler('resize');
1051 }
1052 };
1053
1054 $input.on('keydown keyup update blur', update);
1055 update();
1056 };
1057
1058 var Selectize = function($input, settings) {
1059 var key, i, n, dir, input, self = this;
1060 input = $input[0];
1061 input.selectize = self;
1062
1063 // detect rtl environment
1064 var computedStyle = window.getComputedStyle && window.getComputedStyle(input, null);
1065 dir = computedStyle ? computedStyle.getPropertyValue('direction') : input.currentStyle && input.currentStyle.direction;
1066 dir = dir || $input.parents('[dir]:first').attr('dir') || '';
1067
1068 // setup default state
1069 $.extend(self, {
1070 order : 0,
1071 settings : settings,
1072 $input : $input,
1073 tabIndex : $input.attr('tabindex') || '',
1074 tagType : input.tagName.toLowerCase() === 'select' ? TAG_SELECT : TAG_INPUT,
1075 rtl : /rtl/i.test(dir),
1076
1077 eventNS : '.selectize' + (++Selectize.count),
1078 highlightedValue : null,
1079 isOpen : false,
1080 isDisabled : false,
1081 isRequired : $input.is('[required]'),
1082 isInvalid : false,
1083 isLocked : false,
1084 isFocused : false,
1085 isInputHidden : false,
1086 isSetup : false,
1087 isShiftDown : false,
1088 isCmdDown : false,
1089 isCtrlDown : false,
1090 ignoreFocus : false,
1091 ignoreBlur : false,
1092 ignoreHover : false,
1093 hasOptions : false,
1094 currentResults : null,
1095 lastValue : '',
1096 caretPos : 0,
1097 loading : 0,
1098 loadedSearches : {},
1099
1100 $activeOption : null,
1101 $activeItems : [],
1102
1103 optgroups : {},
1104 options : {},
1105 userOptions : {},
1106 items : [],
1107 renderCache : {},
1108 onSearchChange : settings.loadThrottle === null ? self.onSearchChange : debounce(self.onSearchChange, settings.loadThrottle)
1109 });
1110
1111 // search system
1112 self.sifter = new Sifter(this.options, {diacritics: settings.diacritics});
1113
1114 // build options table
1115 if (self.settings.options) {
1116 for (i = 0, n = self.settings.options.length; i < n; i++) {
1117 self.registerOption(self.settings.options[i]);
1118 }
1119 delete self.settings.options;
1120 }
1121
1122 // build optgroup table
1123 if (self.settings.optgroups) {
1124 for (i = 0, n = self.settings.optgroups.length; i < n; i++) {
1125 self.registerOptionGroup(self.settings.optgroups[i]);
1126 }
1127 delete self.settings.optgroups;
1128 }
1129
1130 // option-dependent defaults
1131 self.settings.mode = self.settings.mode || (self.settings.maxItems === 1 ? 'single' : 'multi');
1132 if (typeof self.settings.hideSelected !== 'boolean') {
1133 self.settings.hideSelected = self.settings.mode === 'multi';
1134 }
1135
1136 self.initializePlugins(self.settings.plugins);
1137 self.setupCallbacks();
1138 self.setupTemplates();
1139 self.setup();
1140 };
1141
1142 // mixins
1143 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1144
1145 MicroEvent.mixin(Selectize);
1146 MicroPlugin.mixin(Selectize);
1147
1148 // methods
1149 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1150
1151 $.extend(Selectize.prototype, {
1152
1153 /**
1154 * Creates all elements and sets up event bindings.
1155 */
1156 setup: function() {
1157 var self = this;
1158 var settings = self.settings;
1159 var eventNS = self.eventNS;
1160 var $window = $(window);
1161 var $document = $(document);
1162 var $input = self.$input;
1163
1164 var $wrapper;
1165 var $control;
1166 var $control_input;
1167 var $dropdown;
1168 var $dropdown_content;
1169 var $dropdown_parent;
1170 var inputMode;
1171 var timeout_blur;
1172 var timeout_focus;
1173 var classes;
1174 var classes_plugins;
1175
1176 inputMode = self.settings.mode;
1177 classes = $input.attr('class') || '';
1178
1179 $wrapper = $('<div>').addClass(settings.wrapperClass).addClass(classes).addClass(inputMode);
1180 $control = $('<div>').addClass(settings.inputClass).addClass('items').appendTo($wrapper);
1181 $control_input = $('<input type="text" autocomplete="off" />').appendTo($control).attr('tabindex', $input.is(':disabled') ? '-1' : self.tabIndex);
1182 $dropdown_parent = $(settings.dropdownParent || $wrapper);
1183 $dropdown = $('<div>').addClass(settings.dropdownClass).addClass(inputMode).hide().appendTo($dropdown_parent);
1184 $dropdown_content = $('<div>').addClass(settings.dropdownContentClass).appendTo($dropdown);
1185
1186 if(self.settings.copyClassesToDropdown) {
1187 $dropdown.addClass(classes);
1188 }
1189
1190 $wrapper.css({
1191 width: $input[0].style.width
1192 });
1193
1194 if (self.plugins.names.length) {
1195 classes_plugins = 'plugin-' + self.plugins.names.join(' plugin-');
1196 $wrapper.addClass(classes_plugins);
1197 $dropdown.addClass(classes_plugins);
1198 }
1199
1200 if ((settings.maxItems === null || settings.maxItems > 1) && self.tagType === TAG_SELECT) {
1201 $input.attr('multiple', 'multiple');
1202 }
1203
1204 if (self.settings.placeholder) {
1205 $control_input.attr('placeholder', settings.placeholder);
1206 }
1207
1208 // if splitOn was not passed in, construct it from the delimiter to allow pasting universally
1209 if (!self.settings.splitOn && self.settings.delimiter) {
1210 var delimiterEscaped = self.settings.delimiter.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
1211 self.settings.splitOn = new RegExp('\\s*' + delimiterEscaped + '+\\s*');
1212 }
1213
1214 if ($input.attr('autocorrect')) {
1215 $control_input.attr('autocorrect', $input.attr('autocorrect'));
1216 }
1217
1218 if ($input.attr('autocapitalize')) {
1219 $control_input.attr('autocapitalize', $input.attr('autocapitalize'));
1220 }
1221
1222 self.$wrapper = $wrapper;
1223 self.$control = $control;
1224 self.$control_input = $control_input;
1225 self.$dropdown = $dropdown;
1226 self.$dropdown_content = $dropdown_content;
1227
1228 $dropdown.on('mouseenter', '[data-selectable]', function() { return self.onOptionHover.apply(self, arguments); });
1229 $dropdown.on('mousedown click', '[data-selectable]', function() { return self.onOptionSelect.apply(self, arguments); });
1230 watchChildEvent($control, 'mousedown', '*:not(input)', function() { return self.onItemSelect.apply(self, arguments); });
1231 autoGrow($control_input);
1232
1233 $control.on({
1234 mousedown : function() { return self.onMouseDown.apply(self, arguments); },
1235 click : function() { return self.onClick.apply(self, arguments); }
1236 });
1237
1238 $control_input.on({
1239 mousedown : function(e) { e.stopPropagation(); },
1240 keydown : function() { return self.onKeyDown.apply(self, arguments); },
1241 keyup : function() { return self.onKeyUp.apply(self, arguments); },
1242 keypress : function() { return self.onKeyPress.apply(self, arguments); },
1243 resize : function() { self.positionDropdown.apply(self, []); },
1244 blur : function() { return self.onBlur.apply(self, arguments); },
1245 focus : function() { self.ignoreBlur = false; return self.onFocus.apply(self, arguments); },
1246 paste : function() { return self.onPaste.apply(self, arguments); }
1247 });
1248
1249 $document.on('keydown' + eventNS, function(e) {
1250 self.isCmdDown = e[IS_MAC ? 'metaKey' : 'ctrlKey'];
1251 self.isCtrlDown = e[IS_MAC ? 'altKey' : 'ctrlKey'];
1252 self.isShiftDown = e.shiftKey;
1253 });
1254
1255 $document.on('keyup' + eventNS, function(e) {
1256 if (e.keyCode === KEY_CTRL) self.isCtrlDown = false;
1257 if (e.keyCode === KEY_SHIFT) self.isShiftDown = false;
1258 if (e.keyCode === KEY_CMD) self.isCmdDown = false;
1259 });
1260
1261 $document.on('mousedown' + eventNS, function(e) {
1262 if (self.isFocused) {
1263 // prevent events on the dropdown scrollbar from causing the control to blur
1264 if (e.target === self.$dropdown[0] || e.target.parentNode === self.$dropdown[0]) {
1265 return false;
1266 }
1267 // blur on click outside
1268 if (!self.$control.has(e.target).length && e.target !== self.$control[0]) {
1269 self.blur(e.target);
1270 }
1271 }
1272 });
1273
1274 $window.on(['scroll' + eventNS, 'resize' + eventNS].join(' '), function() {
1275 if (self.isOpen) {
1276 self.positionDropdown.apply(self, arguments);
1277 }
1278 });
1279 $window.on('mousemove' + eventNS, function() {
1280 self.ignoreHover = false;
1281 });
1282
1283 // store original children and tab index so that they can be
1284 // restored when the destroy() method is called.
1285 this.revertSettings = {
1286 $children : $input.children().detach(),
1287 tabindex : $input.attr('tabindex')
1288 };
1289
1290 $input.attr('tabindex', -1).hide().after(self.$wrapper);
1291
1292 if ($.isArray(settings.items)) {
1293 self.setValue(settings.items);
1294 delete settings.items;
1295 }
1296
1297 // feature detect for the validation API
1298 if (SUPPORTS_VALIDITY_API) {
1299 $input.on('invalid' + eventNS, function(e) {
1300 e.preventDefault();
1301 self.isInvalid = true;
1302 self.refreshState();
1303 });
1304 }
1305
1306 self.updateOriginalInput();
1307 self.refreshItems();
1308 self.refreshState();
1309 self.updatePlaceholder();
1310 self.isSetup = true;
1311
1312 if ($input.is(':disabled')) {
1313 self.disable();
1314 }
1315
1316 self.on('change', this.onChange);
1317
1318 $input.data('selectize', self);
1319 $input.addClass('selectized');
1320 self.trigger('initialize');
1321
1322 // preload options
1323 if (settings.preload === true) {
1324 self.onSearchChange('');
1325 }
1326
1327 },
1328
1329 /**
1330 * Sets up default rendering functions.
1331 */
1332 setupTemplates: function() {
1333 var self = this;
1334 var field_label = self.settings.labelField;
1335 var field_optgroup = self.settings.optgroupLabelField;
1336
1337 var templates = {
1338 'optgroup': function(data) {
1339 return '<div class="optgroup">' + data.html + '</div>';
1340 },
1341 'optgroup_header': function(data, escape) {
1342 return '<div class="optgroup-header">' + escape(data[field_optgroup]) + '</div>';
1343 },
1344 'option': function(data, escape) {
1345 return '<div class="option">' + escape(data[field_label]) + '</div>';
1346 },
1347 'item': function(data, escape) {
1348 return '<div class="item">' + escape(data[field_label]) + '</div>';
1349 },
1350 'option_create': function(data, escape) {
1351 return '<div class="create">Add <strong>' + escape(data.input) + '</strong>&hellip;</div>';
1352 }
1353 };
1354
1355 self.settings.render = $.extend({}, templates, self.settings.render);
1356 },
1357
1358 /**
1359 * Maps fired events to callbacks provided
1360 * in the settings used when creating the control.
1361 */
1362 setupCallbacks: function() {
1363 var key, fn, callbacks = {
1364 'initialize' : 'onInitialize',
1365 'change' : 'onChange',
1366 'item_add' : 'onItemAdd',
1367 'item_remove' : 'onItemRemove',
1368 'clear' : 'onClear',
1369 'option_add' : 'onOptionAdd',
1370 'option_remove' : 'onOptionRemove',
1371 'option_clear' : 'onOptionClear',
1372 'optgroup_add' : 'onOptionGroupAdd',
1373 'optgroup_remove' : 'onOptionGroupRemove',
1374 'optgroup_clear' : 'onOptionGroupClear',
1375 'dropdown_open' : 'onDropdownOpen',
1376 'dropdown_close' : 'onDropdownClose',
1377 'type' : 'onType',
1378 'load' : 'onLoad',
1379 'focus' : 'onFocus',
1380 'blur' : 'onBlur'
1381 };
1382
1383 for (key in callbacks) {
1384 if (callbacks.hasOwnProperty(key)) {
1385 fn = this.settings[callbacks[key]];
1386 if (fn) this.on(key, fn);
1387 }
1388 }
1389 },
1390
1391 /**
1392 * Triggered when the main control element
1393 * has a click event.
1394 *
1395 * @param {object} e
1396 * @return {boolean}
1397 */
1398 onClick: function(e) {
1399 var self = this;
1400
1401 // necessary for mobile webkit devices (manual focus triggering
1402 // is ignored unless invoked within a click event)
1403 if (!self.isFocused) {
1404 self.focus();
1405 e.preventDefault();
1406 }
1407 },
1408
1409 /**
1410 * Triggered when the main control element
1411 * has a mouse down event.
1412 *
1413 * @param {object} e
1414 * @return {boolean}
1415 */
1416 onMouseDown: function(e) {
1417 var self = this;
1418 var defaultPrevented = e.isDefaultPrevented();
1419 var $target = $(e.target);
1420
1421 if (self.isFocused) {
1422 // retain focus by preventing native handling. if the
1423 // event target is the input it should not be modified.
1424 // otherwise, text selection within the input won't work.
1425 if (e.target !== self.$control_input[0]) {
1426 if (self.settings.mode === 'single') {
1427 // toggle dropdown
1428 self.isOpen ? self.close() : self.open();
1429 } else if (!defaultPrevented) {
1430 self.setActiveItem(null);
1431 }
1432 return false;
1433 }
1434 } else {
1435 // give control focus
1436 if (!defaultPrevented) {
1437 window.setTimeout(function() {
1438 self.focus();
1439 }, 0);
1440 }
1441 }
1442 },
1443
1444 /**
1445 * Triggered when the value of the control has been changed.
1446 * This should propagate the event to the original DOM
1447 * input / select element.
1448 */
1449 onChange: function() {
1450 this.$input.trigger('change');
1451 },
1452
1453 /**
1454 * Triggered on <input> paste.
1455 *
1456 * @param {object} e
1457 * @returns {boolean}
1458 */
1459 onPaste: function(e) {
1460 var self = this;
1461 if (self.isFull() || self.isInputHidden || self.isLocked) {
1462 e.preventDefault();
1463 } else {
1464 // If a regex or string is included, this will split the pasted
1465 // input and create Items for each separate value
1466 if (self.settings.splitOn) {
1467 setTimeout(function() {
1468 var splitInput = $.trim(self.$control_input.val() || '').split(self.settings.splitOn);
1469 for (var i = 0, n = splitInput.length; i < n; i++) {
1470 self.createItem(splitInput[i]);
1471 }
1472 }, 0);
1473 }
1474 }
1475 },
1476
1477 /**
1478 * Triggered on <input> keypress.
1479 *
1480 * @param {object} e
1481 * @returns {boolean}
1482 */
1483 onKeyPress: function(e) {
1484 if (this.isLocked) return e && e.preventDefault();
1485 var character = String.fromCharCode(e.keyCode || e.which);
1486 if (this.settings.create && this.settings.mode === 'multi' && character === this.settings.delimiter) {
1487 this.createItem();
1488 e.preventDefault();
1489 return false;
1490 }
1491 },
1492
1493 /**
1494 * Triggered on <input> keydown.
1495 *
1496 * @param {object} e
1497 * @returns {boolean}
1498 */
1499 onKeyDown: function(e) {
1500 var isInput = e.target === this.$control_input[0];
1501 var self = this;
1502
1503 if (self.isLocked) {
1504 if (e.keyCode !== KEY_TAB) {
1505 e.preventDefault();
1506 }
1507 return;
1508 }
1509
1510 switch (e.keyCode) {
1511 case KEY_A:
1512 if (self.isCmdDown) {
1513 self.selectAll();
1514 return;
1515 }
1516 break;
1517 case KEY_ESC:
1518 if (self.isOpen) {
1519 e.preventDefault();
1520 e.stopPropagation();
1521 self.close();
1522 }
1523 return;
1524 case KEY_N:
1525 if (!e.ctrlKey || e.altKey) break;
1526 case KEY_DOWN:
1527 if (!self.isOpen && self.hasOptions) {
1528 self.open();
1529 } else if (self.$activeOption) {
1530 self.ignoreHover = true;
1531 var $next = self.getAdjacentOption(self.$activeOption, 1);
1532 if ($next.length) self.setActiveOption($next, true, true);
1533 }
1534 e.preventDefault();
1535 return;
1536 case KEY_P:
1537 if (!e.ctrlKey || e.altKey) break;
1538 case KEY_UP:
1539 if (self.$activeOption) {
1540 self.ignoreHover = true;
1541 var $prev = self.getAdjacentOption(self.$activeOption, -1);
1542 if ($prev.length) self.setActiveOption($prev, true, true);
1543 }
1544 e.preventDefault();
1545 return;
1546 case KEY_RETURN:
1547 if (self.isOpen && self.$activeOption) {
1548 self.onOptionSelect({currentTarget: self.$activeOption});
1549 e.preventDefault();
1550 }
1551 return;
1552 case KEY_LEFT:
1553 self.advanceSelection(-1, e);
1554 return;
1555 case KEY_RIGHT:
1556 self.advanceSelection(1, e);
1557 return;
1558 case KEY_TAB:
1559 if (self.settings.selectOnTab && self.isOpen && self.$activeOption) {
1560 self.onOptionSelect({currentTarget: self.$activeOption});
1561
1562 // Default behaviour is to jump to the next field, we only want this
1563 // if the current field doesn't accept any more entries
1564 if (!self.isFull()) {
1565 e.preventDefault();
1566 }
1567 }
1568 if (self.settings.create && self.createItem()) {
1569 e.preventDefault();
1570 }
1571 return;
1572 case KEY_BACKSPACE:
1573 case KEY_DELETE:
1574 self.deleteSelection(e);
1575 return;
1576 }
1577
1578 if ((self.isFull() || self.isInputHidden) && !(IS_MAC ? e.metaKey : e.ctrlKey)) {
1579 e.preventDefault();
1580 return;
1581 }
1582 },
1583
1584 /**
1585 * Triggered on <input> keyup.
1586 *
1587 * @param {object} e
1588 * @returns {boolean}
1589 */
1590 onKeyUp: function(e) {
1591 var self = this;
1592
1593 if (self.isLocked) return e && e.preventDefault();
1594 var value = self.$control_input.val() || '';
1595 if (self.lastValue !== value) {
1596 self.lastValue = value;
1597 self.onSearchChange(value);
1598 self.refreshOptions();
1599 self.trigger('type', value);
1600 }
1601 },
1602
1603 /**
1604 * Invokes the user-provide option provider / loader.
1605 *
1606 * Note: this function is debounced in the Selectize
1607 * constructor (by `settings.loadDelay` milliseconds)
1608 *
1609 * @param {string} value
1610 */
1611 onSearchChange: function(value) {
1612 var self = this;
1613 var fn = self.settings.load;
1614 if (!fn) return;
1615 if (self.loadedSearches.hasOwnProperty(value)) return;
1616 self.loadedSearches[value] = true;
1617 self.load(function(callback) {
1618 fn.apply(self, [value, callback]);
1619 });
1620 },
1621
1622 /**
1623 * Triggered on <input> focus.
1624 *
1625 * @param {object} e (optional)
1626 * @returns {boolean}
1627 */
1628 onFocus: function(e) {
1629 var self = this;
1630 var wasFocused = self.isFocused;
1631
1632 if (self.isDisabled) {
1633 self.blur();
1634 e && e.preventDefault();
1635 return false;
1636 }
1637
1638 if (self.ignoreFocus) return;
1639 self.isFocused = true;
1640 if (self.settings.preload === 'focus') self.onSearchChange('');
1641
1642 if (!wasFocused) self.trigger('focus');
1643
1644 if (!self.$activeItems.length) {
1645 self.showInput();
1646 self.setActiveItem(null);
1647 self.refreshOptions(!!self.settings.openOnFocus);
1648 }
1649
1650 self.refreshState();
1651 },
1652
1653 /**
1654 * Triggered on <input> blur.
1655 *
1656 * @param {object} e
1657 * @param {Element} dest
1658 */
1659 onBlur: function(e, dest) {
1660 var self = this;
1661 if (!self.isFocused) return;
1662 self.isFocused = false;
1663
1664 if (self.ignoreFocus) {
1665 return;
1666 } else if (!self.ignoreBlur && document.activeElement === self.$dropdown_content[0]) {
1667 // necessary to prevent IE closing the dropdown when the scrollbar is clicked
1668 self.ignoreBlur = true;
1669 self.onFocus(e);
1670 return;
1671 }
1672
1673 var deactivate = function() {
1674 self.close();
1675 self.setTextboxValue('');
1676 self.setActiveItem(null);
1677 self.setActiveOption(null);
1678 self.setCaret(self.items.length);
1679 self.refreshState();
1680
1681 // IE11 bug: element still marked as active
1682 (dest || document.body).focus();
1683
1684 self.ignoreFocus = false;
1685 self.trigger('blur');
1686 };
1687
1688 self.ignoreFocus = true;
1689 if (self.settings.create && self.settings.createOnBlur) {
1690 self.createItem(null, false, deactivate);
1691 } else {
1692 deactivate();
1693 }
1694 },
1695
1696 /**
1697 * Triggered when the user rolls over
1698 * an option in the autocomplete dropdown menu.
1699 *
1700 * @param {object} e
1701 * @returns {boolean}
1702 */
1703 onOptionHover: function(e) {
1704 if (this.ignoreHover) return;
1705 this.setActiveOption(e.currentTarget, false);
1706 },
1707
1708 /**
1709 * Triggered when the user clicks on an option
1710 * in the autocomplete dropdown menu.
1711 *
1712 * @param {object} e
1713 * @returns {boolean}
1714 */
1715 onOptionSelect: function(e) {
1716 var value, $target, $option, self = this;
1717
1718 if (e.preventDefault) {
1719 e.preventDefault();
1720 e.stopPropagation();
1721 }
1722
1723 $target = $(e.currentTarget);
1724 if ($target.hasClass('create')) {
1725 self.createItem(null, function() {
1726 if (self.settings.closeAfterSelect) {
1727 self.close();
1728 }
1729 });
1730 } else {
1731 value = $target.attr('data-value');
1732 if (typeof value !== 'undefined') {
1733 self.lastQuery = null;
1734 self.setTextboxValue('');
1735 self.addItem(value);
1736 if (self.settings.closeAfterSelect) {
1737 self.close();
1738 } else if (!self.settings.hideSelected && e.type && /mouse/.test(e.type)) {
1739 self.setActiveOption(self.getOption(value));
1740 }
1741 }
1742 }
1743 },
1744
1745 /**
1746 * Triggered when the user clicks on an item
1747 * that has been selected.
1748 *
1749 * @param {object} e
1750 * @returns {boolean}
1751 */
1752 onItemSelect: function(e) {
1753 var self = this;
1754
1755 if (self.isLocked) return;
1756 if (self.settings.mode === 'multi') {
1757 e.preventDefault();
1758 self.setActiveItem(e.currentTarget, e);
1759 }
1760 },
1761
1762 /**
1763 * Invokes the provided method that provides
1764 * results to a callback---which are then added
1765 * as options to the control.
1766 *
1767 * @param {function} fn
1768 */
1769 load: function(fn) {
1770 var self = this;
1771 var $wrapper = self.$wrapper.addClass(self.settings.loadingClass);
1772
1773 self.loading++;
1774 fn.apply(self, [function(results) {
1775 self.loading = Math.max(self.loading - 1, 0);
1776 if (results && results.length) {
1777 self.addOption(results);
1778 self.refreshOptions(self.isFocused && !self.isInputHidden);
1779 }
1780 if (!self.loading) {
1781 $wrapper.removeClass(self.settings.loadingClass);
1782 }
1783 self.trigger('load', results);
1784 }]);
1785 },
1786
1787 /**
1788 * Sets the input field of the control to the specified value.
1789 *
1790 * @param {string} value
1791 */
1792 setTextboxValue: function(value) {
1793 var $input = this.$control_input;
1794 var changed = $input.val() !== value;
1795 if (changed) {
1796 $input.val(value).triggerHandler('update');
1797 this.lastValue = value;
1798 }
1799 },
1800
1801 /**
1802 * Returns the value of the control. If multiple items
1803 * can be selected (e.g. <select multiple>), this returns
1804 * an array. If only one item can be selected, this
1805 * returns a string.
1806 *
1807 * @returns {mixed}
1808 */
1809 getValue: function() {
1810 if (this.tagType === TAG_SELECT && this.$input.attr('multiple')) {
1811 return this.items;
1812 } else {
1813 return this.items.join(this.settings.delimiter);
1814 }
1815 },
1816
1817 /**
1818 * Resets the selected items to the given value.
1819 *
1820 * @param {mixed} value
1821 */
1822 setValue: function(value, silent) {
1823 var events = silent ? [] : ['change'];
1824
1825 debounce_events(this, events, function() {
1826 this.clear(silent);
1827 this.addItems(value, silent);
1828 });
1829 },
1830
1831 /**
1832 * Sets the selected item.
1833 *
1834 * @param {object} $item
1835 * @param {object} e (optional)
1836 */
1837 setActiveItem: function($item, e) {
1838 var self = this;
1839 var eventName;
1840 var i, idx, begin, end, item, swap;
1841 var $last;
1842
1843 if (self.settings.mode === 'single') return;
1844 $item = $($item);
1845
1846 // clear the active selection
1847 if (!$item.length) {
1848 $(self.$activeItems).removeClass('active');
1849 self.$activeItems = [];
1850 if (self.isFocused) {
1851 self.showInput();
1852 }
1853 return;
1854 }
1855
1856 // modify selection
1857 eventName = e && e.type.toLowerCase();
1858
1859 if (eventName === 'mousedown' && self.isShiftDown && self.$activeItems.length) {
1860 $last = self.$control.children('.active:last');
1861 begin = Array.prototype.indexOf.apply(self.$control[0].childNodes, [$last[0]]);
1862 end = Array.prototype.indexOf.apply(self.$control[0].childNodes, [$item[0]]);
1863 if (begin > end) {
1864 swap = begin;
1865 begin = end;
1866 end = swap;
1867 }
1868 for (i = begin; i <= end; i++) {
1869 item = self.$control[0].childNodes[i];
1870 if (self.$activeItems.indexOf(item) === -1) {
1871 $(item).addClass('active');
1872 self.$activeItems.push(item);
1873 }
1874 }
1875 e.preventDefault();
1876 } else if ((eventName === 'mousedown' && self.isCtrlDown) || (eventName === 'keydown' && this.isShiftDown)) {
1877 if ($item.hasClass('active')) {
1878 idx = self.$activeItems.indexOf($item[0]);
1879 self.$activeItems.splice(idx, 1);
1880 $item.removeClass('active');
1881 } else {
1882 self.$activeItems.push($item.addClass('active')[0]);
1883 }
1884 } else {
1885 $(self.$activeItems).removeClass('active');
1886 self.$activeItems = [$item.addClass('active')[0]];
1887 }
1888
1889 // ensure control has focus
1890 self.hideInput();
1891 if (!this.isFocused) {
1892 self.focus();
1893 }
1894 },
1895
1896 /**
1897 * Sets the selected item in the dropdown menu
1898 * of available options.
1899 *
1900 * @param {object} $object
1901 * @param {boolean} scroll
1902 * @param {boolean} animate
1903 */
1904 setActiveOption: function($option, scroll, animate) {
1905 var height_menu, height_item, y;
1906 var scroll_top, scroll_bottom;
1907 var self = this;
1908
1909 if (self.$activeOption) self.$activeOption.removeClass('active');
1910 self.$activeOption = null;
1911
1912 $option = $($option);
1913 if (!$option.length) return;
1914
1915 self.$activeOption = $option.addClass('active');
1916
1917 if (scroll || !isset(scroll)) {
1918
1919 height_menu = self.$dropdown_content.height();
1920 height_item = self.$activeOption.outerHeight(true);
1921 scroll = self.$dropdown_content.scrollTop() || 0;
1922 y = self.$activeOption.offset().top - self.$dropdown_content.offset().top + scroll;
1923 scroll_top = y;
1924 scroll_bottom = y - height_menu + height_item;
1925
1926 if (y + height_item > height_menu + scroll) {
1927 self.$dropdown_content.stop().animate({scrollTop: scroll_bottom}, animate ? self.settings.scrollDuration : 0);
1928 } else if (y < scroll) {
1929 self.$dropdown_content.stop().animate({scrollTop: scroll_top}, animate ? self.settings.scrollDuration : 0);
1930 }
1931
1932 }
1933 },
1934
1935 /**
1936 * Selects all items (CTRL + A).
1937 */
1938 selectAll: function() {
1939 var self = this;
1940 if (self.settings.mode === 'single') return;
1941
1942 self.$activeItems = Array.prototype.slice.apply(self.$control.children(':not(input)').addClass('active'));
1943 if (self.$activeItems.length) {
1944 self.hideInput();
1945 self.close();
1946 }
1947 self.focus();
1948 },
1949
1950 /**
1951 * Hides the input element out of view, while
1952 * retaining its focus.
1953 */
1954 hideInput: function() {
1955 var self = this;
1956
1957 self.setTextboxValue('');
1958 self.$control_input.css({opacity: 0, position: 'absolute', left: self.rtl ? 10000 : -10000});
1959 self.isInputHidden = true;
1960 },
1961
1962 /**
1963 * Restores input visibility.
1964 */
1965 showInput: function() {
1966 this.$control_input.css({opacity: 1, position: 'relative', left: 0});
1967 this.isInputHidden = false;
1968 },
1969
1970 /**
1971 * Gives the control focus.
1972 */
1973 focus: function() {
1974 var self = this;
1975 if (self.isDisabled) return;
1976
1977 self.ignoreFocus = true;
1978 self.$control_input[0].focus();
1979 window.setTimeout(function() {
1980 self.ignoreFocus = false;
1981 self.onFocus();
1982 }, 0);
1983 },
1984
1985 /**
1986 * Forces the control out of focus.
1987 *
1988 * @param {Element} dest
1989 */
1990 blur: function(dest) {
1991 this.$control_input[0].blur();
1992 this.onBlur(null, dest);
1993 },
1994
1995 /**
1996 * Returns a function that scores an object
1997 * to show how good of a match it is to the
1998 * provided query.
1999 *
2000 * @param {string} query
2001 * @param {object} options
2002 * @return {function}
2003 */
2004 getScoreFunction: function(query) {
2005 return this.sifter.getScoreFunction(query, this.getSearchOptions());
2006 },
2007
2008 /**
2009 * Returns search options for sifter (the system
2010 * for scoring and sorting results).
2011 *
2012 * @see https://github.com/brianreavis/sifter.js
2013 * @return {object}
2014 */
2015 getSearchOptions: function() {
2016 var settings = this.settings;
2017 var sort = settings.sortField;
2018 if (typeof sort === 'string') {
2019 sort = [{field: sort}];
2020 }
2021
2022 return {
2023 fields : settings.searchField,
2024 conjunction : settings.searchConjunction,
2025 sort : sort
2026 };
2027 },
2028
2029 /**
2030 * Searches through available options and returns
2031 * a sorted array of matches.
2032 *
2033 * Returns an object containing:
2034 *
2035 * - query {string}
2036 * - tokens {array}
2037 * - total {int}
2038 * - items {array}
2039 *
2040 * @param {string} query
2041 * @returns {object}
2042 */
2043 search: function(query) {
2044 var i, value, score, result, calculateScore;
2045 var self = this;
2046 var settings = self.settings;
2047 var options = this.getSearchOptions();
2048
2049 // validate user-provided result scoring function
2050 if (settings.score) {
2051 calculateScore = self.settings.score.apply(this, [query]);
2052 if (typeof calculateScore !== 'function') {
2053 throw new Error('Selectize "score" setting must be a function that returns a function');
2054 }
2055 }
2056
2057 // perform search
2058 if (query !== self.lastQuery) {
2059 self.lastQuery = query;
2060 result = self.sifter.search(query, $.extend(options, {score: calculateScore}));
2061 self.currentResults = result;
2062 } else {
2063 result = $.extend(true, {}, self.currentResults);
2064 }
2065
2066 // filter out selected items
2067 if (settings.hideSelected) {
2068 for (i = result.items.length - 1; i >= 0; i--) {
2069 if (self.items.indexOf(hash_key(result.items[i].id)) !== -1) {
2070 result.items.splice(i, 1);
2071 }
2072 }
2073 }
2074
2075 return result;
2076 },
2077
2078 /**
2079 * Refreshes the list of available options shown
2080 * in the autocomplete dropdown menu.
2081 *
2082 * @param {boolean} triggerDropdown
2083 */
2084 refreshOptions: function(triggerDropdown) {
2085 var i, j, k, n, groups, groups_order, option, option_html, optgroup, optgroups, html, html_children, has_create_option;
2086 var $active, $active_before, $create;
2087
2088 if (typeof triggerDropdown === 'undefined') {
2089 triggerDropdown = true;
2090 }
2091
2092 var self = this;
2093 var query = $.trim(self.$control_input.val());
2094 var results = self.search(query);
2095 var $dropdown_content = self.$dropdown_content;
2096 var active_before = self.$activeOption && hash_key(self.$activeOption.attr('data-value'));
2097
2098 // build markup
2099 n = results.items.length;
2100 if (typeof self.settings.maxOptions === 'number') {
2101 n = Math.min(n, self.settings.maxOptions);
2102 }
2103
2104 // render and group available options individually
2105 groups = {};
2106 groups_order = [];
2107
2108 for (i = 0; i < n; i++) {
2109 option = self.options[results.items[i].id];
2110 option_html = self.render('option', option);
2111 optgroup = option[self.settings.optgroupField] || '';
2112 optgroups = $.isArray(optgroup) ? optgroup : [optgroup];
2113
2114 for (j = 0, k = optgroups && optgroups.length; j < k; j++) {
2115 optgroup = optgroups[j];
2116 if (!self.optgroups.hasOwnProperty(optgroup)) {
2117 optgroup = '';
2118 }
2119 if (!groups.hasOwnProperty(optgroup)) {
2120 groups[optgroup] = [];
2121 groups_order.push(optgroup);
2122 }
2123 groups[optgroup].push(option_html);
2124 }
2125 }
2126
2127 // sort optgroups
2128 if (this.settings.lockOptgroupOrder) {
2129 groups_order.sort(function(a, b) {
2130 var a_order = self.optgroups[a].$order || 0;
2131 var b_order = self.optgroups[b].$order || 0;
2132 return a_order - b_order;
2133 });
2134 }
2135
2136 // render optgroup headers & join groups
2137 html = [];
2138 for (i = 0, n = groups_order.length; i < n; i++) {
2139 optgroup = groups_order[i];
2140 if (self.optgroups.hasOwnProperty(optgroup) && groups[optgroup].length) {
2141 // render the optgroup header and options within it,
2142 // then pass it to the wrapper template
2143 html_children = self.render('optgroup_header', self.optgroups[optgroup]) || '';
2144 html_children += groups[optgroup].join('');
2145 html.push(self.render('optgroup', $.extend({}, self.optgroups[optgroup], {
2146 html: html_children
2147 })));
2148 } else {
2149 html.push(groups[optgroup].join(''));
2150 }
2151 }
2152
2153 $dropdown_content.html(html.join(''));
2154
2155 // highlight matching terms inline
2156 if (self.settings.highlight && results.query.length && results.tokens.length) {
2157 for (i = 0, n = results.tokens.length; i < n; i++) {
2158 highlight($dropdown_content, results.tokens[i].regex);
2159 }
2160 }
2161
2162 // add "selected" class to selected options
2163 if (!self.settings.hideSelected) {
2164 for (i = 0, n = self.items.length; i < n; i++) {
2165 self.getOption(self.items[i]).addClass('selected');
2166 }
2167 }
2168
2169 // add create option
2170 has_create_option = self.canCreate(query);
2171 if (has_create_option) {
2172 $dropdown_content.prepend(self.render('option_create', {input: query}));
2173 $create = $($dropdown_content[0].childNodes[0]);
2174 }
2175
2176 // activate
2177 self.hasOptions = results.items.length > 0 || has_create_option;
2178 if (self.hasOptions) {
2179 if (results.items.length > 0) {
2180 $active_before = active_before && self.getOption(active_before);
2181 if ($active_before && $active_before.length) {
2182 $active = $active_before;
2183 } else if (self.settings.mode === 'single' && self.items.length) {
2184 $active = self.getOption(self.items[0]);
2185 }
2186 if (!$active || !$active.length) {
2187 if ($create && !self.settings.addPrecedence) {
2188 $active = self.getAdjacentOption($create, 1);
2189 } else {
2190 $active = $dropdown_content.find('[data-selectable]:first');
2191 }
2192 }
2193 } else {
2194 $active = $create;
2195 }
2196 self.setActiveOption($active);
2197 if (triggerDropdown && !self.isOpen) { self.open(); }
2198 } else {
2199 self.setActiveOption(null);
2200 if (triggerDropdown && self.isOpen) { self.close(); }
2201 }
2202 },
2203
2204 /**
2205 * Adds an available option. If it already exists,
2206 * nothing will happen. Note: this does not refresh
2207 * the options list dropdown (use `refreshOptions`
2208 * for that).
2209 *
2210 * Usage:
2211 *
2212 * this.addOption(data)
2213 *
2214 * @param {object|array} data
2215 */
2216 addOption: function(data) {
2217 var i, n, value, self = this;
2218
2219 if ($.isArray(data)) {
2220 for (i = 0, n = data.length; i < n; i++) {
2221 self.addOption(data[i]);
2222 }
2223 return;
2224 }
2225
2226 if (value = self.registerOption(data)) {
2227 self.userOptions[value] = true;
2228 self.lastQuery = null;
2229 self.trigger('option_add', value, data);
2230 }
2231 },
2232
2233 /**
2234 * Registers an option to the pool of options.
2235 *
2236 * @param {object} data
2237 * @return {boolean|string}
2238 */
2239 registerOption: function(data) {
2240 var key = hash_key(data[this.settings.valueField]);
2241 if (!key || this.options.hasOwnProperty(key)) return false;
2242 data.$order = data.$order || ++this.order;
2243 this.options[key] = data;
2244 return key;
2245 },
2246
2247 /**
2248 * Registers an option group to the pool of option groups.
2249 *
2250 * @param {object} data
2251 * @return {boolean|string}
2252 */
2253 registerOptionGroup: function(data) {
2254 var key = hash_key(data[this.settings.optgroupValueField]);
2255 if (!key) return false;
2256
2257 data.$order = data.$order || ++this.order;
2258 this.optgroups[key] = data;
2259 return key;
2260 },
2261
2262 /**
2263 * Registers a new optgroup for options
2264 * to be bucketed into.
2265 *
2266 * @param {string} id
2267 * @param {object} data
2268 */
2269 addOptionGroup: function(id, data) {
2270 data[this.settings.optgroupValueField] = id;
2271 if (id = this.registerOptionGroup(data)) {
2272 this.trigger('optgroup_add', id, data);
2273 }
2274 },
2275
2276 /**
2277 * Removes an existing option group.
2278 *
2279 * @param {string} id
2280 */
2281 removeOptionGroup: function(id) {
2282 if (this.optgroups.hasOwnProperty(id)) {
2283 delete this.optgroups[id];
2284 this.renderCache = {};
2285 this.trigger('optgroup_remove', id);
2286 }
2287 },
2288
2289 /**
2290 * Clears all existing option groups.
2291 */
2292 clearOptionGroups: function() {
2293 this.optgroups = {};
2294 this.renderCache = {};
2295 this.trigger('optgroup_clear');
2296 },
2297
2298 /**
2299 * Updates an option available for selection. If
2300 * it is visible in the selected items or options
2301 * dropdown, it will be re-rendered automatically.
2302 *
2303 * @param {string} value
2304 * @param {object} data
2305 */
2306 updateOption: function(value, data) {
2307 var self = this;
2308 var $item, $item_new;
2309 var value_new, index_item, cache_items, cache_options, order_old;
2310
2311 value = hash_key(value);
2312 value_new = hash_key(data[self.settings.valueField]);
2313
2314 // sanity checks
2315 if (value === null) return;
2316 if (!self.options.hasOwnProperty(value)) return;
2317 if (typeof value_new !== 'string') throw new Error('Value must be set in option data');
2318
2319 order_old = self.options[value].$order;
2320
2321 // update references
2322 if (value_new !== value) {
2323 delete self.options[value];
2324 index_item = self.items.indexOf(value);
2325 if (index_item !== -1) {
2326 self.items.splice(index_item, 1, value_new);
2327 }
2328 }
2329 data.$order = data.$order || order_old;
2330 self.options[value_new] = data;
2331
2332 // invalidate render cache
2333 cache_items = self.renderCache['item'];
2334 cache_options = self.renderCache['option'];
2335
2336 if (cache_items) {
2337 delete cache_items[value];
2338 delete cache_items[value_new];
2339 }
2340 if (cache_options) {
2341 delete cache_options[value];
2342 delete cache_options[value_new];
2343 }
2344
2345 // update the item if it's selected
2346 if (self.items.indexOf(value_new) !== -1) {
2347 $item = self.getItem(value);
2348 $item_new = $(self.render('item', data));
2349 if ($item.hasClass('active')) $item_new.addClass('active');
2350 $item.replaceWith($item_new);
2351 }
2352
2353 // invalidate last query because we might have updated the sortField
2354 self.lastQuery = null;
2355
2356 // update dropdown contents
2357 if (self.isOpen) {
2358 self.refreshOptions(false);
2359 }
2360 },
2361
2362 /**
2363 * Removes a single option.
2364 *
2365 * @param {string} value
2366 * @param {boolean} silent
2367 */
2368 removeOption: function(value, silent) {
2369 var self = this;
2370 value = hash_key(value);
2371
2372 var cache_items = self.renderCache['item'];
2373 var cache_options = self.renderCache['option'];
2374 if (cache_items) delete cache_items[value];
2375 if (cache_options) delete cache_options[value];
2376
2377 delete self.userOptions[value];
2378 delete self.options[value];
2379 self.lastQuery = null;
2380 self.trigger('option_remove', value);
2381 self.removeItem(value, silent);
2382 },
2383
2384 /**
2385 * Clears all options.
2386 */
2387 clearOptions: function() {
2388 var self = this;
2389
2390 self.loadedSearches = {};
2391 self.userOptions = {};
2392 self.renderCache = {};
2393 self.options = self.sifter.items = {};
2394 self.lastQuery = null;
2395 self.trigger('option_clear');
2396 self.clear();
2397 },
2398
2399 /**
2400 * Returns the jQuery element of the option
2401 * matching the given value.
2402 *
2403 * @param {string} value
2404 * @returns {object}
2405 */
2406 getOption: function(value) {
2407 return this.getElementWithValue(value, this.$dropdown_content.find('[data-selectable]'));
2408 },
2409
2410 /**
2411 * Returns the jQuery element of the next or
2412 * previous selectable option.
2413 *
2414 * @param {object} $option
2415 * @param {int} direction can be 1 for next or -1 for previous
2416 * @return {object}
2417 */
2418 getAdjacentOption: function($option, direction) {
2419 var $options = this.$dropdown.find('[data-selectable]');
2420 var index = $options.index($option) + direction;
2421
2422 return index >= 0 && index < $options.length ? $options.eq(index) : $();
2423 },
2424
2425 /**
2426 * Finds the first element with a "data-value" attribute
2427 * that matches the given value.
2428 *
2429 * @param {mixed} value
2430 * @param {object} $els
2431 * @return {object}
2432 */
2433 getElementWithValue: function(value, $els) {
2434 value = hash_key(value);
2435
2436 if (typeof value !== 'undefined' && value !== null) {
2437 for (var i = 0, n = $els.length; i < n; i++) {
2438 if ($els[i].getAttribute('data-value') === value) {
2439 return $($els[i]);
2440 }
2441 }
2442 }
2443
2444 return $();
2445 },
2446
2447 /**
2448 * Returns the jQuery element of the item
2449 * matching the given value.
2450 *
2451 * @param {string} value
2452 * @returns {object}
2453 */
2454 getItem: function(value) {
2455 return this.getElementWithValue(value, this.$control.children());
2456 },
2457
2458 /**
2459 * "Selects" multiple items at once. Adds them to the list
2460 * at the current caret position.
2461 *
2462 * @param {string} value
2463 * @param {boolean} silent
2464 */
2465 addItems: function(values, silent) {
2466 var items = $.isArray(values) ? values : [values];
2467 for (var i = 0, n = items.length; i < n; i++) {
2468 this.isPending = (i < n - 1);
2469 this.addItem(items[i], silent);
2470 }
2471 },
2472
2473 /**
2474 * "Selects" an item. Adds it to the list
2475 * at the current caret position.
2476 *
2477 * @param {string} value
2478 * @param {boolean} silent
2479 */
2480 addItem: function(value, silent) {
2481 var events = silent ? [] : ['change'];
2482
2483 debounce_events(this, events, function() {
2484 var $item, $option, $options;
2485 var self = this;
2486 var inputMode = self.settings.mode;
2487 var i, active, value_next, wasFull;
2488 value = hash_key(value);
2489
2490 if (self.items.indexOf(value) !== -1) {
2491 if (inputMode === 'single') self.close();
2492 return;
2493 }
2494
2495 if (!self.options.hasOwnProperty(value)) return;
2496 if (inputMode === 'single') self.clear(silent);
2497 if (inputMode === 'multi' && self.isFull()) return;
2498
2499 $item = $(self.render('item', self.options[value]));
2500 wasFull = self.isFull();
2501 self.items.splice(self.caretPos, 0, value);
2502 self.insertAtCaret($item);
2503 if (!self.isPending || (!wasFull && self.isFull())) {
2504 self.refreshState();
2505 }
2506
2507 if (self.isSetup) {
2508 $options = self.$dropdown_content.find('[data-selectable]');
2509
2510 // update menu / remove the option (if this is not one item being added as part of series)
2511 if (!self.isPending) {
2512 $option = self.getOption(value);
2513 value_next = self.getAdjacentOption($option, 1).attr('data-value');
2514 self.refreshOptions(self.isFocused && inputMode !== 'single');
2515 if (value_next) {
2516 self.setActiveOption(self.getOption(value_next));
2517 }
2518 }
2519
2520 // hide the menu if the maximum number of items have been selected or no options are left
2521 if (!$options.length || self.isFull()) {
2522 self.close();
2523 } else {
2524 self.positionDropdown();
2525 }
2526
2527 self.updatePlaceholder();
2528 self.trigger('item_add', value, $item);
2529 self.updateOriginalInput({silent: silent});
2530 }
2531 });
2532 },
2533
2534 /**
2535 * Removes the selected item matching
2536 * the provided value.
2537 *
2538 * @param {string} value
2539 */
2540 removeItem: function(value, silent) {
2541 var self = this;
2542 var $item, i, idx;
2543
2544 $item = (typeof value === 'object') ? value : self.getItem(value);
2545 value = hash_key($item.attr('data-value'));
2546 i = self.items.indexOf(value);
2547
2548 if (i !== -1) {
2549 $item.remove();
2550 if ($item.hasClass('active')) {
2551 idx = self.$activeItems.indexOf($item[0]);
2552 self.$activeItems.splice(idx, 1);
2553 }
2554
2555 self.items.splice(i, 1);
2556 self.lastQuery = null;
2557 if (!self.settings.persist && self.userOptions.hasOwnProperty(value)) {
2558 self.removeOption(value, silent);
2559 }
2560
2561 if (i < self.caretPos) {
2562 self.setCaret(self.caretPos - 1);
2563 }
2564
2565 self.refreshState();
2566 self.updatePlaceholder();
2567 self.updateOriginalInput({silent: silent});
2568 self.positionDropdown();
2569 self.trigger('item_remove', value, $item);
2570 }
2571 },
2572
2573 /**
2574 * Invokes the `create` method provided in the
2575 * selectize options that should provide the data
2576 * for the new item, given the user input.
2577 *
2578 * Once this completes, it will be added
2579 * to the item list.
2580 *
2581 * @param {string} value
2582 * @param {boolean} [triggerDropdown]
2583 * @param {function} [callback]
2584 * @return {boolean}
2585 */
2586 createItem: function(input, triggerDropdown) {
2587 var self = this;
2588 var caret = self.caretPos;
2589 input = input || $.trim(self.$control_input.val() || '');
2590
2591 var callback = arguments[arguments.length - 1];
2592 if (typeof callback !== 'function') callback = function() {};
2593
2594 if (typeof triggerDropdown !== 'boolean') {
2595 triggerDropdown = true;
2596 }
2597
2598 if (!self.canCreate(input)) {
2599 callback();
2600 return false;
2601 }
2602
2603 self.lock();
2604
2605 var setup = (typeof self.settings.create === 'function') ? this.settings.create : function(input) {
2606 var data = {};
2607 data[self.settings.labelField] = input;
2608 data[self.settings.valueField] = input;
2609 return data;
2610 };
2611
2612 var create = once(function(data) {
2613 self.unlock();
2614
2615 if (!data || typeof data !== 'object') return callback();
2616 var value = hash_key(data[self.settings.valueField]);
2617 if (typeof value !== 'string') return callback();
2618
2619 self.setTextboxValue('');
2620 self.addOption(data);
2621 self.setCaret(caret);
2622 self.addItem(value);
2623 self.refreshOptions(triggerDropdown && self.settings.mode !== 'single');
2624 callback(data);
2625 });
2626
2627 var output = setup.apply(this, [input, create]);
2628 if (typeof output !== 'undefined') {
2629 create(output);
2630 }
2631
2632 return true;
2633 },
2634
2635 /**
2636 * Re-renders the selected item lists.
2637 */
2638 refreshItems: function() {
2639 this.lastQuery = null;
2640
2641 if (this.isSetup) {
2642 this.addItem(this.items);
2643 }
2644
2645 this.refreshState();
2646 this.updateOriginalInput();
2647 },
2648
2649 /**
2650 * Updates all state-dependent attributes
2651 * and CSS classes.
2652 */
2653 refreshState: function() {
2654 var invalid, self = this;
2655 if (self.isRequired) {
2656 if (self.items.length) self.isInvalid = false;
2657 self.$control_input.prop('required', invalid);
2658 }
2659 self.refreshClasses();
2660 },
2661
2662 /**
2663 * Updates all state-dependent CSS classes.
2664 */
2665 refreshClasses: function() {
2666 var self = this;
2667 var isFull = self.isFull();
2668 var isLocked = self.isLocked;
2669
2670 self.$wrapper
2671 .toggleClass('rtl', self.rtl);
2672
2673 self.$control
2674 .toggleClass('focus', self.isFocused)
2675 .toggleClass('disabled', self.isDisabled)
2676 .toggleClass('required', self.isRequired)
2677 .toggleClass('invalid', self.isInvalid)
2678 .toggleClass('locked', isLocked)
2679 .toggleClass('full', isFull).toggleClass('not-full', !isFull)
2680 .toggleClass('input-active', self.isFocused && !self.isInputHidden)
2681 .toggleClass('dropdown-active', self.isOpen)
2682 .toggleClass('has-options', !$.isEmptyObject(self.options))
2683 .toggleClass('has-items', self.items.length > 0);
2684
2685 self.$control_input.data('grow', !isFull && !isLocked);
2686 },
2687
2688 /**
2689 * Determines whether or not more items can be added
2690 * to the control without exceeding the user-defined maximum.
2691 *
2692 * @returns {boolean}
2693 */
2694 isFull: function() {
2695 return this.settings.maxItems !== null && this.items.length >= this.settings.maxItems;
2696 },
2697
2698 /**
2699 * Refreshes the original <select> or <input>
2700 * element to reflect the current state.
2701 */
2702 updateOriginalInput: function(opts) {
2703 var i, n, options, label, self = this;
2704 opts = opts || {};
2705
2706 if (self.tagType === TAG_SELECT) {
2707 options = [];
2708 for (i = 0, n = self.items.length; i < n; i++) {
2709 label = self.options[self.items[i]][self.settings.labelField] || '';
2710 options.push('<option value="' + escape_html(self.items[i]) + '" selected="selected">' + escape_html(label) + '</option>');
2711 }
2712 if (!options.length && !this.$input.attr('multiple')) {
2713 options.push('<option value="" selected="selected"></option>');
2714 }
2715 self.$input.html(options.join(''));
2716 } else {
2717 self.$input.val(self.getValue());
2718 self.$input.attr('value',self.$input.val());
2719 }
2720
2721 if (self.isSetup) {
2722 if (!opts.silent) {
2723 self.trigger('change', self.$input.val());
2724 }
2725 }
2726 },
2727
2728 /**
2729 * Shows/hide the input placeholder depending
2730 * on if there items in the list already.
2731 */
2732 updatePlaceholder: function() {
2733 if (!this.settings.placeholder) return;
2734 var $input = this.$control_input;
2735
2736 if (this.items.length) {
2737 $input.removeAttr('placeholder');
2738 } else {
2739 $input.attr('placeholder', this.settings.placeholder);
2740 }
2741 $input.triggerHandler('update', {force: true});
2742 },
2743
2744 /**
2745 * Shows the autocomplete dropdown containing
2746 * the available options.
2747 */
2748 open: function() {
2749 var self = this;
2750
2751 if (self.isLocked || self.isOpen || (self.settings.mode === 'multi' && self.isFull())) return;
2752 self.focus();
2753 self.isOpen = true;
2754 self.refreshState();
2755 self.$dropdown.css({visibility: 'hidden', display: 'block'});
2756 self.positionDropdown();
2757 self.$dropdown.css({visibility: 'visible'});
2758 self.trigger('dropdown_open', self.$dropdown);
2759 },
2760
2761 /**
2762 * Closes the autocomplete dropdown menu.
2763 */
2764 close: function() {
2765 var self = this;
2766 var trigger = self.isOpen;
2767
2768 if (self.settings.mode === 'single' && self.items.length) {
2769 self.hideInput();
2770 }
2771
2772 self.isOpen = false;
2773 self.$dropdown.hide();
2774 self.setActiveOption(null);
2775 self.refreshState();
2776
2777 if (trigger) self.trigger('dropdown_close', self.$dropdown);
2778 },
2779
2780 /**
2781 * Calculates and applies the appropriate
2782 * position of the dropdown.
2783 */
2784 positionDropdown: function() {
2785 var $control = this.$control;
2786 var offset = this.settings.dropdownParent === 'body' ? $control.offset() : $control.position();
2787 offset.top += $control.outerHeight(true);
2788
2789 this.$dropdown.css({
2790 width : $control.outerWidth(),
2791 top : offset.top,
2792 left : offset.left
2793 });
2794 },
2795
2796 /**
2797 * Resets / clears all selected items
2798 * from the control.
2799 *
2800 * @param {boolean} silent
2801 */
2802 clear: function(silent) {
2803 var self = this;
2804
2805 if (!self.items.length) return;
2806 self.$control.children(':not(input)').remove();
2807 self.items = [];
2808 self.lastQuery = null;
2809 self.setCaret(0);
2810 self.setActiveItem(null);
2811 self.updatePlaceholder();
2812 self.updateOriginalInput({silent: silent});
2813 self.refreshState();
2814 self.showInput();
2815 self.trigger('clear');
2816 },
2817
2818 /**
2819 * A helper method for inserting an element
2820 * at the current caret position.
2821 *
2822 * @param {object} $el
2823 */
2824 insertAtCaret: function($el) {
2825 var caret = Math.min(this.caretPos, this.items.length);
2826 if (caret === 0) {
2827 this.$control.prepend($el);
2828 } else {
2829 $(this.$control[0].childNodes[caret]).before($el);
2830 }
2831 this.setCaret(caret + 1);
2832 },
2833
2834 /**
2835 * Removes the current selected item(s).
2836 *
2837 * @param {object} e (optional)
2838 * @returns {boolean}
2839 */
2840 deleteSelection: function(e) {
2841 var i, n, direction, selection, values, caret, option_select, $option_select, $tail;
2842 var self = this;
2843
2844 direction = (e && e.keyCode === KEY_BACKSPACE) ? -1 : 1;
2845 selection = getSelection(self.$control_input[0]);
2846
2847 if (self.$activeOption && !self.settings.hideSelected) {
2848 option_select = self.getAdjacentOption(self.$activeOption, -1).attr('data-value');
2849 }
2850
2851 // determine items that will be removed
2852 values = [];
2853
2854 if (self.$activeItems.length) {
2855 $tail = self.$control.children('.active:' + (direction > 0 ? 'last' : 'first'));
2856 caret = self.$control.children(':not(input)').index($tail);
2857 if (direction > 0) { caret++; }
2858
2859 for (i = 0, n = self.$activeItems.length; i < n; i++) {
2860 values.push($(self.$activeItems[i]).attr('data-value'));
2861 }
2862 if (e) {
2863 e.preventDefault();
2864 e.stopPropagation();
2865 }
2866 } else if ((self.isFocused || self.settings.mode === 'single') && self.items.length) {
2867 if (direction < 0 && selection.start === 0 && selection.length === 0) {
2868 values.push(self.items[self.caretPos - 1]);
2869 } else if (direction > 0 && selection.start === self.$control_input.val().length) {
2870 values.push(self.items[self.caretPos]);
2871 }
2872 }
2873
2874 // allow the callback to abort
2875 if (!values.length || (typeof self.settings.onDelete === 'function' && self.settings.onDelete.apply(self, [values]) === false)) {
2876 return false;
2877 }
2878
2879 // perform removal
2880 if (typeof caret !== 'undefined') {
2881 self.setCaret(caret);
2882 }
2883 while (values.length) {
2884 self.removeItem(values.pop());
2885 }
2886
2887 self.showInput();
2888 self.positionDropdown();
2889 self.refreshOptions(true);
2890
2891 // select previous option
2892 if (option_select) {
2893 $option_select = self.getOption(option_select);
2894 if ($option_select.length) {
2895 self.setActiveOption($option_select);
2896 }
2897 }
2898
2899 return true;
2900 },
2901
2902 /**
2903 * Selects the previous / next item (depending
2904 * on the `direction` argument).
2905 *
2906 * > 0 - right
2907 * < 0 - left
2908 *
2909 * @param {int} direction
2910 * @param {object} e (optional)
2911 */
2912 advanceSelection: function(direction, e) {
2913 var tail, selection, idx, valueLength, cursorAtEdge, $tail;
2914 var self = this;
2915
2916 if (direction === 0) return;
2917 if (self.rtl) direction *= -1;
2918
2919 tail = direction > 0 ? 'last' : 'first';
2920 selection = getSelection(self.$control_input[0]);
2921
2922 if (self.isFocused && !self.isInputHidden) {
2923 valueLength = self.$control_input.val().length;
2924 cursorAtEdge = direction < 0
2925 ? selection.start === 0 && selection.length === 0
2926 : selection.start === valueLength;
2927
2928 if (cursorAtEdge && !valueLength) {
2929 self.advanceCaret(direction, e);
2930 }
2931 } else {
2932 $tail = self.$control.children('.active:' + tail);
2933 if ($tail.length) {
2934 idx = self.$control.children(':not(input)').index($tail);
2935 self.setActiveItem(null);
2936 self.setCaret(direction > 0 ? idx + 1 : idx);
2937 }
2938 }
2939 },
2940
2941 /**
2942 * Moves the caret left / right.
2943 *
2944 * @param {int} direction
2945 * @param {object} e (optional)
2946 */
2947 advanceCaret: function(direction, e) {
2948 var self = this, fn, $adj;
2949
2950 if (direction === 0) return;
2951
2952 fn = direction > 0 ? 'next' : 'prev';
2953 if (self.isShiftDown) {
2954 $adj = self.$control_input[fn]();
2955 if ($adj.length) {
2956 self.hideInput();
2957 self.setActiveItem($adj);
2958 e && e.preventDefault();
2959 }
2960 } else {
2961 self.setCaret(self.caretPos + direction);
2962 }
2963 },
2964
2965 /**
2966 * Moves the caret to the specified index.
2967 *
2968 * @param {int} i
2969 */
2970 setCaret: function(i) {
2971 var self = this;
2972
2973 if (self.settings.mode === 'single') {
2974 i = self.items.length;
2975 } else {
2976 i = Math.max(0, Math.min(self.items.length, i));
2977 }
2978
2979 if(!self.isPending) {
2980 // the input must be moved by leaving it in place and moving the
2981 // siblings, due to the fact that focus cannot be restored once lost
2982 // on mobile webkit devices
2983 var j, n, fn, $children, $child;
2984 $children = self.$control.children(':not(input)');
2985 for (j = 0, n = $children.length; j < n; j++) {
2986 $child = $($children[j]).detach();
2987 if (j < i) {
2988 self.$control_input.before($child);
2989 } else {
2990 self.$control.append($child);
2991 }
2992 }
2993 }
2994
2995 self.caretPos = i;
2996 },
2997
2998 /**
2999 * Disables user input on the control. Used while
3000 * items are being asynchronously created.
3001 */
3002 lock: function() {
3003 this.close();
3004 this.isLocked = true;
3005 this.refreshState();
3006 },
3007
3008 /**
3009 * Re-enables user input on the control.
3010 */
3011 unlock: function() {
3012 this.isLocked = false;
3013 this.refreshState();
3014 },
3015
3016 /**
3017 * Disables user input on the control completely.
3018 * While disabled, it cannot receive focus.
3019 */
3020 disable: function() {
3021 var self = this;
3022 self.$input.prop('disabled', true);
3023 self.$control_input.prop('disabled', true).prop('tabindex', -1);
3024 self.isDisabled = true;
3025 self.lock();
3026 },
3027
3028 /**
3029 * Enables the control so that it can respond
3030 * to focus and user input.
3031 */
3032 enable: function() {
3033 var self = this;
3034 self.$input.prop('disabled', false);
3035 self.$control_input.prop('disabled', false).prop('tabindex', self.tabIndex);
3036 self.isDisabled = false;
3037 self.unlock();
3038 },
3039
3040 /**
3041 * Completely destroys the control and
3042 * unbinds all event listeners so that it can
3043 * be garbage collected.
3044 */
3045 destroy: function() {
3046 var self = this;
3047 var eventNS = self.eventNS;
3048 var revertSettings = self.revertSettings;
3049
3050 self.trigger('destroy');
3051 self.off();
3052 self.$wrapper.remove();
3053 self.$dropdown.remove();
3054
3055 self.$input
3056 .html('')
3057 .append(revertSettings.$children)
3058 .removeAttr('tabindex')
3059 .removeClass('selectized')
3060 .attr({tabindex: revertSettings.tabindex})
3061 .show();
3062
3063 self.$control_input.removeData('grow');
3064 self.$input.removeData('selectize');
3065
3066 $(window).off(eventNS);
3067 $(document).off(eventNS);
3068 $(document.body).off(eventNS);
3069
3070 delete self.$input[0].selectize;
3071 },
3072
3073 /**
3074 * A helper method for rendering "item" and
3075 * "option" templates, given the data.
3076 *
3077 * @param {string} templateName
3078 * @param {object} data
3079 * @returns {string}
3080 */
3081 render: function(templateName, data) {
3082 var value, id, label;
3083 var html = '';
3084 var cache = false;
3085 var self = this;
3086 var regex_tag = /^[\t \r\n]*<([a-z][a-z0-9\-_]*(?:\:[a-z][a-z0-9\-_]*)?)/i;
3087
3088 if (templateName === 'option' || templateName === 'item') {
3089 value = hash_key(data[self.settings.valueField]);
3090 cache = !!value;
3091 }
3092
3093 // pull markup from cache if it exists
3094 if (cache) {
3095 if (!isset(self.renderCache[templateName])) {
3096 self.renderCache[templateName] = {};
3097 }
3098 if (self.renderCache[templateName].hasOwnProperty(value)) {
3099 return self.renderCache[templateName][value];
3100 }
3101 }
3102
3103 // render markup
3104 html = self.settings.render[templateName].apply(this, [data, escape_html]);
3105
3106 // add mandatory attributes
3107 if (templateName === 'option' || templateName === 'option_create') {
3108 html = html.replace(regex_tag, '<$1 data-selectable');
3109 }
3110 if (templateName === 'optgroup') {
3111 id = data[self.settings.optgroupValueField] || '';
3112 html = html.replace(regex_tag, '<$1 data-group="' + escape_replace(escape_html(id)) + '"');
3113 }
3114 if (templateName === 'option' || templateName === 'item') {
3115 html = html.replace(regex_tag, '<$1 data-value="' + escape_replace(escape_html(value || '')) + '"');
3116 }
3117
3118 // update cache
3119 if (cache) {
3120 self.renderCache[templateName][value] = html;
3121 }
3122
3123 return html;
3124 },
3125
3126 /**
3127 * Clears the render cache for a template. If
3128 * no template is given, clears all render
3129 * caches.
3130 *
3131 * @param {string} templateName
3132 */
3133 clearCache: function(templateName) {
3134 var self = this;
3135 if (typeof templateName === 'undefined') {
3136 self.renderCache = {};
3137 } else {
3138 delete self.renderCache[templateName];
3139 }
3140 },
3141
3142 /**
3143 * Determines whether or not to display the
3144 * create item prompt, given a user input.
3145 *
3146 * @param {string} input
3147 * @return {boolean}
3148 */
3149 canCreate: function(input) {
3150 var self = this;
3151 if (!self.settings.create) return false;
3152 var filter = self.settings.createFilter;
3153 return input.length
3154 && (typeof filter !== 'function' || filter.apply(self, [input]))
3155 && (typeof filter !== 'string' || new RegExp(filter).test(input))
3156 && (!(filter instanceof RegExp) || filter.test(input));
3157 }
3158
3159 });
3160
3161
3162 Selectize.count = 0;
3163 Selectize.defaults = {
3164 options: [],
3165 optgroups: [],
3166
3167 plugins: [],
3168 delimiter: ',',
3169 splitOn: null, // regexp or string for splitting up values from a paste command
3170 persist: true,
3171 diacritics: true,
3172 create: false,
3173 createOnBlur: false,
3174 createFilter: null,
3175 highlight: true,
3176 openOnFocus: true,
3177 maxOptions: 1000,
3178 maxItems: null,
3179 hideSelected: null,
3180 addPrecedence: false,
3181 selectOnTab: false,
3182 preload: false,
3183 allowEmptyOption: false,
3184 closeAfterSelect: false,
3185
3186 scrollDuration: 60,
3187 loadThrottle: 300,
3188 loadingClass: 'loading',
3189
3190 dataAttr: 'data-data',
3191 optgroupField: 'optgroup',
3192 valueField: 'value',
3193 labelField: 'text',
3194 optgroupLabelField: 'label',
3195 optgroupValueField: 'value',
3196 lockOptgroupOrder: false,
3197
3198 sortField: '$order',
3199 searchField: ['text'],
3200 searchConjunction: 'and',
3201
3202 mode: null,
3203 wrapperClass: 'selectize-control',
3204 inputClass: 'selectize-input',
3205 dropdownClass: 'selectize-dropdown',
3206 dropdownContentClass: 'selectize-dropdown-content',
3207
3208 dropdownParent: null,
3209
3210 copyClassesToDropdown: true,
3211
3212 /*
3213 load : null, // function(query, callback) { ... }
3214 score : null, // function(search) { ... }
3215 onInitialize : null, // function() { ... }
3216 onChange : null, // function(value) { ... }
3217 onItemAdd : null, // function(value, $item) { ... }
3218 onItemRemove : null, // function(value) { ... }
3219 onClear : null, // function() { ... }
3220 onOptionAdd : null, // function(value, data) { ... }
3221 onOptionRemove : null, // function(value) { ... }
3222 onOptionClear : null, // function() { ... }
3223 onOptionGroupAdd : null, // function(id, data) { ... }
3224 onOptionGroupRemove : null, // function(id) { ... }
3225 onOptionGroupClear : null, // function() { ... }
3226 onDropdownOpen : null, // function($dropdown) { ... }
3227 onDropdownClose : null, // function($dropdown) { ... }
3228 onType : null, // function(str) { ... }
3229 onDelete : null, // function(values) { ... }
3230 */
3231
3232 render: {
3233 /*
3234 item: null,
3235 optgroup: null,
3236 optgroup_header: null,
3237 option: null,
3238 option_create: null
3239 */
3240 }
3241 };
3242
3243
3244 $.fn.selectize = function(settings_user) {
3245 var defaults = $.fn.selectize.defaults;
3246 var settings = $.extend({}, defaults, settings_user);
3247 var attr_data = settings.dataAttr;
3248 var field_label = settings.labelField;
3249 var field_value = settings.valueField;
3250 var field_optgroup = settings.optgroupField;
3251 var field_optgroup_label = settings.optgroupLabelField;
3252 var field_optgroup_value = settings.optgroupValueField;
3253
3254 /**
3255 * Initializes selectize from a <input type="text"> element.
3256 *
3257 * @param {object} $input
3258 * @param {object} settings_element
3259 */
3260 var init_textbox = function($input, settings_element) {
3261 var i, n, values, option;
3262
3263 var data_raw = $input.attr(attr_data);
3264
3265 if (!data_raw) {
3266 var value = $.trim($input.val() || '');
3267 if (!settings.allowEmptyOption && !value.length) return;
3268 values = value.split(settings.delimiter);
3269 for (i = 0, n = values.length; i < n; i++) {
3270 option = {};
3271 option[field_label] = values[i];
3272 option[field_value] = values[i];
3273 settings_element.options.push(option);
3274 }
3275 settings_element.items = values;
3276 } else {
3277 settings_element.options = JSON.parse(data_raw);
3278 for (i = 0, n = settings_element.options.length; i < n; i++) {
3279 settings_element.items.push(settings_element.options[i][field_value]);
3280 }
3281 }
3282 };
3283
3284 /**
3285 * Initializes selectize from a <select> element.
3286 *
3287 * @param {object} $input
3288 * @param {object} settings_element
3289 */
3290 var init_select = function($input, settings_element) {
3291 var i, n, tagName, $children, order = 0;
3292 var options = settings_element.options;
3293 var optionsMap = {};
3294
3295 var readData = function($el) {
3296 var data = attr_data && $el.attr(attr_data);
3297 if (typeof data === 'string' && data.length) {
3298 return JSON.parse(data);
3299 }
3300 return null;
3301 };
3302
3303 var addOption = function($option, group) {
3304 $option = $($option);
3305
3306 var value = hash_key($option.attr('value'));
3307 if (!value && !settings.allowEmptyOption) return;
3308
3309 // if the option already exists, it's probably been
3310 // duplicated in another optgroup. in this case, push
3311 // the current group to the "optgroup" property on the
3312 // existing option so that it's rendered in both places.
3313 if (optionsMap.hasOwnProperty(value)) {
3314 if (group) {
3315 var arr = optionsMap[value][field_optgroup];
3316 if (!arr) {
3317 optionsMap[value][field_optgroup] = group;
3318 } else if (!$.isArray(arr)) {
3319 optionsMap[value][field_optgroup] = [arr, group];
3320 } else {
3321 arr.push(group);
3322 }
3323 }
3324 return;
3325 }
3326
3327 var option = readData($option) || {};
3328 option[field_label] = option[field_label] || $option.text();
3329 option[field_value] = option[field_value] || value;
3330 option[field_optgroup] = option[field_optgroup] || group;
3331
3332 optionsMap[value] = option;
3333 options.push(option);
3334
3335 if ($option.is(':selected')) {
3336 settings_element.items.push(value);
3337 }
3338 };
3339
3340 var addGroup = function($optgroup) {
3341 var i, n, id, optgroup, $options;
3342
3343 $optgroup = $($optgroup);
3344 id = $optgroup.attr('label');
3345
3346 if (id) {
3347 optgroup = readData($optgroup) || {};
3348 optgroup[field_optgroup_label] = id;
3349 optgroup[field_optgroup_value] = id;
3350 settings_element.optgroups.push(optgroup);
3351 }
3352
3353 $options = $('option', $optgroup);
3354 for (i = 0, n = $options.length; i < n; i++) {
3355 addOption($options[i], id);
3356 }
3357 };
3358
3359 settings_element.maxItems = $input.attr('multiple') ? null : 1;
3360
3361 $children = $input.children();
3362 for (i = 0, n = $children.length; i < n; i++) {
3363 tagName = $children[i].tagName.toLowerCase();
3364 if (tagName === 'optgroup') {
3365 addGroup($children[i]);
3366 } else if (tagName === 'option') {
3367 addOption($children[i]);
3368 }
3369 }
3370 };
3371
3372 return this.each(function() {
3373 if (this.selectize) return;
3374
3375 var instance;
3376 var $input = $(this);
3377 var tag_name = this.tagName.toLowerCase();
3378 var placeholder = $input.attr('placeholder') || $input.attr('data-placeholder');
3379 if (!placeholder && !settings.allowEmptyOption) {
3380 placeholder = $input.children('option[value=""]').text();
3381 }
3382
3383 var settings_element = {
3384 'placeholder' : placeholder,
3385 'options' : [],
3386 'optgroups' : [],
3387 'items' : []
3388 };
3389
3390 if (tag_name === 'select') {
3391 init_select($input, settings_element);
3392 } else {
3393 init_textbox($input, settings_element);
3394 }
3395
3396 instance = new Selectize($input, $.extend(true, {}, defaults, settings_element, settings_user));
3397 });
3398 };
3399
3400 $.fn.selectize.defaults = Selectize.defaults;
3401 $.fn.selectize.support = {
3402 validity: SUPPORTS_VALIDITY_API
3403 };
3404
3405
3406 Selectize.define('drag_drop', function(options) {
3407 if (!$.fn.sortable) throw new Error('The "drag_drop" plugin requires jQuery UI "sortable".');
3408 if (this.settings.mode !== 'multi') return;
3409 var self = this;
3410
3411 self.lock = (function() {
3412 var original = self.lock;
3413 return function() {
3414 var sortable = self.$control.data('sortable');
3415 if (sortable) sortable.disable();
3416 return original.apply(self, arguments);
3417 };
3418 })();
3419
3420 self.unlock = (function() {
3421 var original = self.unlock;
3422 return function() {
3423 var sortable = self.$control.data('sortable');
3424 if (sortable) sortable.enable();
3425 return original.apply(self, arguments);
3426 };
3427 })();
3428
3429 self.setup = (function() {
3430 var original = self.setup;
3431 return function() {
3432 original.apply(this, arguments);
3433
3434 var $control = self.$control.sortable({
3435 items: '[data-value]',
3436 forcePlaceholderSize: true,
3437 disabled: self.isLocked,
3438 start: function(e, ui) {
3439 ui.placeholder.css('width', ui.helper.css('width'));
3440 $control.css({overflow: 'visible'});
3441 },
3442 stop: function() {
3443 $control.css({overflow: 'hidden'});
3444 var active = self.$activeItems ? self.$activeItems.slice() : null;
3445 var values = [];
3446 $control.children('[data-value]').each(function() {
3447 values.push($(this).attr('data-value'));
3448 });
3449 self.setValue(values);
3450 self.setActiveItem(active);
3451 }
3452 });
3453 };
3454 })();
3455
3456 });
3457
3458 Selectize.define('dropdown_header', function(options) {
3459 var self = this;
3460
3461 options = $.extend({
3462 title : 'Untitled',
3463 headerClass : 'selectize-dropdown-header',
3464 titleRowClass : 'selectize-dropdown-header-title',
3465 labelClass : 'selectize-dropdown-header-label',
3466 closeClass : 'selectize-dropdown-header-close',
3467
3468 html: function(data) {
3469 return (
3470 '<div class="' + data.headerClass + '">' +
3471 '<div class="' + data.titleRowClass + '">' +
3472 '<span class="' + data.labelClass + '">' + data.title + '</span>' +
3473 '<a href="javascript:void(0)" class="' + data.closeClass + '">&times;</a>' +
3474 '</div>' +
3475 '</div>'
3476 );
3477 }
3478 }, options);
3479
3480 self.setup = (function() {
3481 var original = self.setup;
3482 return function() {
3483 original.apply(self, arguments);
3484 self.$dropdown_header = $(options.html(options));
3485 self.$dropdown.prepend(self.$dropdown_header);
3486 };
3487 })();
3488
3489 });
3490
3491 Selectize.define('optgroup_columns', function(options) {
3492 var self = this;
3493
3494 options = $.extend({
3495 equalizeWidth : true,
3496 equalizeHeight : true
3497 }, options);
3498
3499 this.getAdjacentOption = function($option, direction) {
3500 var $options = $option.closest('[data-group]').find('[data-selectable]');
3501 var index = $options.index($option) + direction;
3502
3503 return index >= 0 && index < $options.length ? $options.eq(index) : $();
3504 };
3505
3506 this.onKeyDown = (function() {
3507 var original = self.onKeyDown;
3508 return function(e) {
3509 var index, $option, $options, $optgroup;
3510
3511 if (this.isOpen && (e.keyCode === KEY_LEFT || e.keyCode === KEY_RIGHT)) {
3512 self.ignoreHover = true;
3513 $optgroup = this.$activeOption.closest('[data-group]');
3514 index = $optgroup.find('[data-selectable]').index(this.$activeOption);
3515
3516 if(e.keyCode === KEY_LEFT) {
3517 $optgroup = $optgroup.prev('[data-group]');
3518 } else {
3519 $optgroup = $optgroup.next('[data-group]');
3520 }
3521
3522 $options = $optgroup.find('[data-selectable]');
3523 $option = $options.eq(Math.min($options.length - 1, index));
3524 if ($option.length) {
3525 this.setActiveOption($option);
3526 }
3527 return;
3528 }
3529
3530 return original.apply(this, arguments);
3531 };
3532 })();
3533
3534 var getScrollbarWidth = function() {
3535 var div;
3536 var width = getScrollbarWidth.width;
3537 var doc = document;
3538
3539 if (typeof width === 'undefined') {
3540 div = doc.createElement('div');
3541 div.innerHTML = '<div style="width:50px;height:50px;position:absolute;left:-50px;top:-50px;overflow:auto;"><div style="width:1px;height:100px;"></div></div>';
3542 div = div.firstChild;
3543 doc.body.appendChild(div);
3544 width = getScrollbarWidth.width = div.offsetWidth - div.clientWidth;
3545 doc.body.removeChild(div);
3546 }
3547 return width;
3548 };
3549
3550 var equalizeSizes = function() {
3551 var i, n, height_max, width, width_last, width_parent, $optgroups;
3552
3553 $optgroups = $('[data-group]', self.$dropdown_content);
3554 n = $optgroups.length;
3555 if (!n || !self.$dropdown_content.width()) return;
3556
3557 if (options.equalizeHeight) {
3558 height_max = 0;
3559 for (i = 0; i < n; i++) {
3560 height_max = Math.max(height_max, $optgroups.eq(i).height());
3561 }
3562 $optgroups.css({height: height_max});
3563 }
3564
3565 if (options.equalizeWidth) {
3566 width_parent = self.$dropdown_content.innerWidth() - getScrollbarWidth();
3567 width = Math.round(width_parent / n);
3568 $optgroups.css({width: width});
3569 if (n > 1) {
3570 width_last = width_parent - width * (n - 1);
3571 $optgroups.eq(n - 1).css({width: width_last});
3572 }
3573 }
3574 };
3575
3576 if (options.equalizeHeight || options.equalizeWidth) {
3577 hook.after(this, 'positionDropdown', equalizeSizes);
3578 hook.after(this, 'refreshOptions', equalizeSizes);
3579 }
3580
3581
3582 });
3583
3584 Selectize.define('remove_button', function(options) {
3585 if (this.settings.mode === 'single') return;
3586
3587 options = $.extend({
3588 label : '&times;',
3589 title : 'Remove',
3590 className : 'remove',
3591 append : true
3592 }, options);
3593
3594 var self = this;
3595 var html = '<a href="javascript:void(0)" class="' + options.className + '" tabindex="-1" title="' + escape_html(options.title) + '">' + options.label + '</a>';
3596
3597 /**
3598 * Appends an element as a child (with raw HTML).
3599 *
3600 * @param {string} html_container
3601 * @param {string} html_element
3602 * @return {string}
3603 */
3604 var append = function(html_container, html_element) {
3605 var pos = html_container.search(/(<\/[^>]+>\s*)$/);
3606 return html_container.substring(0, pos) + html_element + html_container.substring(pos);
3607 };
3608
3609 this.setup = (function() {
3610 var original = self.setup;
3611 return function() {
3612 // override the item rendering method to add the button to each
3613 if (options.append) {
3614 var render_item = self.settings.render.item;
3615 self.settings.render.item = function(data) {
3616 return append(render_item.apply(this, arguments), html);
3617 };
3618 }
3619
3620 original.apply(this, arguments);
3621
3622 // add event listener
3623 this.$control.on('click', '.' + options.className, function(e) {
3624 e.preventDefault();
3625 if (self.isLocked) return;
3626
3627 var $item = $(e.currentTarget).parent();
3628 self.setActiveItem($item);
3629 if (self.deleteSelection()) {
3630 self.setCaret(self.items.length);
3631 }
3632 });
3633
3634 };
3635 })();
3636
3637 });
3638
3639 Selectize.define('restore_on_backspace', function(options) {
3640 var self = this;
3641
3642 options.text = options.text || function(option) {
3643 return option[this.settings.labelField];
3644 };
3645
3646 this.onKeyDown = (function() {
3647 var original = self.onKeyDown;
3648 return function(e) {
3649 var index, option;
3650 if (e.keyCode === KEY_BACKSPACE && this.$control_input.val() === '' && !this.$activeItems.length) {
3651 index = this.caretPos - 1;
3652 if (index >= 0 && index < this.items.length) {
3653 option = this.options[this.items[index]];
3654 if (this.deleteSelection(e)) {
3655 this.setTextboxValue(options.text.apply(this, [option]));
3656 this.refreshOptions(true);
3657 }
3658 e.preventDefault();
3659 return;
3660 }
3661 }
3662 return original.apply(this, arguments);
3663 };
3664 })();
3665 });
3666
3667
3668 return Selectize;
3669 }));