Skip to content

Business intelligence made simple

Switched to Tom Select [skip ci]

Andrew Kane965eb4195823
diff --git a/app/assets/javascripts/blazer/application.js b/app/assets/javascripts/blazer/application.js
index 4a3e2be5..02d9e91a 100644
--- a/app/assets/javascripts/blazer/application.js
+++ b/app/assets/javascripts/blazer/application.js
@@ -1,6 +1,6 @@
//= require ./jquery
//= require ./tablesort
-//= require ./selectize
+//= require ./tom-select.base
//= require ./highlight.min
//= require ./moment
//= require ./moment-timezone-with-data
diff --git a/app/assets/javascripts/blazer/selectize.js b/app/assets/javascripts/blazer/selectize.js
deleted file mode 100644
index e064981c..00000000
--- a/app/assets/javascripts/blazer/selectize.js
+++ /dev/null
@@ -1,3891 +0,0 @@
-/**
- * sifter.js
- * Copyright (c) 2013 Brian Reavis & contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
- * file except in compliance with the License. You may obtain a copy of the License at:
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under
- * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
- * ANY KIND, either express or implied. See the License for the specific language
- * governing permissions and limitations under the License.
- *
- * @author Brian Reavis <[email protected]>
- */
-
-(function(root, factory) {
- if (typeof define === 'function' && define.amd) {
- define('sifter', factory);
- } else if (typeof exports === 'object') {
- module.exports = factory();
- } else {
- root.Sifter = factory();
- }
-}(this, function() {
-
- /**
- * Textually searches arrays and hashes of objects
- * by property (or multiple properties). Designed
- * specifically for autocomplete.
- *
- * @constructor
- * @param {array|object} items
- * @param {object} items
- */
- var Sifter = function(items, settings) {
- this.items = items;
- this.settings = settings || {diacritics: true};
- };
-
- /**
- * Splits a search string into an array of individual
- * regexps to be used to match results.
- *
- * @param {string} query
- * @returns {array}
- */
- Sifter.prototype.tokenize = function(query) {
- query = trim(String(query || '').toLowerCase());
- if (!query || !query.length) return [];
-
- var i, n, regex, letter;
- var tokens = [];
- var words = query.split(/ +/);
-
- for (i = 0, n = words.length; i < n; i++) {
- regex = escape_regex(words[i]);
- if (this.settings.diacritics) {
- for (letter in DIACRITICS) {
- if (DIACRITICS.hasOwnProperty(letter)) {
- regex = regex.replace(new RegExp(letter, 'g'), DIACRITICS[letter]);
- }
- }
- }
- tokens.push({
- string : words[i],
- regex : new RegExp(regex, 'i')
- });
- }
-
- return tokens;
- };
-
- /**
- * Iterates over arrays and hashes.
- *
- * ```
- * this.iterator(this.items, function(item, id) {
- * // invoked for each item
- * });
- * ```
- *
- * @param {array|object} object
- */
- Sifter.prototype.iterator = function(object, callback) {
- var iterator;
- if (is_array(object)) {
- iterator = Array.prototype.forEach || function(callback) {
- for (var i = 0, n = this.length; i < n; i++) {
- callback(this[i], i, this);
- }
- };
- } else {
- iterator = function(callback) {
- for (var key in this) {
- if (this.hasOwnProperty(key)) {
- callback(this[key], key, this);
- }
- }
- };
- }
-
- iterator.apply(object, [callback]);
- };
-
- /**
- * Returns a function to be used to score individual results.
- *
- * Good matches will have a higher score than poor matches.
- * If an item is not a match, 0 will be returned by the function.
- *
- * @param {object|string} search
- * @param {object} options (optional)
- * @returns {function}
- */
- Sifter.prototype.getScoreFunction = function(search, options) {
- var self, fields, tokens, token_count, nesting;
-
- self = this;
- search = self.prepareSearch(search, options);
- tokens = search.tokens;
- fields = search.options.fields;
- token_count = tokens.length;
- nesting = search.options.nesting;
-
- /**
- * Calculates how close of a match the
- * given value is against a search token.
- *
- * @param {mixed} value
- * @param {object} token
- * @return {number}
- */
- var scoreValue = function(value, token) {
- var score, pos;
-
- if (!value) return 0;
- value = String(value || '');
- pos = value.search(token.regex);
- if (pos === -1) return 0;
- score = token.string.length / value.length;
- if (pos === 0) score += 0.5;
- return score;
- };
-
- /**
- * Calculates the score of an object
- * against the search query.
- *
- * @param {object} token
- * @param {object} data
- * @return {number}
- */
- var scoreObject = (function() {
- var field_count = fields.length;
- if (!field_count) {
- return function() { return 0; };
- }
- if (field_count === 1) {
- return function(token, data) {
- return scoreValue(getattr(data, fields[0], nesting), token);
- };
- }
- return function(token, data) {
- for (var i = 0, sum = 0; i < field_count; i++) {
- sum += scoreValue(getattr(data, fields[i], nesting), token);
- }
- return sum / field_count;
- };
- })();
-
- if (!token_count) {
- return function() { return 0; };
- }
- if (token_count === 1) {
- return function(data) {
- return scoreObject(tokens[0], data);
- };
- }
-
- if (search.options.conjunction === 'and') {
- return function(data) {
- var score;
- for (var i = 0, sum = 0; i < token_count; i++) {
- score = scoreObject(tokens[i], data);
- if (score <= 0) return 0;
- sum += score;
- }
- return sum / token_count;
- };
- } else {
- return function(data) {
- for (var i = 0, sum = 0; i < token_count; i++) {
- sum += scoreObject(tokens[i], data);
- }
- return sum / token_count;
- };
- }
- };
-
- /**
- * Returns a function that can be used to compare two
- * results, for sorting purposes. If no sorting should
- * be performed, `null` will be returned.
- *
- * @param {string|object} search
- * @param {object} options
- * @return function(a,b)
- */
- Sifter.prototype.getSortFunction = function(search, options) {
- var i, n, self, field, fields, fields_count, multiplier, multipliers, get_field, implicit_score, sort;
-
- self = this;
- search = self.prepareSearch(search, options);
- sort = (!search.query && options.sort_empty) || options.sort;
-
- /**
- * Fetches the specified sort field value
- * from a search result item.
- *
- * @param {string} name
- * @param {object} result
- * @return {mixed}
- */
- get_field = function(name, result) {
- if (name === '$score') return result.score;
- return getattr(self.items[result.id], name, options.nesting);
- };
-
- // parse options
- fields = [];
- if (sort) {
- for (i = 0, n = sort.length; i < n; i++) {
- if (search.query || sort[i].field !== '$score') {
- fields.push(sort[i]);
- }
- }
- }
-
- // the "$score" field is implied to be the primary
- // sort field, unless it's manually specified
- if (search.query) {
- implicit_score = true;
- for (i = 0, n = fields.length; i < n; i++) {
- if (fields[i].field === '$score') {
- implicit_score = false;
- break;
- }
- }
- if (implicit_score) {
- fields.unshift({field: '$score', direction: 'desc'});
- }
- } else {
- for (i = 0, n = fields.length; i < n; i++) {
- if (fields[i].field === '$score') {
- fields.splice(i, 1);
- break;
- }
- }
- }
-
- multipliers = [];
- for (i = 0, n = fields.length; i < n; i++) {
- multipliers.push(fields[i].direction === 'desc' ? -1 : 1);
- }
-
- // build function
- fields_count = fields.length;
- if (!fields_count) {
- return null;
- } else if (fields_count === 1) {
- field = fields[0].field;
- multiplier = multipliers[0];
- return function(a, b) {
- return multiplier * cmp(
- get_field(field, a),
- get_field(field, b)
- );
- };
- } else {
- return function(a, b) {
- var i, result, a_value, b_value, field;
- for (i = 0; i < fields_count; i++) {
- field = fields[i].field;
- result = multipliers[i] * cmp(
- get_field(field, a),
- get_field(field, b)
- );
- if (result) return result;
- }
- return 0;
- };
- }
- };
-
- /**
- * Parses a search query and returns an object
- * with tokens and fields ready to be populated
- * with results.
- *
- * @param {string} query
- * @param {object} options
- * @returns {object}
- */
- Sifter.prototype.prepareSearch = function(query, options) {
- if (typeof query === 'object') return query;
-
- options = extend({}, options);
-
- var option_fields = options.fields;
- var option_sort = options.sort;
- var option_sort_empty = options.sort_empty;
-
- if (option_fields && !is_array(option_fields)) options.fields = [option_fields];
- if (option_sort && !is_array(option_sort)) options.sort = [option_sort];
- if (option_sort_empty && !is_array(option_sort_empty)) options.sort_empty = [option_sort_empty];
-
- return {
- options : options,
- query : String(query || '').toLowerCase(),
- tokens : this.tokenize(query),
- total : 0,
- items : []
- };
- };
-
- /**
- * Searches through all items and returns a sorted array of matches.
- *
- * The `options` parameter can contain:
- *
- * - fields {string|array}
- * - sort {array}
- * - score {function}
- * - filter {bool}
- * - limit {integer}
- *
- * Returns an object containing:
- *
- * - options {object}
- * - query {string}
- * - tokens {array}
- * - total {int}
- * - items {array}
- *
- * @param {string} query
- * @param {object} options
- * @returns {object}
- */
- Sifter.prototype.search = function(query, options) {
- var self = this, value, score, search, calculateScore;
- var fn_sort;
- var fn_score;
-
- search = this.prepareSearch(query, options);
- options = search.options;
- query = search.query;
-
- // generate result scoring function
- fn_score = options.score || self.getScoreFunction(search);
-
- // perform search and sort
- if (query.length) {
- self.iterator(self.items, function(item, id) {
- score = fn_score(item);
- if (options.filter === false || score > 0) {
- search.items.push({'score': score, 'id': id});
- }
- });
- } else {
- self.iterator(self.items, function(item, id) {
- search.items.push({'score': 1, 'id': id});
- });
- }
-
- fn_sort = self.getSortFunction(search, options);
- if (fn_sort) search.items.sort(fn_sort);
-
- // apply limits
- search.total = search.items.length;
- if (typeof options.limit === 'number') {
- search.items = search.items.slice(0, options.limit);
- }
-
- return search;
- };
-
- // utilities
- // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
- var cmp = function(a, b) {
- if (typeof a === 'number' && typeof b === 'number') {
- return a > b ? 1 : (a < b ? -1 : 0);
- }
- a = asciifold(String(a || ''));
- b = asciifold(String(b || ''));
- if (a > b) return 1;
- if (b > a) return -1;
- return 0;
- };
-
- var extend = function(a, b) {
- var i, n, k, object;
- for (i = 1, n = arguments.length; i < n; i++) {
- object = arguments[i];
- if (!object) continue;
- for (k in object) {
- if (object.hasOwnProperty(k)) {
- a[k] = object[k];
- }
- }
- }
- return a;
- };
-
- /**
- * A property getter resolving dot-notation
- * @param {Object} obj The root object to fetch property on
- * @param {String} name The optionally dotted property name to fetch
- * @param {Boolean} nesting Handle nesting or not
- * @return {Object} The resolved property value
- */
- var getattr = function(obj, name, nesting) {
- if (!obj || !name) return;
- if (!nesting) return obj[name];
- var names = name.split(".");
- while(names.length && (obj = obj[names.shift()]));
- return obj;
- };
-
- var trim = function(str) {
- return (str + '').replace(/^\s+|\s+$|/g, '');
- };
-
- var escape_regex = function(str) {
- return (str + '').replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
- };
-
- var is_array = Array.isArray || (typeof $ !== 'undefined' && $.isArray) || function(object) {
- return Object.prototype.toString.call(object) === '[object Array]';
- };
-
- var DIACRITICS = {
- 'a': '[aḀḁĂăÂâǍǎȺⱥȦȧẠạÄäÀàÁáĀāÃãÅåąĄÃąĄ]',
- 'b': '[b␢βΒB฿𐌁ᛒ]',
- 'c': '[cĆćĈĉČčĊċC̄c̄ÇçḈḉȻȼƇƈɕᴄCc]',
- 'd': '[dĎďḊḋḐḑḌḍḒḓḎḏĐđD̦d̦ƉɖƊɗƋƌᵭᶁᶑȡᴅDdð]',
- 'e': '[eÉéÈèÊêḘḙĚěĔĕẼẽḚḛẺẻĖėËëĒēȨȩĘęᶒɆɇȄȅẾếỀềỄễỂểḜḝḖḗḔḕȆȇẸẹỆệⱸᴇEeɘǝƏƐε]',
- 'f': '[fƑƒḞḟ]',
- 'g': '[gɢ₲ǤǥĜĝĞğĢģƓɠĠġ]',
- 'h': '[hĤĥĦħḨḩẖẖḤḥḢḣɦʰǶƕ]',
- 'i': '[iÍíÌìĬĭÎîǏǐÏïḮḯĨĩĮįĪīỈỉȈȉȊȋỊịḬḭƗɨɨ̆ᵻᶖİiIıɪIi]',
- 'j': '[jȷĴĵɈɉʝɟʲ]',
- 'k': '[kƘƙꝀꝁḰḱǨǩḲḳḴḵκϰ₭]',
- 'l': '[lŁłĽľĻļĹĺḶḷḸḹḼḽḺḻĿŀȽƚⱠⱡⱢɫɬᶅɭȴʟLl]',
- 'n': '[nŃńǸǹŇňÑñṄṅŅņṆṇṊṋṈṉN̈n̈ƝɲȠƞᵰᶇɳȵɴNnŊŋ]',
- 'o': '[oØøÖöÓóÒòÔôǑǒŐőŎŏȮȯỌọƟɵƠơỎỏŌōÕõǪǫȌȍՕօ]',
- 'p': '[pṔṕṖṗⱣᵽƤƥᵱ]',
- 'q': '[qꝖꝗʠɊɋꝘꝙq̃]',
- 'r': '[rŔŕɌɍŘřŖŗṘṙȐȑȒȓṚṛⱤɽ]',
- 's': '[sŚśṠṡṢṣꞨꞩŜŝŠšŞşȘșS̈s̈]',
- 't': '[tŤťṪṫŢţṬṭƮʈȚțṰṱṮṯƬƭ]',
- 'u': '[uŬŭɄʉỤụÜüÚúÙùÛûǓǔŰűŬŭƯưỦủŪūŨũŲųȔȕ∪]',
- 'v': '[vṼṽṾṿƲʋꝞꝟⱱʋ]',
- 'w': '[wẂẃẀẁŴŵẄẅẆẇẈẉ]',
- 'x': '[xẌẍẊẋχ]',
- 'y': '[yÝýỲỳŶŷŸÿỸỹẎẏỴỵɎɏƳƴ]',
- 'z': '[zŹźẐẑŽžŻżẒẓẔẕƵƶ]'
- };
-
- var asciifold = (function() {
- var i, n, k, chunk;
- var foreignletters = '';
- var lookup = {};
- for (k in DIACRITICS) {
- if (DIACRITICS.hasOwnProperty(k)) {
- chunk = DIACRITICS[k].substring(2, DIACRITICS[k].length - 1);
- foreignletters += chunk;
- for (i = 0, n = chunk.length; i < n; i++) {
- lookup[chunk.charAt(i)] = k;
- }
- }
- }
- var regexp = new RegExp('[' + foreignletters + ']', 'g');
- return function(str) {
- return str.replace(regexp, function(foreignletter) {
- return lookup[foreignletter];
- }).toLowerCase();
- };
- })();
-
-
- // export
- // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
- return Sifter;
-}));
-
-
-
-/**
- * microplugin.js
- * Copyright (c) 2013 Brian Reavis & contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
- * file except in compliance with the License. You may obtain a copy of the License at:
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under
- * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
- * ANY KIND, either express or implied. See the License for the specific language
- * governing permissions and limitations under the License.
- *
- * @author Brian Reavis <[email protected]>
- */
-
-(function(root, factory) {
- if (typeof define === 'function' && define.amd) {
- define('microplugin', factory);
- } else if (typeof exports === 'object') {
- module.exports = factory();
- } else {
- root.MicroPlugin = factory();
- }
-}(this, function() {
- var MicroPlugin = {};
-
- MicroPlugin.mixin = function(Interface) {
- Interface.plugins = {};
-
- /**
- * Initializes the listed plugins (with options).
- * Acceptable formats:
- *
- * List (without options):
- * ['a', 'b', 'c']
- *
- * List (with options):
- * [{'name': 'a', options: {}}, {'name': 'b', options: {}}]
- *
- * Hash (with options):
- * {'a': { ... }, 'b': { ... }, 'c': { ... }}
- *
- * @param {mixed} plugins
- */
- Interface.prototype.initializePlugins = function(plugins) {
- var i, n, key;
- var self = this;
- var queue = [];
-
- self.plugins = {
- names : [],
- settings : {},
- requested : {},
- loaded : {}
- };
-
- if (utils.isArray(plugins)) {
- for (i = 0, n = plugins.length; i < n; i++) {
- if (typeof plugins[i] === 'string') {
- queue.push(plugins[i]);
- } else {
- self.plugins.settings[plugins[i].name] = plugins[i].options;
- queue.push(plugins[i].name);
- }
- }
- } else if (plugins) {
- for (key in plugins) {
- if (plugins.hasOwnProperty(key)) {
- self.plugins.settings[key] = plugins[key];
- queue.push(key);
- }
- }
- }
-
- while (queue.length) {
- self.require(queue.shift());
- }
- };
-
- Interface.prototype.loadPlugin = function(name) {
- var self = this;
- var plugins = self.plugins;
- var plugin = Interface.plugins[name];
-
- if (!Interface.plugins.hasOwnProperty(name)) {
- throw new Error('Unable to find "' + name + '" plugin');
- }
-
- plugins.requested[name] = true;
- plugins.loaded[name] = plugin.fn.apply(self, [self.plugins.settings[name] || {}]);
- plugins.names.push(name);
- };
-
- /**
- * Initializes a plugin.
- *
- * @param {string} name
- */
- Interface.prototype.require = function(name) {
- var self = this;
- var plugins = self.plugins;
-
- if (!self.plugins.loaded.hasOwnProperty(name)) {
- if (plugins.requested[name]) {
- throw new Error('Plugin has circular dependency ("' + name + '")');
- }
- self.loadPlugin(name);
- }
-
- return plugins.loaded[name];
- };
-
- /**
- * Registers a plugin.
- *
- * @param {string} name
- * @param {function} fn
- */
- Interface.define = function(name, fn) {
- Interface.plugins[name] = {
- 'name' : name,
- 'fn' : fn
- };
- };
- };
-
- var utils = {
- isArray: Array.isArray || function(vArg) {
- return Object.prototype.toString.call(vArg) === '[object Array]';
- }
- };
-
- return MicroPlugin;
-}));
-
-/**
- * selectize.js (v0.12.6)
- * Copyright (c) 2013–2015 Brian Reavis & contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
- * file except in compliance with the License. You may obtain a copy of the License at:
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under
- * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
- * ANY KIND, either express or implied. See the License for the specific language
- * governing permissions and limitations under the License.
- *
- * @author Brian Reavis <[email protected]>
- */
-
-/*jshint curly:false */
-/*jshint browser:true */
-
-(function(root, factory) {
- if (typeof define === 'function' && define.amd) {
- define('selectize', ['jquery','sifter','microplugin'], factory);
- } else if (typeof exports === 'object') {
- module.exports = factory(require('jquery'), require('sifter'), require('microplugin'));
- } else {
- root.Selectize = factory(root.jQuery, root.Sifter, root.MicroPlugin);
- }
-}(this, function($, Sifter, MicroPlugin) {
- 'use strict';
-
- var highlight = function($element, pattern) {
- if (typeof pattern === 'string' && !pattern.length) return;
- var regex = (typeof pattern === 'string') ? new RegExp(pattern, 'i') : pattern;
-
- var highlight = function(node) {
- var skip = 0;
- // Wrap matching part of text node with highlighting <span>, e.g.
- // Soccer -> <span class="highlight">Soc</span>cer for regex = /soc/i
- if (node.nodeType === 3) {
- var pos = node.data.search(regex);
- if (pos >= 0 && node.data.length > 0) {
- var match = node.data.match(regex);
- var spannode = document.createElement('span');
- spannode.className = 'highlight';
- var middlebit = node.splitText(pos);
- var endbit = middlebit.splitText(match[0].length);
- var middleclone = middlebit.cloneNode(true);
- spannode.appendChild(middleclone);
- middlebit.parentNode.replaceChild(spannode, middlebit);
- skip = 1;
- }
- }
- // Recurse element node, looking for child text nodes to highlight, unless element
- // is childless, <script>, <style>, or already highlighted: <span class="hightlight">
- else if (node.nodeType === 1 && node.childNodes && !/(script|style)/i.test(node.tagName) && ( node.className !== 'highlight' || node.tagName !== 'SPAN' )) {
- for (var i = 0; i < node.childNodes.length; ++i) {
- i += highlight(node.childNodes[i]);
- }
- }
- return skip;
- };
-
- return $element.each(function() {
- highlight(this);
- });
- };
-
- /**
- * removeHighlight fn copied from highlight v5 and
- * edited to remove with() and pass js strict mode
- */
- $.fn.removeHighlight = function() {
- return this.find("span.highlight").each(function() {
- this.parentNode.firstChild.nodeName;
- var parent = this.parentNode;
- parent.replaceChild(this.firstChild, this);
- parent.normalize();
- }).end();
- };
-
-
- var MicroEvent = function() {};
- MicroEvent.prototype = {
- on: function(event, fct){
- this._events = this._events || {};
- this._events[event] = this._events[event] || [];
- this._events[event].push(fct);
- },
- off: function(event, fct){
- var n = arguments.length;
- if (n === 0) return delete this._events;
- if (n === 1) return delete this._events[event];
-
- this._events = this._events || {};
- if (event in this._events === false) return;
- this._events[event].splice(this._events[event].indexOf(fct), 1);
- },
- trigger: function(event /* , args... */){
- this._events = this._events || {};
- if (event in this._events === false) return;
- for (var i = 0; i < this._events[event].length; i++){
- this._events[event][i].apply(this, Array.prototype.slice.call(arguments, 1));
- }
- }
- };
-
- /**
- * Mixin will delegate all MicroEvent.js function in the destination object.
- *
- * - MicroEvent.mixin(Foobar) will make Foobar able to use MicroEvent
- *
- * @param {object} the object which will support MicroEvent
- */
- MicroEvent.mixin = function(destObject){
- var props = ['on', 'off', 'trigger'];
- for (var i = 0; i < props.length; i++){
- destObject.prototype[props[i]] = MicroEvent.prototype[props[i]];
- }
- };
-
- var IS_MAC = /Mac/.test(navigator.userAgent);
-
- var KEY_A = 65;
- var KEY_COMMA = 188;
- var KEY_RETURN = 13;
- var KEY_ESC = 27;
- var KEY_LEFT = 37;
- var KEY_UP = 38;
- var KEY_P = 80;
- var KEY_RIGHT = 39;
- var KEY_DOWN = 40;
- var KEY_N = 78;
- var KEY_BACKSPACE = 8;
- var KEY_DELETE = 46;
- var KEY_SHIFT = 16;
- var KEY_CMD = IS_MAC ? 91 : 17;
- var KEY_CTRL = IS_MAC ? 18 : 17;
- var KEY_TAB = 9;
-
- var TAG_SELECT = 1;
- var TAG_INPUT = 2;
-
- // for now, android support in general is too spotty to support validity
- var SUPPORTS_VALIDITY_API = !/android/i.test(window.navigator.userAgent) && !!document.createElement('input').validity;
-
-
- var isset = function(object) {
- return typeof object !== 'undefined';
- };
-
- /**
- * Converts a scalar to its best string representation
- * for hash keys and HTML attribute values.
- *
- * Transformations:
- * 'str' -> 'str'
- * null -> ''
- * undefined -> ''
- * true -> '1'
- * false -> '0'
- * 0 -> '0'
- * 1 -> '1'
- *
- * @param {string} value
- * @returns {string|null}
- */
- var hash_key = function(value) {
- if (typeof value === 'undefined' || value === null) return null;
- if (typeof value === 'boolean') return value ? '1' : '0';
- return value + '';
- };
-
- /**
- * Escapes a string for use within HTML.
- *
- * @param {string} str
- * @returns {string}
- */
- var escape_html = function(str) {
- return (str + '')
- .replace(/&/g, '&amp;')
- .replace(/</g, '&lt;')
- .replace(/>/g, '&gt;')
- .replace(/"/g, '&quot;');
- };
-
- /**
- * Escapes "$" characters in replacement strings.
- *
- * @param {string} str
- * @returns {string}
- */
- var escape_replace = function(str) {
- return (str + '').replace(/\$/g, '$$$$');
- };
-
- var hook = {};
-
- /**
- * Wraps `method` on `self` so that `fn`
- * is invoked before the original method.
- *
- * @param {object} self
- * @param {string} method
- * @param {function} fn
- */
- hook.before = function(self, method, fn) {
- var original = self[method];
- self[method] = function() {
- fn.apply(self, arguments);
- return original.apply(self, arguments);
- };
- };
-
- /**
- * Wraps `method` on `self` so that `fn`
- * is invoked after the original method.
- *
- * @param {object} self
- * @param {string} method
- * @param {function} fn
- */
- hook.after = function(self, method, fn) {
- var original = self[method];
- self[method] = function() {
- var result = original.apply(self, arguments);
- fn.apply(self, arguments);
- return result;
- };
- };
-
- /**
- * Wraps `fn` so that it can only be invoked once.
- *
- * @param {function} fn
- * @returns {function}
- */
- var once = function(fn) {
- var called = false;
- return function() {
- if (called) return;
- called = true;
- fn.apply(this, arguments);
- };
- };
-
- /**
- * Wraps `fn` so that it can only be called once
- * every `delay` milliseconds (invoked on the falling edge).
- *
- * @param {function} fn
- * @param {int} delay
- * @returns {function}
- */
- var debounce = function(fn, delay) {
- var timeout;
- return function() {
- var self = this;
- var args = arguments;
- window.clearTimeout(timeout);
- timeout = window.setTimeout(function() {
- fn.apply(self, args);
- }, delay);
- };
- };
-
- /**
- * Debounce all fired events types listed in `types`
- * while executing the provided `fn`.
- *
- * @param {object} self
- * @param {array} types
- * @param {function} fn
- */
- var debounce_events = function(self, types, fn) {
- var type;
- var trigger = self.trigger;
- var event_args = {};
-
- // override trigger method
- self.trigger = function() {
- var type = arguments[0];
- if (types.indexOf(type) !== -1) {
- event_args[type] = arguments;
- } else {
- return trigger.apply(self, arguments);
- }
- };
-
- // invoke provided function
- fn.apply(self, []);
- self.trigger = trigger;
-
- // trigger queued events
- for (type in event_args) {
- if (event_args.hasOwnProperty(type)) {
- trigger.apply(self, event_args[type]);
- }
- }
- };
-
- /**
- * A workaround for http://bugs.jquery.com/ticket/6696
- *
- * @param {object} $parent - Parent element to listen on.
- * @param {string} event - Event name.
- * @param {string} selector - Descendant selector to filter by.
- * @param {function} fn - Event handler.
- */
- var watchChildEvent = function($parent, event, selector, fn) {
- $parent.on(event, selector, function(e) {
- var child = e.target;
- while (child && child.parentNode !== $parent[0]) {
- child = child.parentNode;
- }
- e.currentTarget = child;
- return fn.apply(this, [e]);
- });
- };
-
- /**
- * Determines the current selection within a text input control.
- * Returns an object containing:
- * - start
- * - length
- *
- * @param {object} input
- * @returns {object}
- */
- var getSelection = function(input) {
- var result = {};
- if ('selectionStart' in input) {
- result.start = input.selectionStart;
- result.length = input.selectionEnd - result.start;
- } else if (document.selection) {
- input.focus();
- var sel = document.selection.createRange();
- var selLen = document.selection.createRange().text.length;
- sel.moveStart('character', -input.value.length);
- result.start = sel.text.length - selLen;
- result.length = selLen;
- }
- return result;
- };
-
- /**
- * Copies CSS properties from one element to another.
- *
- * @param {object} $from
- * @param {object} $to
- * @param {array} properties
- */
- var transferStyles = function($from, $to, properties) {
- var i, n, styles = {};
- if (properties) {
- for (i = 0, n = properties.length; i < n; i++) {
- styles[properties[i]] = $from.css(properties[i]);
- }
- } else {
- styles = $from.css();
- }
- $to.css(styles);
- };
-
- /**
- * Measures the width of a string within a
- * parent element (in pixels).
- *
- * @param {string} str
- * @param {object} $parent
- * @returns {int}
- */
- var measureString = function(str, $parent) {
- if (!str) {
- return 0;
- }
-
- if (!Selectize.$testInput) {
- Selectize.$testInput = $('<span />').css({
- position: 'absolute',
- top: -99999,
- left: -99999,
- width: 'auto',
- padding: 0,
- whiteSpace: 'pre'
- }).appendTo('body');
- }
-
- Selectize.$testInput.text(str);
-
- transferStyles($parent, Selectize.$testInput, [
- 'letterSpacing',
- 'fontSize',
- 'fontFamily',
- 'fontWeight',
- 'textTransform'
- ]);
-
- return Selectize.$testInput.width();
- };
-
- /**
- * Sets up an input to grow horizontally as the user
- * types. If the value is changed manually, you can
- * trigger the "update" handler to resize:
- *
- * $input.trigger('update');
- *
- * @param {object} $input
- */
- var autoGrow = function($input) {
- var currentWidth = null;
-
- var update = function(e, options) {
- var value, keyCode, printable, placeholder, width;
- var shift, character, selection;
- e = e || window.event || {};
- options = options || {};
-
- if (e.metaKey || e.altKey) return;
- if (!options.force && $input.data('grow') === false) return;
-
- value = $input.val();
- if (e.type && e.type.toLowerCase() === 'keydown') {
- keyCode = e.keyCode;
- printable = (
- (keyCode >= 48 && keyCode <= 57) || // 0-9
- (keyCode >= 65 && keyCode <= 90) || // a-z
- (keyCode >= 96 && keyCode <= 111) || // numpad 0-9, numeric operators
- (keyCode >= 186 && keyCode <= 222) || // semicolon, equal, comma, dash, etc.
- keyCode === 32 // space
- );
-
- if (keyCode === KEY_DELETE || keyCode === KEY_BACKSPACE) {
- selection = getSelection($input[0]);
- if (selection.length) {
- value = value.substring(0, selection.start) + value.substring(selection.start + selection.length);
- } else if (keyCode === KEY_BACKSPACE && selection.start) {
- value = value.substring(0, selection.start - 1) + value.substring(selection.start + 1);
- } else if (keyCode === KEY_DELETE && typeof selection.start !== 'undefined') {
- value = value.substring(0, selection.start) + value.substring(selection.start + 1);
- }
- } else if (printable) {
- shift = e.shiftKey;
- character = String.fromCharCode(e.keyCode);
- if (shift) character = character.toUpperCase();
- else character = character.toLowerCase();
- value += character;
- }
- }
-
- placeholder = $input.attr('placeholder');
- if (!value && placeholder) {
- value = placeholder;
- }
-
- width = measureString(value, $input) + 4;
- if (width !== currentWidth) {
- currentWidth = width;
- $input.width(width);
- $input.triggerHandler('resize');
- }
- };
-
- $input.on('keydown keyup update blur', update);
- update();
- };
-
- var domToString = function(d) {
- var tmp = document.createElement('div');
-
- tmp.appendChild(d.cloneNode(true));
-
- return tmp.innerHTML;
- };
-
- var logError = function(message, options){
- if(!options) options = {};
- var component = "Selectize";
-
- console.error(component + ": " + message)
-
- if(options.explanation){
- // console.group is undefined in <IE11
- if(console.group) console.group();
- console.error(options.explanation);
- if(console.group) console.groupEnd();
- }
- }
-
-
- var Selectize = function($input, settings) {
- var key, i, n, dir, input, self = this;
- input = $input[0];
- input.selectize = self;
-
- // detect rtl environment
- var computedStyle = window.getComputedStyle && window.getComputedStyle(input, null);
- dir = computedStyle ? computedStyle.getPropertyValue('direction') : input.currentStyle && input.currentStyle.direction;
- dir = dir || $input.parents('[dir]:first').attr('dir') || '';
-
- // setup default state
- $.extend(self, {
- order : 0,
- settings : settings,
- $input : $input,
- tabIndex : $input.attr('tabindex') || '',
- tagType : input.tagName.toLowerCase() === 'select' ? TAG_SELECT : TAG_INPUT,
- rtl : /rtl/i.test(dir),
-
- eventNS : '.selectize' + (++Selectize.count),
- highlightedValue : null,
- isBlurring : false,
- isOpen : false,
- isDisabled : false,
- isRequired : $input.is('[required]'),
- isInvalid : false,
- isLocked : false,
- isFocused : false,
- isInputHidden : false,
- isSetup : false,
- isShiftDown : false,
- isCmdDown : false,
- isCtrlDown : false,
- ignoreFocus : false,
- ignoreBlur : false,
- ignoreHover : false,
- hasOptions : false,
- currentResults : null,
- lastValue : '',
- caretPos : 0,
- loading : 0,
- loadedSearches : {},
-
- $activeOption : null,
- $activeItems : [],
-
- optgroups : {},
- options : {},
- userOptions : {},
- items : [],
- renderCache : {},
- onSearchChange : settings.loadThrottle === null ? self.onSearchChange : debounce(self.onSearchChange, settings.loadThrottle)
- });
-
- // search system
- self.sifter = new Sifter(this.options, {diacritics: settings.diacritics});
-
- // build options table
- if (self.settings.options) {
- for (i = 0, n = self.settings.options.length; i < n; i++) {
- self.registerOption(self.settings.options[i]);
- }
- delete self.settings.options;
- }
-
- // build optgroup table
- if (self.settings.optgroups) {
- for (i = 0, n = self.settings.optgroups.length; i < n; i++) {
- self.registerOptionGroup(self.settings.optgroups[i]);
- }
- delete self.settings.optgroups;
- }
-
- // option-dependent defaults
- self.settings.mode = self.settings.mode || (self.settings.maxItems === 1 ? 'single' : 'multi');
- if (typeof self.settings.hideSelected !== 'boolean') {
- self.settings.hideSelected = self.settings.mode === 'multi';
- }
-
- self.initializePlugins(self.settings.plugins);
- self.setupCallbacks();
- self.setupTemplates();
- self.setup();
- };
-
- // mixins
- // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
- MicroEvent.mixin(Selectize);
-
- if(typeof MicroPlugin !== "undefined"){
- MicroPlugin.mixin(Selectize);
- }else{
- logError("Dependency MicroPlugin is missing",
- {explanation:
- "Make sure you either: (1) are using the \"standalone\" "+
- "version of Selectize, or (2) require MicroPlugin before you "+
- "load Selectize."}
- );
- }
-
-
- // methods
- // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
- $.extend(Selectize.prototype, {
-
- /**
- * Creates all elements and sets up event bindings.
- */
- setup: function() {
- var self = this;
- var settings = self.settings;
- var eventNS = self.eventNS;
- var $window = $(window);
- var $document = $(document);
- var $input = self.$input;
-
- var $wrapper;
- var $control;
- var $control_input;
- var $dropdown;
- var $dropdown_content;
- var $dropdown_parent;
- var inputMode;
- var timeout_blur;
- var timeout_focus;
- var classes;
- var classes_plugins;
- var inputId;
-
- inputMode = self.settings.mode;
- classes = $input.attr('class') || '';
-
- $wrapper = $('<div>').addClass(settings.wrapperClass).addClass(classes).addClass(inputMode);
- $control = $('<div>').addClass(settings.inputClass).addClass('items').appendTo($wrapper);
- $control_input = $('<input type="text" autocomplete="off" />').appendTo($control).attr('tabindex', $input.is(':disabled') ? '-1' : self.tabIndex);
- $dropdown_parent = $(settings.dropdownParent || $wrapper);
- $dropdown = $('<div>').addClass(settings.dropdownClass).addClass(inputMode).hide().appendTo($dropdown_parent);
- $dropdown_content = $('<div>').addClass(settings.dropdownContentClass).appendTo($dropdown);
-
- if(inputId = $input.attr('id')) {
- $control_input.attr('id', inputId + '-selectized');
- $("label[for='"+inputId+"']").attr('for', inputId + '-selectized');
- }
-
- if(self.settings.copyClassesToDropdown) {
- $dropdown.addClass(classes);
- }
-
- $wrapper.css({
- width: $input[0].style.width
- });
-
- if (self.plugins.names.length) {
- classes_plugins = 'plugin-' + self.plugins.names.join(' plugin-');
- $wrapper.addClass(classes_plugins);
- $dropdown.addClass(classes_plugins);
- }
-
- if ((settings.maxItems === null || settings.maxItems > 1) && self.tagType === TAG_SELECT) {
- $input.attr('multiple', 'multiple');
- }
-
- if (self.settings.placeholder) {
- $control_input.attr('placeholder', settings.placeholder);
- }
-
- // if splitOn was not passed in, construct it from the delimiter to allow pasting universally
- if (!self.settings.splitOn && self.settings.delimiter) {
- var delimiterEscaped = self.settings.delimiter.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
- self.settings.splitOn = new RegExp('\\s*' + delimiterEscaped + '+\\s*');
- }
-
- if ($input.attr('autocorrect')) {
- $control_input.attr('autocorrect', $input.attr('autocorrect'));
- }
-
- if ($input.attr('autocapitalize')) {
- $control_input.attr('autocapitalize', $input.attr('autocapitalize'));
- }
- $control_input[0].type = $input[0].type;
-
- self.$wrapper = $wrapper;
- self.$control = $control;
- self.$control_input = $control_input;
- self.$dropdown = $dropdown;
- self.$dropdown_content = $dropdown_content;
-
- $dropdown.on('mouseenter mousedown click', '[data-disabled]>[data-selectable]', function(e) { e.stopImmediatePropagation(); });
- $dropdown.on('mouseenter', '[data-selectable]', function() { return self.onOptionHover.apply(self, arguments); });
- $dropdown.on('mousedown click', '[data-selectable]', function() { return self.onOptionSelect.apply(self, arguments); });
- watchChildEvent($control, 'mousedown', '*:not(input)', function() { return self.onItemSelect.apply(self, arguments); });
- autoGrow($control_input);
-
- $control.on({
- mousedown : function() { return self.onMouseDown.apply(self, arguments); },
- click : function() { return self.onClick.apply(self, arguments); }
- });
-
- $control_input.on({
- mousedown : function(e) { e.stopPropagation(); },
- keydown : function() { return self.onKeyDown.apply(self, arguments); },
- keyup : function() { return self.onKeyUp.apply(self, arguments); },
- keypress : function() { return self.onKeyPress.apply(self, arguments); },
- resize : function() { self.positionDropdown.apply(self, []); },
- blur : function() { return self.onBlur.apply(self, arguments); },
- focus : function() { self.ignoreBlur = false; return self.onFocus.apply(self, arguments); },
- paste : function() { return self.onPaste.apply(self, arguments); }
- });
-
- $document.on('keydown' + eventNS, function(e) {
- self.isCmdDown = e[IS_MAC ? 'metaKey' : 'ctrlKey'];
- self.isCtrlDown = e[IS_MAC ? 'altKey' : 'ctrlKey'];
- self.isShiftDown = e.shiftKey;
- });
-
- $document.on('keyup' + eventNS, function(e) {
- if (e.keyCode === KEY_CTRL) self.isCtrlDown = false;
- if (e.keyCode === KEY_SHIFT) self.isShiftDown = false;
- if (e.keyCode === KEY_CMD) self.isCmdDown = false;
- });
-
- $document.on('mousedown' + eventNS, function(e) {
- if (self.isFocused) {
- // prevent events on the dropdown scrollbar from causing the control to blur
- if (e.target === self.$dropdown[0] || e.target.parentNode === self.$dropdown[0]) {
- return false;
- }
- // blur on click outside
- if (!self.$control.has(e.target).length && e.target !== self.$control[0]) {
- self.blur(e.target);
- }
- }
- });
-
- $window.on(['scroll' + eventNS, 'resize' + eventNS].join(' '), function() {
- if (self.isOpen) {
- self.positionDropdown.apply(self, arguments);
- }
- });
- $window.on('mousemove' + eventNS, function() {
- self.ignoreHover = false;
- });
-
- // store original children and tab index so that they can be
- // restored when the destroy() method is called.
- this.revertSettings = {
- $children : $input.children().detach(),
- tabindex : $input.attr('tabindex')
- };
-
- $input.attr('tabindex', -1).hide().after(self.$wrapper);
-
- if ($.isArray(settings.items)) {
- self.setValue(settings.items);
- delete settings.items;
- }
-
- // feature detect for the validation API
- if (SUPPORTS_VALIDITY_API) {
- $input.on('invalid' + eventNS, function(e) {
- e.preventDefault();
- self.isInvalid = true;
- self.refreshState();
- });
- }
-
- self.updateOriginalInput();
- self.refreshItems();
- self.refreshState();
- self.updatePlaceholder();
- self.isSetup = true;
-
- if ($input.is(':disabled')) {
- self.disable();
- }
-
- self.on('change', this.onChange);
-
- $input.data('selectize', self);
- $input.addClass('selectized');
- self.trigger('initialize');
-
- // preload options
- if (settings.preload === true) {
- self.onSearchChange('');
- }
-
- },
-
- /**
- * Sets up default rendering functions.
- */
- setupTemplates: function() {
- var self = this;
- var field_label = self.settings.labelField;
- var field_optgroup = self.settings.optgroupLabelField;
-
- var templates = {
- 'optgroup': function(data) {
- return '<div class="optgroup">' + data.html + '</div>';
- },
- 'optgroup_header': function(data, escape) {
- return '<div class="optgroup-header">' + escape(data[field_optgroup]) + '</div>';
- },
- 'option': function(data, escape) {
- return '<div class="option">' + escape(data[field_label]) + '</div>';
- },
- 'item': function(data, escape) {
- return '<div class="item">' + escape(data[field_label]) + '</div>';
- },
- 'option_create': function(data, escape) {
- return '<div class="create">Add <strong>' + escape(data.input) + '</strong>&hellip;</div>';
- }
- };
-
- self.settings.render = $.extend({}, templates, self.settings.render);
- },
-
- /**
- * Maps fired events to callbacks provided
- * in the settings used when creating the control.
- */
- setupCallbacks: function() {
- var key, fn, callbacks = {
- 'initialize' : 'onInitialize',
- 'change' : 'onChange',
- 'item_add' : 'onItemAdd',
- 'item_remove' : 'onItemRemove',
- 'clear' : 'onClear',
- 'option_add' : 'onOptionAdd',
- 'option_remove' : 'onOptionRemove',
- 'option_clear' : 'onOptionClear',
- 'optgroup_add' : 'onOptionGroupAdd',
- 'optgroup_remove' : 'onOptionGroupRemove',
- 'optgroup_clear' : 'onOptionGroupClear',
- 'dropdown_open' : 'onDropdownOpen',
- 'dropdown_close' : 'onDropdownClose',
- 'type' : 'onType',
- 'load' : 'onLoad',
- 'focus' : 'onFocus',
- 'blur' : 'onBlur'
- };
-
- for (key in callbacks) {
- if (callbacks.hasOwnProperty(key)) {
- fn = this.settings[callbacks[key]];
- if (fn) this.on(key, fn);
- }
- }
- },
-
- /**
- * Triggered when the main control element
- * has a click event.
- *
- * @param {object} e
- * @return {boolean}
- */
- onClick: function(e) {
- var self = this;
-
- // necessary for mobile webkit devices (manual focus triggering
- // is ignored unless invoked within a click event)
- // also necessary to reopen a dropdown that has been closed by
- // closeAfterSelect
- if (!self.isFocused || !self.isOpen) {
- self.focus();
- e.preventDefault();
- }
- },
-
- /**
- * Triggered when the main control element
- * has a mouse down event.
- *
- * @param {object} e
- * @return {boolean}
- */
- onMouseDown: function(e) {
- var self = this;
- var defaultPrevented = e.isDefaultPrevented();
- var $target = $(e.target);
-
- if (self.isFocused) {
- // retain focus by preventing native handling. if the
- // event target is the input it should not be modified.
- // otherwise, text selection within the input won't work.
- if (e.target !== self.$control_input[0]) {
- if (self.settings.mode === 'single') {
- // toggle dropdown
- self.isOpen ? self.close() : self.open();
- } else if (!defaultPrevented) {
- self.setActiveItem(null);
- }
- return false;
- }
- } else {
- // give control focus
- if (!defaultPrevented) {
- window.setTimeout(function() {
- self.focus();
- }, 0);
- }
- }
- },
-
- /**
- * Triggered when the value of the control has been changed.
- * This should propagate the event to the original DOM
- * input / select element.
- */
- onChange: function() {
- this.$input.trigger('change');
- },
-
- /**
- * Triggered on <input> paste.
- *
- * @param {object} e
- * @returns {boolean}
- */
- onPaste: function(e) {
- var self = this;
-
- if (self.isFull() || self.isInputHidden || self.isLocked) {
- e.preventDefault();
- return;
- }
-
- // If a regex or string is included, this will split the pasted
- // input and create Items for each separate value
- if (self.settings.splitOn) {
-
- // Wait for pasted text to be recognized in value
- setTimeout(function() {
- var pastedText = self.$control_input.val();
- if(!pastedText.match(self.settings.splitOn)){ return }
-
- var splitInput = $.trim(pastedText).split(self.settings.splitOn);
- for (var i = 0, n = splitInput.length; i < n; i++) {
- self.createItem(splitInput[i]);
- }
- }, 0);
- }
- },
-
- /**
- * Triggered on <input> keypress.
- *
- * @param {object} e
- * @returns {boolean}
- */
- onKeyPress: function(e) {
- if (this.isLocked) return e && e.preventDefault();
- var character = String.fromCharCode(e.keyCode || e.which);
- if (this.settings.create && this.settings.mode === 'multi' && character === this.settings.delimiter) {
- this.createItem();
- e.preventDefault();
- return false;
- }
- },
-
- /**
- * Triggered on <input> keydown.
- *
- * @param {object} e
- * @returns {boolean}
- */
- onKeyDown: function(e) {
- var isInput = e.target === this.$control_input[0];
- var self = this;
-
- if (self.isLocked) {
- if (e.keyCode !== KEY_TAB) {
- e.preventDefault();
- }
- return;
- }
-
- switch (e.keyCode) {
- case KEY_A:
- if (self.isCmdDown) {
- self.selectAll();
- return;
- }
- break;
- case KEY_ESC:
- if (self.isOpen) {
- e.preventDefault();
- e.stopPropagation();
- self.close();
- }
- return;
- case KEY_N:
- if (!e.ctrlKey || e.altKey) break;
- case KEY_DOWN:
- if (!self.isOpen && self.hasOptions) {
- self.open();
- } else if (self.$activeOption) {
- self.ignoreHover = true;
- var $next = self.getAdjacentOption(self.$activeOption, 1);
- if ($next.length) self.setActiveOption($next, true, true);
- }
- e.preventDefault();
- return;
- case KEY_P:
- if (!e.ctrlKey || e.altKey) break;
- case KEY_UP:
- if (self.$activeOption) {
- self.ignoreHover = true;
- var $prev = self.getAdjacentOption(self.$activeOption, -1);
- if ($prev.length) self.setActiveOption($prev, true, true);
- }
- e.preventDefault();
- return;
- case KEY_RETURN:
- if (self.isOpen && self.$activeOption) {
- self.onOptionSelect({currentTarget: self.$activeOption});
- e.preventDefault();
- }
- return;
- case KEY_LEFT:
- self.advanceSelection(-1, e);
- return;
- case KEY_RIGHT:
- self.advanceSelection(1, e);
- return;
- case KEY_TAB:
- if (self.settings.selectOnTab && self.isOpen && self.$activeOption) {
- self.onOptionSelect({currentTarget: self.$activeOption});
-
- // Default behaviour is to jump to the next field, we only want this
- // if the current field doesn't accept any more entries
- if (!self.isFull()) {
- e.preventDefault();
- }
- }
- if (self.settings.create && self.createItem()) {
- e.preventDefault();
- }
- return;
- case KEY_BACKSPACE:
- case KEY_DELETE:
- self.deleteSelection(e);
- return;
- }
-
- if ((self.isFull() || self.isInputHidden) && !(IS_MAC ? e.metaKey : e.ctrlKey)) {
- e.preventDefault();
- return;
- }
- },
-
- /**
- * Triggered on <input> keyup.
- *
- * @param {object} e
- * @returns {boolean}
- */
- onKeyUp: function(e) {
- var self = this;
-
- if (self.isLocked) return e && e.preventDefault();
- var value = self.$control_input.val() || '';
- if (self.lastValue !== value) {
- self.lastValue = value;
- self.onSearchChange(value);
- self.refreshOptions();
- self.trigger('type', value);
- }
- },
-
- /**
- * Invokes the user-provide option provider / loader.
- *
- * Note: this function is debounced in the Selectize
- * constructor (by `settings.loadThrottle` milliseconds)
- *
- * @param {string} value
- */
- onSearchChange: function(value) {
- var self = this;
- var fn = self.settings.load;
- if (!fn) return;
- if (self.loadedSearches.hasOwnProperty(value)) return;
- self.loadedSearches[value] = true;
- self.load(function(callback) {
- fn.apply(self, [value, callback]);
- });
- },
-
- /**
- * Triggered on <input> focus.
- *
- * @param {object} e (optional)
- * @returns {boolean}
- */
- onFocus: function(e) {
- var self = this;
- var wasFocused = self.isFocused;
-
- if (self.isDisabled) {
- self.blur();
- e && e.preventDefault();
- return false;
- }
-
- if (self.ignoreFocus) return;
- self.isFocused = true;
- if (self.settings.preload === 'focus') self.onSearchChange('');
-
- if (!wasFocused) self.trigger('focus');
-
- if (!self.$activeItems.length) {
- self.showInput();
- self.setActiveItem(null);
- self.refreshOptions(!!self.settings.openOnFocus);
- }
-
- self.refreshState();
- },
-
- /**
- * Triggered on <input> blur.
- *
- * @param {object} e
- * @param {Element} dest
- */
- onBlur: function(e, dest) {
- var self = this;
- if (!self.isFocused) return;
- self.isFocused = false;
-
- if (self.ignoreFocus) {
- return;
- } else if (!self.ignoreBlur && document.activeElement === self.$dropdown_content[0]) {
- // necessary to prevent IE closing the dropdown when the scrollbar is clicked
- self.ignoreBlur = true;
- self.onFocus(e);
- return;
- }
-
- var deactivate = function() {
- self.close();
- self.setTextboxValue('');
- self.setActiveItem(null);
- self.setActiveOption(null);
- self.setCaret(self.items.length);
- self.refreshState();
-
- // IE11 bug: element still marked as active
- dest && dest.focus && dest.focus();
-
- self.isBlurring = false;
- self.ignoreFocus = false;
- self.trigger('blur');
- };
-
- self.isBlurring = true;
- self.ignoreFocus = true;
- if (self.settings.create && self.settings.createOnBlur) {
- self.createItem(null, false, deactivate);
- } else {
- deactivate();
- }
- },
-
- /**
- * Triggered when the user rolls over
- * an option in the autocomplete dropdown menu.
- *
- * @param {object} e
- * @returns {boolean}
- */
- onOptionHover: function(e) {
- if (this.ignoreHover) return;
- this.setActiveOption(e.currentTarget, false);
- },
-
- /**
- * Triggered when the user clicks on an option
- * in the autocomplete dropdown menu.
- *
- * @param {object} e
- * @returns {boolean}
- */
- onOptionSelect: function(e) {
- var value, $target, $option, self = this;
-
- if (e.preventDefault) {
- e.preventDefault();
- e.stopPropagation();
- }
-
- $target = $(e.currentTarget);
- if ($target.hasClass('create')) {
- self.createItem(null, function() {
- if (self.settings.closeAfterSelect) {
- self.close();
- }
- });
- } else {
- value = $target.attr('data-value');
- if (typeof value !== 'undefined') {
- self.lastQuery = null;
- self.setTextboxValue('');
- self.addItem(value);
- if (self.settings.closeAfterSelect) {
- self.close();
- } else if (!self.settings.hideSelected && e.type && /mouse/.test(e.type)) {
- self.setActiveOption(self.getOption(value));
- }
- }
- }
- },
-
- /**
- * Triggered when the user clicks on an item
- * that has been selected.
- *
- * @param {object} e
- * @returns {boolean}
- */
- onItemSelect: function(e) {
- var self = this;
-
- if (self.isLocked) return;
- if (self.settings.mode === 'multi') {
- e.preventDefault();
- self.setActiveItem(e.currentTarget, e);
- }
- },
-
- /**
- * Invokes the provided method that provides
- * results to a callback---which are then added
- * as options to the control.
- *
- * @param {function} fn
- */
- load: function(fn) {
- var self = this;
- var $wrapper = self.$wrapper.addClass(self.settings.loadingClass);
-
- self.loading++;
- fn.apply(self, [function(results) {
- self.loading = Math.max(self.loading - 1, 0);
- if (results && results.length) {
- self.addOption(results);
- self.refreshOptions(self.isFocused && !self.isInputHidden);
- }
- if (!self.loading) {
- $wrapper.removeClass(self.settings.loadingClass);
- }
- self.trigger('load', results);
- }]);
- },
-
- /**
- * Sets the input field of the control to the specified value.
- *
- * @param {string} value
- */
- setTextboxValue: function(value) {
- var $input = this.$control_input;
- var changed = $input.val() !== value;
- if (changed) {
- $input.val(value).triggerHandler('update');
- this.lastValue = value;
- }
- },
-
- /**
- * Returns the value of the control. If multiple items
- * can be selected (e.g. <select multiple>), this returns
- * an array. If only one item can be selected, this
- * returns a string.
- *
- * @returns {mixed}
- */
- getValue: function() {
- if (this.tagType === TAG_SELECT && this.$input.attr('multiple')) {
- return this.items;
- } else {
- return this.items.join(this.settings.delimiter);
- }
- },
-
- /**
- * Resets the selected items to the given value.
- *
- * @param {mixed} value
- */
- setValue: function(value, silent) {
- var events = silent ? [] : ['change'];
-
- debounce_events(this, events, function() {
- this.clear(silent);
- this.addItems(value, silent);
- });
- },
-
- /**
- * Sets the selected item.
- *
- * @param {object} $item
- * @param {object} e (optional)
- */
- setActiveItem: function($item, e) {
- var self = this;
- var eventName;
- var i, idx, begin, end, item, swap;
- var $last;
-
- if (self.settings.mode === 'single') return;
- $item = $($item);
-
- // clear the active selection
- if (!$item.length) {
- $(self.$activeItems).removeClass('active');
- self.$activeItems = [];
- if (self.isFocused) {
- self.showInput();
- }
- return;
- }
-
- // modify selection
- eventName = e && e.type.toLowerCase();
-
- if (eventName === 'mousedown' && self.isShiftDown && self.$activeItems.length) {
- $last = self.$control.children('.active:last');
- begin = Array.prototype.indexOf.apply(self.$control[0].childNodes, [$last[0]]);
- end = Array.prototype.indexOf.apply(self.$control[0].childNodes, [$item[0]]);
- if (begin > end) {
- swap = begin;
- begin = end;
- end = swap;
- }
- for (i = begin; i <= end; i++) {
- item = self.$control[0].childNodes[i];
- if (self.$activeItems.indexOf(item) === -1) {
- $(item).addClass('active');
- self.$activeItems.push(item);
- }
- }
- e.preventDefault();
- } else if ((eventName === 'mousedown' && self.isCtrlDown) || (eventName === 'keydown' && this.isShiftDown)) {
- if ($item.hasClass('active')) {
- idx = self.$activeItems.indexOf($item[0]);
- self.$activeItems.splice(idx, 1);
- $item.removeClass('active');
- } else {
- self.$activeItems.push($item.addClass('active')[0]);
- }
- } else {
- $(self.$activeItems).removeClass('active');
- self.$activeItems = [$item.addClass('active')[0]];
- }
-
- // ensure control has focus
- self.hideInput();
- if (!this.isFocused) {
- self.focus();
- }
- },
-
- /**
- * Sets the selected item in the dropdown menu
- * of available options.
- *
- * @param {object} $object
- * @param {boolean} scroll
- * @param {boolean} animate
- */
- setActiveOption: function($option, scroll, animate) {
- var height_menu, height_item, y;
- var scroll_top, scroll_bottom;
- var self = this;
-
- if (self.$activeOption) self.$activeOption.removeClass('active');
- self.$activeOption = null;
-
- $option = $($option);
- if (!$option.length) return;
-
- self.$activeOption = $option.addClass('active');
-
- if (scroll || !isset(scroll)) {
-
- height_menu = self.$dropdown_content.height();
- height_item = self.$activeOption.outerHeight(true);
- scroll = self.$dropdown_content.scrollTop() || 0;
- y = self.$activeOption.offset().top - self.$dropdown_content.offset().top + scroll;
- scroll_top = y;
- scroll_bottom = y - height_menu + height_item;
-
- if (y + height_item > height_menu + scroll) {
- self.$dropdown_content.stop().animate({scrollTop: scroll_bottom}, animate ? self.settings.scrollDuration : 0);
- } else if (y < scroll) {
- self.$dropdown_content.stop().animate({scrollTop: scroll_top}, animate ? self.settings.scrollDuration : 0);
- }
-
- }
- },
-
- /**
- * Selects all items (CTRL + A).
- */
- selectAll: function() {
- var self = this;
- if (self.settings.mode === 'single') return;
-
- self.$activeItems = Array.prototype.slice.apply(self.$control.children(':not(input)').addClass('active'));
- if (self.$activeItems.length) {
- self.hideInput();
- self.close();
- }
- self.focus();
- },
-
- /**
- * Hides the input element out of view, while
- * retaining its focus.
- */
- hideInput: function() {
- var self = this;
-
- self.setTextboxValue('');
- self.$control_input.css({opacity: 0, position: 'absolute', left: self.rtl ? 10000 : -10000});
- self.isInputHidden = true;
- },
-
- /**
- * Restores input visibility.
- */
- showInput: function() {
- this.$control_input.css({opacity: 1, position: 'relative', left: 0});
- this.isInputHidden = false;
- },
-
- /**
- * Gives the control focus.
- */
- focus: function() {
- var self = this;
- if (self.isDisabled) return;
-
- self.ignoreFocus = true;
- self.$control_input[0].focus();
- window.setTimeout(function() {
- self.ignoreFocus = false;
- self.onFocus();
- }, 0);
- },
-
- /**
- * Forces the control out of focus.
- *
- * @param {Element} dest
- */
- blur: function(dest) {
- this.$control_input[0].blur();
- this.onBlur(null, dest);
- },
-
- /**
- * Returns a function that scores an object
- * to show how good of a match it is to the
- * provided query.
- *
- * @param {string} query
- * @param {object} options
- * @return {function}
- */
- getScoreFunction: function(query) {
- return this.sifter.getScoreFunction(query, this.getSearchOptions());
- },
-
- /**
- * Returns search options for sifter (the system
- * for scoring and sorting results).
- *
- * @see https://github.com/brianreavis/sifter.js
- * @return {object}
- */
- getSearchOptions: function() {
- var settings = this.settings;
- var sort = settings.sortField;
- if (typeof sort === 'string') {
- sort = [{field: sort}];
- }
-
- return {
- fields : settings.searchField,
- conjunction : settings.searchConjunction,
- sort : sort,
- nesting : settings.nesting
- };
- },
-
- /**
- * Searches through available options and returns
- * a sorted array of matches.
- *
- * Returns an object containing:
- *
- * - query {string}
- * - tokens {array}
- * - total {int}
- * - items {array}
- *
- * @param {string} query
- * @returns {object}
- */
- search: function(query) {
- var i, value, score, result, calculateScore;
- var self = this;
- var settings = self.settings;
- var options = this.getSearchOptions();
-
- // validate user-provided result scoring function
- if (settings.score) {
- calculateScore = self.settings.score.apply(this, [query]);
- if (typeof calculateScore !== 'function') {
- throw new Error('Selectize "score" setting must be a function that returns a function');
- }
- }
-
- // perform search
- if (query !== self.lastQuery) {
- self.lastQuery = query;
- result = self.sifter.search(query, $.extend(options, {score: calculateScore}));
- self.currentResults = result;
- } else {
- result = $.extend(true, {}, self.currentResults);
- }
-
- // filter out selected items
- if (settings.hideSelected) {
- for (i = result.items.length - 1; i >= 0; i--) {
- if (self.items.indexOf(hash_key(result.items[i].id)) !== -1) {
- result.items.splice(i, 1);
- }
- }
- }
-
- return result;
- },
-
- /**
- * Refreshes the list of available options shown
- * in the autocomplete dropdown menu.
- *
- * @param {boolean} triggerDropdown
- */
- refreshOptions: function(triggerDropdown) {
- var i, j, k, n, groups, groups_order, option, option_html, optgroup, optgroups, html, html_children, has_create_option;
- var $active, $active_before, $create;
-
- if (typeof triggerDropdown === 'undefined') {
- triggerDropdown = true;
- }
-
- var self = this;
- var query = $.trim(self.$control_input.val());
- var results = self.search(query);
- var $dropdown_content = self.$dropdown_content;
- var active_before = self.$activeOption && hash_key(self.$activeOption.attr('data-value'));
-
- // build markup
- n = results.items.length;
- if (typeof self.settings.maxOptions === 'number') {
- n = Math.min(n, self.settings.maxOptions);
- }
-
- // render and group available options individually
- groups = {};
- groups_order = [];
-
- for (i = 0; i < n; i++) {
- option = self.options[results.items[i].id];
- option_html = self.render('option', option);
- optgroup = option[self.settings.optgroupField] || '';
- optgroups = $.isArray(optgroup) ? optgroup : [optgroup];
-
- for (j = 0, k = optgroups && optgroups.length; j < k; j++) {
- optgroup = optgroups[j];
- if (!self.optgroups.hasOwnProperty(optgroup)) {
- optgroup = '';
- }
- if (!groups.hasOwnProperty(optgroup)) {
- groups[optgroup] = document.createDocumentFragment();
- groups_order.push(optgroup);
- }
- groups[optgroup].appendChild(option_html);
- }
- }
-
- // sort optgroups
- if (this.settings.lockOptgroupOrder) {
- groups_order.sort(function(a, b) {
- var a_order = self.optgroups[a].$order || 0;
- var b_order = self.optgroups[b].$order || 0;
- return a_order - b_order;
- });
- }
-
- // render optgroup headers & join groups
- html = document.createDocumentFragment();
- for (i = 0, n = groups_order.length; i < n; i++) {
- optgroup = groups_order[i];
- if (self.optgroups.hasOwnProperty(optgroup) && groups[optgroup].childNodes.length) {
- // render the optgroup header and options within it,
- // then pass it to the wrapper template
- html_children = document.createDocumentFragment();
- html_children.appendChild(self.render('optgroup_header', self.optgroups[optgroup]));
- html_children.appendChild(groups[optgroup]);
-
- html.appendChild(self.render('optgroup', $.extend({}, self.optgroups[optgroup], {
- html: domToString(html_children),
- dom: html_children
- })));
- } else {
- html.appendChild(groups[optgroup]);
- }
- }
-
- $dropdown_content.html(html);
-
- // highlight matching terms inline
- if (self.settings.highlight) {
- $dropdown_content.removeHighlight();
- if (results.query.length && results.tokens.length) {
- for (i = 0, n = results.tokens.length; i < n; i++) {
- highlight($dropdown_content, results.tokens[i].regex);
- }
- }
- }
-
- // add "selected" class to selected options
- if (!self.settings.hideSelected) {
- for (i = 0, n = self.items.length; i < n; i++) {
- self.getOption(self.items[i]).addClass('selected');
- }
- }
-
- // add create option
- has_create_option = self.canCreate(query);
- if (has_create_option) {
- $dropdown_content.prepend(self.render('option_create', {input: query}));
- $create = $($dropdown_content[0].childNodes[0]);
- }
-
- // activate
- self.hasOptions = results.items.length > 0 || has_create_option;
- if (self.hasOptions) {
- if (results.items.length > 0) {
- $active_before = active_before && self.getOption(active_before);
- if ($active_before && $active_before.length) {
- $active = $active_before;
- } else if (self.settings.mode === 'single' && self.items.length) {
- $active = self.getOption(self.items[0]);
- }
- if (!$active || !$active.length) {
- if ($create && !self.settings.addPrecedence) {
- $active = self.getAdjacentOption($create, 1);
- } else {
- $active = $dropdown_content.find('[data-selectable]:first');
- }
- }
- } else {
- $active = $create;
- }
- self.setActiveOption($active);
- if (triggerDropdown && !self.isOpen) { self.open(); }
- } else {
- self.setActiveOption(null);
- if (triggerDropdown && self.isOpen) { self.close(); }
- }
- },
-
- /**
- * Adds an available option. If it already exists,
- * nothing will happen. Note: this does not refresh
- * the options list dropdown (use `refreshOptions`
- * for that).
- *
- * Usage:
- *
- * this.addOption(data)
- *
- * @param {object|array} data
- */
- addOption: function(data) {
- var i, n, value, self = this;
-
- if ($.isArray(data)) {
- for (i = 0, n = data.length; i < n; i++) {
- self.addOption(data[i]);
- }
- return;
- }
-
- if (value = self.registerOption(data)) {
- self.userOptions[value] = true;
- self.lastQuery = null;
- self.trigger('option_add', value, data);
- }
- },
-
- /**
- * Registers an option to the pool of options.
- *
- * @param {object} data
- * @return {boolean|string}
- */
- registerOption: function(data) {
- var key = hash_key(data[this.settings.valueField]);
- if (typeof key === 'undefined' || key === null || this.options.hasOwnProperty(key)) return false;
- data.$order = data.$order || ++this.order;
- this.options[key] = data;
- return key;
- },
-
- /**
- * Registers an option group to the pool of option groups.
- *
- * @param {object} data
- * @return {boolean|string}
- */
- registerOptionGroup: function(data) {
- var key = hash_key(data[this.settings.optgroupValueField]);
- if (!key) return false;
-
- data.$order = data.$order || ++this.order;
- this.optgroups[key] = data;
- return key;
- },
-
- /**
- * Registers a new optgroup for options
- * to be bucketed into.
- *
- * @param {string} id
- * @param {object} data
- */
- addOptionGroup: function(id, data) {
- data[this.settings.optgroupValueField] = id;
- if (id = this.registerOptionGroup(data)) {
- this.trigger('optgroup_add', id, data);
- }
- },
-
- /**
- * Removes an existing option group.
- *
- * @param {string} id
- */
- removeOptionGroup: function(id) {
- if (this.optgroups.hasOwnProperty(id)) {
- delete this.optgroups[id];
- this.renderCache = {};
- this.trigger('optgroup_remove', id);
- }
- },
-
- /**
- * Clears all existing option groups.
- */
- clearOptionGroups: function() {
- this.optgroups = {};
- this.renderCache = {};
- this.trigger('optgroup_clear');
- },
-
- /**
- * Updates an option available for selection. If
- * it is visible in the selected items or options
- * dropdown, it will be re-rendered automatically.
- *
- * @param {string} value
- * @param {object} data
- */
- updateOption: function(value, data) {
- var self = this;
- var $item, $item_new;
- var value_new, index_item, cache_items, cache_options, order_old;
-
- value = hash_key(value);
- value_new = hash_key(data[self.settings.valueField]);
-
- // sanity checks
- if (value === null) return;
- if (!self.options.hasOwnProperty(value)) return;
- if (typeof value_new !== 'string') throw new Error('Value must be set in option data');
-
- order_old = self.options[value].$order;
-
- // update references
- if (value_new !== value) {
- delete self.options[value];
- index_item = self.items.indexOf(value);
- if (index_item !== -1) {
- self.items.splice(index_item, 1, value_new);
- }
- }
- data.$order = data.$order || order_old;
- self.options[value_new] = data;
-
- // invalidate render cache
- cache_items = self.renderCache['item'];
- cache_options = self.renderCache['option'];
-
- if (cache_items) {
- delete cache_items[value];
- delete cache_items[value_new];
- }
- if (cache_options) {
- delete cache_options[value];
- delete cache_options[value_new];
- }
-
- // update the item if it's selected
- if (self.items.indexOf(value_new) !== -1) {
- $item = self.getItem(value);
- $item_new = $(self.render('item', data));
- if ($item.hasClass('active')) $item_new.addClass('active');
- $item.replaceWith($item_new);
- }
-
- // invalidate last query because we might have updated the sortField
- self.lastQuery = null;
-
- // update dropdown contents
- if (self.isOpen) {
- self.refreshOptions(false);
- }
- },
-
- /**
- * Removes a single option.
- *
- * @param {string} value
- * @param {boolean} silent
- */
- removeOption: function(value, silent) {
- var self = this;
- value = hash_key(value);
-
- var cache_items = self.renderCache['item'];
- var cache_options = self.renderCache['option'];
- if (cache_items) delete cache_items[value];
- if (cache_options) delete cache_options[value];
-
- delete self.userOptions[value];
- delete self.options[value];
- self.lastQuery = null;
- self.trigger('option_remove', value);
- self.removeItem(value, silent);
- },
-
- /**
- * Clears all options.
- */
- clearOptions: function() {
- var self = this;
-
- self.loadedSearches = {};
- self.userOptions = {};
- self.renderCache = {};
- var options = self.options;
- $.each(self.options, function(key, value) {
- if(self.items.indexOf(key) == -1) {
- delete options[key];
- }
- });
- self.options = self.sifter.items = options;
- self.lastQuery = null;
- self.trigger('option_clear');
- },
-
- /**
- * Returns the jQuery element of the option
- * matching the given value.
- *
- * @param {string} value
- * @returns {object}
- */
- getOption: function(value) {
- return this.getElementWithValue(value, this.$dropdown_content.find('[data-selectable]'));
- },
-
- /**
- * Returns the jQuery element of the next or
- * previous selectable option.
- *
- * @param {object} $option
- * @param {int} direction can be 1 for next or -1 for previous
- * @return {object}
- */
- getAdjacentOption: function($option, direction) {
- var $options = this.$dropdown.find('[data-selectable]');
- var index = $options.index($option) + direction;
-
- return index >= 0 && index < $options.length ? $options.eq(index) : $();
- },
-
- /**
- * Finds the first element with a "data-value" attribute
- * that matches the given value.
- *
- * @param {mixed} value
- * @param {object} $els
- * @return {object}
- */
- getElementWithValue: function(value, $els) {
- value = hash_key(value);
-
- if (typeof value !== 'undefined' && value !== null) {
- for (var i = 0, n = $els.length; i < n; i++) {
- if ($els[i].getAttribute('data-value') === value) {
- return $($els[i]);
- }
- }
- }
-
- return $();
- },
-
- /**
- * Returns the jQuery element of the item
- * matching the given value.
- *
- * @param {string} value
- * @returns {object}
- */
- getItem: function(value) {
- return this.getElementWithValue(value, this.$control.children());
- },
-
- /**
- * "Selects" multiple items at once. Adds them to the list
- * at the current caret position.
- *
- * @param {string} value
- * @param {boolean} silent
- */
- addItems: function(values, silent) {
- this.buffer = document.createDocumentFragment();
-
- var childNodes = this.$control[0].childNodes;
- for (var i = 0; i < childNodes.length; i++) {
- this.buffer.appendChild(childNodes[i]);
- }
-
- var items = $.isArray(values) ? values : [values];
- for (var i = 0, n = items.length; i < n; i++) {
- this.isPending = (i < n - 1);
- this.addItem(items[i], silent);
- }
-
- var control = this.$control[0];
- control.insertBefore(this.buffer, control.firstChild);
-
- this.buffer = null;
- },
-
- /**
- * "Selects" an item. Adds it to the list
- * at the current caret position.
- *
- * @param {string} value
- * @param {boolean} silent
- */
- addItem: function(value, silent) {
- var events = silent ? [] : ['change'];
-
- debounce_events(this, events, function() {
- var $item, $option, $options;
- var self = this;
- var inputMode = self.settings.mode;
- var i, active, value_next, wasFull;
- value = hash_key(value);
-
- if (self.items.indexOf(value) !== -1) {
- if (inputMode === 'single') self.close();
- return;
- }
-
- if (!self.options.hasOwnProperty(value)) return;
- if (inputMode === 'single') self.clear(silent);
- if (inputMode === 'multi' && self.isFull()) return;
-
- $item = $(self.render('item', self.options[value]));
- wasFull = self.isFull();
- self.items.splice(self.caretPos, 0, value);
- self.insertAtCaret($item);
- if (!self.isPending || (!wasFull && self.isFull())) {
- self.refreshState();
- }
-
- if (self.isSetup) {
- $options = self.$dropdown_content.find('[data-selectable]');
-
- // update menu / remove the option (if this is not one item being added as part of series)
- if (!self.isPending) {
- $option = self.getOption(value);
- value_next = self.getAdjacentOption($option, 1).attr('data-value');
- self.refreshOptions(self.isFocused && inputMode !== 'single');
- if (value_next) {
- self.setActiveOption(self.getOption(value_next));
- }
- }
-
- // hide the menu if the maximum number of items have been selected or no options are left
- if (!$options.length || self.isFull()) {
- self.close();
- } else if (!self.isPending) {
- self.positionDropdown();
- }
-
- self.updatePlaceholder();
- self.trigger('item_add', value, $item);
-
- if (!self.isPending) {
- self.updateOriginalInput({silent: silent});
- }
- }
- });
- },
-
- /**
- * Removes the selected item matching
- * the provided value.
- *
- * @param {string} value
- */
- removeItem: function(value, silent) {
- var self = this;
- var $item, i, idx;
-
- $item = (value instanceof $) ? value : self.getItem(value);
- value = hash_key($item.attr('data-value'));
- i = self.items.indexOf(value);
-
- if (i !== -1) {
- $item.remove();
- if ($item.hasClass('active')) {
- idx = self.$activeItems.indexOf($item[0]);
- self.$activeItems.splice(idx, 1);
- }
-
- self.items.splice(i, 1);
- self.lastQuery = null;
- if (!self.settings.persist && self.userOptions.hasOwnProperty(value)) {
- self.removeOption(value, silent);
- }
-
- if (i < self.caretPos) {
- self.setCaret(self.caretPos - 1);
- }
-
- self.refreshState();
- self.updatePlaceholder();
- self.updateOriginalInput({silent: silent});
- self.positionDropdown();
- self.trigger('item_remove', value, $item);
- }
- },
-
- /**
- * Invokes the `create` method provided in the
- * selectize options that should provide the data
- * for the new item, given the user input.
- *
- * Once this completes, it will be added
- * to the item list.
- *
- * @param {string} value
- * @param {boolean} [triggerDropdown]
- * @param {function} [callback]
- * @return {boolean}
- */
- createItem: function(input, triggerDropdown) {
- var self = this;
- var caret = self.caretPos;
- input = input || $.trim(self.$control_input.val() || '');
-
- var callback = arguments[arguments.length - 1];
- if (typeof callback !== 'function') callback = function() {};
-
- if (typeof triggerDropdown !== 'boolean') {
- triggerDropdown = true;
- }
-
- if (!self.canCreate(input)) {
- callback();
- return false;
- }
-
- self.lock();
-
- var setup = (typeof self.settings.create === 'function') ? this.settings.create : function(input) {
- var data = {};
- data[self.settings.labelField] = input;
- data[self.settings.valueField] = input;
- return data;
- };
-
- var create = once(function(data) {
- self.unlock();
-
- if (!data || typeof data !== 'object') return callback();
- var value = hash_key(data[self.settings.valueField]);
- if (typeof value !== 'string') return callback();
-
- self.setTextboxValue('');
- self.addOption(data);
- self.setCaret(caret);
- self.addItem(value);
- self.refreshOptions(triggerDropdown && self.settings.mode !== 'single');
- callback(data);
- });
-
- var output = setup.apply(this, [input, create]);
- if (typeof output !== 'undefined') {
- create(output);
- }
-
- return true;
- },
-
- /**
- * Re-renders the selected item lists.
- */
- refreshItems: function() {
- this.lastQuery = null;
-
- if (this.isSetup) {
- this.addItem(this.items);
- }
-
- this.refreshState();
- this.updateOriginalInput();
- },
-
- /**
- * Updates all state-dependent attributes
- * and CSS classes.
- */
- refreshState: function() {
- this.refreshValidityState();
- this.refreshClasses();
- },
-
- /**
- * Update the `required` attribute of both input and control input.
- *
- * The `required` property needs to be activated on the control input
- * for the error to be displayed at the right place. `required` also
- * needs to be temporarily deactivated on the input since the input is
- * hidden and can't show errors.
- */
- refreshValidityState: function() {
- if (!this.isRequired) return false;
-
- var invalid = !this.items.length;
-
- this.isInvalid = invalid;
- this.$control_input.prop('required', invalid);
- this.$input.prop('required', !invalid);
- },
-
- /**
- * Updates all state-dependent CSS classes.
- */
- refreshClasses: function() {
- var self = this;
- var isFull = self.isFull();
- var isLocked = self.isLocked;
-
- self.$wrapper
- .toggleClass('rtl', self.rtl);
-
- self.$control
- .toggleClass('focus', self.isFocused)
- .toggleClass('disabled', self.isDisabled)
- .toggleClass('required', self.isRequired)
- .toggleClass('invalid', self.isInvalid)
- .toggleClass('locked', isLocked)
- .toggleClass('full', isFull).toggleClass('not-full', !isFull)
- .toggleClass('input-active', self.isFocused && !self.isInputHidden)
- .toggleClass('dropdown-active', self.isOpen)
- .toggleClass('has-options', !$.isEmptyObject(self.options))
- .toggleClass('has-items', self.items.length > 0);
-
- self.$control_input.data('grow', !isFull && !isLocked);
- },
-
- /**
- * Determines whether or not more items can be added
- * to the control without exceeding the user-defined maximum.
- *
- * @returns {boolean}
- */
- isFull: function() {
- return this.settings.maxItems !== null && this.items.length >= this.settings.maxItems;
- },
-
- /**
- * Refreshes the original <select> or <input>
- * element to reflect the current state.
- */
- updateOriginalInput: function(opts) {
- var i, n, options, label, self = this;
- opts = opts || {};
-
- if (self.tagType === TAG_SELECT) {
- options = [];
- for (i = 0, n = self.items.length; i < n; i++) {
- label = self.options[self.items[i]][self.settings.labelField] || '';
- options.push('<option value="' + escape_html(self.items[i]) + '" selected="selected">' + escape_html(label) + '</option>');
- }
- if (!options.length && !this.$input.attr('multiple')) {
- options.push('<option value="" selected="selected"></option>');
- }
- self.$input.html(options.join(''));
- } else {
- self.$input.val(self.getValue());
- self.$input.attr('value',self.$input.val());
- }
-
- if (self.isSetup) {
- if (!opts.silent) {
- self.trigger('change', self.$input.val());
- }
- }
- },
-
- /**
- * Shows/hide the input placeholder depending
- * on if there items in the list already.
- */
- updatePlaceholder: function() {
- if (!this.settings.placeholder) return;
- var $input = this.$control_input;
-
- if (this.items.length) {
- $input.removeAttr('placeholder');
- } else {
- $input.attr('placeholder', this.settings.placeholder);
- }
- $input.triggerHandler('update', {force: true});
- },
-
- /**
- * Shows the autocomplete dropdown containing
- * the available options.
- */
- open: function() {
- var self = this;
-
- if (self.isLocked || self.isOpen || (self.settings.mode === 'multi' && self.isFull())) return;
- self.focus();
- self.isOpen = true;
- self.refreshState();
- self.$dropdown.css({visibility: 'hidden', display: 'block'});
- self.positionDropdown();
- self.$dropdown.css({visibility: 'visible'});
- self.trigger('dropdown_open', self.$dropdown);
- },
-
- /**
- * Closes the autocomplete dropdown menu.
- */
- close: function() {
- var self = this;
- var trigger = self.isOpen;
-
- if (self.settings.mode === 'single' && self.items.length) {
- self.hideInput();
-
- // Do not trigger blur while inside a blur event,
- // this fixes some weird tabbing behavior in FF and IE.
- // See #1164
- if (!self.isBlurring) {
- self.$control_input.blur(); // close keyboard on iOS
- }
- }
-
- self.isOpen = false;
- self.$dropdown.hide();
- self.setActiveOption(null);
- self.refreshState();
-
- if (trigger) self.trigger('dropdown_close', self.$dropdown);
- },
-
- /**
- * Calculates and applies the appropriate
- * position of the dropdown.
- */
- positionDropdown: function() {
- var $control = this.$control;
- var offset = this.settings.dropdownParent === 'body' ? $control.offset() : $control.position();
- offset.top += $control.outerHeight(true);
-
- this.$dropdown.css({
- width : $control[0].getBoundingClientRect().width,
- top : offset.top,
- left : offset.left
- });
- },
-
- /**
- * Resets / clears all selected items
- * from the control.
- *
- * @param {boolean} silent
- */
- clear: function(silent) {
- var self = this;
-
- if (!self.items.length) return;
- self.$control.children(':not(input)').remove();
- self.items = [];
- self.lastQuery = null;
- self.setCaret(0);
- self.setActiveItem(null);
- self.updatePlaceholder();
- self.updateOriginalInput({silent: silent});
- self.refreshState();
- self.showInput();
- self.trigger('clear');
- },
-
- /**
- * A helper method for inserting an element
- * at the current caret position.
- *
- * @param {object} $el
- */
- insertAtCaret: function($el) {
- var caret = Math.min(this.caretPos, this.items.length);
- var el = $el[0];
- var target = this.buffer || this.$control[0];
-
- if (caret === 0) {
- target.insertBefore(el, target.firstChild);
- } else {
- target.insertBefore(el, target.childNodes[caret]);
- }
-
- this.setCaret(caret + 1);
- },
-
- /**
- * Removes the current selected item(s).
- *
- * @param {object} e (optional)
- * @returns {boolean}
- */
- deleteSelection: function(e) {
- var i, n, direction, selection, values, caret, option_select, $option_select, $tail;
- var self = this;
-
- direction = (e && e.keyCode === KEY_BACKSPACE) ? -1 : 1;
- selection = getSelection(self.$control_input[0]);
-
- if (self.$activeOption && !self.settings.hideSelected) {
- option_select = self.getAdjacentOption(self.$activeOption, -1).attr('data-value');
- }
-
- // determine items that will be removed
- values = [];
-
- if (self.$activeItems.length) {
- $tail = self.$control.children('.active:' + (direction > 0 ? 'last' : 'first'));
- caret = self.$control.children(':not(input)').index($tail);
- if (direction > 0) { caret++; }
-
- for (i = 0, n = self.$activeItems.length; i < n; i++) {
- values.push($(self.$activeItems[i]).attr('data-value'));
- }
- if (e) {
- e.preventDefault();
- e.stopPropagation();
- }
- } else if ((self.isFocused || self.settings.mode === 'single') && self.items.length) {
- if (direction < 0 && selection.start === 0 && selection.length === 0) {
- values.push(self.items[self.caretPos - 1]);
- } else if (direction > 0 && selection.start === self.$control_input.val().length) {
- values.push(self.items[self.caretPos]);
- }
- }
-
- // allow the callback to abort
- if (!values.length || (typeof self.settings.onDelete === 'function' && self.settings.onDelete.apply(self, [values]) === false)) {
- return false;
- }
-
- // perform removal
- if (typeof caret !== 'undefined') {
- self.setCaret(caret);
- }
- while (values.length) {
- self.removeItem(values.pop());
- }
-
- self.showInput();
- self.positionDropdown();
- self.refreshOptions(true);
-
- // select previous option
- if (option_select) {
- $option_select = self.getOption(option_select);
- if ($option_select.length) {
- self.setActiveOption($option_select);
- }
- }
-
- return true;
- },
-
- /**
- * Selects the previous / next item (depending
- * on the `direction` argument).
- *
- * > 0 - right
- * < 0 - left
- *
- * @param {int} direction
- * @param {object} e (optional)
- */
- advanceSelection: function(direction, e) {
- var tail, selection, idx, valueLength, cursorAtEdge, $tail;
- var self = this;
-
- if (direction === 0) return;
- if (self.rtl) direction *= -1;
-
- tail = direction > 0 ? 'last' : 'first';
- selection = getSelection(self.$control_input[0]);
-
- if (self.isFocused && !self.isInputHidden) {
- valueLength = self.$control_input.val().length;
- cursorAtEdge = direction < 0
- ? selection.start === 0 && selection.length === 0
- : selection.start === valueLength;
-
- if (cursorAtEdge && !valueLength) {
- self.advanceCaret(direction, e);
- }
- } else {
- $tail = self.$control.children('.active:' + tail);
- if ($tail.length) {
- idx = self.$control.children(':not(input)').index($tail);
- self.setActiveItem(null);
- self.setCaret(direction > 0 ? idx + 1 : idx);
- }
- }
- },
-
- /**
- * Moves the caret left / right.
- *
- * @param {int} direction
- * @param {object} e (optional)
- */
- advanceCaret: function(direction, e) {
- var self = this, fn, $adj;
-
- if (direction === 0) return;
-
- fn = direction > 0 ? 'next' : 'prev';
- if (self.isShiftDown) {
- $adj = self.$control_input[fn]();
- if ($adj.length) {
- self.hideInput();
- self.setActiveItem($adj);
- e && e.preventDefault();
- }
- } else {
- self.setCaret(self.caretPos + direction);
- }
- },
-
- /**
- * Moves the caret to the specified index.
- *
- * @param {int} i
- */
- setCaret: function(i) {
- var self = this;
-
- if (self.settings.mode === 'single') {
- i = self.items.length;
- } else {
- i = Math.max(0, Math.min(self.items.length, i));
- }
-
- if(!self.isPending) {
- // the input must be moved by leaving it in place and moving the
- // siblings, due to the fact that focus cannot be restored once lost
- // on mobile webkit devices
- var j, n, fn, $children, $child;
- $children = self.$control.children(':not(input)');
- for (j = 0, n = $children.length; j < n; j++) {
- $child = $($children[j]).detach();
- if (j < i) {
- self.$control_input.before($child);
- } else {
- self.$control.append($child);
- }
- }
- }
-
- self.caretPos = i;
- },
-
- /**
- * Disables user input on the control. Used while
- * items are being asynchronously created.
- */
- lock: function() {
- this.close();
- this.isLocked = true;
- this.refreshState();
- },
-
- /**
- * Re-enables user input on the control.
- */
- unlock: function() {
- this.isLocked = false;
- this.refreshState();
- },
-
- /**
- * Disables user input on the control completely.
- * While disabled, it cannot receive focus.
- */
- disable: function() {
- var self = this;
- self.$input.prop('disabled', true);
- self.$control_input.prop('disabled', true).prop('tabindex', -1);
- self.isDisabled = true;
- self.lock();
- },
-
- /**
- * Enables the control so that it can respond
- * to focus and user input.
- */
- enable: function() {
- var self = this;
- self.$input.prop('disabled', false);
- self.$control_input.prop('disabled', false).prop('tabindex', self.tabIndex);
- self.isDisabled = false;
- self.unlock();
- },
-
- /**
- * Completely destroys the control and
- * unbinds all event listeners so that it can
- * be garbage collected.
- */
- destroy: function() {
- var self = this;
- var eventNS = self.eventNS;
- var revertSettings = self.revertSettings;
-
- self.trigger('destroy');
- self.off();
- self.$wrapper.remove();
- self.$dropdown.remove();
-
- self.$input
- .html('')
- .append(revertSettings.$children)
- .removeAttr('tabindex')
- .removeClass('selectized')
- .attr({tabindex: revertSettings.tabindex})
- .show();
-
- self.$control_input.removeData('grow');
- self.$input.removeData('selectize');
-
- if (--Selectize.count == 0 && Selectize.$testInput) {
- Selectize.$testInput.remove();
- Selectize.$testInput = undefined;
- }
-
- $(window).off(eventNS);
- $(document).off(eventNS);
- $(document.body).off(eventNS);
-
- delete self.$input[0].selectize;
- },
-
- /**
- * A helper method for rendering "item" and
- * "option" templates, given the data.
- *
- * @param {string} templateName
- * @param {object} data
- * @returns {string}
- */
- render: function(templateName, data) {
- var value, id, label;
- var html = '';
- var cache = false;
- var self = this;
- var regex_tag = /^[\t \r\n]*<([a-z][a-z0-9\-_]*(?:\:[a-z][a-z0-9\-_]*)?)/i;
-
- if (templateName === 'option' || templateName === 'item') {
- value = hash_key(data[self.settings.valueField]);
- cache = !!value;
- }
-
- // pull markup from cache if it exists
- if (cache) {
- if (!isset(self.renderCache[templateName])) {
- self.renderCache[templateName] = {};
- }
- if (self.renderCache[templateName].hasOwnProperty(value)) {
- return self.renderCache[templateName][value];
- }
- }
-
- // render markup
- html = $(self.settings.render[templateName].apply(this, [data, escape_html]));
-
- // add mandatory attributes
- if (templateName === 'option' || templateName === 'option_create') {
- if (!data[self.settings.disabledField]) {
- html.attr('data-selectable', '');
- }
- }
- else if (templateName === 'optgroup') {
- id = data[self.settings.optgroupValueField] || '';
- html.attr('data-group', id);
- if(data[self.settings.disabledField]) {
- html.attr('data-disabled', '');
- }
- }
- if (templateName === 'option' || templateName === 'item') {
- html.attr('data-value', value || '');
- }
-
- // update cache
- if (cache) {
- self.renderCache[templateName][value] = html[0];
- }
-
- return html[0];
- },
-
- /**
- * Clears the render cache for a template. If
- * no template is given, clears all render
- * caches.
- *
- * @param {string} templateName
- */
- clearCache: function(templateName) {
- var self = this;
- if (typeof templateName === 'undefined') {
- self.renderCache = {};
- } else {
- delete self.renderCache[templateName];
- }
- },
-
- /**
- * Determines whether or not to display the
- * create item prompt, given a user input.
- *
- * @param {string} input
- * @return {boolean}
- */
- canCreate: function(input) {
- var self = this;
- if (!self.settings.create) return false;
- var filter = self.settings.createFilter;
- return input.length
- && (typeof filter !== 'function' || filter.apply(self, [input]))
- && (typeof filter !== 'string' || new RegExp(filter).test(input))
- && (!(filter instanceof RegExp) || filter.test(input));
- }
-
- });
-
-
- Selectize.count = 0;
- Selectize.defaults = {
- options: [],
- optgroups: [],
-
- plugins: [],
- delimiter: ',',
- splitOn: null, // regexp or string for splitting up values from a paste command
- persist: true,
- diacritics: true,
- create: false,
- createOnBlur: false,
- createFilter: null,
- highlight: true,
- openOnFocus: true,
- maxOptions: 1000,
- maxItems: null,
- hideSelected: null,
- addPrecedence: false,
- selectOnTab: false,
- preload: false,
- allowEmptyOption: false,
- closeAfterSelect: false,
-
- scrollDuration: 60,
- loadThrottle: 300,
- loadingClass: 'loading',
-
- dataAttr: 'data-data',
- optgroupField: 'optgroup',
- valueField: 'value',
- labelField: 'text',
- disabledField: 'disabled',
- optgroupLabelField: 'label',
- optgroupValueField: 'value',
- lockOptgroupOrder: false,
-
- sortField: '$order',
- searchField: ['text'],
- searchConjunction: 'and',
-
- mode: null,
- wrapperClass: 'selectize-control',
- inputClass: 'selectize-input',
- dropdownClass: 'selectize-dropdown',
- dropdownContentClass: 'selectize-dropdown-content',
-
- dropdownParent: null,
-
- copyClassesToDropdown: true,
-
- /*
- load : null, // function(query, callback) { ... }
- score : null, // function(search) { ... }
- onInitialize : null, // function() { ... }
- onChange : null, // function(value) { ... }
- onItemAdd : null, // function(value, $item) { ... }
- onItemRemove : null, // function(value) { ... }
- onClear : null, // function() { ... }
- onOptionAdd : null, // function(value, data) { ... }
- onOptionRemove : null, // function(value) { ... }
- onOptionClear : null, // function() { ... }
- onOptionGroupAdd : null, // function(id, data) { ... }
- onOptionGroupRemove : null, // function(id) { ... }
- onOptionGroupClear : null, // function() { ... }
- onDropdownOpen : null, // function($dropdown) { ... }
- onDropdownClose : null, // function($dropdown) { ... }
- onType : null, // function(str) { ... }
- onDelete : null, // function(values) { ... }
- */
-
- render: {
- /*
- item: null,
- optgroup: null,
- optgroup_header: null,
- option: null,
- option_create: null
- */
- }
- };
-
-
- $.fn.selectize = function(settings_user) {
- var defaults = $.fn.selectize.defaults;
- var settings = $.extend({}, defaults, settings_user);
- var attr_data = settings.dataAttr;
- var field_label = settings.labelField;
- var field_value = settings.valueField;
- var field_disabled = settings.disabledField;
- var field_optgroup = settings.optgroupField;
- var field_optgroup_label = settings.optgroupLabelField;
- var field_optgroup_value = settings.optgroupValueField;
-
- /**
- * Initializes selectize from a <input type="text"> element.
- *
- * @param {object} $input
- * @param {object} settings_element
- */
- var init_textbox = function($input, settings_element) {
- var i, n, values, option;
-
- var data_raw = $input.attr(attr_data);
-
- if (!data_raw) {
- var value = $.trim($input.val() || '');
- if (!settings.allowEmptyOption && !value.length) return;
- values = value.split(settings.delimiter);
- for (i = 0, n = values.length; i < n; i++) {
- option = {};
- option[field_label] = values[i];
- option[field_value] = values[i];
- settings_element.options.push(option);
- }
- settings_element.items = values;
- } else {
- settings_element.options = JSON.parse(data_raw);
- for (i = 0, n = settings_element.options.length; i < n; i++) {
- settings_element.items.push(settings_element.options[i][field_value]);
- }
- }
- };
-
- /**
- * Initializes selectize from a <select> element.
- *
- * @param {object} $input
- * @param {object} settings_element
- */
- var init_select = function($input, settings_element) {
- var i, n, tagName, $children, order = 0;
- var options = settings_element.options;
- var optionsMap = {};
-
- var readData = function($el) {
- var data = attr_data && $el.attr(attr_data);
- if (typeof data === 'string' && data.length) {
- return JSON.parse(data);
- }
- return null;
- };
-
- var addOption = function($option, group) {
- $option = $($option);
-
- var value = hash_key($option.val());
- if (!value && !settings.allowEmptyOption) return;
-
- // if the option already exists, it's probably been
- // duplicated in another optgroup. in this case, push
- // the current group to the "optgroup" property on the
- // existing option so that it's rendered in both places.
- if (optionsMap.hasOwnProperty(value)) {
- if (group) {
- var arr = optionsMap[value][field_optgroup];
- if (!arr) {
- optionsMap[value][field_optgroup] = group;
- } else if (!$.isArray(arr)) {
- optionsMap[value][field_optgroup] = [arr, group];
- } else {
- arr.push(group);
- }
- }
- return;
- }
-
- var option = readData($option) || {};
- option[field_label] = option[field_label] || $option.text();
- option[field_value] = option[field_value] || value;
- option[field_disabled] = option[field_disabled] || $option.prop('disabled');
- option[field_optgroup] = option[field_optgroup] || group;
-
- optionsMap[value] = option;
- options.push(option);
-
- if ($option.is(':selected')) {
- settings_element.items.push(value);
- }
- };
-
- var addGroup = function($optgroup) {
- var i, n, id, optgroup, $options;
-
- $optgroup = $($optgroup);
- id = $optgroup.attr('label');
-
- if (id) {
- optgroup = readData($optgroup) || {};
- optgroup[field_optgroup_label] = id;
- optgroup[field_optgroup_value] = id;
- optgroup[field_disabled] = $optgroup.prop('disabled');
- settings_element.optgroups.push(optgroup);
- }
-
- $options = $('option', $optgroup);
- for (i = 0, n = $options.length; i < n; i++) {
- addOption($options[i], id);
- }
- };
-
- settings_element.maxItems = $input.attr('multiple') ? null : 1;
-
- $children = $input.children();
- for (i = 0, n = $children.length; i < n; i++) {
- tagName = $children[i].tagName.toLowerCase();
- if (tagName === 'optgroup') {
- addGroup($children[i]);
- } else if (tagName === 'option') {
- addOption($children[i]);
- }
- }
- };
-
- return this.each(function() {
- if (this.selectize) return;
-
- var instance;
- var $input = $(this);
- var tag_name = this.tagName.toLowerCase();
- var placeholder = $input.attr('placeholder') || $input.attr('data-placeholder');
- if (!placeholder && !settings.allowEmptyOption) {
- placeholder = $input.children('option[value=""]').text();
- }
-
- var settings_element = {
- 'placeholder' : placeholder,
- 'options' : [],
- 'optgroups' : [],
- 'items' : []
- };
-
- if (tag_name === 'select') {
- init_select($input, settings_element);
- } else {
- init_textbox($input, settings_element);
- }
-
- instance = new Selectize($input, $.extend(true, {}, defaults, settings_element, settings_user));
- });
- };
-
- $.fn.selectize.defaults = Selectize.defaults;
- $.fn.selectize.support = {
- validity: SUPPORTS_VALIDITY_API
- };
-
-
- Selectize.define('drag_drop', function(options) {
- if (!$.fn.sortable) throw new Error('The "drag_drop" plugin requires jQuery UI "sortable".');
- if (this.settings.mode !== 'multi') return;
- var self = this;
-
- self.lock = (function() {
- var original = self.lock;
- return function() {
- var sortable = self.$control.data('sortable');
- if (sortable) sortable.disable();
- return original.apply(self, arguments);
- };
- })();
-
- self.unlock = (function() {
- var original = self.unlock;
- return function() {
- var sortable = self.$control.data('sortable');
- if (sortable) sortable.enable();
- return original.apply(self, arguments);
- };
- })();
-
- self.setup = (function() {
- var original = self.setup;
- return function() {
- original.apply(this, arguments);
-
- var $control = self.$control.sortable({
- items: '[data-value]',
- forcePlaceholderSize: true,
- disabled: self.isLocked,
- start: function(e, ui) {
- ui.placeholder.css('width', ui.helper.css('width'));
- $control.css({overflow: 'visible'});
- },
- stop: function() {
- $control.css({overflow: 'hidden'});
- var active = self.$activeItems ? self.$activeItems.slice() : null;
- var values = [];
- $control.children('[data-value]').each(function() {
- values.push($(this).attr('data-value'));
- });
- self.setValue(values);
- self.setActiveItem(active);
- }
- });
- };
- })();
-
- });
-
- Selectize.define('dropdown_header', function(options) {
- var self = this;
-
- options = $.extend({
- title : 'Untitled',
- headerClass : 'selectize-dropdown-header',
- titleRowClass : 'selectize-dropdown-header-title',
- labelClass : 'selectize-dropdown-header-label',
- closeClass : 'selectize-dropdown-header-close',
-
- html: function(data) {
- return (
- '<div class="' + data.headerClass + '">' +
- '<div class="' + data.titleRowClass + '">' +
- '<span class="' + data.labelClass + '">' + data.title + '</span>' +
- '<a href="javascript:void(0)" class="' + data.closeClass + '">&times;</a>' +
- '</div>' +
- '</div>'
- );
- }
- }, options);
-
- self.setup = (function() {
- var original = self.setup;
- return function() {
- original.apply(self, arguments);
- self.$dropdown_header = $(options.html(options));
- self.$dropdown.prepend(self.$dropdown_header);
- };
- })();
-
- });
-
- Selectize.define('optgroup_columns', function(options) {
- var self = this;
-
- options = $.extend({
- equalizeWidth : true,
- equalizeHeight : true
- }, options);
-
- this.getAdjacentOption = function($option, direction) {
- var $options = $option.closest('[data-group]').find('[data-selectable]');
- var index = $options.index($option) + direction;
-
- return index >= 0 && index < $options.length ? $options.eq(index) : $();
- };
-
- this.onKeyDown = (function() {
- var original = self.onKeyDown;
- return function(e) {
- var index, $option, $options, $optgroup;
-
- if (this.isOpen && (e.keyCode === KEY_LEFT || e.keyCode === KEY_RIGHT)) {
- self.ignoreHover = true;
- $optgroup = this.$activeOption.closest('[data-group]');
- index = $optgroup.find('[data-selectable]').index(this.$activeOption);
-
- if(e.keyCode === KEY_LEFT) {
- $optgroup = $optgroup.prev('[data-group]');
- } else {
- $optgroup = $optgroup.next('[data-group]');
- }
-
- $options = $optgroup.find('[data-selectable]');
- $option = $options.eq(Math.min($options.length - 1, index));
- if ($option.length) {
- this.setActiveOption($option);
- }
- return;
- }
-
- return original.apply(this, arguments);
- };
- })();
-
- var getScrollbarWidth = function() {
- var div;
- var width = getScrollbarWidth.width;
- var doc = document;
-
- if (typeof width === 'undefined') {
- div = doc.createElement('div');
- div.innerHTML = '<div style="width:50px;height:50px;position:absolute;left:-50px;top:-50px;overflow:auto;"><div style="width:1px;height:100px;"></div></div>';
- div = div.firstChild;
- doc.body.appendChild(div);
- width = getScrollbarWidth.width = div.offsetWidth - div.clientWidth;
- doc.body.removeChild(div);
- }
- return width;
- };
-
- var equalizeSizes = function() {
- var i, n, height_max, width, width_last, width_parent, $optgroups;
-
- $optgroups = $('[data-group]', self.$dropdown_content);
- n = $optgroups.length;
- if (!n || !self.$dropdown_content.width()) return;
-
- if (options.equalizeHeight) {
- height_max = 0;
- for (i = 0; i < n; i++) {
- height_max = Math.max(height_max, $optgroups.eq(i).height());
- }
- $optgroups.css({height: height_max});
- }
-
- if (options.equalizeWidth) {
- width_parent = self.$dropdown_content.innerWidth() - getScrollbarWidth();
- width = Math.round(width_parent / n);
- $optgroups.css({width: width});
- if (n > 1) {
- width_last = width_parent - width * (n - 1);
- $optgroups.eq(n - 1).css({width: width_last});
- }
- }
- };
-
- if (options.equalizeHeight || options.equalizeWidth) {
- hook.after(this, 'positionDropdown', equalizeSizes);
- hook.after(this, 'refreshOptions', equalizeSizes);
- }
-
-
- });
-
- Selectize.define('remove_button', function(options) {
- options = $.extend({
- label : '&times;',
- title : 'Remove',
- className : 'remove',
- append : true
- }, options);
-
- var singleClose = function(thisRef, options) {
-
- options.className = 'remove-single';
-
- var self = thisRef;
- var html = '<a href="javascript:void(0)" class="' + options.className + '" tabindex="-1" title="' + escape_html(options.title) + '">' + options.label + '</a>';
-
- /**
- * Appends an element as a child (with raw HTML).
- *
- * @param {string} html_container
- * @param {string} html_element
- * @return {string}
- */
- var append = function(html_container, html_element) {
- return $('<span>').append(html_container)
- .append(html_element);
- };
-
- thisRef.setup = (function() {
- var original = self.setup;
- return function() {
- // override the item rendering method to add the button to each
- if (options.append) {
- var id = $(self.$input.context).attr('id');
- var selectizer = $('#'+id);
-
- var render_item = self.settings.render.item;
- self.settings.render.item = function(data) {
- return append(render_item.apply(thisRef, arguments), html);
- };
- }
-
- original.apply(thisRef, arguments);
-
- // add event listener
- thisRef.$control.on('click', '.' + options.className, function(e) {
- e.preventDefault();
- if (self.isLocked) return;
-
- self.clear();
- });
-
- };
- })();
- };
-
- var multiClose = function(thisRef, options) {
-
- var self = thisRef;
- var html = '<a href="javascript:void(0)" class="' + options.className + '" tabindex="-1" title="' + escape_html(options.title) + '">' + options.label + '</a>';
-
- /**
- * Appends an element as a child (with raw HTML).
- *
- * @param {string} html_container
- * @param {string} html_element
- * @return {string}
- */
- var append = function(html_container, html_element) {
- var pos = html_container.search(/(<\/[^>]+>\s*)$/);
- return html_container.substring(0, pos) + html_element + html_container.substring(pos);
- };
-
- thisRef.setup = (function() {
- var original = self.setup;
- return function() {
- // override the item rendering method to add the button to each
- if (options.append) {
- var render_item = self.settings.render.item;
- self.settings.render.item = function(data) {
- return append(render_item.apply(thisRef, arguments), html);
- };
- }
-
- original.apply(thisRef, arguments);
-
- // add event listener
- thisRef.$control.on('click', '.' + options.className, function(e) {
- e.preventDefault();
- if (self.isLocked) return;
-
- var $item = $(e.currentTarget).parent();
- self.setActiveItem($item);
- if (self.deleteSelection()) {
- self.setCaret(self.items.length);
- }
- });
-
- };
- })();
- };
-
- if (this.settings.mode === 'single') {
- singleClose(this, options);
- return;
- } else {
- multiClose(this, options);
- }
- });
-
-
- Selectize.define('restore_on_backspace', function(options) {
- var self = this;
-
- options.text = options.text || function(option) {
- return option[this.settings.labelField];
- };
-
- this.onKeyDown = (function() {
- var original = self.onKeyDown;
- return function(e) {
- var index, option;
- if (e.keyCode === KEY_BACKSPACE && this.$control_input.val() === '' && !this.$activeItems.length) {
- index = this.caretPos - 1;
- if (index >= 0 && index < this.items.length) {
- option = this.options[this.items[index]];
- if (this.deleteSelection(e)) {
- this.setTextboxValue(options.text.apply(this, [option]));
- this.refreshOptions(true);
- }
- e.preventDefault();
- return;
- }
- }
- return original.apply(this, arguments);
- };
- })();
- });
-
-
- return Selectize;
-}));
\ No newline at end of file
diff --git a/app/assets/javascripts/blazer/tom-select.base.js b/app/assets/javascripts/blazer/tom-select.base.js
new file mode 100644
index 00000000..ff964289
--- /dev/null
+++ b/app/assets/javascripts/blazer/tom-select.base.js
@@ -0,0 +1,4175 @@
+/**
+* Tom Select v2.6.1
+* Licensed under the Apache License, Version 2.0 (the "License");
+*/
+
+(function (global, factory) {
+ typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
+ typeof define === 'function' && define.amd ? define(factory) :
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.TomSelect = factory());
+})(this, (function () { 'use strict';
+
+ /**
+ * MicroEvent - to make any js object an event emitter
+ *
+ * - pure javascript - server compatible, browser compatible
+ * - dont rely on the browser doms
+ * - super simple - you get it immediatly, no mistery, no magic involved
+ *
+ * @author Jerome Etienne (https://github.com/jeromeetienne)
+ */
+
+ /**
+ * Execute callback for each event in space separated list of event names
+ *
+ */
+ function forEvents(events, callback) {
+ events.split(/\s+/).forEach(event => {
+ callback(event);
+ });
+ }
+ class MicroEvent {
+ constructor() {
+ this._events = {};
+ }
+ on(events, fct) {
+ forEvents(events, event => {
+ const event_array = this._events[event] || [];
+ event_array.push(fct);
+ this._events[event] = event_array;
+ });
+ }
+ off(events, fct) {
+ var n = arguments.length;
+ if (n === 0) {
+ this._events = {};
+ return;
+ }
+ forEvents(events, event => {
+ if (n === 1) {
+ delete this._events[event];
+ return;
+ }
+ const event_array = this._events[event];
+ if (event_array === undefined) return;
+ event_array.splice(event_array.indexOf(fct), 1);
+ this._events[event] = event_array;
+ });
+ }
+ trigger(events, ...args) {
+ var self = this;
+ forEvents(events, event => {
+ const event_array = self._events[event];
+ if (event_array === undefined) return;
+ event_array.forEach(fct => {
+ fct.apply(self, args);
+ });
+ });
+ }
+ }
+
+ /**
+ * microplugin.js
+ * Copyright (c) 2013 Brian Reavis & contributors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
+ * file except in compliance with the License. You may obtain a copy of the License at:
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
+ * ANY KIND, either express or implied. See the License for the specific language
+ * governing permissions and limitations under the License.
+ *
+ * @author Brian Reavis <[email protected]>
+ */
+
+ function MicroPlugin(Interface) {
+ Interface.plugins = {};
+ return class extends Interface {
+ constructor(...args) {
+ super(...args);
+ this.plugins = {
+ names: [],
+ settings: {},
+ requested: {},
+ loaded: {}
+ };
+ }
+ /**
+ * Registers a plugin.
+ *
+ * @param {function} fn
+ */
+ static define(name, fn) {
+ Interface.plugins[name] = {
+ 'name': name,
+ 'fn': fn
+ };
+ }
+
+ /**
+ * Initializes the listed plugins (with options).
+ * Acceptable formats:
+ *
+ * List (without options):
+ * ['a', 'b', 'c']
+ *
+ * List (with options):
+ * [{'name': 'a', options: {}}, {'name': 'b', options: {}}]
+ *
+ * Hash (with options):
+ * {'a': { ... }, 'b': { ... }, 'c': { ... }}
+ *
+ * @param {array|object} plugins
+ */
+ initializePlugins(plugins) {
+ var key, name;
+ const self = this;
+ const queue = [];
+ if (Array.isArray(plugins)) {
+ plugins.forEach(plugin => {
+ if (typeof plugin === 'string') {
+ queue.push(plugin);
+ } else {
+ self.plugins.settings[plugin.name] = plugin.options;
+ queue.push(plugin.name);
+ }
+ });
+ } else if (plugins) {
+ for (key in plugins) {
+ if (plugins.hasOwnProperty(key)) {
+ self.plugins.settings[key] = plugins[key];
+ queue.push(key);
+ }
+ }
+ }
+ while (name = queue.shift()) {
+ self.require(name);
+ }
+ }
+ loadPlugin(name) {
+ var self = this;
+ var plugins = self.plugins;
+ var plugin = Interface.plugins[name];
+ if (!Interface.plugins.hasOwnProperty(name)) {
+ throw new Error('Unable to find "' + name + '" plugin');
+ }
+ plugins.requested[name] = true;
+ plugins.loaded[name] = plugin.fn.apply(self, [self.plugins.settings[name] || {}]);
+ plugins.names.push(name);
+ }
+
+ /**
+ * Initializes a plugin.
+ *
+ */
+ require(name) {
+ var self = this;
+ var plugins = self.plugins;
+ if (!self.plugins.loaded.hasOwnProperty(name)) {
+ if (plugins.requested[name]) {
+ throw new Error('Plugin has circular dependency ("' + name + '")');
+ }
+ self.loadPlugin(name);
+ }
+ return plugins.loaded[name];
+ }
+ };
+ }
+
+ /**
+ * Convert array of strings to a regular expression
+ * ex ['ab','a'] => (?:ab|a)
+ * ex ['a','b'] => [ab]
+ */
+ const arrayToPattern = (chars) => {
+ chars = chars.filter(Boolean);
+ if (chars.length < 2) {
+ return chars[0] || '';
+ }
+ return (maxValueLength(chars) == 1) ? '[' + chars.join('') + ']' : '(?:' + chars.join('|') + ')';
+ };
+ const sequencePattern = (array) => {
+ if (!hasDuplicates(array)) {
+ return array.join('');
+ }
+ let pattern = '';
+ let prev_char_count = 0;
+ const prev_pattern = () => {
+ if (prev_char_count > 1) {
+ pattern += '{' + prev_char_count + '}';
+ }
+ };
+ array.forEach((char, i) => {
+ if (char === array[i - 1]) {
+ prev_char_count++;
+ return;
+ }
+ prev_pattern();
+ pattern += char;
+ prev_char_count = 1;
+ });
+ prev_pattern();
+ return pattern;
+ };
+ /**
+ * Convert array of strings to a regular expression
+ * ex ['ab','a'] => (?:ab|a)
+ * ex ['a','b'] => [ab]
+ */
+ const setToPattern = (chars) => {
+ let array = Array.from(chars);
+ return arrayToPattern(array);
+ };
+ /**
+ * https://stackoverflow.com/questions/7376598/in-javascript-how-do-i-check-if-an-array-has-duplicate-values
+ */
+ const hasDuplicates = (array) => {
+ return (new Set(array)).size !== array.length;
+ };
+ /**
+ * https://stackoverflow.com/questions/63006601/why-does-u-throw-an-invalid-escape-error
+ */
+ const escape_regex = (str) => {
+ return (str + '').replace(/([\$\(\)\*\+\.\?\[\]\^\{\|\}\\])/gu, '\\$1');
+ };
+ /**
+ * Return the max length of array values
+ */
+ const maxValueLength = (array) => {
+ return array.reduce((longest, value) => Math.max(longest, unicodeLength(value)), 0);
+ };
+ const unicodeLength = (str) => {
+ return Array.from(str).length;
+ };
+
+ /**
+ * Get all possible combinations of substrings that add up to the given string
+ * https://stackoverflow.com/questions/30169587/find-all-the-combination-of-substrings-that-add-up-to-the-given-string
+ */
+ const allSubstrings = (input) => {
+ if (input.length === 1)
+ return [[input]];
+ let result = [];
+ const start = input.substring(1);
+ const suba = allSubstrings(start);
+ suba.forEach(function (subresult) {
+ let tmp = subresult.slice(0);
+ tmp[0] = input.charAt(0) + tmp[0];
+ result.push(tmp);
+ tmp = subresult.slice(0);
+ tmp.unshift(input.charAt(0));
+ result.push(tmp);
+ });
+ return result;
+ };
+
+ const code_points = [[0, 65535]];
+ const accent_pat = '[\u0300-\u036F\u{b7}\u{2be}\u{2bc}]';
+ let unicode_map;
+ let multi_char_reg;
+ const max_char_length = 3;
+ const latin_convert = {};
+ const latin_condensed = {
+ '/': '⁄∕',
+ '0': '߀',
+ "a": "ⱥɐɑ",
+ "aa": "ꜳ",
+ "ae": "æǽǣ",
+ "ao": "ꜵ",
+ "au": "ꜷ",
+ "av": "ꜹꜻ",
+ "ay": "ꜽ",
+ "b": "ƀɓƃ",
+ "c": "ꜿƈȼↄ",
+ "d": "đɗɖᴅƌꮷԁɦ",
+ "e": "ɛǝᴇɇ",
+ "f": "ꝼƒ",
+ "g": "ǥɠꞡᵹꝿɢ",
+ "h": "ħⱨⱶɥ",
+ "i": "ɨı",
+ "j": "ɉȷ",
+ "k": "ƙⱪꝁꝃꝅꞣ",
+ "l": "łƚɫⱡꝉꝇꞁɭ",
+ "m": "ɱɯϻ",
+ "n": "ꞥƞɲꞑᴎлԉ",
+ "o": "øǿɔɵꝋꝍᴑ",
+ "oe": "œ",
+ "oi": "ƣ",
+ "oo": "ꝏ",
+ "ou": "ȣ",
+ "p": "ƥᵽꝑꝓꝕρ",
+ "q": "ꝗꝙɋ",
+ "r": "ɍɽꝛꞧꞃ",
+ "s": "ßȿꞩꞅʂ",
+ "t": "ŧƭʈⱦꞇ",
+ "th": "þ",
+ "tz": "ꜩ",
+ "u": "ʉ",
+ "v": "ʋꝟʌ",
+ "vy": "ꝡ",
+ "w": "ⱳ",
+ "y": "ƴɏỿ",
+ "z": "ƶȥɀⱬꝣ",
+ "hv": "ƕ"
+ };
+ for (let latin in latin_condensed) {
+ let unicode = latin_condensed[latin] || '';
+ for (let i = 0; i < unicode.length; i++) {
+ let char = unicode.substring(i, i + 1);
+ latin_convert[char] = latin;
+ }
+ }
+ const convert_pat = new RegExp(Object.keys(latin_convert).join('|') + '|' + accent_pat, 'gu');
+ /**
+ * Initialize the unicode_map from the give code point ranges
+ */
+ const initialize = (_code_points) => {
+ if (unicode_map !== undefined)
+ return;
+ unicode_map = generateMap(code_points);
+ };
+ /**
+ * Helper method for normalize a string
+ * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize
+ */
+ const normalize = (str, form = 'NFKD') => str.normalize(form);
+ /**
+ * Remove accents without reordering string
+ * calling str.normalize('NFKD') on \u{594}\u{595}\u{596} becomes \u{596}\u{594}\u{595}
+ * via https://github.com/krisk/Fuse/issues/133#issuecomment-318692703
+ */
+ const asciifold = (str) => {
+ return Array.from(str).reduce(
+ /**
+ * @param {string} result
+ * @param {string} char
+ */
+ (result, char) => {
+ return result + _asciifold(char);
+ }, '');
+ };
+ const _asciifold = (str) => {
+ str = normalize(str)
+ .toLowerCase()
+ .replace(convert_pat, (/** @type {string} */ char) => {
+ return latin_convert[char] || '';
+ });
+ //return str;
+ return normalize(str, 'NFC');
+ };
+ /**
+ * Generate a list of unicode variants from the list of code points
+ */
+ function* generator(code_points) {
+ for (const [code_point_min, code_point_max] of code_points) {
+ for (let i = code_point_min; i <= code_point_max; i++) {
+ let composed = String.fromCharCode(i);
+ let folded = asciifold(composed);
+ if (folded == composed.toLowerCase()) {
+ continue;
+ }
+ // skip when folded is a string longer than 3 characters long
+ // bc the resulting regex patterns will be long
+ // eg:
+ // folded صلى الله عليه وسلم length 18 code point 65018
+ // folded جل جلاله length 8 code point 65019
+ if (folded.length > max_char_length) {
+ continue;
+ }
+ if (folded.length == 0) {
+ continue;
+ }
+ yield { folded: folded, composed: composed, code_point: i };
+ }
+ }
+ }
+ /**
+ * Generate a unicode map from the list of code points
+ */
+ const generateSets = (code_points) => {
+ const unicode_sets = {};
+ const addMatching = (folded, to_add) => {
+ /** @type {Set<string>} */
+ const folded_set = unicode_sets[folded] || new Set();
+ const patt = new RegExp('^' + setToPattern(folded_set) + '$', 'iu');
+ if (to_add.match(patt)) {
+ return;
+ }
+ folded_set.add(escape_regex(to_add));
+ unicode_sets[folded] = folded_set;
+ };
+ for (let value of generator(code_points)) {
+ addMatching(value.folded, value.folded);
+ addMatching(value.folded, value.composed);
+ }
+ return unicode_sets;
+ };
+ /**
+ * Generate a unicode map from the list of code points
+ * ae => (?:(?:ae|Æ|Ǽ|Ǣ)|(?:A|Ⓐ|A...)(?:E|ɛ|Ⓔ...))
+ */
+ const generateMap = (code_points) => {
+ const unicode_sets = generateSets(code_points);
+ const unicode_map = {};
+ let multi_char = [];
+ for (let folded in unicode_sets) {
+ let set = unicode_sets[folded];
+ if (set) {
+ unicode_map[folded] = setToPattern(set);
+ }
+ if (folded.length > 1) {
+ multi_char.push(escape_regex(folded));
+ }
+ }
+ multi_char.sort((a, b) => b.length - a.length);
+ const multi_char_patt = arrayToPattern(multi_char);
+ multi_char_reg = new RegExp('^' + multi_char_patt, 'u');
+ return unicode_map;
+ };
+ /**
+ * Map each element of an array from its folded value to all possible unicode matches
+ */
+ const mapSequence = (strings, min_replacement = 1) => {
+ let chars_replaced = 0;
+ strings = strings.map((str) => {
+ if (unicode_map[str]) {
+ chars_replaced += str.length;
+ }
+ return unicode_map[str] || str;
+ });
+ if (chars_replaced >= min_replacement) {
+ return sequencePattern(strings);
+ }
+ return '';
+ };
+ /**
+ * Convert a short string and split it into all possible patterns
+ * Keep a pattern only if min_replacement is met
+ *
+ * 'abc'
+ * => [['abc'],['ab','c'],['a','bc'],['a','b','c']]
+ * => ['abc-pattern','ab-c-pattern'...]
+ */
+ const substringsToPattern = (str, min_replacement = 1) => {
+ min_replacement = Math.max(min_replacement, str.length - 1);
+ return arrayToPattern(allSubstrings(str).map((sub_pat) => {
+ return mapSequence(sub_pat, min_replacement);
+ }));
+ };
+ /**
+ * Convert an array of sequences into a pattern
+ * [{start:0,end:3,length:3,substr:'iii'}...] => (?:iii...)
+ */
+ const sequencesToPattern = (sequences, all = true) => {
+ let min_replacement = sequences.length > 1 ? 1 : 0;
+ return arrayToPattern(sequences.map((sequence) => {
+ let seq = [];
+ const len = all ? sequence.length() : sequence.length() - 1;
+ for (let j = 0; j < len; j++) {
+ seq.push(substringsToPattern(sequence.substrs[j] || '', min_replacement));
+ }
+ return sequencePattern(seq);
+ }));
+ };
+ /**
+ * Return true if the sequence is already in the sequences
+ */
+ const inSequences = (needle_seq, sequences) => {
+ for (const seq of sequences) {
+ if (seq.start != needle_seq.start || seq.end != needle_seq.end) {
+ continue;
+ }
+ if (seq.substrs.join('') !== needle_seq.substrs.join('')) {
+ continue;
+ }
+ let needle_parts = needle_seq.parts;
+ const filter = (part) => {
+ for (const needle_part of needle_parts) {
+ if (needle_part.start === part.start && needle_part.substr === part.substr) {
+ return false;
+ }
+ if (part.length == 1 || needle_part.length == 1) {
+ continue;
+ }
+ // check for overlapping parts
+ // a = ['::=','==']
+ // b = ['::','===']
+ // a = ['r','sm']
+ // b = ['rs','m']
+ if (part.start < needle_part.start && part.end > needle_part.start) {
+ return true;
+ }
+ if (needle_part.start < part.start && needle_part.end > part.start) {
+ return true;
+ }
+ }
+ return false;
+ };
+ let filtered = seq.parts.filter(filter);
+ if (filtered.length > 0) {
+ continue;
+ }
+ return true;
+ }
+ return false;
+ };
+ class Sequence {
+ parts;
+ substrs;
+ start;
+ end;
+ constructor() {
+ this.parts = [];
+ this.substrs = [];
+ this.start = 0;
+ this.end = 0;
+ }
+ add(part) {
+ if (part) {
+ this.parts.push(part);
+ this.substrs.push(part.substr);
+ this.start = Math.min(part.start, this.start);
+ this.end = Math.max(part.end, this.end);
+ }
+ }
+ last() {
+ return this.parts[this.parts.length - 1];
+ }
+ length() {
+ return this.parts.length;
+ }
+ clone(position, last_piece) {
+ let clone = new Sequence();
+ let parts = JSON.parse(JSON.stringify(this.parts));
+ let last_part = parts.pop();
+ for (const part of parts) {
+ clone.add(part);
+ }
+ let last_substr = last_piece.substr.substring(0, position - last_part.start);
+ let clone_last_len = last_substr.length;
+ clone.add({ start: last_part.start, end: last_part.start + clone_last_len, length: clone_last_len, substr: last_substr });
+ return clone;
+ }
+ }
+ /**
+ * Expand a regular expression pattern to include unicode variants
+ * eg /a/ becomes /aⓐaẚàáâầấẫẩãāăằắẵẳȧǡäǟảåǻǎȁȃạậặḁąⱥɐɑAⒶAÀÁÂẦẤẪẨÃĀĂẰẮẴẲȦǠÄǞẢÅǺǍȀȂẠẬẶḀĄȺⱯ/
+ *
+ * Issue:
+ * ﺊﺋ [ 'ﺊ = \\u{fe8a}', 'ﺋ = \\u{fe8b}' ]
+ * becomes: ئئ [ 'ي = \\u{64a}', 'ٔ = \\u{654}', 'ي = \\u{64a}', 'ٔ = \\u{654}' ]
+ *
+ * İIJ = IIJ = ⅡJ
+ *
+ * 1/2/4
+ */
+ const getPattern = (str) => {
+ initialize();
+ str = asciifold(str);
+ let pattern = '';
+ let sequences = [new Sequence()];
+ for (let i = 0; i < str.length; i++) {
+ let substr = str.substring(i);
+ let match = substr.match(multi_char_reg);
+ const char = str.substring(i, i + 1);
+ const match_str = match ? match[0] : null;
+ // loop through sequences
+ // add either the char or multi_match
+ let overlapping = [];
+ let added_types = new Set();
+ for (const sequence of sequences) {
+ const last_piece = sequence.last();
+ if (!last_piece || last_piece.length == 1 || last_piece.end <= i) {
+ // if we have a multi match
+ if (match_str) {
+ const len = match_str.length;
+ sequence.add({ start: i, end: i + len, length: len, substr: match_str });
+ added_types.add('1');
+ }
+ else {
+ sequence.add({ start: i, end: i + 1, length: 1, substr: char });
+ added_types.add('2');
+ }
+ }
+ else if (match_str) {
+ let clone = sequence.clone(i, last_piece);
+ const len = match_str.length;
+ clone.add({ start: i, end: i + len, length: len, substr: match_str });
+ overlapping.push(clone);
+ }
+ else {
+ // don't add char
+ // adding would create invalid patterns: 234 => [2,34,4]
+ added_types.add('3');
+ }
+ }
+ // if we have overlapping
+ if (overlapping.length > 0) {
+ // ['ii','iii'] before ['i','i','iii']
+ overlapping = overlapping.sort((a, b) => {
+ return a.length() - b.length();
+ });
+ for (let clone of overlapping) {
+ // don't add if we already have an equivalent sequence
+ if (inSequences(clone, sequences)) {
+ continue;
+ }
+ sequences.push(clone);
+ }
+ continue;
+ }
+ // if we haven't done anything unique
+ // clean up the patterns
+ // helps keep patterns smaller
+ // if str = 'r₨㎧aarss', pattern will be 446 instead of 655
+ if (i > 0 && added_types.size == 1 && !added_types.has('3')) {
+ pattern += sequencesToPattern(sequences, false);
+ let new_seq = new Sequence();
+ const old_seq = sequences[0];
+ if (old_seq) {
+ new_seq.add(old_seq.last());
+ }
+ sequences = [new_seq];
+ }
+ }
+ pattern += sequencesToPattern(sequences, true);
+ return pattern;
+ };
+
+ /**
+ * A property getter resolving dot-notation
+ * @param {Object} obj The root object to fetch property on
+ * @param {String} name The optionally dotted property name to fetch
+ * @return {Object} The resolved property value
+ */
+ const getAttr = (obj, name) => {
+ if (!obj)
+ return;
+ return obj[name];
+ };
+ /**
+ * A property getter resolving dot-notation
+ * @param {Object} obj The root object to fetch property on
+ * @param {String} name The optionally dotted property name to fetch
+ * @return {Object} The resolved property value
+ */
+ const getAttrNesting = (obj, name) => {
+ if (!obj)
+ return;
+ var part, names = name.split(".");
+ while ((part = names.shift()) && (obj = obj[part]))
+ ;
+ return obj;
+ };
+ /**
+ * Calculates how close of a match the
+ * given value is against a search token.
+ *
+ */
+ const scoreValue = (value, token, weight) => {
+ var score, pos;
+ if (!value)
+ return 0;
+ value = value + '';
+ if (token.regex == null)
+ return 0;
+ pos = value.search(token.regex);
+ if (pos === -1)
+ return 0;
+ score = token.string.length / value.length;
+ if (pos === 0)
+ score += 0.5;
+ return score * weight;
+ };
+ /**
+ * Cast object property to an array if it exists and has a value
+ *
+ */
+ const propToArray = (obj, key) => {
+ var value = obj[key];
+ if (typeof value == 'function')
+ return value;
+ if (value && !Array.isArray(value)) {
+ obj[key] = [value];
+ }
+ };
+ /**
+ * Iterates over arrays and hashes.
+ *
+ * ```
+ * iterate(this.items, function(item, id) {
+ * // invoked for each item
+ * });
+ * ```
+ *
+ */
+ const iterate$1 = (object, callback) => {
+ if (Array.isArray(object)) {
+ object.forEach(callback);
+ }
+ else {
+ for (var key in object) {
+ if (object.hasOwnProperty(key)) {
+ callback(object[key], key);
+ }
+ }
+ }
+ };
+ const cmp = (a, b) => {
+ if (typeof a === 'number' && typeof b === 'number') {
+ return a > b ? 1 : (a < b ? -1 : 0);
+ }
+ a = asciifold(a + '').toLowerCase();
+ b = asciifold(b + '').toLowerCase();
+ if (a > b)
+ return 1;
+ if (b > a)
+ return -1;
+ return 0;
+ };
+
+ /**
+ * sifter.js
+ * Copyright (c) 2013–2020 Brian Reavis & contributors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
+ * file except in compliance with the License. You may obtain a copy of the License at:
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
+ * ANY KIND, either express or implied. See the License for the specific language
+ * governing permissions and limitations under the License.
+ *
+ * @author Brian Reavis <[email protected]>
+ */
+ class Sifter {
+ items; // []|{};
+ settings;
+ /**
+ * Textually searches arrays and hashes of objects
+ * by property (or multiple properties). Designed
+ * specifically for autocomplete.
+ *
+ */
+ constructor(items, settings) {
+ this.items = items;
+ this.settings = settings || { diacritics: true };
+ }
+ ;
+ /**
+ * Splits a search string into an array of individual
+ * regexps to be used to match results.
+ *
+ */
+ tokenize(query, respect_word_boundaries, weights) {
+ if (!query || !query.length)
+ return [];
+ const tokens = [];
+ const words = query.split(/\s+/);
+ var field_regex;
+ if (weights) {
+ field_regex = new RegExp('^(' + Object.keys(weights).map(escape_regex).join('|') + ')\:(.*)$');
+ }
+ words.forEach((word) => {
+ let field_match;
+ let field = null;
+ let regex = null;
+ // look for "field:query" tokens
+ if (field_regex && (field_match = word.match(field_regex))) {
+ field = field_match[1];
+ word = field_match[2];
+ }
+ if (word.length > 0) {
+ if (this.settings.diacritics) {
+ regex = getPattern(word) || null;
+ }
+ else {
+ regex = escape_regex(word);
+ }
+ if (regex && respect_word_boundaries)
+ regex = "\\b" + regex;
+ }
+ tokens.push({
+ string: word,
+ regex: regex ? new RegExp(regex, 'iu') : null,
+ field: field,
+ });
+ });
+ return tokens;
+ }
+ ;
+ /**
+ * Returns a function to be used to score individual results.
+ *
+ * Good matches will have a higher score than poor matches.
+ * If an item is not a match, 0 will be returned by the function.
+ *
+ * @returns {T.ScoreFn}
+ */
+ getScoreFunction(query, options) {
+ var search = this.prepareSearch(query, options);
+ return this._getScoreFunction(search);
+ }
+ /**
+ * @returns {T.ScoreFn}
+ *
+ */
+ _getScoreFunction(search) {
+ const tokens = search.tokens, token_count = tokens.length;
+ if (!token_count) {
+ return function () { return 0; };
+ }
+ const fields = search.options.fields, weights = search.weights, field_count = fields.length, getAttrFn = search.getAttrFn;
+ if (!field_count) {
+ return function () { return 1; };
+ }
+ /**
+ * Calculates the score of an object
+ * against the search query.
+ *
+ */
+ const scoreObject = (function () {
+ if (field_count === 1) {
+ return function (token, data) {
+ const field = fields[0].field;
+ return scoreValue(getAttrFn(data, field), token, weights[field] || 1);
+ };
+ }
+ return function (token, data) {
+ var sum = 0;
+ // is the token specific to a field?
+ if (token.field) {
+ const value = getAttrFn(data, token.field);
+ if (!token.regex && value) {
+ sum += (1 / field_count);
+ }
+ else {
+ sum += scoreValue(value, token, 1);
+ }
+ }
+ else {
+ iterate$1(weights, (weight, field) => {
+ sum += scoreValue(getAttrFn(data, field), token, weight);
+ });
+ }
+ return sum / field_count;
+ };
+ })();
+ if (token_count === 1) {
+ return function (data) {
+ return scoreObject(tokens[0], data);
+ };
+ }
+ if (search.options.conjunction === 'and') {
+ return function (data) {
+ var score, sum = 0;
+ for (let token of tokens) {
+ score = scoreObject(token, data);
+ if (score <= 0)
+ return 0;
+ sum += score;
+ }
+ return sum / token_count;
+ };
+ }
+ else {
+ return function (data) {
+ var sum = 0;
+ iterate$1(tokens, (token) => {
+ sum += scoreObject(token, data);
+ });
+ return sum / token_count;
+ };
+ }
+ }
+ ;
+ /**
+ * Returns a function that can be used to compare two
+ * results, for sorting purposes. If no sorting should
+ * be performed, `null` will be returned.
+ *
+ * @return function(a,b)
+ */
+ getSortFunction(query, options) {
+ var search = this.prepareSearch(query, options);
+ return this._getSortFunction(search);
+ }
+ _getSortFunction(search) {
+ var implicit_score, sort_flds = [];
+ const self = this, options = search.options, sort = (!search.query && options.sort_empty) ? options.sort_empty : options.sort;
+ if (typeof sort == 'function') {
+ return sort.bind(this);
+ }
+ /**
+ * Fetches the specified sort field value
+ * from a search result item.
+ *
+ */
+ const get_field = function (name, result) {
+ if (name === '$score')
+ return result.score;
+ return search.getAttrFn(self.items[result.id], name);
+ };
+ // parse options
+ if (sort) {
+ for (let s of sort) {
+ if (search.query || s.field !== '$score') {
+ sort_flds.push(s);
+ }
+ }
+ }
+ // the "$score" field is implied to be the primary
+ // sort field, unless it's manually specified
+ if (search.query) {
+ implicit_score = true;
+ for (let fld of sort_flds) {
+ if (fld.field === '$score') {
+ implicit_score = false;
+ break;
+ }
+ }
+ if (implicit_score) {
+ sort_flds.unshift({ field: '$score', direction: 'desc' });
+ }
+ // without a search.query, all items will have the same score
+ }
+ else {
+ sort_flds = sort_flds.filter((fld) => fld.field !== '$score');
+ }
+ // build function
+ const sort_flds_count = sort_flds.length;
+ if (!sort_flds_count) {
+ return null;
+ }
+ return function (a, b) {
+ var result, field;
+ for (let sort_fld of sort_flds) {
+ field = sort_fld.field;
+ let multiplier = sort_fld.direction === 'desc' ? -1 : 1;
+ result = multiplier * cmp(get_field(field, a), get_field(field, b));
+ if (result)
+ return result;
+ }
+ return 0;
+ };
+ }
+ ;
+ /**
+ * Parses a search query and returns an object
+ * with tokens and fields ready to be populated
+ * with results.
+ *
+ */
+ prepareSearch(query, optsUser) {
+ const weights = {};
+ var options = Object.assign({}, optsUser);
+ propToArray(options, 'sort');
+ propToArray(options, 'sort_empty');
+ // convert fields to new format
+ if (options.fields) {
+ propToArray(options, 'fields');
+ const fields = [];
+ options.fields.forEach((field) => {
+ if (typeof field == 'string') {
+ field = { field: field, weight: 1 };
+ }
+ fields.push(field);
+ weights[field.field] = ('weight' in field) ? field.weight : 1;
+ });
+ options.fields = fields;
+ }
+ return {
+ options: options,
+ query: query.toLowerCase().trim(),
+ tokens: this.tokenize(query, options.respect_word_boundaries, weights),
+ total: 0,
+ items: [],
+ weights: weights,
+ getAttrFn: (options.nesting) ? getAttrNesting : getAttr,
+ };
+ }
+ ;
+ /**
+ * Searches through all items and returns a sorted array of matches.
+ *
+ */
+ search(query, options) {
+ var self = this, score, search;
+ search = this.prepareSearch(query, options);
+ options = search.options;
+ query = search.query;
+ // generate result scoring function
+ const fn_score = options.score || self._getScoreFunction(search);
+ // perform search and sort
+ if (query.length) {
+ iterate$1(self.items, (item, id) => {
+ score = fn_score(item);
+ if (options.filter === false || score > 0) {
+ search.items.push({ 'score': score, 'id': id });
+ }
+ });
+ }
+ else {
+ iterate$1(self.items, (_, id) => {
+ search.items.push({ 'score': 1, 'id': id });
+ });
+ }
+ const fn_sort = self._getSortFunction(search);
+ if (fn_sort)
+ search.items.sort(fn_sort);
+ // apply limits
+ search.total = search.items.length;
+ if (typeof options.limit === 'number') {
+ search.items = search.items.slice(0, options.limit);
+ }
+ return search;
+ }
+ ;
+ }
+
+ /**
+ * Converts a scalar to its best string representation
+ * for hash keys and HTML attribute values.
+ *
+ * Transformations:
+ * 'str' -> 'str'
+ * null -> ''
+ * undefined -> ''
+ * true -> '1'
+ * false -> '0'
+ * 0 -> '0'
+ * 1 -> '1'
+ *
+ */
+ const hash_key = value => {
+ if (typeof value === 'undefined' || value === null) return null;
+ return get_hash(value);
+ };
+ const get_hash = value => {
+ if (typeof value === 'boolean') return value ? '1' : '0';
+ return value + '';
+ };
+
+ /**
+ * Escapes a string for use within HTML.
+ *
+ */
+ const escape_html = str => {
+ return (str + '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
+ };
+
+ /**
+ * use setTimeout if timeout > 0
+ */
+ const timeout = (fn, timeout) => {
+ if (timeout > 0) {
+ return window.setTimeout(fn, timeout);
+ }
+ fn.call(null);
+ return null;
+ };
+
+ /**
+ * Debounce the user provided load function
+ *
+ */
+ const loadDebounce = (fn, delay) => {
+ var timeout;
+ return function (value, callback) {
+ var self = this;
+ if (timeout) {
+ self.loading = Math.max(self.loading - 1, 0);
+ clearTimeout(timeout);
+ }
+ timeout = setTimeout(function () {
+ timeout = null;
+ self.loadedSearches[value] = true;
+ fn.call(self, value, callback);
+ }, delay);
+ };
+ };
+
+ /**
+ * Debounce all fired events types listed in `types`
+ * while executing the provided `fn`.
+ *
+ */
+ const debounce_events = (self, types, fn) => {
+ var type;
+ var trigger = self.trigger;
+ var event_args = {};
+
+ // override trigger method
+ self.trigger = function () {
+ var type = arguments[0];
+ if (types.indexOf(type) !== -1) {
+ event_args[type] = arguments;
+ } else {
+ return trigger.apply(self, arguments);
+ }
+ };
+
+ // invoke provided function
+ fn.apply(self, []);
+ self.trigger = trigger;
+
+ // trigger queued events
+ for (type of types) {
+ if (type in event_args) {
+ trigger.apply(self, event_args[type]);
+ }
+ }
+ };
+
+ /**
+ * Determines the current selection within a text input control.
+ * Returns an object containing:
+ * - start
+ * - length
+ *
+ * Note: "selectionStart, selectionEnd ... apply only to inputs of types text, search, URL, tel and password"
+ * - https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange
+ */
+ const getSelection = input => {
+ return {
+ start: input.selectionStart || 0,
+ length: (input.selectionEnd || 0) - (input.selectionStart || 0)
+ };
+ };
+
+ /**
+ * Prevent default
+ *
+ */
+ const preventDefault = (evt, stop = false) => {
+ if (evt) {
+ evt.preventDefault();
+ if (stop) {
+ evt.stopPropagation();
+ }
+ }
+ };
+
+ /**
+ * Add event helper
+ *
+ */
+ const addEvent = (target, type, callback, options) => {
+ target.addEventListener(type, callback, options);
+ };
+
+ /**
+ * Return true if the requested key is down
+ * Will return false if more than one control character is pressed ( when [ctrl+shift+a] != [ctrl+a] )
+ * The current evt may not always set ( eg calling advanceSelection() )
+ *
+ */
+ const isKeyDown = (key_name, evt) => {
+ if (!evt) {
+ return false;
+ }
+ if (!evt[key_name]) {
+ return false;
+ }
+ var count = (evt.altKey ? 1 : 0) + (evt.ctrlKey ? 1 : 0) + (evt.shiftKey ? 1 : 0) + (evt.metaKey ? 1 : 0);
+ if (count === 1) {
+ return true;
+ }
+ return false;
+ };
+
+ /**
+ * Get the id of an element
+ * If the id attribute is not set, set the attribute with the given id
+ *
+ */
+ const getId = (el, id) => {
+ const existing_id = el.getAttribute('id');
+ if (existing_id) {
+ return existing_id;
+ }
+ el.setAttribute('id', id);
+ return id;
+ };
+
+ /**
+ * Returns a string with backslashes added before characters that need to be escaped.
+ */
+ const addSlashes = str => {
+ return str.replace(/[\\"']/g, '\\$&');
+ };
+
+ /**
+ *
+ */
+ const append = (parent, node) => {
+ if (node) parent.append(node);
+ };
+
+ /**
+ * Iterates over arrays and hashes.
+ *
+ * ```
+ * iterate(this.items, function(item, id) {
+ * // invoked for each item
+ * });
+ * ```
+ *
+ */
+ const iterate = (object, callback) => {
+ if (Array.isArray(object)) {
+ object.forEach(callback);
+ } else {
+ for (var key in object) {
+ if (object.hasOwnProperty(key)) {
+ callback(object[key], key);
+ }
+ }
+ }
+ };
+
+ /**
+ * Return a dom element from either a dom query string, jQuery object, a dom element or html string
+ * https://stackoverflow.com/questions/494143/creating-a-new-dom-element-from-an-html-string-using-built-in-dom-methods-or-pro/35385518#35385518
+ *
+ * param query should be {}
+ */
+ const getDom = query => {
+ if (query.jquery) {
+ return query[0];
+ }
+ if (query instanceof HTMLElement) {
+ return query;
+ }
+ if (isHtmlString(query)) {
+ var tpl = document.createElement('template');
+ tpl.innerHTML = query.trim(); // Never return a text node of whitespace as the result
+ return tpl.content.firstChild;
+ }
+ return document.querySelector(query);
+ };
+ const isHtmlString = arg => {
+ if (typeof arg === 'string' && arg.indexOf('<') > -1) {
+ return true;
+ }
+ return false;
+ };
+ const escapeQuery = query => {
+ return query.replace(/['"\\]/g, '\\$&');
+ };
+
+ /**
+ * Dispatch an event
+ *
+ */
+ const triggerEvent = (dom_el, event_name) => {
+ var event = document.createEvent('HTMLEvents');
+ event.initEvent(event_name, true, false);
+ dom_el.dispatchEvent(event);
+ };
+
+ /**
+ * Apply CSS rules to a dom element
+ *
+ */
+ const applyCSS = (dom_el, css) => {
+ Object.assign(dom_el.style, css);
+ };
+
+ /**
+ * Add css classes
+ *
+ */
+ const addClasses = (elmts, ...classes) => {
+ var norm_classes = classesArray(classes);
+ elmts = castAsArray(elmts);
+ elmts.map(el => {
+ norm_classes.map(cls => {
+ el.classList.add(cls);
+ });
+ });
+ };
+
+ /**
+ * Remove css classes
+ *
+ */
+ const removeClasses = (elmts, ...classes) => {
+ var norm_classes = classesArray(classes);
+ elmts = castAsArray(elmts);
+ elmts.map(el => {
+ norm_classes.map(cls => {
+ el.classList.remove(cls);
+ });
+ });
+ };
+
+ /**
+ * Return arguments
+ *
+ */
+ const classesArray = args => {
+ var classes = [];
+ iterate(args, _classes => {
+ if (typeof _classes === 'string') {
+ _classes = _classes.trim().split(/[\t\n\f\r\s]/);
+ }
+ if (Array.isArray(_classes)) {
+ classes = classes.concat(_classes);
+ }
+ });
+ return classes.filter(Boolean);
+ };
+
+ /**
+ * Create an array from arg if it's not already an array
+ *
+ */
+ const castAsArray = arg => {
+ if (!Array.isArray(arg)) {
+ arg = [arg];
+ }
+ return arg;
+ };
+
+ /**
+ * Get the closest node to the evt.target matching the selector
+ * Stops at wrapper
+ *
+ */
+ const parentMatch = (target, selector, wrapper) => {
+ if (wrapper && !wrapper.contains(target)) {
+ return;
+ }
+ while (target && target.matches) {
+ if (target.matches(selector)) {
+ return target;
+ }
+ target = target.parentNode;
+ }
+ };
+
+ /**
+ * Get the first or last item from an array
+ *
+ * > 0 - right (last)
+ * <= 0 - left (first)
+ *
+ */
+ const getTail = (list, direction = 0) => {
+ if (direction > 0) {
+ return list[list.length - 1];
+ }
+ return list[0];
+ };
+
+ /**
+ * Return true if an object is empty
+ *
+ */
+ const isEmptyObject = obj => {
+ return Object.keys(obj).length === 0;
+ };
+
+ /**
+ * Get the index of an element amongst sibling nodes of the same type
+ *
+ */
+ const nodeIndex = (el, amongst) => {
+ if (!el) return -1;
+ amongst = amongst || el.nodeName;
+ var i = 0;
+ while (el = el.previousElementSibling) {
+ if (el.matches(amongst)) {
+ i++;
+ }
+ }
+ return i;
+ };
+
+ /**
+ * Set attributes of an element
+ *
+ */
+ const setAttr = (el, attrs) => {
+ iterate(attrs, (val, attr) => {
+ if (val == null) {
+ el.removeAttribute(attr);
+ } else {
+ el.setAttribute(attr, '' + val);
+ }
+ });
+ };
+
+ /**
+ * Replace a node
+ */
+ const replaceNode = (existing, replacement) => {
+ if (existing.parentNode) existing.parentNode.replaceChild(replacement, existing);
+ };
+
+ /**
+ * highlight v3 | MIT license | Johann Burkard <[email protected]>
+ * Highlights arbitrary terms in a node.
+ *
+ * - Modified by Marshal <[email protected]> 2011-6-24 (added regex)
+ * - Modified by Brian Reavis <[email protected]> 2012-8-27 (cleanup)
+ */
+
+ const highlight = (element, regex) => {
+ if (regex === null) return;
+
+ // convet string to regex
+ if (typeof regex === 'string') {
+ if (!regex.length) return;
+ regex = new RegExp(regex, 'i');
+ }
+
+ // Wrap matching part of text node with highlighting <span>, e.g.
+ // Soccer -> <span class="highlight">Soc</span>cer for regex = /soc/i
+ const highlightText = node => {
+ var match = node.data.match(regex);
+ if (match && node.data.length > 0) {
+ var spannode = document.createElement('span');
+ spannode.className = 'highlight';
+ var middlebit = node.splitText(match.index);
+ middlebit.splitText(match[0].length);
+ var middleclone = middlebit.cloneNode(true);
+ spannode.appendChild(middleclone);
+ replaceNode(middlebit, spannode);
+ return 1;
+ }
+ return 0;
+ };
+
+ // Recurse element node, looking for child text nodes to highlight, unless element
+ // is childless, <script>, <style>, or already highlighted: <span class="hightlight">
+ const highlightChildren = node => {
+ if (node.nodeType === 1 && node.childNodes && !/(script|style)/i.test(node.tagName) && (node.className !== 'highlight' || node.tagName !== 'SPAN')) {
+ Array.from(node.childNodes).forEach(element => {
+ highlightRecursive(element);
+ });
+ }
+ };
+ const highlightRecursive = node => {
+ if (node.nodeType === 3) {
+ return highlightText(node);
+ }
+ highlightChildren(node);
+ return 0;
+ };
+ highlightRecursive(element);
+ };
+
+ /**
+ * removeHighlight fn copied from highlight v5 and
+ * edited to remove with(), pass js strict mode, and use without jquery
+ */
+ const removeHighlight = el => {
+ var elements = el.querySelectorAll("span.highlight");
+ Array.prototype.forEach.call(elements, function (el) {
+ var parent = el.parentNode;
+ parent.replaceChild(el.firstChild, el);
+ parent.normalize();
+ });
+ };
+
+ const KEY_A = 65;
+ const KEY_RETURN = 13;
+ const KEY_ESC = 27;
+ const KEY_LEFT = 37;
+ const KEY_UP = 38;
+ const KEY_RIGHT = 39;
+ const KEY_DOWN = 40;
+ const KEY_BACKSPACE = 8;
+ const KEY_DELETE = 46;
+ const KEY_TAB = 9;
+ const IS_MAC = typeof navigator === 'undefined' ? false : /Mac/.test(navigator.userAgent);
+ const KEY_SHORTCUT = IS_MAC ? 'metaKey' : 'ctrlKey'; // ctrl key or apple key for ma
+
+ var defaults = {
+ options: [],
+ optgroups: [],
+ plugins: [],
+ delimiter: ',',
+ splitOn: null,
+ // regexp or string for splitting up values from a paste command
+ persist: true,
+ diacritics: true,
+ create: null,
+ createOnBlur: false,
+ createFilter: null,
+ clearAfterSelect: false,
+ highlight: true,
+ openOnFocus: true,
+ shouldOpen: null,
+ maxOptions: 50,
+ maxItems: null,
+ hideSelected: null,
+ duplicates: false,
+ addPrecedence: false,
+ selectOnTab: false,
+ preload: null,
+ allowEmptyOption: false,
+ //closeAfterSelect: false,
+ refreshThrottle: 300,
+ loadThrottle: 300,
+ loadingClass: 'loading',
+ dataAttr: null,
+ //'data-data',
+ optgroupField: 'optgroup',
+ valueField: 'value',
+ labelField: 'text',
+ disabledField: 'disabled',
+ optgroupLabelField: 'label',
+ optgroupValueField: 'value',
+ lockOptgroupOrder: false,
+ sortField: '$order',
+ searchField: ['text'],
+ searchConjunction: 'and',
+ mode: null,
+ wrapperClass: 'ts-wrapper',
+ controlClass: 'ts-control',
+ dropdownClass: 'ts-dropdown',
+ dropdownContentClass: 'ts-dropdown-content',
+ itemClass: 'item',
+ optionClass: 'option',
+ dropdownParent: null,
+ controlInput: '<input type="text" autocomplete="off" size="1" />',
+ copyClassesToDropdown: false,
+ placeholder: null,
+ hidePlaceholder: null,
+ shouldLoad: function (query) {
+ return query.length > 0;
+ },
+ /*
+ load : null, // function(query, callback) { ... }
+ score : null, // function(search) { ... }
+ onInitialize : null, // function() { ... }
+ onChange : null, // function(value) { ... }
+ onItemAdd : null, // function(value, $item) { ... }
+ onItemRemove : null, // function(value) { ... }
+ onClear : null, // function() { ... }
+ onOptionAdd : null, // function(value, data) { ... }
+ onOptionRemove : null, // function(value) { ... }
+ onOptionClear : null, // function() { ... }
+ onOptionGroupAdd : null, // function(id, data) { ... }
+ onOptionGroupRemove : null, // function(id) { ... }
+ onOptionGroupClear : null, // function() { ... }
+ onDropdownOpen : null, // function(dropdown) { ... }
+ onDropdownClose : null, // function(dropdown) { ... }
+ onType : null, // function(str) { ... }
+ onDelete : null, // function(values) { ... }
+ */
+
+ render: {
+ /*
+ item: null,
+ optgroup: null,
+ optgroup_header: null,
+ option: null,
+ option_create: null
+ */
+ }
+ };
+
+ function getSettings(input, settings_user) {
+ var settings = Object.assign({}, defaults, settings_user);
+ var attr_data = settings.dataAttr;
+ var field_label = settings.labelField;
+ var field_value = settings.valueField;
+ var field_disabled = settings.disabledField;
+ var field_optgroup = settings.optgroupField;
+ var field_optgroup_label = settings.optgroupLabelField;
+ var field_optgroup_value = settings.optgroupValueField;
+ var tag_name = input.tagName.toLowerCase();
+ var placeholder = input.getAttribute('placeholder') || input.getAttribute('data-placeholder');
+ if (!placeholder && !settings.allowEmptyOption) {
+ let option = input.querySelector('option[value=""]');
+ if (option) {
+ placeholder = option.textContent;
+ }
+ }
+ var settings_element = {
+ placeholder: placeholder,
+ options: [],
+ optgroups: [],
+ items: [],
+ maxItems: null
+ };
+
+ /**
+ * Initialize from a <select> element.
+ *
+ */
+ var init_select = () => {
+ var tagName;
+ var options = settings_element.options;
+ var optionsMap = {};
+ var group_count = 1;
+ let $order = 0;
+ var readData = el => {
+ var data = Object.assign({}, el.dataset); // get plain object from DOMStringMap
+ var json = attr_data && data[attr_data];
+ if (typeof json === 'string' && json.length) {
+ data = Object.assign(data, JSON.parse(json));
+ }
+ return data;
+ };
+ var addOption = (option, group) => {
+ var value = hash_key(option.value);
+ if (value == null) return;
+ if (!value && !settings.allowEmptyOption) return;
+
+ // if the option already exists, it's probably been
+ // duplicated in another optgroup. in this case, push
+ // the current group to the "optgroup" property on the
+ // existing option so that it's rendered in both places.
+ if (optionsMap.hasOwnProperty(value)) {
+ if (group) {
+ var arr = optionsMap[value][field_optgroup];
+ if (!arr) {
+ optionsMap[value][field_optgroup] = group;
+ } else if (!Array.isArray(arr)) {
+ optionsMap[value][field_optgroup] = [arr, group];
+ } else {
+ arr.push(group);
+ }
+ }
+ } else {
+ var option_data = readData(option);
+ option_data[field_label] = option_data[field_label] || option.textContent;
+ option_data[field_value] = option_data[field_value] || value;
+ option_data[field_disabled] = option_data[field_disabled] || option.disabled;
+ option_data[field_optgroup] = option_data[field_optgroup] || group;
+ option_data.$option = option;
+ option_data.$order = option_data.$order || ++$order;
+ optionsMap[value] = option_data;
+ options.push(option_data);
+ }
+ if (option.selected) {
+ settings_element.items.push(value);
+ }
+ };
+ var addGroup = optgroup => {
+ var id, optgroup_data;
+ optgroup_data = readData(optgroup);
+ optgroup_data[field_optgroup_label] = optgroup_data[field_optgroup_label] || optgroup.getAttribute('label') || '';
+ optgroup_data[field_optgroup_value] = optgroup_data[field_optgroup_value] || group_count++;
+ optgroup_data[field_disabled] = optgroup_data[field_disabled] || optgroup.disabled;
+ optgroup_data.$order = optgroup_data.$order || ++$order;
+ settings_element.optgroups.push(optgroup_data);
+ id = optgroup_data[field_optgroup_value];
+ iterate(optgroup.children, option => {
+ addOption(option, id);
+ });
+ };
+ settings_element.maxItems = input.hasAttribute('multiple') ? null : 1;
+ iterate(input.children, child => {
+ tagName = child.tagName.toLowerCase();
+ if (tagName === 'optgroup') {
+ addGroup(child);
+ } else if (tagName === 'option') {
+ addOption(child);
+ }
+ });
+ };
+
+ /**
+ * Initialize from a <input type="text"> element.
+ *
+ */
+ var init_textbox = () => {
+ const data_raw = input.getAttribute(attr_data);
+ if (!data_raw) {
+ var _input$value$trim, _input$value;
+ var value = (_input$value$trim = input == null || (_input$value = input.value) == null ? void 0 : _input$value.trim()) != null ? _input$value$trim : '';
+ if (!settings.allowEmptyOption && !value.length) return;
+ const values = value.split(settings.delimiter);
+ iterate(values, value => {
+ const option = {};
+ option[field_label] = value;
+ option[field_value] = value;
+ settings_element.options.push(option);
+ });
+ settings_element.items = values;
+ } else {
+ settings_element.options = JSON.parse(data_raw);
+ iterate(settings_element.options, opt => {
+ settings_element.items.push(opt[field_value]);
+ });
+ }
+ };
+ if (tag_name === 'select') {
+ init_select();
+ } else {
+ init_textbox();
+ }
+ return Object.assign({}, defaults, settings_element, settings_user);
+ }
+
+ var instance_i = 0;
+ class TomSelect extends MicroPlugin(MicroEvent) {
+ constructor(input_arg, user_settings) {
+ super();
+ this.order = 0;
+ this.isOpen = false;
+ this.isDisabled = false;
+ this.isReadOnly = false;
+ this.isInvalid = false;
+ // @deprecated 1.8
+ this.isValid = true;
+ this.isLocked = false;
+ this.isFocused = false;
+ this.isInputHidden = false;
+ this.isSetup = false;
+ this.isDropdownContentStale = true;
+ this.ignoreFocus = false;
+ this.ignoreHover = false;
+ this.hasOptions = false;
+ this.lastValue = '';
+ this.caretPos = 0;
+ this.loading = 0;
+ this.loadedSearches = {};
+ this.activeOption = null;
+ this.activeItems = [];
+ this.optgroups = {};
+ this.options = {};
+ this.userOptions = {};
+ this.items = [];
+ this.refreshTimeout = null;
+ instance_i++;
+ var dir;
+ var input = getDom(input_arg);
+ if (input.tomselect) {
+ throw new Error('Tom Select already initialized on this element');
+ }
+ input.tomselect = this;
+
+ // detect rtl environment
+ var computedStyle = window.getComputedStyle && window.getComputedStyle(input, null);
+ dir = computedStyle.getPropertyValue('direction');
+
+ // setup default state
+ const settings = getSettings(input, user_settings);
+ this.settings = settings;
+ this.input = input;
+ this.tabIndex = input.tabIndex || 0;
+ this.is_select_tag = input.tagName.toLowerCase() === 'select';
+ this.rtl = /rtl/i.test(dir);
+ this.inputId = getId(input, 'tomselect-' + instance_i);
+ this.isRequired = input.required;
+
+ // search system
+ this.sifter = new Sifter(this.options, {
+ diacritics: settings.diacritics
+ });
+
+ // option-dependent defaults
+ settings.mode = settings.mode || (settings.maxItems === 1 ? 'single' : 'multi');
+ if (typeof settings.hideSelected !== 'boolean') {
+ settings.hideSelected = settings.mode === 'multi';
+ }
+ if (typeof settings.hidePlaceholder !== 'boolean') {
+ settings.hidePlaceholder = settings.mode !== 'multi';
+ }
+
+ // set up createFilter callback
+ var filter = settings.createFilter;
+ if (typeof filter !== 'function') {
+ if (typeof filter === 'string') {
+ filter = new RegExp(filter);
+ }
+ if (filter instanceof RegExp) {
+ settings.createFilter = input => filter.test(input);
+ } else {
+ settings.createFilter = value => {
+ return this.settings.duplicates || !this.options[value];
+ };
+ }
+ }
+ this.initializePlugins(settings.plugins);
+ this.setupCallbacks();
+ this.setupTemplates();
+
+ // Create all elements
+ const wrapper = getDom('<div>');
+ const control = getDom('<div>');
+ const dropdown = this._render('dropdown');
+ const dropdown_content = getDom(`<div role="listbox" tabindex="-1">`);
+ const classes = this.input.getAttribute('class') || '';
+ const inputMode = settings.mode;
+ var control_input;
+ addClasses(wrapper, settings.wrapperClass, classes, inputMode);
+ addClasses(control, settings.controlClass);
+ append(wrapper, control);
+ addClasses(dropdown, settings.dropdownClass, inputMode);
+ if (settings.copyClassesToDropdown) {
+ addClasses(dropdown, classes);
+ }
+ addClasses(dropdown_content, settings.dropdownContentClass);
+ append(dropdown, dropdown_content);
+ getDom(settings.dropdownParent || wrapper).appendChild(dropdown);
+
+ // default controlInput
+ if (isHtmlString(settings.controlInput)) {
+ control_input = getDom(settings.controlInput);
+
+ // set attributes
+ var attrs = ['autocorrect', 'autocapitalize', 'autocomplete', 'spellcheck', 'aria-label'];
+ iterate(attrs, attr => {
+ if (input.getAttribute(attr)) {
+ setAttr(control_input, {
+ [attr]: input.getAttribute(attr)
+ });
+ }
+ });
+ control_input.tabIndex = -1;
+ control.appendChild(control_input);
+ this.focus_node = control_input;
+
+ // dom element
+ } else if (settings.controlInput) {
+ control_input = getDom(settings.controlInput);
+ this.focus_node = control_input;
+ } else {
+ control_input = getDom('<input/>');
+ this.focus_node = control;
+ }
+ this.wrapper = wrapper;
+ this.dropdown = dropdown;
+ this.dropdown_content = dropdown_content;
+ this.control = control;
+ this.control_input = control_input;
+ this.setup();
+ }
+
+ /**
+ * set up event bindings.
+ *
+ */
+ setup() {
+ const self = this;
+ const settings = self.settings;
+ const control_input = self.control_input;
+ const dropdown = self.dropdown;
+ const dropdown_content = self.dropdown_content;
+ const wrapper = self.wrapper;
+ const control = self.control;
+ const input = self.input;
+ const focus_node = self.focus_node;
+ const passive_event = {
+ passive: true
+ };
+ const listboxId = self.inputId + '-ts-dropdown';
+ setAttr(dropdown_content, {
+ id: listboxId
+ });
+ setAttr(focus_node, {
+ role: 'combobox',
+ 'aria-haspopup': 'listbox',
+ 'aria-expanded': 'false',
+ 'aria-controls': listboxId
+ });
+ const control_id = getId(focus_node, self.inputId + '-ts-control');
+ const query = "label[for='" + escapeQuery(self.inputId) + "']";
+ const label = document.querySelector(query);
+ const label_click = self.focus.bind(self);
+ if (label) {
+ addEvent(label, 'click', label_click);
+ setAttr(label, {
+ for: control_id
+ });
+ const label_id = getId(label, self.inputId + '-ts-label');
+ setAttr(focus_node, {
+ 'aria-labelledby': label_id
+ });
+ setAttr(dropdown_content, {
+ 'aria-labelledby': label_id
+ });
+ }
+ wrapper.style.width = input.style.width;
+ wrapper.style.minWidth = input.style.minWidth;
+ wrapper.style.maxWidth = input.style.maxWidth;
+ if (self.plugins.names.length) {
+ const classes_plugins = 'plugin-' + self.plugins.names.join(' plugin-');
+ addClasses([wrapper, dropdown], classes_plugins);
+ }
+ if ((settings.maxItems === null || settings.maxItems > 1) && self.is_select_tag) {
+ setAttr(input, {
+ multiple: 'multiple'
+ });
+ }
+ if (settings.placeholder) {
+ setAttr(control_input, {
+ placeholder: settings.placeholder
+ });
+ }
+
+ // if splitOn was not passed in, construct it from the delimiter to allow pasting universally
+ if (!settings.splitOn && settings.delimiter) {
+ settings.splitOn = new RegExp('\\s*' + escape_regex(settings.delimiter) + '+\\s*');
+ }
+
+ // debounce user defined load() if loadThrottle > 0
+ // after initializePlugins() so plugins can create/modify user defined loaders
+ if (settings.load && settings.loadThrottle) {
+ settings.load = loadDebounce(settings.load, settings.loadThrottle);
+ }
+ addEvent(dropdown, 'mousemove', () => {
+ self.ignoreHover = false;
+ });
+ addEvent(dropdown, 'mouseenter', e => {
+ var target_match = parentMatch(e.target, '[data-selectable]', dropdown);
+ if (target_match) self.onOptionHover(e, target_match);
+ }, {
+ capture: true
+ });
+
+ // clicking on an option should select it
+ addEvent(dropdown, 'click', evt => {
+ const option = parentMatch(evt.target, '[data-selectable]');
+ if (option) {
+ self.onOptionSelect(evt, option);
+ preventDefault(evt, true);
+ }
+ });
+ addEvent(control, 'click', evt => {
+ var target_match = parentMatch(evt.target, '[data-ts-item]', control);
+ if (target_match && self.onItemSelect(evt, target_match)) {
+ preventDefault(evt, true);
+ return;
+ }
+
+ // retain focus (see control_input mousedown)
+ if (control_input.value != '') {
+ return;
+ }
+ self.onClick();
+ preventDefault(evt, true);
+ });
+
+ // keydown on focus_node for arrow_down/arrow_up
+ addEvent(focus_node, 'keydown', e => self.onKeyDown(e));
+
+ // keypress and input/keyup
+ addEvent(control_input, 'keypress', e => self.onKeyPress(e));
+ addEvent(control_input, 'input', e => self.onInput(e));
+ addEvent(focus_node, 'blur', e => self.onBlur(e));
+ addEvent(focus_node, 'focus', e => self.onFocus(e));
+ addEvent(control_input, 'paste', e => self.onPaste(e));
+ const doc_mousedown = evt => {
+ // blur if target is outside of this instance
+ // dropdown is not always inside wrapper
+ const target = evt.composedPath()[0];
+ if (!wrapper.contains(target) && !dropdown.contains(target)) {
+ if (self.isFocused) {
+ self.blur();
+ }
+ self.inputState();
+ return;
+ }
+
+ // retain focus by preventing native handling. if the
+ // event target is the input it should not be modified.
+ // otherwise, text selection within the input won't work.
+ // Fixes bug #212 which is no covered by tests
+ if (target == control_input && self.isOpen) {
+ evt.stopPropagation();
+
+ // clicking anywhere in the control should not blur the control_input (which would close the dropdown)
+ } else {
+ preventDefault(evt, true);
+ }
+ };
+ const win_scroll = () => {
+ if (self.isOpen) {
+ self.positionDropdown();
+ }
+ };
+ const input_invalid = () => {
+ if (self.isValid) {
+ self.isValid = false;
+ self.isInvalid = true;
+ self.refreshState();
+ }
+ };
+ addEvent(input, 'invalid', input_invalid);
+ addEvent(document, 'mousedown', doc_mousedown);
+ addEvent(window, 'scroll', win_scroll, passive_event);
+ addEvent(window, 'resize', win_scroll, passive_event);
+ this._destroy = () => {
+ input.removeEventListener('invalid', input_invalid);
+ document.removeEventListener('mousedown', doc_mousedown);
+ window.removeEventListener('scroll', win_scroll);
+ window.removeEventListener('resize', win_scroll);
+ if (label) label.removeEventListener('click', label_click);
+ };
+
+ // store original html and tab index so that they can be
+ // restored when the destroy() method is called.
+ this.revertSettings = {
+ innerHTML: input.innerHTML,
+ tabIndex: input.tabIndex
+ };
+ input.tabIndex = -1;
+ input.insertAdjacentElement('afterend', self.wrapper);
+ self.sync(false);
+ settings.items = [];
+ delete settings.optgroups;
+ delete settings.options;
+ self.refreshItems();
+ self.close(false);
+ self.inputState();
+ self.isSetup = true;
+ self.on('change', this.onChange);
+ addClasses(input, 'tomselected', 'ts-hidden-accessible');
+ self.trigger('initialize');
+
+ // preload options
+ if (settings.preload === true) {
+ self.preload();
+ }
+ }
+
+ /**
+ * Register options and optgroups
+ *
+ */
+ setupOptions(options = [], optgroups = []) {
+ // build options table
+ this.addOptions(options);
+
+ // build optgroup table
+ iterate(optgroups, optgroup => {
+ this.registerOptionGroup(optgroup);
+ });
+ }
+
+ /**
+ * Sets up default rendering functions.
+ */
+ setupTemplates() {
+ var self = this;
+ var field_label = self.settings.labelField;
+ var field_optgroup = self.settings.optgroupLabelField;
+ var templates = {
+ 'optgroup': data => {
+ let optgroup = document.createElement('div');
+ optgroup.className = 'optgroup';
+ optgroup.appendChild(data.options);
+ return optgroup;
+ },
+ 'optgroup_header': (data, escape) => {
+ return '<div class="optgroup-header">' + escape(data[field_optgroup]) + '</div>';
+ },
+ 'option': (data, escape) => {
+ return '<div>' + escape(data[field_label]) + '</div>';
+ },
+ 'item': (data, escape) => {
+ return '<div>' + escape(data[field_label]) + '</div>';
+ },
+ 'option_create': (data, escape) => {
+ return '<div class="create">Add <strong>' + escape(data.input) + '</strong>&hellip;</div>';
+ },
+ 'no_results': () => {
+ return '<div class="no-results">No results found</div>';
+ },
+ 'loading': () => {
+ return '<div class="spinner"></div>';
+ },
+ 'not_loading': () => {},
+ 'dropdown': () => {
+ return '<div></div>';
+ }
+ };
+ self.settings.render = Object.assign({}, templates, self.settings.render);
+ }
+
+ /**
+ * Maps fired events to callbacks provided
+ * in the settings used when creating the control.
+ */
+ setupCallbacks() {
+ var key, fn;
+ var callbacks = {
+ 'initialize': 'onInitialize',
+ 'change': 'onChange',
+ 'item_add': 'onItemAdd',
+ 'item_remove': 'onItemRemove',
+ 'item_select': 'onItemSelect',
+ 'clear': 'onClear',
+ 'option_add': 'onOptionAdd',
+ 'option_remove': 'onOptionRemove',
+ 'option_clear': 'onOptionClear',
+ 'optgroup_add': 'onOptionGroupAdd',
+ 'optgroup_remove': 'onOptionGroupRemove',
+ 'optgroup_clear': 'onOptionGroupClear',
+ 'dropdown_open': 'onDropdownOpen',
+ 'dropdown_close': 'onDropdownClose',
+ 'type': 'onType',
+ 'load': 'onLoad',
+ 'focus': 'onFocus',
+ 'blur': 'onBlur'
+ };
+ for (key in callbacks) {
+ fn = this.settings[callbacks[key]];
+ if (fn) this.on(key, fn);
+ }
+ }
+
+ /**
+ * Sync the Tom Select instance with the original input or select
+ *
+ */
+ sync(get_settings = true) {
+ const self = this;
+ const settings = get_settings ? getSettings(self.input, {
+ delimiter: self.settings.delimiter,
+ allowEmptyOption: self.settings.allowEmptyOption
+ }) : self.settings;
+ self.setupOptions(settings.options, settings.optgroups);
+ self.setValue(settings.items || [], true); // silent prevents recursion
+
+ if (self.input.disabled) {
+ self.disable();
+ } else if (self.input.readOnly) {
+ self.setReadOnly(true);
+ } else {
+ self.enable(); //sets tabIndex
+ }
+ self.lastQuery = null; // so updated options will be displayed in dropdown
+ }
+
+ /**
+ * Triggered when the main control element
+ * has a click event.
+ *
+ */
+ onClick() {
+ var self = this;
+ if (self.activeItems.length > 0) {
+ self.clearActiveItems();
+ self.focus();
+ return;
+ }
+ if (self.isFocused && self.isOpen) {
+ self.blur();
+ } else {
+ self.focus();
+ }
+ }
+
+ /**
+ * @deprecated v1.7
+ *
+ */
+ onMouseDown() {}
+
+ /**
+ * Triggered when the value of the control has been changed.
+ * This should propagate the event to the original DOM
+ * input / select element.
+ */
+ onChange() {
+ triggerEvent(this.input, 'input');
+ triggerEvent(this.input, 'change');
+ }
+
+ /**
+ * Triggered on <input> paste.
+ *
+ */
+ onPaste(e) {
+ var self = this;
+ if (self.isInputHidden || self.isLocked) {
+ preventDefault(e);
+ return;
+ }
+
+ // If a regex or string is included, this will split the pasted
+ // input and create Items for each separate value
+ if (!self.settings.splitOn) {
+ return;
+ }
+
+ // Wait for pasted text to be recognized in value
+ setTimeout(() => {
+ var pastedText = self.inputValue();
+ if (!pastedText.match(self.settings.splitOn)) {
+ return;
+ }
+ var splitInput = pastedText.trim().split(self.settings.splitOn);
+ iterate(splitInput, piece => {
+ const hash = hash_key(piece);
+ if (hash) {
+ if (this.options[piece]) {
+ self.addItem(piece);
+ } else {
+ self.createItem(piece);
+ }
+ }
+ });
+ }, 0);
+ }
+
+ /**
+ * Triggered on <input> keypress.
+ *
+ */
+ onKeyPress(e) {
+ var self = this;
+ if (self.isLocked) {
+ preventDefault(e);
+ return;
+ }
+ var character = String.fromCharCode(e.keyCode || e.which);
+ if (self.settings.create && self.settings.mode === 'multi' && character === self.settings.delimiter) {
+ self.createItem();
+ preventDefault(e);
+ return;
+ }
+ }
+
+ /**
+ * Triggered on <input> keydown.
+ *
+ */
+ onKeyDown(e) {
+ var self = this;
+ self.ignoreHover = true;
+ if (self.isLocked) {
+ if (e.keyCode !== KEY_TAB) {
+ preventDefault(e);
+ }
+ return;
+ }
+ switch (e.keyCode) {
+ // ctrl+A: select all
+ case KEY_A:
+ if (isKeyDown(KEY_SHORTCUT, e)) {
+ if (self.control_input.value == '') {
+ preventDefault(e);
+ self.selectAll();
+ return;
+ }
+ }
+ break;
+
+ // esc: close dropdown
+ case KEY_ESC:
+ if (self.isOpen) {
+ preventDefault(e, true);
+ self.close();
+ }
+ self.clearActiveItems();
+ return;
+
+ // down: open dropdown or move selection down
+ case KEY_DOWN:
+ if (!self.isOpen && self.hasOptions) {
+ self.open();
+ } else if (self.activeOption) {
+ let next = self.getAdjacent(self.activeOption, 1);
+ if (next) self.setActiveOption(next);
+ }
+ preventDefault(e);
+ return;
+
+ // up: move selection up
+ case KEY_UP:
+ if (self.activeOption) {
+ let prev = self.getAdjacent(self.activeOption, -1);
+ if (prev) self.setActiveOption(prev);
+ }
+ preventDefault(e);
+ return;
+
+ // return: select active option
+ case KEY_RETURN:
+ if (self.canSelect(self.activeOption)) {
+ self.onOptionSelect(e, self.activeOption);
+ preventDefault(e);
+
+ // if the option_create=null, the dropdown might be closed
+ } else if (self.settings.create && self.createItem()) {
+ preventDefault(e);
+
+ // don't submit form when searching for a value
+ } else if (document.activeElement == self.control_input && self.isOpen) {
+ preventDefault(e);
+ }
+ return;
+
+ // left: modifiy item selection to the left
+ case KEY_LEFT:
+ self.advanceSelection(-1, e);
+ return;
+
+ // right: modifiy item selection to the right
+ case KEY_RIGHT:
+ self.advanceSelection(1, e);
+ return;
+
+ // tab: select active option and/or create item
+ case KEY_TAB:
+ if (self.settings.selectOnTab) {
+ if (self.canSelect(self.activeOption)) {
+ self.onOptionSelect(e, self.activeOption);
+
+ // prevent default [tab] behaviour of jump to the next field
+ // if select isFull, then the dropdown won't be open and [tab] will work normally
+ preventDefault(e);
+ } else if (self.settings.create && self.createItem()) {
+ preventDefault(e);
+ }
+ }
+ return;
+
+ // delete|backspace: delete items
+ case KEY_BACKSPACE:
+ case KEY_DELETE:
+ self.deleteSelection(e);
+ return;
+ }
+
+ // don't enter text in the control_input when active items are selected
+ if (self.isInputHidden && !isKeyDown(KEY_SHORTCUT, e)) {
+ preventDefault(e);
+ }
+ }
+
+ /**
+ * Triggered on <input> keyup.
+ *
+ */
+ onInput(e) {
+ if (this.isLocked) {
+ return;
+ }
+ const value = this.inputValue();
+ if (this.lastValue === value) return;
+ this.lastValue = value;
+ if (value == '') {
+ this._onInput();
+ return;
+ }
+ if (this.refreshTimeout) {
+ window.clearTimeout(this.refreshTimeout);
+ }
+ this.refreshTimeout = timeout(() => {
+ this.refreshTimeout = null;
+ this._onInput();
+ }, this.settings.refreshThrottle);
+ }
+ _onInput() {
+ const value = this.lastValue;
+ if (this.settings.shouldLoad.call(this, value)) {
+ this.load(value);
+ }
+ this.refreshOptions();
+ this.trigger('type', value);
+ }
+
+ /**
+ * Triggered when the user rolls over
+ * an option in the autocomplete dropdown menu.
+ *
+ */
+ onOptionHover(evt, option) {
+ if (this.ignoreHover) return;
+ this.setActiveOption(option, false);
+ }
+
+ /**
+ * Triggered on <input> focus.
+ *
+ */
+ onFocus(e) {
+ var self = this;
+ var wasFocused = self.isFocused;
+ if (self.isDisabled || self.isReadOnly) {
+ self.blur();
+ preventDefault(e);
+ return;
+ }
+ if (self.ignoreFocus) return;
+ self.isFocused = true;
+ if (self.settings.preload === 'focus') self.preload();
+ if (!wasFocused) self.trigger('focus');
+ if (!self.activeItems.length) {
+ self.inputState();
+ self.refreshOptions(!!self.settings.openOnFocus);
+ }
+ self.refreshState();
+ }
+
+ /**
+ * Triggered on <input> blur.
+ *
+ */
+ onBlur(e) {
+ if (document.hasFocus() === false) return;
+ var self = this;
+ if (!self.isFocused) return;
+ self.isFocused = false;
+ self.ignoreFocus = false;
+ var deactivate = () => {
+ self.close();
+ self.setActiveItem();
+ self.setCaret(self.items.length);
+ self.trigger('blur');
+ };
+ if (self.settings.create && self.settings.createOnBlur) {
+ self.createItem(null, deactivate);
+ } else {
+ deactivate();
+ }
+ }
+
+ /**
+ * Triggered when the user clicks on an option
+ * in the autocomplete dropdown menu.
+ *
+ */
+ onOptionSelect(evt, option) {
+ var value,
+ self = this;
+
+ // should not be possible to trigger a option under a disabled optgroup
+ if (option.parentElement && option.parentElement.matches('[data-disabled]')) {
+ return;
+ }
+ if (option.classList.contains('create')) {
+ self.createItem(null, () => {
+ if (self.settings.closeAfterSelect) {
+ self.close();
+ } else if (self.settings.clearAfterSelect) {
+ self.setTextboxValue();
+ }
+ });
+ } else {
+ value = option.dataset.value;
+ if (typeof value !== 'undefined') {
+ self.isDropdownContentStale = self.settings.hideSelected;
+ self.addItem(value);
+ if (self.settings.closeAfterSelect) {
+ self.close();
+ } else if (self.settings.clearAfterSelect) {
+ self.setTextboxValue();
+ }
+ if (!self.settings.hideSelected && evt.type && /click/.test(evt.type)) {
+ self.setActiveOption(option);
+ }
+ }
+ }
+ }
+
+ /**
+ * Return true if the given option can be selected
+ *
+ */
+ canSelect(option) {
+ if (this.isOpen && option && this.dropdown_content.contains(option)) {
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Triggered when the user clicks on an item
+ * that has been selected.
+ *
+ */
+ onItemSelect(evt, item) {
+ var self = this;
+ if (!self.isLocked && self.settings.mode === 'multi') {
+ preventDefault(evt);
+ self.setActiveItem(item, evt);
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Determines whether or not to invoke
+ * the user-provided option provider / loader
+ *
+ * Note, there is a subtle difference between
+ * this.canLoad() and this.settings.shouldLoad();
+ *
+ * - settings.shouldLoad() is a user-input validator.
+ * When false is returned, the not_loading template
+ * will be added to the dropdown
+ *
+ * - canLoad() is lower level validator that checks
+ * the Tom Select instance. There is no inherent user
+ * feedback when canLoad returns false
+ *
+ */
+ canLoad(value) {
+ if (!this.settings.load) return false;
+ if (this.loadedSearches.hasOwnProperty(value)) return false;
+ return true;
+ }
+
+ /**
+ * Invokes the user-provided option provider / loader.
+ *
+ */
+ load(value) {
+ const self = this;
+ if (!self.canLoad(value)) return;
+ addClasses(self.wrapper, self.settings.loadingClass);
+ self.loading++;
+ const callback = self.loadCallback.bind(self);
+ self.settings.load.call(self, value, callback);
+ }
+
+ /**
+ * Invoked by the user-provided option provider
+ *
+ */
+ loadCallback(options, optgroups) {
+ const self = this;
+ self.loading = Math.max(self.loading - 1, 0);
+ self.isDropdownContentStale = true;
+ self.clearActiveOption(); // when new results load, focus should be on first option
+ self.setupOptions(options, optgroups);
+ self.refreshOptions(self.isFocused && !self.isInputHidden);
+ if (!self.loading) {
+ removeClasses(self.wrapper, self.settings.loadingClass);
+ }
+ self.trigger('load', options, optgroups);
+ }
+ preload() {
+ var classList = this.wrapper.classList;
+ if (classList.contains('preloaded')) return;
+ classList.add('preloaded');
+ this.load('');
+ }
+
+ /**
+ * Sets the input field of the control to the specified value.
+ *
+ */
+ setTextboxValue(value = '') {
+ var input = this.control_input;
+ var changed = input.value !== value;
+ if (changed) {
+ input.value = value;
+ triggerEvent(input, 'update');
+ this.lastValue = value;
+ }
+ }
+
+ /**
+ * Returns the value of the control. If multiple items
+ * can be selected (e.g. <select multiple>), this returns
+ * an array. If only one item can be selected, this
+ * returns a string.
+ *
+ */
+ getValue() {
+ if (this.is_select_tag && this.input.hasAttribute('multiple')) {
+ return this.items;
+ }
+ return this.items.join(this.settings.delimiter);
+ }
+
+ /**
+ * Resets the selected items to the given value.
+ *
+ */
+ setValue(value, silent) {
+ var events = silent ? [] : ['change'];
+ debounce_events(this, events, () => {
+ this.clear(silent);
+ this.addItems(value, silent);
+ });
+ }
+
+ /**
+ * Resets the number of max items to the given value
+ *
+ */
+ setMaxItems(value) {
+ if (value === 0) value = null; //reset to unlimited items.
+ this.settings.maxItems = value;
+ this.refreshState();
+ }
+
+ /**
+ * Sets the selected item.
+ *
+ */
+ setActiveItem(item, e) {
+ var self = this;
+ var eventName;
+ var i, begin, end, swap;
+ var last;
+ if (self.settings.mode === 'single') return;
+
+ // clear the active selection
+ if (!item) {
+ self.clearActiveItems();
+ if (self.isFocused) {
+ self.inputState();
+ }
+ return;
+ }
+
+ // modify selection
+ eventName = e && e.type.toLowerCase();
+ if (eventName === 'click' && isKeyDown('shiftKey', e) && self.activeItems.length) {
+ last = self.getLastActive();
+ begin = Array.prototype.indexOf.call(self.control.children, last);
+ end = Array.prototype.indexOf.call(self.control.children, item);
+ if (begin > end) {
+ swap = begin;
+ begin = end;
+ end = swap;
+ }
+ for (i = begin; i <= end; i++) {
+ item = self.control.children[i];
+ if (self.activeItems.indexOf(item) === -1) {
+ self.setActiveItemClass(item);
+ }
+ }
+ preventDefault(e);
+ } else if (eventName === 'click' && isKeyDown(KEY_SHORTCUT, e) || eventName === 'keydown' && isKeyDown('shiftKey', e)) {
+ if (item.classList.contains('active')) {
+ self.removeActiveItem(item);
+ } else {
+ self.setActiveItemClass(item);
+ }
+ } else {
+ self.clearActiveItems();
+ self.setActiveItemClass(item);
+ }
+
+ // ensure control has focus
+ self.inputState();
+ if (!self.isFocused) {
+ self.focus();
+ }
+ }
+
+ /**
+ * Set the active and last-active classes
+ *
+ */
+ setActiveItemClass(item) {
+ const self = this;
+ const last_active = self.control.querySelector('.last-active');
+ if (last_active) removeClasses(last_active, 'last-active');
+ addClasses(item, 'active last-active');
+ self.trigger('item_select', item);
+ if (self.activeItems.indexOf(item) == -1) {
+ self.activeItems.push(item);
+ }
+ }
+
+ /**
+ * Remove active item
+ *
+ */
+ removeActiveItem(item) {
+ var idx = this.activeItems.indexOf(item);
+ this.activeItems.splice(idx, 1);
+ removeClasses(item, 'active');
+ }
+
+ /**
+ * Clears all the active items
+ *
+ */
+ clearActiveItems() {
+ removeClasses(this.activeItems, 'active');
+ this.activeItems = [];
+ }
+
+ /**
+ * Sets the selected item in the dropdown menu
+ * of available options.
+ *
+ */
+ setActiveOption(option, scroll = true) {
+ if (option === this.activeOption) {
+ return;
+ }
+ this.clearActiveOption();
+ if (!option) return;
+ this.activeOption = option;
+ setAttr(this.focus_node, {
+ 'aria-activedescendant': option.getAttribute('id')
+ });
+ setAttr(option, {
+ 'aria-selected': 'true'
+ });
+ addClasses(option, 'active');
+ if (scroll) this.scrollToOption(option);
+ }
+
+ /**
+ * Sets the dropdown_content scrollTop to display the option
+ *
+ */
+ scrollToOption(option, behavior) {
+ if (!option) return;
+ const content = this.dropdown_content;
+ const height_menu = content.clientHeight;
+ const scrollTop = content.scrollTop || 0;
+ const height_item = option.offsetHeight;
+ const y = option.getBoundingClientRect().top - content.getBoundingClientRect().top + scrollTop;
+ if (y + height_item > height_menu + scrollTop) {
+ this.scroll(y - height_menu + height_item, behavior);
+ } else if (y < scrollTop) {
+ this.scroll(y, behavior);
+ }
+ }
+
+ /**
+ * Scroll the dropdown to the given position
+ *
+ */
+ scroll(scrollTop, behavior) {
+ const content = this.dropdown_content;
+ if (behavior) {
+ content.style.scrollBehavior = behavior;
+ }
+ content.scrollTop = scrollTop;
+ content.style.scrollBehavior = '';
+ }
+
+ /**
+ * Clears the active option
+ *
+ */
+ clearActiveOption() {
+ if (this.activeOption) {
+ removeClasses(this.activeOption, 'active');
+ setAttr(this.activeOption, {
+ 'aria-selected': null
+ });
+ }
+ this.activeOption = null;
+ setAttr(this.focus_node, {
+ 'aria-activedescendant': null
+ });
+ }
+
+ /**
+ * Selects all items (CTRL + A).
+ */
+ selectAll() {
+ const self = this;
+ if (self.settings.mode === 'single') return;
+ const activeItems = self.controlChildren();
+ if (!activeItems.length) return;
+ self.inputState();
+ self.close();
+ self.activeItems = activeItems;
+ iterate(activeItems, item => {
+ self.setActiveItemClass(item);
+ });
+ }
+
+ /**
+ * Determines if the control_input should be in a hidden or visible state
+ *
+ */
+ inputState() {
+ var self = this;
+ if (!self.control.contains(self.control_input)) return;
+ setAttr(self.control_input, {
+ placeholder: self.settings.placeholder
+ });
+ if (self.activeItems.length > 0 || !self.isFocused && self.settings.hidePlaceholder && self.items.length > 0) {
+ self.setTextboxValue();
+ self.isInputHidden = true;
+ } else {
+ if (self.settings.hidePlaceholder && self.items.length > 0) {
+ setAttr(self.control_input, {
+ placeholder: ''
+ });
+ }
+ self.isInputHidden = false;
+ }
+ self.wrapper.classList.toggle('input-hidden', self.isInputHidden);
+ }
+
+ /**
+ * Get the input value
+ */
+ inputValue() {
+ return this.control_input.value.trim();
+ }
+
+ /**
+ * Gives the control focus.
+ */
+ focus() {
+ var self = this;
+ if (self.isDisabled || self.isReadOnly) return;
+ self.ignoreFocus = true;
+ const focusTarget = this.control_input.offsetWidth ? this.control_input : this.focus_node;
+ focusTarget.focus();
+ setTimeout(() => {
+ self.ignoreFocus = false;
+ // Fix https://github.com/orchidjs/tom-select/issues/806
+ // Only proceed if this instance's element is still the active element. If Edge autofill
+ // (or anything else) has moved focus to a different element in the interim, calling
+ // onFocus() here would steal focus back and restart the cascade loop.
+ const root = focusTarget.getRootNode();
+ if (root.activeElement !== focusTarget) {
+ return;
+ }
+ this.onFocus();
+ }, 0);
+ }
+
+ /**
+ * Forces the control out of focus.
+ *
+ */
+ blur() {
+ this.focus_node.blur();
+ this.onBlur();
+ }
+
+ /**
+ * Returns a function that scores an object
+ * to show how good of a match it is to the
+ * provided query.
+ *
+ * @return {function}
+ */
+ getScoreFunction(query) {
+ return this.sifter.getScoreFunction(query, this.getSearchOptions());
+ }
+
+ /**
+ * Returns search options for sifter (the system
+ * for scoring and sorting results).
+ *
+ * @see https://github.com/orchidjs/sifter.js
+ * @return {object}
+ */
+ getSearchOptions() {
+ var settings = this.settings;
+ var sort = settings.sortField;
+ if (typeof settings.sortField === 'string') {
+ sort = [{
+ field: settings.sortField
+ }];
+ }
+ return {
+ fields: settings.searchField,
+ conjunction: settings.searchConjunction,
+ sort: sort,
+ nesting: settings.nesting
+ };
+ }
+
+ /**
+ * Searches through available options and returns
+ * a sorted array of matches.
+ *
+ */
+ search(query) {
+ var result, calculateScore;
+ var self = this;
+ var options = this.getSearchOptions();
+
+ // validate user-provided result scoring function
+ if (self.settings.score) {
+ calculateScore = self.settings.score.call(self, query);
+ if (typeof calculateScore !== 'function') {
+ throw new Error('Tom Select "score" setting must be a function that returns a function');
+ }
+ }
+
+ // perform search
+ if (self.isDropdownContentStale || query !== self.lastQuery) {
+ self.lastQuery = query;
+ // temp fix for https://github.com/orchidjs/tom-select/issues/987
+ // UI crashed when more than 30 same chars in a row, prevent search and return empt result
+ if (/(.)\1{15,}/.test(query)) {
+ query = '';
+ }
+ result = self.sifter.search(query, Object.assign(options, {
+ score: calculateScore
+ }));
+ self.currentResults = result;
+ } else {
+ result = Object.assign({}, self.currentResults);
+ }
+
+ // filter out selected items
+ if (self.settings.hideSelected) {
+ result.items = result.items.filter(item => {
+ let hashed = hash_key(item.id);
+ return !(hashed !== null && self.items.indexOf(hashed) !== -1);
+ });
+ }
+ return result;
+ }
+
+ /**
+ * Refreshes the list of available options shown
+ * in the autocomplete dropdown menu.
+ *
+ */
+ refreshOptions(triggerDropdown = true) {
+ var i, j, k, n, optgroup, optgroups, html, has_create_option, active_group;
+ var create;
+ const groups = {};
+ const groups_order = [];
+ var self = this;
+ var query = self.inputValue();
+ const same_query = query === self.lastQuery || query == '' && self.lastQuery == null;
+ var results = self.search(query);
+ var active_option = null;
+ var show_dropdown = self.settings.shouldOpen || false;
+ var dropdown_content = self.dropdown_content;
+ if (same_query) {
+ active_option = self.activeOption;
+ if (active_option) {
+ active_group = active_option.closest('[data-group]');
+ }
+ }
+
+ // build markup
+ n = results.items.length;
+ if (typeof self.settings.maxOptions === 'number') {
+ n = Math.min(n, self.settings.maxOptions);
+ }
+ if (n > 0) {
+ show_dropdown = true;
+ }
+
+ // get fragment for group and the position of the group in group_order
+ const getGroupFragment = (optgroup, order) => {
+ let group_order_i = groups[optgroup];
+ if (group_order_i !== undefined) {
+ let order_group = groups_order[group_order_i];
+ if (order_group !== undefined) {
+ return [group_order_i, order_group.fragment];
+ }
+ }
+ let group_fragment = document.createDocumentFragment();
+ group_order_i = groups_order.length;
+ groups_order.push({
+ fragment: group_fragment,
+ order,
+ optgroup
+ });
+ return [group_order_i, group_fragment];
+ };
+
+ // render and group available options individually
+ for (i = 0; i < n; i++) {
+ // get option dom element
+ let item = results.items[i];
+ if (!item) continue;
+ let opt_value = item.id;
+ let option = self.options[opt_value];
+ if (option === undefined) continue;
+ let opt_hash = get_hash(opt_value);
+ let option_el = self.getOption(opt_hash, true);
+
+ // toggle 'selected' class
+ if (!self.settings.hideSelected) {
+ option_el.classList.toggle('selected', self.items.includes(opt_hash));
+ }
+ optgroup = option[self.settings.optgroupField] || '';
+ optgroups = Array.isArray(optgroup) ? optgroup : [optgroup];
+ for (j = 0, k = optgroups && optgroups.length; j < k; j++) {
+ optgroup = optgroups[j];
+ let order = option.$order;
+ let self_optgroup = self.optgroups[optgroup];
+ if (self_optgroup === undefined && typeof self.settings.optionGroupRegister === 'function') {
+ var regGroup;
+ if (regGroup = self.settings.optionGroupRegister.apply(self, [optgroup])) {
+ self.registerOptionGroup(regGroup);
+ }
+ }
+ self_optgroup = self.optgroups[optgroup];
+ if (self_optgroup === undefined) {
+ optgroup = '';
+ } else {
+ order = self_optgroup.$order;
+ }
+ const [group_order_i, group_fragment] = getGroupFragment(optgroup, order);
+
+ // nodes can only have one parent, so if the option is in mutple groups, we need a clone
+ if (j > 0) {
+ option_el = option_el.cloneNode(true);
+ setAttr(option_el, {
+ id: option.$id + '-clone-' + j,
+ 'aria-selected': null
+ });
+ option_el.classList.add('ts-cloned');
+ removeClasses(option_el, 'active');
+
+ // make sure we keep the activeOption in the same group
+ if (self.activeOption && self.activeOption.dataset.value == opt_value) {
+ if (active_group && active_group.dataset.group === optgroup.toString()) {
+ active_option = option_el;
+ }
+ }
+ }
+ group_fragment.appendChild(option_el);
+ if (optgroup != '') {
+ groups[optgroup] = group_order_i;
+ }
+ }
+ }
+
+ // sort optgroups
+ if (self.settings.lockOptgroupOrder) {
+ groups_order.sort((a, b) => {
+ return a.order - b.order;
+ });
+ }
+
+ // render optgroup headers & join groups
+ html = document.createDocumentFragment();
+ iterate(groups_order, group_order => {
+ let group_fragment = group_order.fragment;
+ let optgroup = group_order.optgroup;
+ if (!group_fragment || !group_fragment.children.length) return;
+ let group_heading = self.optgroups[optgroup];
+ if (group_heading !== undefined) {
+ let group_options = document.createDocumentFragment();
+ let header = self.render('optgroup_header', group_heading);
+ append(group_options, header);
+ append(group_options, group_fragment);
+ let group_html = self.render('optgroup', {
+ group: group_heading,
+ options: group_options
+ });
+ append(html, group_html);
+ } else {
+ append(html, group_fragment);
+ }
+ });
+ dropdown_content.innerHTML = '';
+ append(dropdown_content, html);
+ self.isDropdownContentStale = false;
+
+ // highlight matching terms inline
+ if (self.settings.highlight) {
+ removeHighlight(dropdown_content);
+ if (results.query.length && results.tokens.length) {
+ iterate(results.tokens, tok => {
+ highlight(dropdown_content, tok.regex);
+ });
+ }
+ }
+
+ // helper method for adding templates to dropdown
+ var add_template = template => {
+ let content = self.render(template, {
+ input: query
+ });
+ if (content) {
+ show_dropdown = true;
+ dropdown_content.insertBefore(content, dropdown_content.firstChild);
+ }
+ return content;
+ };
+
+ // add loading message
+ if (self.loading) {
+ add_template('loading');
+
+ // invalid query
+ } else if (!self.settings.shouldLoad.call(self, query)) {
+ add_template('not_loading');
+
+ // add no_results message
+ } else if (results.items.length === 0) {
+ add_template('no_results');
+ }
+
+ // add create option
+ has_create_option = self.canCreate(query);
+ if (has_create_option) {
+ create = add_template('option_create');
+ }
+
+ // activate
+ self.hasOptions = results.items.length > 0 || has_create_option;
+ if (show_dropdown) {
+ if (results.items.length > 0) {
+ if (!active_option && self.settings.mode === 'single' && self.items[0] != undefined) {
+ active_option = self.getOption(self.items[0]);
+ }
+ if (!dropdown_content.contains(active_option)) {
+ let active_index = 0;
+ if (create && !self.settings.addPrecedence) {
+ active_index = 1;
+ }
+ active_option = self.selectable()[active_index];
+ }
+ } else if (create) {
+ active_option = create;
+ }
+ if (triggerDropdown && !self.isOpen) {
+ self.open();
+ self.scrollToOption(active_option, 'auto');
+ }
+ self.setActiveOption(active_option);
+ } else {
+ self.clearActiveOption();
+ if (triggerDropdown && self.isOpen) {
+ self.close(false); // if create_option=null, we want the dropdown to close but not reset the textbox value
+ }
+ }
+ }
+
+ /**
+ * Return list of selectable options
+ *
+ */
+ selectable() {
+ return this.dropdown_content.querySelectorAll('[data-selectable]');
+ }
+
+ /**
+ * Adds an available option. If it already exists,
+ * nothing will happen. Note: this does not refresh
+ * the options list dropdown (use `refreshOptions`
+ * for that).
+ *
+ * Usage:
+ *
+ * this.addOption(data)
+ *
+ */
+ addOption(data, user_created = false) {
+ const self = this;
+
+ // @deprecated 1.7.7
+ // use addOptions( array, user_created ) for adding multiple options
+ if (Array.isArray(data)) {
+ self.addOptions(data, user_created);
+ return false;
+ }
+ const key = hash_key(data[self.settings.valueField]);
+ if (key === null || self.options.hasOwnProperty(key)) {
+ self.updateOption(data[self.settings.valueField], data);
+ return false;
+ }
+ data.$order = data.$order || ++self.order;
+ data.$id = self.inputId + '-opt-' + data.$order;
+ self.options[key] = data;
+ self.isDropdownContentStale = true;
+ if (user_created) {
+ self.userOptions[key] = user_created;
+ self.trigger('option_add', key, data);
+ }
+ return key;
+ }
+
+ /**
+ * Add multiple options
+ *
+ */
+ addOptions(data, user_created = false) {
+ iterate(data, dat => {
+ this.addOption(dat, user_created);
+ });
+ }
+
+ /**
+ * @deprecated 1.7.7
+ */
+ registerOption(data) {
+ return this.addOption(data);
+ }
+
+ /**
+ * Registers an option group to the pool of option groups.
+ *
+ * @return {boolean|string}
+ */
+ registerOptionGroup(data) {
+ var key = hash_key(data[this.settings.optgroupValueField]);
+ if (key === null) return false;
+ data.$order = data.$order || ++this.order;
+ this.optgroups[key] = data;
+ return key;
+ }
+
+ /**
+ * Registers a new optgroup for options
+ * to be bucketed into.
+ *
+ */
+ addOptionGroup(id, data) {
+ var hashed_id;
+ data[this.settings.optgroupValueField] = id;
+ if (hashed_id = this.registerOptionGroup(data)) {
+ this.trigger('optgroup_add', hashed_id, data);
+ }
+ }
+
+ /**
+ * Removes an existing option group.
+ *
+ */
+ removeOptionGroup(id) {
+ if (this.optgroups.hasOwnProperty(id)) {
+ delete this.optgroups[id];
+ this.clearCache();
+ this.trigger('optgroup_remove', id);
+ }
+ }
+
+ /**
+ * Clears all existing option groups.
+ */
+ clearOptionGroups() {
+ this.optgroups = {};
+ this.clearCache();
+ this.trigger('optgroup_clear');
+ }
+
+ /**
+ * Updates an option available for selection. If
+ * it is visible in the selected items or options
+ * dropdown, it will be re-rendered automatically.
+ *
+ */
+ updateOption(value, data) {
+ const self = this;
+ var item_new;
+ var index_item;
+ const value_old = hash_key(value);
+ const value_new = hash_key(data[self.settings.valueField]);
+
+ // sanity checks
+ if (value_old === null) return;
+ const data_old = self.options[value_old];
+ if (data_old == undefined) return;
+ if (typeof value_new !== 'string') throw new Error('Value must be set in option data');
+ const option = self.getOption(value_old);
+ const item = self.getItem(value_old);
+ data.$order = data.$order || data_old.$order;
+ delete self.options[value_old];
+
+ // invalidate render cache
+ // don't remove existing node yet, we'll remove it after replacing it
+ self.uncacheValue(value_new);
+ self.options[value_new] = data;
+
+ // update the option if it's in the dropdown
+ if (option) {
+ if (self.dropdown_content.contains(option)) {
+ const option_new = self._render('option', data);
+ replaceNode(option, option_new);
+ if (self.activeOption === option) {
+ self.setActiveOption(option_new);
+ }
+ }
+ option.remove();
+ }
+
+ // update the item if we have one
+ if (item) {
+ index_item = self.items.indexOf(value_old);
+ if (index_item !== -1) {
+ self.items.splice(index_item, 1, value_new);
+ }
+ item_new = self._render('item', data);
+ if (item.classList.contains('active')) addClasses(item_new, 'active');
+ replaceNode(item, item_new);
+ }
+
+ // we might have updated the sortField
+ self.isDropdownContentStale = true;
+ }
+
+ /**
+ * Removes a single option.
+ *
+ */
+ removeOption(value, silent) {
+ const self = this;
+ value = get_hash(value);
+ self.uncacheValue(value);
+ delete self.userOptions[value];
+ delete self.options[value];
+ self.isDropdownContentStale = true;
+ self.trigger('option_remove', value);
+ self.removeItem(value, silent);
+ }
+
+ /**
+ * Clears all options.
+ */
+ clearOptions(filter) {
+ const boundFilter = (filter || this.clearFilter).bind(this);
+ this.loadedSearches = {};
+ this.userOptions = {};
+ this.clearCache();
+ const selected = {};
+ iterate(this.options, (option, key) => {
+ if (boundFilter(option, key)) {
+ selected[key] = option;
+ }
+ });
+ this.options = this.sifter.items = selected;
+ this.isDropdownContentStale = true;
+ this.trigger('option_clear');
+ }
+
+ /**
+ * Used by clearOptions() to decide whether or not an option should be removed
+ * Return true to keep an option, false to remove
+ *
+ */
+ clearFilter(option, value) {
+ if (this.items.indexOf(value) >= 0) {
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Returns the dom element of the option
+ * matching the given value.
+ *
+ */
+ getOption(value, create = false) {
+ const hashed = hash_key(value);
+ if (hashed === null) return null;
+ const option = this.options[hashed];
+ if (option != undefined) {
+ if (option.$div) {
+ return option.$div;
+ }
+ if (create) {
+ return this._render('option', option);
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Returns the dom element of the next or previous dom element of the same type
+ * Note: adjacent options may not be adjacent DOM elements (optgroups)
+ *
+ */
+ getAdjacent(option, direction, type = 'option') {
+ var self = this,
+ all;
+ if (!option) {
+ return null;
+ }
+ if (type == 'item') {
+ all = self.controlChildren();
+ } else {
+ all = self.dropdown_content.querySelectorAll('[data-selectable]');
+ }
+ for (let i = 0; i < all.length; i++) {
+ if (all[i] != option) {
+ continue;
+ }
+ if (direction > 0) {
+ return all[i + 1];
+ }
+ return all[i - 1];
+ }
+ return null;
+ }
+
+ /**
+ * Returns the dom element of the item
+ * matching the given value.
+ *
+ */
+ getItem(item) {
+ if (typeof item == 'object') {
+ return item;
+ }
+ var value = hash_key(item);
+ return value !== null ? this.control.querySelector(`[data-value="${addSlashes(value)}"]`) : null;
+ }
+
+ /**
+ * "Selects" multiple items at once. Adds them to the list
+ * at the current caret position.
+ *
+ */
+ addItems(values, silent) {
+ var self = this;
+ var items = Array.isArray(values) ? values : [values];
+ items = items.filter(x => self.items.indexOf(x) === -1);
+ const last_item = items[items.length - 1];
+ items.forEach(item => {
+ self.isPending = item !== last_item;
+ self.addItem(item, silent);
+ });
+ }
+
+ /**
+ * "Selects" an item. Adds it to the list
+ * at the current caret position.
+ *
+ */
+ addItem(value, silent) {
+ var events = silent ? [] : ['change', 'dropdown_close'];
+ debounce_events(this, events, () => {
+ var item, wasFull;
+ const self = this;
+ const inputMode = self.settings.mode;
+ const hashed = hash_key(value);
+ if (hashed && self.items.indexOf(hashed) !== -1) {
+ if (inputMode === 'single') {
+ self.close();
+ }
+ if (inputMode === 'single' || !self.settings.duplicates) {
+ return;
+ }
+ }
+ if (hashed === null || !self.options.hasOwnProperty(hashed)) return;
+ if (inputMode === 'single') self.clear(silent);
+ if (inputMode === 'multi' && self.isFull()) return;
+ item = self._render('item', self.options[hashed]);
+ if (self.control.contains(item)) {
+ // duplicates
+ item = item.cloneNode(true);
+ }
+ wasFull = self.isFull();
+ self.items.splice(self.caretPos, 0, hashed);
+ self.insertAtCaret(item);
+ if (self.isSetup) {
+ // update menu / remove the option (if this is not one item being added as part of series)
+ if (!self.isPending && self.settings.hideSelected) {
+ let option = self.getOption(hashed);
+ let next = self.getAdjacent(option, 1);
+ if (next) {
+ self.setActiveOption(next);
+ }
+ }
+
+ //remove input value when enabled
+ if (self.settings.clearAfterSelect) {
+ self.setTextboxValue();
+ }
+
+ // refreshOptions after setActiveOption(),
+ // otherwise setActiveOption() will be called by refreshOptions() with the wrong value
+ if (!self.isPending && !self.settings.closeAfterSelect) {
+ self.refreshOptions(self.isFocused && inputMode !== 'single');
+ }
+
+ // hide the menu if the maximum number of items have been selected or no options are left
+ if (self.settings.closeAfterSelect != false && self.isFull()) {
+ self.close();
+ } else if (!self.isPending) {
+ self.positionDropdown();
+ }
+ self.trigger('item_add', hashed, item);
+ if (!self.isPending) {
+ self.updateOriginalInput({
+ silent: silent
+ });
+ }
+ }
+ if (!self.isPending || !wasFull && self.isFull()) {
+ self.inputState();
+ self.refreshState();
+ }
+ });
+ }
+
+ /**
+ * Removes the selected item matching
+ * the provided value.
+ *
+ */
+ removeItem(item = null, silent) {
+ const self = this;
+ item = self.getItem(item);
+ if (!item) return;
+ var i, idx;
+ const value = item.dataset.value;
+ i = nodeIndex(item);
+ item.remove();
+ if (item.classList.contains('active')) {
+ idx = self.activeItems.indexOf(item);
+ self.activeItems.splice(idx, 1);
+ removeClasses(item, 'active');
+ }
+ self.items.splice(i, 1);
+ self.isDropdownContentStale = true;
+ if (!self.settings.persist && self.userOptions.hasOwnProperty(value)) {
+ self.removeOption(value, silent);
+ }
+ if (i < self.caretPos) {
+ self.setCaret(self.caretPos - 1);
+ }
+ self.updateOriginalInput({
+ silent: silent
+ });
+ self.refreshState();
+ self.positionDropdown();
+ self.trigger('item_remove', value, item);
+ }
+
+ /**
+ * Invokes the `create` method provided in the
+ * TomSelect options that should provide the data
+ * for the new item, given the user input.
+ *
+ * Once this completes, it will be added
+ * to the item list.
+ *
+ */
+ createItem(input = null, callback = () => {}) {
+ // triggerDropdown parameter @deprecated 2.1.1
+ if (arguments.length === 3) {
+ callback = arguments[2];
+ }
+ if (typeof callback != 'function') {
+ callback = () => {};
+ }
+ var self = this;
+ var caret = self.caretPos;
+ var output;
+ input = input || self.inputValue();
+ if (!self.canCreate(input)) {
+ const hash = hash_key(input);
+ if (hash) {
+ if (this.options[input]) {
+ self.addItem(input);
+ }
+ }
+ callback();
+ return false;
+ }
+ self.lock();
+ var created = false;
+ var create = data => {
+ self.unlock();
+ if (!data || typeof data !== 'object') return callback();
+ var value = hash_key(data[self.settings.valueField]);
+ if (typeof value !== 'string') {
+ return callback();
+ }
+ self.setTextboxValue();
+ self.addOption(data, true);
+ self.setCaret(caret);
+ self.addItem(value);
+ callback(data);
+ created = true;
+ };
+ if (typeof self.settings.create === 'function') {
+ output = self.settings.create.call(this, input, create);
+ } else {
+ output = {
+ [self.settings.labelField]: input,
+ [self.settings.valueField]: input
+ };
+ }
+ if (!created) {
+ create(output);
+ }
+ return true;
+ }
+
+ /**
+ * Re-renders the selected item lists.
+ */
+ refreshItems() {
+ var self = this;
+ self.isDropdownContentStale = true;
+ if (self.isSetup) {
+ self.addItems(self.items);
+ }
+ self.updateOriginalInput();
+ self.refreshState();
+ }
+
+ /**
+ * Updates all state-dependent attributes
+ * and CSS classes.
+ */
+ refreshState() {
+ const self = this;
+ self.refreshValidityState();
+ const isFull = self.isFull();
+ const isLocked = self.isLocked;
+ self.wrapper.classList.toggle('rtl', self.rtl);
+ const wrap_classList = self.wrapper.classList;
+ wrap_classList.toggle('focus', self.isFocused);
+ wrap_classList.toggle('disabled', self.isDisabled);
+ wrap_classList.toggle('readonly', self.isReadOnly);
+ wrap_classList.toggle('required', self.isRequired);
+ wrap_classList.toggle('invalid', !self.isValid);
+ wrap_classList.toggle('locked', isLocked);
+ wrap_classList.toggle('full', isFull);
+ wrap_classList.toggle('input-active', self.isFocused && !self.isInputHidden);
+ wrap_classList.toggle('dropdown-active', self.isOpen);
+ wrap_classList.toggle('has-options', isEmptyObject(self.options));
+ wrap_classList.toggle('has-items', self.items.length > 0);
+ }
+
+ /**
+ * Update the `required` attribute of both input and control input.
+ *
+ * The `required` property needs to be activated on the control input
+ * for the error to be displayed at the right place. `required` also
+ * needs to be temporarily deactivated on the input since the input is
+ * hidden and can't show errors.
+ */
+ refreshValidityState() {
+ var self = this;
+ if (!self.input.validity) {
+ return;
+ }
+ self.isValid = self.input.validity.valid;
+ self.isInvalid = !self.isValid;
+ }
+
+ /**
+ * Determines whether or not more items can be added
+ * to the control without exceeding the user-defined maximum.
+ *
+ * @returns {boolean}
+ */
+ isFull() {
+ return this.settings.maxItems !== null && this.items.length >= this.settings.maxItems;
+ }
+
+ /**
+ * Refreshes the original <select> or <input>
+ * element to reflect the current state.
+ *
+ */
+ updateOriginalInput(opts = {}) {
+ const self = this;
+ var option, label;
+ const empty_option = self.input.querySelector('option[value=""]');
+ if (self.is_select_tag) {
+ const selected = [];
+ const has_selected = self.input.querySelectorAll('option:checked').length;
+ function AddSelected(option_el, value, label) {
+ if (!option_el) {
+ option_el = getDom('<option value="' + escape_html(value) + '">' + escape_html(label) + '</option>');
+ }
+
+ // don't move empty option from top of list
+ // fixes bug in firefox https://bugzilla.mozilla.org/show_bug.cgi?id=1725293
+ if (option_el != empty_option) {
+ self.input.append(option_el);
+ }
+ selected.push(option_el);
+
+ // marking empty option as selected can break validation
+ // fixes https://github.com/orchidjs/tom-select/issues/303
+ if (option_el != empty_option || has_selected > 0) {
+ option_el.selected = true;
+ }
+ return option_el;
+ }
+
+ // unselect all selected options
+ self.input.querySelectorAll('option:checked').forEach(option_el => {
+ option_el.selected = false;
+ });
+
+ // nothing selected?
+ if (self.items.length == 0 && self.settings.mode == 'single') {
+ AddSelected(empty_option, "", "");
+
+ // order selected <option> tags for values in self.items
+ } else {
+ self.items.forEach(value => {
+ option = self.options[value];
+ label = option[self.settings.labelField] || '';
+ if (selected.includes(option.$option)) {
+ const reuse_opt = self.input.querySelector(`option[value="${addSlashes(value)}"]:not(:checked)`);
+ AddSelected(reuse_opt, value, label);
+ } else {
+ option.$option = AddSelected(option.$option, value, label);
+ }
+ });
+ }
+ } else {
+ self.input.value = self.getValue();
+ }
+ if (self.isSetup) {
+ if (!opts.silent) {
+ self.trigger('change', self.getValue());
+ }
+ }
+ }
+
+ /**
+ * Shows the autocomplete dropdown containing
+ * the available options.
+ */
+ open() {
+ var self = this;
+ if (self.isLocked || self.isOpen || self.settings.mode === 'multi' && self.isFull()) return;
+ self.isOpen = true;
+ setAttr(self.focus_node, {
+ 'aria-expanded': 'true'
+ });
+ self.refreshState();
+ applyCSS(self.dropdown, {
+ visibility: 'hidden',
+ display: 'block'
+ });
+ self.positionDropdown();
+ applyCSS(self.dropdown, {
+ visibility: 'visible',
+ display: 'block'
+ });
+ self.focus();
+ self.trigger('dropdown_open', self.dropdown);
+ }
+
+ /**
+ * Closes the autocomplete dropdown menu.
+ */
+ close(setTextboxValue = true) {
+ var self = this;
+ var trigger = self.isOpen;
+ if (setTextboxValue) {
+ // before blur() to prevent form onchange event
+ self.setTextboxValue();
+ if (self.settings.mode === 'single' && self.items.length) {
+ self.inputState();
+ }
+ }
+ self.isOpen = false;
+ setAttr(self.focus_node, {
+ 'aria-expanded': 'false'
+ });
+ applyCSS(self.dropdown, {
+ display: 'none'
+ });
+ if (self.settings.hideSelected) {
+ self.clearActiveOption();
+ }
+ self.refreshState();
+ if (trigger) self.trigger('dropdown_close', self.dropdown);
+ }
+
+ /**
+ * Calculates and applies the appropriate
+ * position of the dropdown if dropdownParent = 'body'.
+ * Otherwise, position is determined by css
+ */
+ positionDropdown() {
+ if (this.settings.dropdownParent !== 'body') {
+ return;
+ }
+ var context = this.control;
+ var rect = context.getBoundingClientRect();
+ var top = context.offsetHeight + rect.top + window.scrollY;
+ var left = rect.left + window.scrollX;
+ applyCSS(this.dropdown, {
+ width: rect.width + 'px',
+ top: top + 'px',
+ left: left + 'px'
+ });
+ }
+
+ /**
+ * Resets / clears all selected items
+ * from the control.
+ *
+ */
+ clear(silent) {
+ var self = this;
+ if (!self.items.length) return;
+ var items = self.controlChildren();
+ iterate(items, item => {
+ self.removeItem(item, true);
+ });
+ self.inputState();
+ if (!silent) self.updateOriginalInput();
+ self.trigger('clear');
+ }
+
+ /**
+ * A helper method for inserting an element
+ * at the current caret position.
+ *
+ */
+ insertAtCaret(el) {
+ const self = this;
+ const caret = self.caretPos;
+ const target = self.control;
+ target.insertBefore(el, target.children[caret] || null);
+ self.setCaret(caret + 1);
+ }
+
+ /**
+ * Removes the current selected item(s).
+ *
+ */
+ deleteSelection(e) {
+ var direction, selection, caret, tail;
+ var self = this;
+ direction = e && e.keyCode === KEY_BACKSPACE ? -1 : 1;
+ selection = getSelection(self.control_input);
+
+ // determine items that will be removed
+ const rm_items = [];
+ if (self.activeItems.length) {
+ tail = getTail(self.activeItems, direction);
+ caret = nodeIndex(tail);
+ if (direction > 0) {
+ caret++;
+ }
+ iterate(self.activeItems, item => rm_items.push(item));
+ } else if ((self.isFocused || self.settings.mode === 'single') && self.items.length) {
+ const items = self.controlChildren();
+ let rm_item;
+ if (direction < 0 && selection.start === 0 && selection.length === 0) {
+ rm_item = items[self.caretPos - 1];
+ } else if (direction > 0 && selection.start === self.inputValue().length) {
+ rm_item = items[self.caretPos];
+ }
+ if (rm_item !== undefined) {
+ rm_items.push(rm_item);
+ }
+ }
+ if (!self.shouldDelete(rm_items, e)) {
+ return false;
+ }
+ preventDefault(e, true);
+
+ // perform removal
+ if (typeof caret !== 'undefined') {
+ self.setCaret(caret);
+ }
+ while (rm_items.length) {
+ self.removeItem(rm_items.pop());
+ }
+ self.inputState();
+ self.positionDropdown();
+ self.refreshOptions(false);
+ return true;
+ }
+
+ /**
+ * Return true if the items should be deleted
+ */
+ shouldDelete(items, evt) {
+ const values = items.map(item => item.dataset.value);
+
+ // allow the callback to abort
+ if (!values.length || typeof this.settings.onDelete === 'function' && this.settings.onDelete.call(this, values, evt) === false) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Selects the previous / next item (depending on the `direction` argument).
+ *
+ * > 0 - right
+ * < 0 - left
+ *
+ */
+ advanceSelection(direction, e) {
+ var last_active,
+ adjacent,
+ self = this;
+ if (self.rtl) direction *= -1;
+ if (self.inputValue().length) return;
+
+ // add or remove to active items
+ if (isKeyDown(KEY_SHORTCUT, e) || isKeyDown('shiftKey', e)) {
+ last_active = self.getLastActive(direction);
+ if (last_active) {
+ if (!last_active.classList.contains('active')) {
+ adjacent = last_active;
+ } else {
+ adjacent = self.getAdjacent(last_active, direction, 'item');
+ }
+
+ // if no active item, get items adjacent to the control input
+ } else if (direction > 0) {
+ adjacent = self.control_input.nextElementSibling;
+ } else {
+ adjacent = self.control_input.previousElementSibling;
+ }
+ if (adjacent) {
+ if (adjacent.classList.contains('active')) {
+ self.removeActiveItem(last_active);
+ }
+ self.setActiveItemClass(adjacent); // mark as last_active !! after removeActiveItem() on last_active
+ }
+
+ // move caret to the left or right
+ } else {
+ self.moveCaret(direction);
+ }
+ }
+ moveCaret(direction) {}
+
+ /**
+ * Get the last active item
+ *
+ */
+ getLastActive(direction) {
+ let last_active = this.control.querySelector('.last-active');
+ if (last_active) {
+ return last_active;
+ }
+ var result = this.control.querySelectorAll('.active');
+ if (result) {
+ return getTail(result, direction);
+ }
+ }
+
+ /**
+ * Moves the caret to the specified index.
+ *
+ * The input must be moved by leaving it in place and moving the
+ * siblings, due to the fact that focus cannot be restored once lost
+ * on mobile webkit devices
+ *
+ */
+ setCaret(new_pos) {
+ this.caretPos = this.items.length;
+ }
+
+ /**
+ * Return list of item dom elements
+ *
+ */
+ controlChildren() {
+ return Array.from(this.control.querySelectorAll('[data-ts-item]'));
+ }
+
+ /**
+ * Disables user input on the control. Used while
+ * items are being asynchronously created.
+ */
+ lock() {
+ this.setLocked(true);
+ }
+
+ /**
+ * Re-enables user input on the control.
+ */
+ unlock() {
+ this.setLocked(false);
+ }
+
+ /**
+ * Disable or enable user input on the control
+ */
+ setLocked(lock = this.isReadOnly || this.isDisabled) {
+ this.isLocked = lock;
+ this.refreshState();
+ }
+
+ /**
+ * Disables user input on the control completely.
+ * While disabled, it cannot receive focus.
+ */
+ disable() {
+ this.setDisabled(true);
+ this.close();
+ }
+
+ /**
+ * Enables the control so that it can respond
+ * to focus and user input.
+ */
+ enable() {
+ this.setDisabled(false);
+ }
+ setDisabled(disabled) {
+ this.focus_node.tabIndex = disabled ? -1 : this.tabIndex;
+ this.isDisabled = disabled;
+ this.input.disabled = disabled;
+ this.control_input.disabled = disabled;
+ this.setLocked();
+ }
+ setReadOnly(isReadOnly) {
+ this.isReadOnly = isReadOnly;
+ this.input.readOnly = isReadOnly;
+ this.control_input.readOnly = isReadOnly;
+ this.setLocked();
+ }
+
+ /**
+ * Completely destroys the control and
+ * unbinds all event listeners so that it can
+ * be garbage collected.
+ */
+ destroy() {
+ var self = this;
+ var revertSettings = self.revertSettings;
+ self.trigger('destroy');
+ self.off();
+ self.wrapper.remove();
+ self.dropdown.remove();
+ self.input.innerHTML = revertSettings.innerHTML;
+ self.input.tabIndex = revertSettings.tabIndex;
+ removeClasses(self.input, 'tomselected', 'ts-hidden-accessible');
+ self._destroy();
+ delete self.input.tomselect;
+ }
+
+ /**
+ * A helper method for rendering "item" and
+ * "option" templates, given the data.
+ *
+ */
+ render(templateName, data) {
+ var id, html;
+ const self = this;
+ if (typeof this.settings.render[templateName] !== 'function') {
+ return null;
+ }
+
+ // render markup
+ html = self.settings.render[templateName].call(this, data, escape_html);
+ if (!html) {
+ return null;
+ }
+ html = getDom(html);
+
+ // add mandatory attributes
+ if (templateName === 'option' || templateName === 'option_create') {
+ if (data[self.settings.disabledField]) {
+ setAttr(html, {
+ 'aria-disabled': 'true'
+ });
+ } else {
+ setAttr(html, {
+ 'data-selectable': ''
+ });
+ }
+ } else if (templateName === 'optgroup') {
+ id = data.group[self.settings.optgroupValueField];
+ setAttr(html, {
+ 'data-group': id
+ });
+ if (data.group[self.settings.disabledField]) {
+ setAttr(html, {
+ 'data-disabled': ''
+ });
+ }
+ }
+ if (templateName === 'option' || templateName === 'item') {
+ const value = get_hash(data[self.settings.valueField]);
+ setAttr(html, {
+ 'data-value': value
+ });
+
+ // make sure we have some classes if a template is overwritten
+ if (templateName === 'item') {
+ addClasses(html, self.settings.itemClass);
+ setAttr(html, {
+ 'data-ts-item': ''
+ });
+ } else {
+ addClasses(html, self.settings.optionClass);
+ setAttr(html, {
+ role: 'option',
+ id: data.$id
+ });
+
+ // update cache
+ data.$div = html;
+ self.options[value] = data;
+ }
+ }
+ return html;
+ }
+
+ /**
+ * Type guarded rendering
+ *
+ */
+ _render(templateName, data) {
+ const html = this.render(templateName, data);
+ if (html == null) {
+ throw 'HTMLElement expected';
+ }
+ return html;
+ }
+
+ /**
+ * Clears the render cache for a template. If
+ * no template is given, clears all render
+ * caches.
+ *
+ */
+ clearCache() {
+ iterate(this.options, option => {
+ if (option.$div) {
+ option.$div.remove();
+ delete option.$div;
+ }
+ });
+ }
+
+ /**
+ * Removes a value from item and option caches
+ *
+ */
+ uncacheValue(value) {
+ const option_el = this.getOption(value);
+ if (option_el) option_el.remove();
+ }
+
+ /**
+ * Determines whether or not to display the
+ * create item prompt, given a user input.
+ *
+ */
+ canCreate(input) {
+ return this.settings.create && input.length > 0 && this.settings.createFilter.call(this, input);
+ }
+
+ /**
+ * Wraps this.`method` so that `new_fn` can be invoked 'before', 'after', or 'instead' of the original method
+ *
+ * this.hook('instead','onKeyDown',function( arg1, arg2 ...){
+ *
+ * });
+ */
+ hook(when, method, new_fn) {
+ var self = this;
+ var orig_method = self[method];
+ self[method] = function () {
+ var result, result_new;
+ if (when === 'after') {
+ result = orig_method.apply(self, arguments);
+ }
+ result_new = new_fn.apply(self, arguments);
+ if (when === 'instead') {
+ return result_new;
+ }
+ if (when === 'before') {
+ result = orig_method.apply(self, arguments);
+ }
+ return result;
+ };
+ }
+ }
+
+ return TomSelect;
+
+}));
+var tomSelect=function(el,opts){return new TomSelect(el,opts);}
diff --git a/app/assets/stylesheets/blazer/application.css b/app/assets/stylesheets/blazer/application.css
index d0dd4855..c270dc1c 100644
--- a/app/assets/stylesheets/blazer/application.css
+++ b/app/assets/stylesheets/blazer/application.css
@@ -1,7 +1,7 @@
/*
*= require ./bootstrap-sprockets
*= require ./bootstrap
- *= require ./selectize
+ *= require ./tom-select.default
*= require ./github
*= require ./daterangepicker
*= require_self
@@ -54,7 +54,7 @@ input.search:focus {
outline: none;
}
-.form-inline .selectize-control, .text-right .selectize-control {
+.form-inline .ts-wrapper, .text-right .ts-wrapper {
display: inline-block;
vertical-align: middle;
margin-left: 5px;
@@ -62,10 +62,19 @@ input.search:focus {
text-align: left;
}
-#statement-box .selectize-control {
+#statement-box .ts-wrapper {
margin-right: 0;
}
+.ts-control > input {
+ min-width: 0;
+}
+
+.has-items .ts-control > input {
+ margin-left: 1px !important;
+ margin-right: 0 !important;
+}
+
#editor-container {
background-color: #141414;
padding-top: 10px;
@@ -244,10 +253,14 @@ h2 {
max-width: 500px;
}
-.selectize-dropdown .create {
+.ts-dropdown .create {
padding: 5px 8px;
}
+.ts-dropdown {
+ margin-top: 0 !important;
+}
+
.user-header {
width: 20%;
text-align: right;
diff --git a/app/assets/stylesheets/blazer/selectize.css b/app/assets/stylesheets/blazer/selectize.css
deleted file mode 100644
index 90f388f8..00000000
--- a/app/assets/stylesheets/blazer/selectize.css
+++ /dev/null
@@ -1,403 +0,0 @@
-/**
- * selectize.default.css (v0.12.6) - Default Theme
- * Copyright (c) 2013–2015 Brian Reavis & contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
- * file except in compliance with the License. You may obtain a copy of the License at:
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under
- * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
- * ANY KIND, either express or implied. See the License for the specific language
- * governing permissions and limitations under the License.
- *
- * @author Brian Reavis <[email protected]>
- */
-.selectize-control.plugin-drag_drop.multi > .selectize-input > div.ui-sortable-placeholder {
- visibility: visible !important;
- background: #f2f2f2 !important;
- background: rgba(0, 0, 0, 0.06) !important;
- border: 0 none !important;
- -webkit-box-shadow: inset 0 0 12px 4px #fff;
- box-shadow: inset 0 0 12px 4px #fff;
-}
-.selectize-control.plugin-drag_drop .ui-sortable-placeholder::after {
- content: '!';
- visibility: hidden;
-}
-.selectize-control.plugin-drag_drop .ui-sortable-helper {
- -webkit-box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
- box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
-}
-.selectize-dropdown-header {
- position: relative;
- padding: 5px 8px;
- border-bottom: 1px solid #d0d0d0;
- background: #f8f8f8;
- -webkit-border-radius: 3px 3px 0 0;
- -moz-border-radius: 3px 3px 0 0;
- border-radius: 3px 3px 0 0;
-}
-.selectize-dropdown-header-close {
- position: absolute;
- right: 8px;
- top: 50%;
- color: #303030;
- opacity: 0.4;
- margin-top: -12px;
- line-height: 20px;
- font-size: 20px !important;
-}
-.selectize-dropdown-header-close:hover {
- color: #000000;
-}
-.selectize-dropdown.plugin-optgroup_columns .optgroup {
- border-right: 1px solid #f2f2f2;
- border-top: 0 none;
- float: left;
- -webkit-box-sizing: border-box;
- -moz-box-sizing: border-box;
- box-sizing: border-box;
-}
-.selectize-dropdown.plugin-optgroup_columns .optgroup:last-child {
- border-right: 0 none;
-}
-.selectize-dropdown.plugin-optgroup_columns .optgroup:before {
- display: none;
-}
-.selectize-dropdown.plugin-optgroup_columns .optgroup-header {
- border-top: 0 none;
-}
-.selectize-control.plugin-remove_button [data-value] {
- position: relative;
- padding-right: 24px !important;
-}
-.selectize-control.plugin-remove_button [data-value] .remove {
- z-index: 1;
- /* fixes ie bug (see #392) */
- position: absolute;
- top: 0;
- right: 0;
- bottom: 0;
- width: 17px;
- text-align: center;
- font-weight: bold;
- font-size: 12px;
- color: inherit;
- text-decoration: none;
- vertical-align: middle;
- display: inline-block;
- padding: 2px 0 0 0;
- border-left: 1px solid #0073bb;
- -webkit-border-radius: 0 2px 2px 0;
- -moz-border-radius: 0 2px 2px 0;
- border-radius: 0 2px 2px 0;
- -webkit-box-sizing: border-box;
- -moz-box-sizing: border-box;
- box-sizing: border-box;
-}
-.selectize-control.plugin-remove_button [data-value] .remove:hover {
- background: rgba(0, 0, 0, 0.05);
-}
-.selectize-control.plugin-remove_button [data-value].active .remove {
- border-left-color: #00578d;
-}
-.selectize-control.plugin-remove_button .disabled [data-value] .remove:hover {
- background: none;
-}
-.selectize-control.plugin-remove_button .disabled [data-value] .remove {
- border-left-color: #aaaaaa;
-}
-.selectize-control.plugin-remove_button .remove-single {
- position: absolute;
- right: 0;
- top: 0;
- font-size: 23px;
-}
-.selectize-control {
- position: relative;
-}
-.selectize-dropdown,
-.selectize-input,
-.selectize-input input {
- color: #303030;
- font-family: inherit;
- font-size: 13px;
- line-height: 18px;
- -webkit-font-smoothing: inherit;
-}
-.selectize-input,
-.selectize-control.single .selectize-input.input-active {
- background: #fff;
- cursor: text;
- display: inline-block;
-}
-.selectize-input {
- border: 1px solid #d0d0d0;
- padding: 8px 8px;
- display: inline-block;
- width: 100%;
- overflow: hidden;
- position: relative;
- z-index: 1;
- -webkit-box-sizing: border-box;
- -moz-box-sizing: border-box;
- box-sizing: border-box;
- -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.1);
- box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.1);
- -webkit-border-radius: 3px;
- -moz-border-radius: 3px;
- border-radius: 3px;
-}
-.selectize-control.multi .selectize-input.has-items {
- padding: 5px 8px 2px;
-}
-.selectize-input.full {
- background-color: #fff;
-}
-.selectize-input.disabled,
-.selectize-input.disabled * {
- cursor: default !important;
-}
-.selectize-input.focus {
- -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.15);
- box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.15);
-}
-.selectize-input.dropdown-active {
- -webkit-border-radius: 3px 3px 0 0;
- -moz-border-radius: 3px 3px 0 0;
- border-radius: 3px 3px 0 0;
-}
-.selectize-input > * {
- vertical-align: baseline;
- display: -moz-inline-stack;
- display: inline-block;
- transform: scale(1);
- *display: inline;
-}
-.selectize-control.multi .selectize-input > div {
- cursor: pointer;
- margin: 0 3px 3px 0;
- padding: 2px 6px;
- background: #1da7ee;
- color: #fff;
- border: 1px solid #0073bb;
-}
-.selectize-control.multi .selectize-input > div.active {
- background: #92c836;
- color: #fff;
- border: 1px solid #00578d;
-}
-.selectize-control.multi .selectize-input.disabled > div,
-.selectize-control.multi .selectize-input.disabled > div.active {
- color: #ffffff;
- background: #d2d2d2;
- border: 1px solid #aaaaaa;
-}
-.selectize-input > input {
- display: inline-block !important;
- padding: 0 !important;
- min-height: 0 !important;
- max-height: none !important;
- max-width: 100% !important;
- margin: 0 1px !important;
- text-indent: 0 !important;
- border: 0 none !important;
- background: none !important;
- line-height: inherit !important;
- -webkit-user-select: auto !important;
- -webkit-box-shadow: none !important;
- box-shadow: none !important;
-}
-.selectize-input > input::-ms-clear {
- display: none;
-}
-.selectize-input > input:focus {
- outline: none !important;
-}
-.selectize-input::after {
- content: ' ';
- display: block;
- clear: left;
-}
-.selectize-input.dropdown-active::before {
- content: ' ';
- display: block;
- position: absolute;
- background: #f0f0f0;
- height: 1px;
- bottom: 0;
- left: 0;
- right: 0;
-}
-.selectize-dropdown {
- position: absolute;
- z-index: 10;
- border: 1px solid #d0d0d0;
- background: #fff;
- margin: -1px 0 0 0;
- border-top: 0 none;
- -webkit-box-sizing: border-box;
- -moz-box-sizing: border-box;
- box-sizing: border-box;
- -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
- box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
- -webkit-border-radius: 0 0 3px 3px;
- -moz-border-radius: 0 0 3px 3px;
- border-radius: 0 0 3px 3px;
-}
-.selectize-dropdown [data-selectable] {
- cursor: pointer;
- overflow: hidden;
-}
-.selectize-dropdown [data-selectable] .highlight {
- background: rgba(125, 168, 208, 0.2);
- -webkit-border-radius: 1px;
- -moz-border-radius: 1px;
- border-radius: 1px;
-}
-.selectize-dropdown .option,
-.selectize-dropdown .optgroup-header {
- padding: 5px 8px;
-}
-.selectize-dropdown .option,
-.selectize-dropdown [data-disabled],
-.selectize-dropdown [data-disabled] [data-selectable].option {
- cursor: inherit;
- opacity: 0.5;
-}
-.selectize-dropdown [data-selectable].option {
- opacity: 1;
-}
-.selectize-dropdown .optgroup:first-child .optgroup-header {
- border-top: 0 none;
-}
-.selectize-dropdown .optgroup-header {
- color: #303030;
- background: #fff;
- cursor: default;
-}
-.selectize-dropdown .active {
- background-color: #f5fafd;
- color: #495c68;
-}
-.selectize-dropdown .active.create {
- color: #495c68;
-}
-.selectize-dropdown .create {
- color: rgba(48, 48, 48, 0.5);
-}
-.selectize-dropdown-content {
- overflow-y: auto;
- overflow-x: hidden;
- max-height: 200px;
- -webkit-overflow-scrolling: touch;
-}
-.selectize-control.single .selectize-input,
-.selectize-control.single .selectize-input input {
- cursor: pointer;
-}
-.selectize-control.single .selectize-input.input-active,
-.selectize-control.single .selectize-input.input-active input {
- cursor: text;
-}
-.selectize-control.single .selectize-input:after {
- content: ' ';
- display: block;
- position: absolute;
- top: 50%;
- right: 15px;
- margin-top: -3px;
- width: 0;
- height: 0;
- border-style: solid;
- border-width: 5px 5px 0 5px;
- border-color: #808080 transparent transparent transparent;
-}
-.selectize-control.single .selectize-input.dropdown-active:after {
- margin-top: -4px;
- border-width: 0 5px 5px 5px;
- border-color: transparent transparent #808080 transparent;
-}
-.selectize-control.rtl.single .selectize-input:after {
- left: 15px;
- right: auto;
-}
-.selectize-control.rtl .selectize-input > input {
- margin: 0 4px 0 -2px !important;
-}
-.selectize-control .selectize-input.disabled {
- opacity: 0.5;
- background-color: #fafafa;
-}
-.selectize-control.multi .selectize-input.has-items {
- padding-left: 5px;
- padding-right: 5px;
-}
-.selectize-control.multi .selectize-input.disabled [data-value] {
- color: #999;
- text-shadow: none;
- background: none;
- -webkit-box-shadow: none;
- box-shadow: none;
-}
-.selectize-control.multi .selectize-input.disabled [data-value],
-.selectize-control.multi .selectize-input.disabled [data-value] .remove {
- border-color: #e6e6e6;
-}
-.selectize-control.multi .selectize-input.disabled [data-value] .remove {
- background: none;
-}
-.selectize-control.multi .selectize-input [data-value] {
- text-shadow: 0 1px 0 rgba(0, 51, 83, 0.3);
- -webkit-border-radius: 3px;
- -moz-border-radius: 3px;
- border-radius: 3px;
- background-color: #1b9dec;
- background-image: -moz-linear-gradient(top, #1da7ee, #178ee9);
- background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#1da7ee), to(#178ee9));
- background-image: -webkit-linear-gradient(top, #1da7ee, #178ee9);
- background-image: -o-linear-gradient(top, #1da7ee, #178ee9);
- background-image: linear-gradient(to bottom, #1da7ee, #178ee9);
- background-repeat: repeat-x;
- filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff1da7ee', endColorstr='#ff178ee9', GradientType=0);
- -webkit-box-shadow: 0 1px 0 rgba(0,0,0,0.2),inset 0 1px rgba(255,255,255,0.03);
- box-shadow: 0 1px 0 rgba(0,0,0,0.2),inset 0 1px rgba(255,255,255,0.03);
-}
-.selectize-control.multi .selectize-input [data-value].active {
- background-color: #0085d4;
- background-image: -moz-linear-gradient(top, #008fd8, #0075cf);
- background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#008fd8), to(#0075cf));
- background-image: -webkit-linear-gradient(top, #008fd8, #0075cf);
- background-image: -o-linear-gradient(top, #008fd8, #0075cf);
- background-image: linear-gradient(to bottom, #008fd8, #0075cf);
- background-repeat: repeat-x;
- filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff008fd8', endColorstr='#ff0075cf', GradientType=0);
-}
-.selectize-control.single .selectize-input {
- -webkit-box-shadow: 0 1px 0 rgba(0,0,0,0.05), inset 0 1px 0 rgba(255,255,255,0.8);
- box-shadow: 0 1px 0 rgba(0,0,0,0.05), inset 0 1px 0 rgba(255,255,255,0.8);
- background-color: #f9f9f9;
- background-image: -moz-linear-gradient(top, #fefefe, #f2f2f2);
- background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#fefefe), to(#f2f2f2));
- background-image: -webkit-linear-gradient(top, #fefefe, #f2f2f2);
- background-image: -o-linear-gradient(top, #fefefe, #f2f2f2);
- background-image: linear-gradient(to bottom, #fefefe, #f2f2f2);
- background-repeat: repeat-x;
- filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffefefe', endColorstr='#fff2f2f2', GradientType=0);
-}
-.selectize-control.single .selectize-input,
-.selectize-dropdown.single {
- border-color: #b8b8b8;
-}
-.selectize-dropdown .optgroup-header {
- padding-top: 7px;
- font-weight: bold;
- font-size: 0.85em;
-}
-.selectize-dropdown .optgroup {
- border-top: 1px solid #f0f0f0;
-}
-.selectize-dropdown .optgroup:first-child {
- border-top: 0 none;
-}
diff --git a/app/assets/stylesheets/blazer/tom-select.default.css b/app/assets/stylesheets/blazer/tom-select.default.css
new file mode 100644
index 00000000..8cba0587
--- /dev/null
+++ b/app/assets/stylesheets/blazer/tom-select.default.css
@@ -0,0 +1,502 @@
+/**
+ * tom-select.css (v2.6.1)
+ * Copyright (c) contributors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
+ * file except in compliance with the License. You may obtain a copy of the License at:
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
+ * ANY KIND, either express or implied. See the License for the specific language
+ * governing permissions and limitations under the License.
+ *
+ */
+.ts-control {
+ border: 1px solid #d0d0d0;
+ padding: 8px 8px;
+ width: 100%;
+ overflow: hidden;
+ position: relative;
+ z-index: 1;
+ box-sizing: border-box;
+ box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.1);
+ border-radius: 3px;
+ display: flex;
+ flex-wrap: wrap;
+}
+.ts-wrapper.multi.has-items .ts-control {
+ padding: calc(8px - 2px - 1px) 8px calc(8px - 2px - 3px - 1px);
+}
+.full .ts-control {
+ background-color: #fff;
+}
+.disabled .ts-control, .disabled .ts-control * {
+ cursor: default !important;
+}
+.focus .ts-control {
+ box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.15);
+}
+.ts-control > * {
+ vertical-align: baseline;
+ display: inline-block;
+}
+.ts-wrapper.multi .ts-control > div {
+ cursor: pointer;
+ margin: 0 3px 3px 0;
+ padding: 2px 6px;
+ background: #1da7ee;
+ color: #fff;
+ border: 1px solid #0073bb;
+ overflow: auto;
+}
+.ts-wrapper.multi .ts-control > div.active {
+ background: #92c836;
+ color: #fff;
+ border: 1px solid #00578d;
+}
+.ts-wrapper.multi.disabled .ts-control > div, .ts-wrapper.multi.disabled .ts-control > div.active {
+ color: hsl(0, 0%, 130%);
+ background: #d2d2d2;
+ border: 1px solid #aaaaaa;
+}
+.ts-control > input {
+ flex: 1 1 auto;
+ min-width: 7rem;
+ display: inline-block !important;
+ padding: 0 !important;
+ min-height: 0 !important;
+ max-height: none !important;
+ max-width: 100% !important;
+ margin: 0 !important;
+ text-indent: 0 !important;
+ border: 0 none !important;
+ background: none !important;
+ line-height: inherit !important;
+ -webkit-user-select: auto !important;
+ -moz-user-select: auto !important;
+ -ms-user-select: auto !important;
+ user-select: auto !important;
+ box-shadow: none !important;
+}
+.ts-control > input::-ms-clear {
+ display: none;
+}
+.ts-control > input:focus {
+ outline: none !important;
+}
+.has-items .ts-control > input {
+ margin: 0px 4px !important;
+}
+.ts-control.rtl {
+ text-align: right;
+}
+.ts-control.rtl.single .ts-control:after {
+ left: 15px;
+ right: auto;
+}
+.ts-control.rtl .ts-control > input {
+ margin: 0px 4px 0px -2px !important;
+}
+.disabled .ts-control {
+ opacity: 0.5;
+ background-color: #fafafa;
+}
+.input-hidden .ts-control > input {
+ opacity: 0;
+ position: absolute;
+ left: -10000px;
+}
+
+.ts-dropdown {
+ position: absolute;
+ top: 100%;
+ left: 0;
+ width: 100%;
+ z-index: 10;
+ border: 1px solid #d0d0d0;
+ background: #fff;
+ margin: 0.25rem 0 0;
+ border-top: 0 none;
+ box-sizing: border-box;
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
+ border-radius: 0 0 3px 3px;
+}
+.ts-dropdown [data-selectable] {
+ cursor: pointer;
+ overflow: hidden;
+}
+.ts-dropdown [data-selectable] .highlight {
+ background: rgba(125, 168, 208, 0.2);
+ border-radius: 1px;
+}
+.ts-dropdown .option,
+.ts-dropdown .optgroup-header,
+.ts-dropdown .no-results,
+.ts-dropdown .create {
+ padding: 5px 8px;
+}
+.ts-dropdown .option, .ts-dropdown [data-disabled], .ts-dropdown [data-disabled] [data-selectable].option {
+ cursor: inherit;
+ opacity: 0.5;
+}
+.ts-dropdown [data-selectable].option {
+ opacity: 1;
+ cursor: pointer;
+}
+.ts-dropdown .optgroup:first-child .optgroup-header {
+ border-top: 0 none;
+}
+.ts-dropdown .optgroup-header {
+ color: #303030;
+ background: #fff;
+ cursor: default;
+}
+.ts-dropdown .active {
+ background-color: #f5fafd;
+ color: #495c68;
+}
+.ts-dropdown .active.create {
+ color: #495c68;
+}
+.ts-dropdown .create {
+ color: rgba(48, 48, 48, 0.5);
+}
+.ts-dropdown .spinner {
+ display: inline-block;
+ width: 30px;
+ height: 30px;
+ margin: 5px 8px;
+}
+.ts-dropdown .spinner::after {
+ content: " ";
+ display: block;
+ width: 24px;
+ height: 24px;
+ margin: 3px;
+ border-radius: 50%;
+ border: 5px solid #d0d0d0;
+ border-color: #d0d0d0 transparent #d0d0d0 transparent;
+ animation: lds-dual-ring 1.2s linear infinite;
+}
+@keyframes lds-dual-ring {
+ 0% {
+ transform: rotate(0deg);
+ }
+ 100% {
+ transform: rotate(360deg);
+ }
+}
+
+.ts-dropdown-content {
+ overflow: hidden auto;
+ max-height: 200px;
+ scroll-behavior: smooth;
+}
+
+.ts-wrapper.plugin-drag_drop .ts-dragging {
+ color: transparent !important;
+}
+.ts-wrapper.plugin-drag_drop .ts-dragging > * {
+ visibility: hidden !important;
+}
+
+.plugin-checkbox_options:not(.rtl) .option input {
+ margin-right: 0.5rem;
+}
+
+.plugin-checkbox_options.rtl .option input {
+ margin-left: 0.5rem;
+}
+
+/* stylelint-disable function-name-case */
+.plugin-clear_button {
+ --ts-pr-clear-button: 1em;
+}
+.plugin-clear_button .clear-button {
+ opacity: 0;
+ position: absolute;
+ top: 50%;
+ transform: translateY(-50%);
+ right: calc(8px - 6px);
+ margin-right: 0 !important;
+ background: transparent !important;
+ transition: opacity 0.5s;
+ cursor: pointer;
+}
+.plugin-clear_button.form-select .clear-button, .plugin-clear_button.single .clear-button {
+ right: max(var(--ts-pr-caret), 8px);
+}
+.plugin-clear_button.focus.has-items .clear-button, .plugin-clear_button:not(.disabled):hover.has-items .clear-button {
+ opacity: 1;
+}
+
+.ts-wrapper .dropdown-header {
+ position: relative;
+ padding: 10px 8px;
+ border-bottom: 1px solid #d0d0d0;
+ background: color-mix(#fff, #d0d0d0, 85%);
+ border-radius: 3px 3px 0 0;
+}
+.ts-wrapper .dropdown-header-close {
+ position: absolute;
+ right: 8px;
+ top: 50%;
+ color: #303030;
+ opacity: 0.4;
+ margin-top: -12px;
+ line-height: 20px;
+ font-size: 20px !important;
+}
+.ts-wrapper .dropdown-header-close:hover {
+ color: hsl(0, 0%, -6.1764705882%);
+}
+
+.plugin-dropdown_input.focus.dropdown-active .ts-control {
+ box-shadow: none;
+ border: 1px solid #d0d0d0;
+}
+.plugin-dropdown_input .dropdown-input {
+ border: 1px solid #d0d0d0;
+ border-width: 0 0 1px;
+ display: block;
+ padding: 8px 8px;
+ box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.1);
+ width: 100%;
+ background: transparent;
+}
+.plugin-dropdown_input .items-placeholder {
+ border: 0 none !important;
+ box-shadow: none !important;
+ width: 100%;
+}
+.plugin-dropdown_input.has-items .items-placeholder, .plugin-dropdown_input.dropdown-active .items-placeholder {
+ display: none !important;
+}
+
+.ts-wrapper.plugin-input_autogrow.has-items .ts-control > input {
+ min-width: 0;
+}
+.ts-wrapper.plugin-input_autogrow.has-items.focus .ts-control > input {
+ flex: none;
+ min-width: 4px;
+}
+.ts-wrapper.plugin-input_autogrow.has-items.focus .ts-control > input::-ms-input-placeholder {
+ color: transparent;
+}
+.ts-wrapper.plugin-input_autogrow.has-items.focus .ts-control > input::placeholder {
+ color: transparent;
+}
+
+.ts-dropdown.plugin-optgroup_columns .ts-dropdown-content {
+ display: flex;
+}
+.ts-dropdown.plugin-optgroup_columns .optgroup {
+ border-right: 1px solid #f2f2f2;
+ border-top: 0 none;
+ flex-grow: 1;
+ flex-basis: 0;
+ min-width: 0;
+}
+.ts-dropdown.plugin-optgroup_columns .optgroup:last-child {
+ border-right: 0 none;
+}
+.ts-dropdown.plugin-optgroup_columns .optgroup::before {
+ display: none;
+}
+.ts-dropdown.plugin-optgroup_columns .optgroup-header {
+ border-top: 0 none;
+}
+
+.ts-wrapper.plugin-remove_button .item {
+ display: inline-flex;
+ align-items: center;
+}
+.ts-wrapper.plugin-remove_button .item .remove {
+ color: inherit;
+ text-decoration: none;
+ vertical-align: middle;
+ display: inline-block;
+ padding: 0 6px;
+ border-radius: 0 2px 2px 0;
+ box-sizing: border-box;
+}
+.ts-wrapper.plugin-remove_button .item .remove:hover {
+ background: rgba(0, 0, 0, 0.05);
+}
+.ts-wrapper.plugin-remove_button.disabled .item .remove:hover {
+ background: none;
+}
+.ts-wrapper.plugin-remove_button .remove-single {
+ position: absolute;
+ right: 0;
+ top: 0;
+ font-size: 23px;
+}
+
+.ts-wrapper.plugin-remove_button:not(.rtl) .item {
+ padding-right: 0 !important;
+}
+.ts-wrapper.plugin-remove_button:not(.rtl) .item .remove {
+ border-left: 1px solid #0073bb;
+ margin-left: 6px;
+}
+.ts-wrapper.plugin-remove_button:not(.rtl) .item.active .remove {
+ border-left-color: #00578d;
+}
+.ts-wrapper.plugin-remove_button:not(.rtl).disabled .item .remove {
+ border-left-color: #aaaaaa;
+}
+
+.ts-wrapper.plugin-remove_button.rtl .item {
+ padding-left: 0 !important;
+}
+.ts-wrapper.plugin-remove_button.rtl .item .remove {
+ border-right: 1px solid #0073bb;
+ margin-right: 6px;
+}
+.ts-wrapper.plugin-remove_button.rtl .item.active .remove {
+ border-right-color: #00578d;
+}
+.ts-wrapper.plugin-remove_button.rtl.disabled .item .remove {
+ border-right-color: #aaaaaa;
+}
+
+:root {
+ --ts-pr-clear-button: 0px;
+ --ts-pr-caret: 0px;
+ --ts-pr-min: .75rem;
+}
+
+.ts-wrapper.single .ts-control, .ts-wrapper.single .ts-control input {
+ cursor: pointer;
+}
+
+.ts-control:not(.rtl) {
+ padding-right: max(var(--ts-pr-min), var(--ts-pr-clear-button) + var(--ts-pr-caret)) !important;
+}
+
+.ts-control.rtl {
+ padding-left: max(var(--ts-pr-min), var(--ts-pr-clear-button) + var(--ts-pr-caret)) !important;
+}
+
+.ts-wrapper {
+ position: relative;
+}
+
+.ts-dropdown,
+.ts-control,
+.ts-control input {
+ color: #303030;
+ font-family: inherit;
+ font-size: 13px;
+ line-height: 18px;
+}
+
+.ts-control,
+.ts-wrapper.single.input-active .ts-control {
+ background: #fff;
+ cursor: text;
+}
+
+.ts-hidden-accessible {
+ border: 0 !important;
+ clip: rect(0 0 0 0) !important;
+ -webkit-clip-path: inset(50%) !important;
+ clip-path: inset(50%) !important;
+ overflow: hidden !important;
+ padding: 0 !important;
+ position: absolute !important;
+ width: 1px !important;
+ white-space: nowrap !important;
+}
+
+.ts-wrapper.single .ts-control {
+ --ts-pr-caret: 2rem;
+}
+.ts-wrapper.single .ts-control::after {
+ content: " ";
+ display: block;
+ position: absolute;
+ top: 50%;
+ margin-top: -3px;
+ width: 0;
+ height: 0;
+ border-style: solid;
+ border-width: 5px 5px 0 5px;
+ border-color: #808080 transparent transparent transparent;
+}
+.ts-wrapper.single .ts-control:not(.rtl)::after {
+ right: 15px;
+}
+.ts-wrapper.single .ts-control.rtl::after {
+ left: 15px;
+}
+.ts-wrapper.single.dropdown-active .ts-control::after {
+ margin-top: -4px;
+ border-width: 0 5px 5px 5px;
+ border-color: transparent transparent #808080 transparent;
+}
+.ts-wrapper.single.input-active .ts-control, .ts-wrapper.single.input-active .ts-control input {
+ cursor: text;
+}
+
+.ts-wrapper {
+ display: flex;
+ min-height: 36px;
+}
+.ts-wrapper.multi.has-items .ts-control {
+ padding-left: 5px;
+ --ts-pr-min: 5px;
+}
+.ts-wrapper.multi .ts-control [data-value] {
+ text-shadow: 0 1px 0 rgba(0, 51, 83, 0.3);
+ border-radius: 3px;
+ background-color: color-mix(#1da7ee, #178ee9, 60%);
+ background-image: linear-gradient(to bottom, #1da7ee, #178ee9);
+ background-repeat: repeat-x;
+ box-shadow: 0 1px 0 rgba(0, 0, 0, 0.2), inset 0 1px rgba(255, 255, 255, 0.03);
+}
+.ts-wrapper.multi .ts-control [data-value].active {
+ background-color: color-mix(#008fd8, #0075cf, 60%);
+ background-image: linear-gradient(to bottom, #008fd8, #0075cf);
+ background-repeat: repeat-x;
+}
+.ts-wrapper.multi.disabled .ts-control [data-value] {
+ color: #999;
+ text-shadow: none;
+ background: none;
+ box-shadow: none;
+}
+.ts-wrapper.multi.disabled .ts-control [data-value], .ts-wrapper.multi.disabled .ts-control [data-value] .remove {
+ border-color: #e6e6e6;
+}
+.ts-wrapper.multi.disabled .ts-control [data-value] .remove {
+ background: none;
+}
+.ts-wrapper.single .ts-control {
+ box-shadow: 0 1px 0 rgba(0, 0, 0, 0.05), inset 0 1px 0 rgba(255, 255, 255, 0.8);
+ background-color: color-mix(#fefefe, #f2f2f2, 60%);
+ background-image: linear-gradient(to bottom, #fefefe, #f2f2f2);
+ background-repeat: repeat-x;
+}
+
+.ts-wrapper.single .ts-control, .ts-dropdown.single {
+ border-color: #b8b8b8;
+}
+
+.dropdown-active .ts-control {
+ border-radius: 3px 3px 0 0;
+}
+
+.ts-dropdown .optgroup-header {
+ padding-top: 7px;
+ font-weight: bold;
+ font-size: 0.85em;
+}
+.ts-dropdown .optgroup {
+ border-top: 1px solid #f0f0f0;
+}
+.ts-dropdown .optgroup:first-child {
+ border-top: 0 none;
+}
diff --git a/app/views/blazer/_variables.html.erb b/app/views/blazer/_variables.html.erb
index 2b9023e6..c70ff757 100644
--- a/app/views/blazer/_variables.html.erb
+++ b/app/views/blazer/_variables.html.erb
@@ -24,10 +24,11 @@
<%= javascript_tag nonce: true do %>
(function () {
<%= blazer_js_var "varId", var %>
- $(document.getElementById(varId)).selectize({
+ new TomSelect(document.getElementById(varId), {
create: true,
onChange: function () {
- submitIfCompleted(this.$input.get(0).closest("form"))
+ submitIfCompleted(this.input.closest("form"))
+ this.blur()
}
})
})()
@@ -35,9 +36,9 @@
<% elsif var.end_with?("_at") || var == "start_time" || var == "end_time" %>
<%= hidden_field_tag var, var_params[var] %>
- <div class="selectize-control single" style="width: 200px;">
- <%= tag.div id: "#{var}-select", class: "selectize-input", style: "display: inline-block;" do %>
- <span>Select a date</span>
+ <div class="ts-wrapper single" style="width: 200px;">
+ <%= tag.div id: "#{var}-select", class: "ts-control" do %>
+ <div class="item">Select a date</div>
<% end %>
</div>
@@ -77,9 +78,9 @@
<% end %>
<%= label_tag nil, date_vars.join(" & ") %>
- <div class="selectize-control single" style="width: 300px;">
- <div id="reportrange" class="selectize-input" style="display: inline-block;">
- <span>Select a time range</span>
+ <div class="ts-wrapper single" style="width: 300px;">
+ <div class="ts-control" id="reportrange">
+ <div class="item">Select a time range</div>
</div>
</div>
@@ -118,7 +119,7 @@
}
).on("apply.daterangepicker", function (ev, picker) {
setTimeInputs(picker.startDate, picker.endDate)
- reportrange.querySelector("span").textContent = toDate(picker.startDate).format("MMMM D, YYYY") + " - " + toDate(picker.endDate).format("MMMM D, YYYY")
+ reportrange.querySelector(".item").textContent = toDate(picker.startDate).format("MMMM D, YYYY") + " - " + toDate(picker.endDate).format("MMMM D, YYYY")
})
const picker = $(reportrange).data("daterangepicker")
diff --git a/app/views/blazer/checks/_form.html.erb b/app/views/blazer/checks/_form.html.erb
index 195a50d9..5089659e 100644
--- a/app/views/blazer/checks/_form.html.erb
+++ b/app/views/blazer/checks/_form.html.erb
@@ -1,7 +1,10 @@
<%= javascript_tag nonce: true do %>
- function selectize(id, options) {
+ function createSelect(id, options) {
const element = document.getElementById(id)
- $(element).selectize(options)
+ const onChange = function () {
+ this.blur()
+ }
+ new TomSelect(element, {onChange, ...options})
show(element.closest(".hide"))
}
<% end %>
@@ -23,7 +26,7 @@
<%= javascript_tag nonce: true do %>
<%= blazer_js_var "queries", Blazer::Query.active.named.order(:name).select("id, name").map { |q| {text: q.name, value: q.id} } %>
<%= blazer_js_var "items", [@check.query_id].compact %>
- selectize("check_query_id", {options: queries, items: items, highlight: false, maxOptions: 100})
+ createSelect("check_query_id", {options: queries, items: items, highlight: false, maxOptions: 100})
<% end %>
</div>
@@ -35,7 +38,7 @@
<%= f.select :check_type, check_options %>
</div>
<%= javascript_tag nonce: true do %>
- selectize("check_check_type", {})
+ createSelect("check_check_type", {})
<% end %>
</div>
<% elsif @check.respond_to?(:invert) %>
@@ -45,7 +48,7 @@
<%= f.select :invert, [["Any results (bad data)", false], ["No results (missing data)", true]] %>
</div>
<%= javascript_tag nonce: true do %>
- selectize("check_invert", {})
+ createSelect("check_invert", {})
<% end %>
</div>
<% end %>
@@ -57,7 +60,7 @@
<%= f.select :schedule, Blazer.check_schedules.map { |v| [v, v] } %>
</div>
<%= javascript_tag nonce: true do %>
- selectize("check_schedule", {})
+ createSelect("check_schedule", {})
<% end %>
</div>
<% end %>
diff --git a/app/views/blazer/dashboards/_form.html.erb b/app/views/blazer/dashboards/_form.html.erb
index 32d644a5..5d45614f 100644
--- a/app/views/blazer/dashboards/_form.html.erb
+++ b/app/views/blazer/dashboards/_form.html.erb
@@ -67,7 +67,7 @@
}
})
- $(querySelect).selectize({
+ new TomSelect(querySelect, {
options: queries,
highlight: false,
maxOptions: 100,
@@ -83,8 +83,9 @@
}
}
- addQuery({id: id, name: item.text()})
+ addQuery({id: id, name: item.textContent})
this.setValue("")
+ this.blur()
}
}
})
diff --git a/app/views/blazer/queries/_form.html.erb b/app/views/blazer/queries/_form.html.erb
index 26e27a14..7c557419 100644
--- a/app/views/blazer/queries/_form.html.erb
+++ b/app/views/blazer/queries/_form.html.erb
@@ -134,7 +134,7 @@
docsLink.setAttribute("href", Routes.docs_queries_path({data_source: dataSource}))
schemaLink.setAttribute("href", Routes.schema_queries_path({data_source: dataSource}))
- tableSelect.selectize.clearOptions()
+ tableSelect.tomselect.clearOptions()
if (tablesXhr) {
tablesXhr.abort()
@@ -151,9 +151,9 @@
newOptions.push({text: table, value: table})
}
}
- tableSelect.selectize.clearOptions()
- tableSelect.selectize.addOption(newOptions)
- tableSelect.selectize.refreshOptions(false)
+ tableSelect.tomselect.clearOptions()
+ tableSelect.tomselect.addOption(newOptions)
+ tableSelect.tomselect.refreshOptions(false)
}, tablesXhr)
}
@@ -206,18 +206,20 @@
runButton.addEventListener("click", run)
cancelButton.addEventListener("click", cancel)
- $(tableSelect).selectize({})
- tableSelect.selectize.on("change", function (table) {
- editor.setValue(previewStatement[dsSelect.value].replace("{table}", table), 1)
- run()
- this.clear(true)
- this.blur()
+ new TomSelect(tableSelect, {
+ onChange: function (table) {
+ editor.setValue(previewStatement[dsSelect.value].replace("{table}", table), 1)
+ run()
+ this.clear(true)
+ this.blur()
+ }
})
- $(dsSelect).selectize({})
- dsSelect.selectize.on("change", function () {
- updateDataSource()
- this.blur()
+ new TomSelect(dsSelect, {
+ onChange: function() {
+ updateDataSource()
+ this.blur()
+ }
})
updateDataSource()
diff --git a/app/views/layouts/blazer/application.html.erb b/app/views/layouts/blazer/application.html.erb
index 6cf1f2fb..8bbbd9ea 100644
--- a/app/views/layouts/blazer/application.html.erb
+++ b/app/views/layouts/blazer/application.html.erb
@@ -6,8 +6,8 @@
<meta charset="utf-8" />
<%= favicon_link_tag "blazer/favicon.png" %>
<% if defined?(Propshaft::Railtie) && Rails.application.assets.is_a?(Propshaft::Assembly) %>
- <%= stylesheet_link_tag "blazer/bootstrap-propshaft", "blazer/bootstrap", "blazer/selectize", "blazer/github", "blazer/daterangepicker", "blazer/application", nonce: true %>
- <%= javascript_include_tag "blazer/jquery", "blazer/tablesort", "blazer/selectize", "blazer/highlight.min", "blazer/moment", "blazer/moment-timezone-with-data", "blazer/daterangepicker", "blazer/chart.umd", "blazer/chartjs-adapter-date-fns.bundle", "blazer/chartkick", "blazer/mapkick.bundle", "blazer/ace/ace", "blazer/ace/ext-language_tools", "blazer/ace/theme-twilight", "blazer/ace/mode-sql", "blazer/ace/snippets/text", "blazer/ace/snippets/sql", "blazer/Sortable", "blazer/routes", "blazer/queries", "blazer/fuzzysearch", "blazer/application", nonce: true %>
+ <%= stylesheet_link_tag "blazer/bootstrap-propshaft", "blazer/bootstrap", "blazer/tom-select.default", "blazer/github", "blazer/daterangepicker", "blazer/application", nonce: true %>
+ <%= javascript_include_tag "blazer/jquery", "blazer/tablesort", "blazer/tom-select.base", "blazer/highlight.min", "blazer/moment", "blazer/moment-timezone-with-data", "blazer/daterangepicker", "blazer/chart.umd", "blazer/chartjs-adapter-date-fns.bundle", "blazer/chartkick", "blazer/mapkick.bundle", "blazer/ace/ace", "blazer/ace/ext-language_tools", "blazer/ace/theme-twilight", "blazer/ace/mode-sql", "blazer/ace/snippets/text", "blazer/ace/snippets/sql", "blazer/Sortable", "blazer/routes", "blazer/queries", "blazer/fuzzysearch", "blazer/application", nonce: true %>
<% else %>
<%= stylesheet_link_tag "blazer/application", nonce: true %>
<%= javascript_include_tag "blazer/application", nonce: true %>
diff --git a/licenses/LICENSE-selectize.txt b/licenses/LICENSE-tom-select.txt
similarity index 100%
rename from licenses/LICENSE-selectize.txt
rename to licenses/LICENSE-tom-select.txt