diff --git a/Gemfile b/Gemfile index 81a90af6582c153b0b51e7c6dd2714326574ee7e..0ea1028e607f8c1f2d045223f75b504406022a72 100644 --- a/Gemfile +++ b/Gemfile @@ -119,9 +119,6 @@ gem 'cocoon' gem 'kaminari' gem 'bootstrap-kaminari-views' -# Hybrid text / select input fields -gem 'selectize-rails' - # Diffing for project update comparison gem 'diffy' diff --git a/Gemfile.lock b/Gemfile.lock index de9223e58cf86c84d49e5b5c4edee4023bba9c9a..d6b72303a9f6df505c800b425751b217c3377620 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -434,7 +434,6 @@ GEM tilt seedbank (0.5.0) rake (>= 10.0) - selectize-rails (0.12.6) selenium-webdriver (3.142.7) childprocess (>= 0.5, < 4.0) rubyzip (>= 1.2.2) @@ -569,7 +568,6 @@ DEPENDENCIES rubyzip (>= 1.3.0) sass-rails seedbank - selectize-rails selenium-webdriver (~> 3.6) sentry-rails sentry-ruby diff --git a/app/assets/javascripts/admin_application.js b/app/assets/javascripts/admin_application.js index 4964941cda196e2ee08369ebd20d887436ed2d04..71c5fc4648e343a503bd472fcda5d6f59e994b69 100644 --- a/app/assets/javascripts/admin_application.js +++ b/app/assets/javascripts/admin_application.js @@ -17,7 +17,7 @@ //= require zebra-datepicker/core //= require normal/datepicker_inputs //= require cocoon -//= require selectize +//= require selectize/selectize //= require normal/selectize_inputs //= require mammoth/mammoth.browser //= require toastui/toastui-editor-all diff --git a/app/assets/javascripts/application.js b/app/assets/javascripts/application.js index be2b92cd9165694c14c80e94070f9c0b50756664..4f8b0628ee00b1174e04127815d72a84e47b9436 100644 --- a/app/assets/javascripts/application.js +++ b/app/assets/javascripts/application.js @@ -21,7 +21,7 @@ //= require normal/checkbox //= require normal/slick_carousels //= require lightbox -//= require selectize +//= require selectize/selectize //= require normal/selectize_inputs //= require mammoth/mammoth.browser //= require toastui/toastui-editor-all diff --git a/app/assets/javascripts/selectize/selectize.js b/app/assets/javascripts/selectize/selectize.js new file mode 100644 index 0000000000000000000000000000000000000000..44181e5d3c32fa42e1df926e481ea565f3b715b3 --- /dev/null +++ b/app/assets/javascripts/selectize/selectize.js @@ -0,0 +1,4204 @@ +/* + * Version 0.13.6, 2022-07-09 + */ + +/** + * 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 <brian@thirdroute.com> + */ + +(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, respect_word_boundaries) { + 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]); + } + } + } + if (respect_word_boundaries) regex = "\\b"+regex + 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, options.respect_word_boundaries), + 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 <brian@thirdroute.com> + */ + +(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.13.6) + * Copyright (c) 2013–2015 Brian Reavis & contributors + * Copyright (c) 2020-2022 Selectize Team & 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 <brian@thirdroute.com> + * @author Ris Adams <selectize@risadams.com> + */ + +/*jshint curly:false */ +/*jshint browser:true */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + define('selectize', ['jquery','sifter','microplugin'], factory); + } else if (typeof module === 'object' && typeof module.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="highlight"> + 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]]; + } + }; + + function uaDetect(platform, re) { + if (navigator.userAgentData) { + return platform === navigator.userAgentData.platform; + } + + return re.test(navigator.userAgent); + } + + var IS_MAC = uaDetect("macOS", /Mac/); + + 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 = !uaDetect("Android", /android/i) && !!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, '&') + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/"/g, '"'); + }; + + /** + * 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(input === undefined) { + console.warn('WARN getSelection cannot locate input control'); + return 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', + width: 'auto', + padding: 0, + whiteSpace: 'pre' + }); + + $('<div />').css({ + position: 'absolute', + width: 0, + height: 0, + overflow: 'hidden' + }).append(Selectize.$testInput).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, width; + var placeholder, placeholderWidth; + 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 (placeholder) { + placeholderWidth = measureString(placeholder, $input) + 4; + } else { + placeholderWidth = 0; + } + + width = Math.max(measureString(value, $input), placeholderWidth) + 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 : '', + lastValidValue : '', + 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="new-password" autofill="no" />').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).attr('tabindex', '-1').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')); + } + if ($input.is('input')) { + $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); }, + keypress : function() { return self.onKeyPress.apply(self, arguments); }, + input : function() { return self.onInput.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 (Array.isArray(settings.items)) { + self.lastValidValue = 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_value = self.settings.valueField; + 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 '+( data[field_value] === '' ? 'selectize-dropdown-emptyoptionlabel' : '')+'">' + 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>…</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', + 'dropdown_item_activate' : 'onDropdownItemActivate', + 'dropdown_item_deactivate' : 'onDropdownItemDeactivate' + }; + + 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() { + var self = this; + if (self.getValue() !== "") { + self.lastValidValue = self.getValue(); + } + this.$input.trigger('input'); + 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 = pastedText + .trim() + .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() && self.settings.showAddOptionOnCreate) { + 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> input. + * + * @param {object} e + * @returns {boolean} + */ + onInput: function(e) { + var self = this; + + 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); + }]); + }, + + /** + * Gets the value of input field of the control. + * + * @returns {string} value + */ + getTextboxValue: function() { + var $input = this.$control_input; + return $input.val(); + }, + + /** + * 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); + }); + }, + + /** + * Resets the number of max items to the given value + * + * @param {number} value + */ + setMaxItems: function(value){ + if(value === 0) value = null; //reset to unlimited items. + this.settings.maxItems = value; + this.settings.mode = this.settings.mode || (this.settings.maxItems === 1 ? 'single' : 'multi'); + this.refreshState(); + }, + + /** + * 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.trigger('dropdown_item_deactivate', self.$activeOption.attr('data-value')); + } + self.$activeOption = null; + + $option = $($option); + if (!$option.length) return; + + self.$activeOption = $option.addClass('active'); + if (self.isOpen) self.trigger('dropdown_item_activate', self.$activeOption.attr('data-value')); + + 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; + + self.ignoreFocus = true; + self.$control_input[0].focus(); + window.setTimeout(function() { + self.ignoreFocus = false; + self.onFocus(); + }, 0); + return self; + }, + + /** + * Forces the control out of focus. + * + * @param {Element} dest + */ + blur: function(dest) { + this.$control_input[0].blur(); + this.onBlur(null, dest); + return this; + }, + + /** + * 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 = (self.$control_input.val()).trim(); + 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 = Array.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] && self.optgroups[a].$order || 0; + var b_order = self.optgroups[b] && 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) { + // clear selection on all previously selected elements first + self.$dropdown.find('.selected').removeClass('selected'); + + 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) { + if(self.settings.showAddOptionOnCreate) { + $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 && self.settings.showAddOptionOnCreate ); + if (self.hasOptions) { + if (results.items.length > 0) { + $active_before = active_before && self.getOption(active_before); + if (results.query !== "" && $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 (Array.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. + * + * @param {boolean} silent + */ + clearOptions: function(silent) { + 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'); + self.clear(silent); + }, + + /** + * 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 first + * selectable option. + * + * @return {object} + */ + getFirstOption: function() { + var $options = this.$dropdown.find('[data-selectable]'); + return $options.length > 0 ? $options.eq(0) : $(); + }, + + /** + * 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 $(); + }, + + /** + * Finds the first element with a "textContent" property + * that matches the given textContent value. + * + * @param {mixed} textContent + * @param {boolean} ignoreCase + * @param {object} $els + * @return {object} + */ + getElementWithTextContent: function(textContent, ignoreCase ,$els) { + textContent = hash_key(textContent); + + if (typeof textContent !== 'undefined' && textContent !== null) { + for (var i = 0, n = $els.length; i < n; i++) { + var eleTextContent = $els[i].textContent + if (ignoreCase == true) { + eleTextContent = (eleTextContent !== null) ? eleTextContent.toLowerCase() : null; + textContent = textContent.toLowerCase(); + } + if (eleTextContent === textContent) { + 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()); + }, + + /** + * Returns the jQuery element of the item + * matching the given textContent. + * + * @param {string} value + * @param {boolean} ignoreCase + * @returns {object} + */ + getFirstItemMatchedByTextContent: function(textContent, ignoreCase) { + ignoreCase = (ignoreCase !== null && ignoreCase === true) ? true : false; + return this.getElementWithTextContent(textContent, ignoreCase, this.$dropdown_content.find('[data-selectable]')); + }, + + /** + * "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 = Array.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) { + self.trigger('item_before_remove', value, $item); + $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 || (self.$control_input.val() || '').trim(); + + 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; + var key = input; + if ( self.settings.formatValueToKey && typeof self.settings.formatValueToKey === 'function' ) { + key = self.settings.formatValueToKey.apply(this, [key]); + if (key === null || typeof key === 'undefined' || typeof key === 'object' || typeof key === 'function') { + throw new Error('Selectize "formatValueToKey" setting must be a function that returns a value other than object or function.'); + } + } + data[self.settings.valueField] = key; + 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) { + if (typeof self.settings.deselectBehavior === 'string' && self.settings.deselectBehavior === 'top') { + option_select = self.getFirstOption().attr('data-value'); + } else { + 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, + showAddOptionOnCreate: true, + createOnBlur: false, + createFilter: null, + highlight: true, + openOnFocus: true, + maxOptions: 1000, + maxItems: null, + hideSelected: null, + addPrecedence: false, + selectOnTab: true, + preload: false, + allowEmptyOption: false, + showEmptyOptionInDropdown: false, + emptyOptionLabel: '--', + closeAfterSelect: false, + + scrollDuration: 60, + deselectBehavior: 'previous', //top, previous + 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) { ... } + formatValueToKey : null, // function(key) { ... } + 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(); + } + if (settings.allowEmptyOption && settings.showEmptyOptionInDropdown && !$input.children('option[value=""]').length) { + var input_html = $input.html(); + $input.html('<option value="">'+settings.emptyOptionLabel+'</option>'+input_html); + } + + 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)); + instance.settings_user = settings_user; + }); + }; + + $.fn.selectize.defaults = Selectize.defaults; + $.fn.selectize.support = { + validity: SUPPORTS_VALIDITY_API + }; + + + Selectize.define("auto_position", function () { + var self = this; + + const POSITION = { + top: 'top', + bottom: 'bottom', + }; + + self.positionDropdown = (function() { + return function() { + const $control = this.$control; + const offset = this.settings.dropdownParent === 'body' ? $control.offset() : $control.position(); + offset.top += $control.outerHeight(true); + + const dropdownHeight = this.$dropdown.prop('scrollHeight') + 5; // 5 - padding value; + const controlPosTop = this.$control.get(0).getBoundingClientRect().top; + const wrapperHeight = this.$wrapper.height(); + const position = controlPosTop + dropdownHeight + wrapperHeight > window.innerHeight ? POSITION.top : POSITION.bottom; + const styles = { + width: $control.outerWidth(), + left: offset.left + }; + + if (position === POSITION.top) { + Object.assign(styles, {bottom: offset.top, top: 'unset', margin: '0 0 5px 0'}); + this.$dropdown.addClass('selectize-position-top'); + } else { + Object.assign(styles, {top: offset.top, bottom: 'unset', margin: '5px 0 0 0'}); + this.$dropdown.removeClass('selectize-position-top'); + } + + this.$dropdown.css(styles); + } + }()); + }); + + + Selectize.define('auto_select_on_type', function(options) { + var self = this; + + self.onBlur = (function() { + var originalBlur = self.onBlur; + return function(e) { + var $matchedItem = self.getFirstItemMatchedByTextContent(self.lastValue, true); + if (typeof $matchedItem.attr('data-value') !== 'undefined' && self.getValue() !== $matchedItem.attr('data-value')) + { + self.setValue($matchedItem.attr('data-value')); + } + return originalBlur.apply(this, arguments); + } + }()); + }); + + + Selectize.define("autofill_disable", function (options) { + var self = this; + + self.setup = (function () { + var original = self.setup; + return function () { + original.apply(self, arguments); + + // https://stackoverflow.com/questions/30053167/autocomplete-off-vs-false + self.$control_input.attr({ autocomplete: "new-password", autofill: "no" }); + }; + })(); + }); + + + 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'}); + $control.addClass('dragging'); + }, + stop: function() { + // $control.css({overflow: 'hidden'}); + $control.removeClass('dragging'); + var active = self.$activeItems ? self.$activeItems.slice() : null; + var values = []; + $control.children('[data-value]').each(function() { + values.push($(this).attr('data-value')); + }); + self.isFocused = false; + self.setValue(values); + self.isFocused = true; + self.setActiveItem(active); + self.positionDropdown(); + } + }); + }; + })(); + + }); + + + 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 + '">×</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 : '×', + 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); + } + return false; + }); + + }; + })(); + }; + + 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); + }; + })(); + }); + + + Selectize.define('select_on_focus', function(options) { + var self = this; + + self.on('focus', function() { + var originalFocus = self.onFocus; + return function(e) { + var value = self.getItem(self.getValue()).text(); + self.clear(); + self.setTextboxValue(value); + self.$control_input.select(); + setTimeout( function () { + if (self.settings.selectOnTab) { + self.setActiveOption(self.getFirstItemMatchedByTextContent(value)); + } + self.settings.score = null; + },0); + return originalFocus.apply(this, arguments); + }; + }()); + + self.onBlur = (function() { + var originalBlur = self.onBlur; + return function(e) { + if (self.getValue() === "" && self.lastValidValue !== self.getValue()) { + self.setValue(self.lastValidValue); + } + setTimeout( function () { + self.settings.score = function() { + return function() { + return 1; + }; + }; + }, 0 ); + return originalBlur.apply(this, arguments); + } + }()); + self.settings.score = function() { + return function() { return 1; }; + }; + + }); + + + Selectize.define('tag_limit', function (options) { + const self = this + options.tagLimit = options.tagLimit + this.onBlur = (function (e) { + const original = self.onBlur + + return function (e) { + original.apply(this, e); + if (!e) + return + const $control = this.$control + const $items = $control.find('.item') + const limit = options.tagLimit + if (limit === undefined || $items.length <= limit) + return + + $items.toArray().forEach(function(item, index) { + if (index < limit) + return + $(item).hide() + }); + + $control.append('<span><b>' + ($items.length - limit) + '</b></span>') + }; + })() + + this.onFocus = (function (e) { + const original = self.onFocus + + return function (e) { + original.apply(this, e); + if (!e) + return + const $control = this.$control + const $items = $control.find('.item') + $items.show() + $control.find('span').remove() + + }; + })() + }); + + + return Selectize; +})); diff --git a/app/assets/stylesheets/admin_application.scss b/app/assets/stylesheets/admin_application.scss index 0cd228d487a8916f620918aac7bc58a2667297af..73cbf6bf8ecfa82e3e57410a6cd2fb61704d310e 100644 --- a/app/assets/stylesheets/admin_application.scss +++ b/app/assets/stylesheets/admin_application.scss @@ -22,8 +22,8 @@ body { padding-top: 0px; } .navbar { margin-bottom: 0; } -@import 'selectize'; -@import 'selectize.bootstrap3'; +@import 'selectize/selectize'; +@import 'selectize/selectize.bootstrap3'; @import 'toastui/toastui-editor'; @import 'toastui/prism'; @import 'toastui/toastui-editor-plugin-code-syntax-highlight'; diff --git a/app/assets/stylesheets/application.scss b/app/assets/stylesheets/application.scss index 2f0b53161244a75df3e94b99bc2ee159a307f048..cb491ce91ad50ad18a7ea6ce4bccf7fb736a8d59 100644 --- a/app/assets/stylesheets/application.scss +++ b/app/assets/stylesheets/application.scss @@ -30,8 +30,8 @@ @import 'zebra-datepicker/bootstrap'; -@import 'selectize'; -@import 'selectize.bootstrap3'; +@import 'selectize/selectize'; +@import 'selectize/selectize.bootstrap3'; @import 'toastui/toastui-editor'; @import 'toastui/prism'; @import 'toastui/toastui-editor-plugin-code-syntax-highlight'; diff --git a/app/assets/stylesheets/selectize/selectize.bootstrap3.css b/app/assets/stylesheets/selectize/selectize.bootstrap3.css new file mode 100644 index 0000000000000000000000000000000000000000..be2b1171b406c065a5386dc781c206b5c8b20dfe --- /dev/null +++ b/app/assets/stylesheets/selectize/selectize.bootstrap3.css @@ -0,0 +1,6 @@ +.selectize-control.plugin-drag_drop.multi>.selectize-input.dragging{overflow:visible}.selectize-control.plugin-drag_drop.multi>.selectize-input>div.ui-sortable-placeholder{visibility:visible !important;background:#f2f2f2 !important;background:rgba(0,0,0,.06) !important;border:0 none !important;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{box-shadow:0 2px 5px rgba(0,0,0,.2)}.selectize-control .dropdown-header{position:relative;padding:6px 12px;border-bottom:1px solid #d0d0d0;background:#f8f8f8;border-radius:4px 4px 0 0}.selectize-control .dropdown-header-close{position:absolute;right:12px;top:50%;color:#333;opacity:.4;margin-top:-12px;line-height:20px;font-size:20px !important}.selectize-control .dropdown-header-close:hover{color:#000}.selectize-dropdown.plugin-optgroup_columns .selectize-dropdown-content{display:flex}.selectize-dropdown.plugin-optgroup_columns .optgroup{border-right:1px solid #f2f2f2;border-top:0 none;flex-grow:1;flex-basis:0;min-width:0}.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 .item{display:inline-flex;align-items:center;padding-right:0 !important}.selectize-control.plugin-remove_button .item .remove{color:inherit;text-decoration:none;vertical-align:middle;display:inline-block;padding:1px 5px;border-left:1px solid rgba(0,0,0,0);border-radius:0 2px 2px 0;box-sizing:border-box;margin-left:5px}.selectize-control.plugin-remove_button .item .remove:hover{background:rgba(0,0,0,.05)}.selectize-control.plugin-remove_button .item.active .remove{border-left-color:rgba(0,0,0,0)}.selectize-control.plugin-remove_button .disabled .item .remove:hover{background:none}.selectize-control.plugin-remove_button .disabled .item .remove{border-left-color:rgba(77,77,77,0)}.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:#333;font-family:inherit;font-size:inherit;line-height:20px;font-smoothing:inherit}.selectize-input,.selectize-control.single .selectize-input.input-active{background:#fff;cursor:text;display:inline-block}.selectize-input{border:1px solid #ccc;padding:6px 12px;display:inline-block;width:100%;position:relative;z-index:1;box-sizing:border-box;box-shadow:none;border-radius:4px}.selectize-control.multi .selectize-input.has-items{padding:calc( + 6px - 1px - 0px + ) 12px calc( + 6px - 1px - 3px - + 0px + )}.selectize-input.full{background-color:#fff}.selectize-input.disabled,.selectize-input.disabled *{cursor:default !important}.selectize-input.focus{box-shadow:inset 0 1px 2px rgba(0,0,0,.15)}.selectize-input.dropdown-active{border-radius:4px 4px 0 0}.selectize-input>*{vertical-align:baseline;display:inline-block;zoom:1}.selectize-control.multi .selectize-input>div{cursor:pointer;margin:0 3px 3px 0;padding:1px 5px;background:#efefef;color:#333;border:0px solid rgba(0,0,0,0)}.selectize-control.multi .selectize-input>div.active{background:#337ab7;color:#fff;border:0px solid rgba(0,0,0,0)}.selectize-control.multi .selectize-input.disabled>div,.selectize-control.multi .selectize-input.disabled>div.active{color:gray;background:#fff;border:0px solid rgba(77,77,77,0)}.selectize-input>input{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;user-select:auto !important;box-shadow:none !important}.selectize-input>input::-ms-clear{display:none}.selectize-input>input:focus{outline:none !important}.selectize-input>input[placeholder]{box-sizing:initial}.selectize-input.has-items>input{margin:0 0px !important}.selectize-input::after{content:" ";display:block;clear:left}.selectize-input.dropdown-active::before{content:" ";display:block;position:absolute;background:#fff;height:1px;bottom:0;left:0;right:0}.selectize-dropdown{position:absolute;top:100%;left:0;width:100%;z-index:10;border:1px solid #d0d0d0;background:#fff;margin:-1px 0 0 0;border-top:0 none;box-sizing:border-box;box-shadow:0 1px 3px rgba(0,0,0,.1);border-radius:0 0 4px 4px}.selectize-dropdown [data-selectable]{cursor:pointer;overflow:hidden}.selectize-dropdown [data-selectable] .highlight{background:rgba(255,237,40,.4);border-radius:1px}.selectize-dropdown .option,.selectize-dropdown .optgroup-header,.selectize-dropdown .no-results,.selectize-dropdown .create{padding:3px 12px}.selectize-dropdown .option,.selectize-dropdown [data-disabled],.selectize-dropdown [data-disabled] [data-selectable].option{cursor:inherit;opacity:.5}.selectize-dropdown [data-selectable].option{opacity:1;cursor:pointer}.selectize-dropdown .optgroup:first-child .optgroup-header{border-top:0 none}.selectize-dropdown .optgroup-header{color:#777;background:#fff;cursor:default}.selectize-dropdown .active{background-color:#f5f5f5;color:#262626}.selectize-dropdown .active.create{color:#262626}.selectize-dropdown .create{color:rgba(51,51,51,.5)}.selectize-dropdown-content{overflow-y:auto;overflow-x:hidden;max-height:200px;overflow-scrolling:touch}.selectize-dropdown-emptyoptionlabel{text-align:center}.selectize-dropdown .spinner{display:inline-block;width:30px;height:30px;margin:3px 12px}.selectize-dropdown .spinner:after{content:" ";display:block;width:24px;height:24px;margin:3px;border-radius:50%;border:5px solid #d0d0d0;border-color:#d0d0d0 rgba(0,0,0,0) #d0d0d0 rgba(0,0,0,0);animation:lds-dual-ring 1.2s linear infinite}@keyframes lds-dual-ring{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}.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:17px;margin-top:-3px;width:0;height:0;border-style:solid;border-width:5px 5px 0 5px;border-color:#333 rgba(0,0,0,0) rgba(0,0,0,0) rgba(0,0,0,0)}.selectize-control.single .selectize-input.dropdown-active:after{margin-top:-4px;border-width:0 5px 5px 5px;border-color:rgba(0,0,0,0) rgba(0,0,0,0) #333 rgba(0,0,0,0)}.selectize-control.rtl{text-align:right}.selectize-control.rtl.single .selectize-input:after{left:17px;right:auto}.selectize-control.rtl .selectize-input>input{margin:0 4px 0 -2px !important}.selectize-control .selectize-input.disabled{opacity:.5;background-color:#fff}.selectize-dropdown,.selectize-dropdown.form-control{height:auto;padding:0;margin:2px 0 0 0;z-index:1000;background:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,.15);border-radius:4px;box-shadow:0 6px 12px rgba(0,0,0,.175)}.selectize-dropdown .optgroup-header{font-size:12px;line-height:1.428571429}.selectize-dropdown .optgroup:first-child:before{display:none}.selectize-dropdown .optgroup:before{content:" ";display:block;height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5;margin-left:-12px;margin-right:-12px}.selectize-dropdown-content{padding:5px 0}.selectize-dropdown-emptyoptionlabel{text-align:center}.selectize-input{min-height:34px}.selectize-input.dropdown-active{border-radius:4px}.selectize-input.dropdown-active::before{display:none}.selectize-input.focus{border-color:#66afe9;outline:0;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6)}.has-error .selectize-input{border-color:#a94442;box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-error .selectize-input:focus{border-color:#843534;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483}.selectize-control.multi .selectize-input.has-items{padding-left:7px;padding-right:7px}.selectize-control.multi .selectize-input>div{border-radius:3px}.form-control.selectize-control{padding:0;height:auto;border:none;background:none;box-shadow:none;border-radius:0} \ No newline at end of file diff --git a/app/assets/stylesheets/selectize/selectize.css b/app/assets/stylesheets/selectize/selectize.css new file mode 100644 index 0000000000000000000000000000000000000000..c869ceeed290c7b3f7cd82a8dfd7a8a4abbc8bab --- /dev/null +++ b/app/assets/stylesheets/selectize/selectize.css @@ -0,0 +1,24 @@ +/** + * selectize.css (v0.13.6) + * Copyright (c) 2013–2015 Brian Reavis & contributors + * Copyright (c) 2020-2022 Selectize Team & 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 <brian@thirdroute.com> + * @author Ris Adams <selectize@risadams.com> + */ + +.selectize-control.plugin-drag_drop.multi>.selectize-input.dragging{overflow:visible}.selectize-control.plugin-drag_drop.multi>.selectize-input>div.ui-sortable-placeholder{visibility:visible !important;background:#f2f2f2 !important;background:rgba(0,0,0,.06) !important;border:0 none !important;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{box-shadow:0 2px 5px rgba(0,0,0,.2)}.selectize-control .dropdown-header{position:relative;padding:10px 8px;border-bottom:1px solid #d0d0d0;background:#f8f8f8;border-radius:3px 3px 0 0}.selectize-control .dropdown-header-close{position:absolute;right:8px;top:50%;color:#303030;opacity:.4;margin-top:-12px;line-height:20px;font-size:20px !important}.selectize-control .dropdown-header-close:hover{color:#000}.selectize-dropdown.plugin-optgroup_columns .selectize-dropdown-content{display:flex}.selectize-dropdown.plugin-optgroup_columns .optgroup{border-right:1px solid #f2f2f2;border-top:0 none;flex-grow:1;flex-basis:0;min-width:0}.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 .item{display:inline-flex;align-items:center;padding-right:0 !important}.selectize-control.plugin-remove_button .item .remove{color:inherit;text-decoration:none;vertical-align:middle;display:inline-block;padding:2px 6px;border-left:1px solid #d0d0d0;border-radius:0 2px 2px 0;box-sizing:border-box;margin-left:6px}.selectize-control.plugin-remove_button .item .remove:hover{background:rgba(0,0,0,.05)}.selectize-control.plugin-remove_button .item.active .remove{border-left-color:#cacaca}.selectize-control.plugin-remove_button .disabled .item .remove:hover{background:none}.selectize-control.plugin-remove_button .disabled .item .remove{border-left-color:#fff}.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;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%;position:relative;z-index:1;box-sizing:border-box;box-shadow:inset 0 1px 1px rgba(0,0,0,.1);border-radius:3px}.selectize-control.multi .selectize-input.has-items{padding:calc( + 8px - 2px - 0px + ) 8px calc( + 8px - 2px - 3px - + 0px + )}.selectize-input.full{background-color:#fff}.selectize-input.disabled,.selectize-input.disabled *{cursor:default !important}.selectize-input.focus{box-shadow:inset 0 1px 2px rgba(0,0,0,.15)}.selectize-input.dropdown-active{border-radius:3px 3px 0 0}.selectize-input>*{vertical-align:baseline;display:inline-block;zoom:1}.selectize-control.multi .selectize-input>div{cursor:pointer;margin:0 3px 3px 0;padding:2px 6px;background:#f2f2f2;color:#303030;border:0px solid #d0d0d0}.selectize-control.multi .selectize-input>div.active{background:#e8e8e8;color:#303030;border:0px solid #cacaca}.selectize-control.multi .selectize-input.disabled>div,.selectize-control.multi .selectize-input.disabled>div.active{color:#7d7d7d;background:#fff;border:0px solid #fff}.selectize-input>input{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;user-select:auto !important;box-shadow:none !important}.selectize-input>input::-ms-clear{display:none}.selectize-input>input:focus{outline:none !important}.selectize-input>input[placeholder]{box-sizing:initial}.selectize-input.has-items>input{margin:0 0px !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;top:100%;left:0;width:100%;z-index:10;border:1px solid #d0d0d0;background:#fff;margin:-1px 0 0 0;border-top:0 none;box-sizing:border-box;box-shadow:0 1px 3px rgba(0,0,0,.1);border-radius:0 0 3px 3px}.selectize-dropdown [data-selectable]{cursor:pointer;overflow:hidden}.selectize-dropdown [data-selectable] .highlight{background:rgba(125,168,208,.2);border-radius:1px}.selectize-dropdown .option,.selectize-dropdown .optgroup-header,.selectize-dropdown .no-results,.selectize-dropdown .create{padding:5px 8px}.selectize-dropdown .option,.selectize-dropdown [data-disabled],.selectize-dropdown [data-disabled] [data-selectable].option{cursor:inherit;opacity:.5}.selectize-dropdown [data-selectable].option{opacity:1;cursor:pointer}.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,.5)}.selectize-dropdown-content{overflow-y:auto;overflow-x:hidden;max-height:200px;overflow-scrolling:touch}.selectize-dropdown-emptyoptionlabel{text-align:center}.selectize-dropdown .spinner{display:inline-block;width:30px;height:30px;margin:5px 8px}.selectize-dropdown .spinner:after{content:" ";display:block;width:24px;height:24px;margin:3px;border-radius:50%;border:5px solid #d0d0d0;border-color:#d0d0d0 rgba(0,0,0,0) #d0d0d0 rgba(0,0,0,0);animation:lds-dual-ring 1.2s linear infinite}@keyframes lds-dual-ring{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}.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:gray rgba(0,0,0,0) rgba(0,0,0,0) rgba(0,0,0,0)}.selectize-control.single .selectize-input.dropdown-active:after{margin-top:-4px;border-width:0 5px 5px 5px;border-color:rgba(0,0,0,0) rgba(0,0,0,0) gray rgba(0,0,0,0)}.selectize-control.rtl{text-align:right}.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:.5;background-color:#fafafa} diff --git a/app/controllers/admin/projects_controller.rb b/app/controllers/admin/projects_controller.rb index 0ca479bad9bf5b8236a1c306a9af283aaecfae14..d3fd4d271e87f82bc32bf776d333e8b875f45c35 100644 --- a/app/controllers/admin/projects_controller.rb +++ b/app/controllers/admin/projects_controller.rb @@ -142,7 +142,7 @@ module Admin resource: @project, course_specific_role: csr, unregistered_name: params[:name], - unregistered_email: params[:email] + unregistered_email: params[:email].downcase ) end end diff --git a/app/controllers/admin/research_groups_controller.rb b/app/controllers/admin/research_groups_controller.rb index 64bc7e317a7a5828243be4bc9eac5b181abb553f..6f0df2d0953ec97c6b1ef4124c010f7179381a7e 100644 --- a/app/controllers/admin/research_groups_controller.rb +++ b/app/controllers/admin/research_groups_controller.rb @@ -177,7 +177,7 @@ module Admin def research_group_params_with_tags params.require(:research_group).permit( - research_group_params_keys + [tags: %i[id name _destroy]] + research_group_params_keys + [tags: []] ) end @@ -188,7 +188,7 @@ module Admin end def research_group_update_tags - update_tags(research_group_params_with_tags, @research_group) + update_tags_selectize(research_group_params_with_tags, @research_group) end def update_programmes diff --git a/app/controllers/admin/themes_controller.rb b/app/controllers/admin/themes_controller.rb index ec13f241a1e9dad56f9d95ccc01eeba84d982dd5..914b2ce8061cffca686fb1c239f7c8c42e7749e1 100644 --- a/app/controllers/admin/themes_controller.rb +++ b/app/controllers/admin/themes_controller.rb @@ -155,12 +155,12 @@ module Admin def theme_params_with_tags params.require(:theme).permit( - theme_params_keys + [tags: %i[id name _destroy]] + theme_params_keys + [tags: []] ) end def theme_update_tags - update_tags(theme_params_with_tags, @theme) + update_tags_selectize(theme_params_with_tags, @theme) end end end diff --git a/app/controllers/admin/thesis_projects_controller.rb b/app/controllers/admin/thesis_projects_controller.rb index 097a4a5077ab21df1f5f8db28e0674735b84a381..e6a97eb81330c0f71cf87c1b707d30890eae2b6d 100644 --- a/app/controllers/admin/thesis_projects_controller.rb +++ b/app/controllers/admin/thesis_projects_controller.rb @@ -180,12 +180,12 @@ module Admin def thesis_project_params_with_tags params.require(:thesis_project).permit( - thesis_project_params_keys + [tags: %i[id name _destroy]] + thesis_project_params_keys + [tags: []] ) end def thesis_project_update_tags - update_tags(thesis_project_params_with_tags, @thesis_project) + update_tags_selectize(thesis_project_params_with_tags, @thesis_project) end end end diff --git a/app/controllers/companies/role_invitations_controller.rb b/app/controllers/companies/role_invitations_controller.rb index c3acb8e1ffa3996f9e383b8af1490fedd4b65745..622144317e7d305ddbdd90f188562c9208b9d073 100644 --- a/app/controllers/companies/role_invitations_controller.rb +++ b/app/controllers/companies/role_invitations_controller.rb @@ -6,7 +6,7 @@ module Companies load_and_authorize_resource :company def create - email = role_invitation_params[:email].strip + email = role_invitation_params[:email].strip.downcase match = email.match(/^.+ <(.+@.+\.[\w\-]+)>/) email = match[1] if match diff --git a/app/controllers/concerns/tag_updateable.rb b/app/controllers/concerns/tag_updateable.rb index 83991fb880feefee30b7bfe0f8d3cfc8cf5791aa..44d5aa3c6123eb9f6c9d40b9ff8710bf31f273b5 100644 --- a/app/controllers/concerns/tag_updateable.rb +++ b/app/controllers/concerns/tag_updateable.rb @@ -24,4 +24,53 @@ module TagUpdateable end failed end + + # @param [ActionController::Parameters] params_with_tags the params that includes tags in the :tags property + # @param [Object] taggable the object that is taggable + # @return [Array] the failed ids + def update_tags_selectize(params_with_tags, taggable) + failed = [] + tags = params_with_tags[:tags]&.map(&:downcase)&.to_set || [] + existing_taggings = Tagging.includes(:tag).where(taggable: taggable) + + # delete taggings that have been removed + delete_removed_taggings(failed, existing_taggings, tags) + + # create newly-added taggings + create_new_taggings(failed, existing_taggings, tags, taggable) + + failed + end + + private + + def delete_removed_taggings(failed, existing_taggings, tags) + existing_taggings.each do |tagging| + next if tags.include?(tagging.tag.name) + + destroyed = tagging.destroy + failed << tagging.tag.name unless destroyed + end + end + + def create_new_taggings(failed, existing_taggings, tags, taggable) + existing_tags = existing_taggings.map { |t| t.tag.name }.to_set + tags.each do |tag| + next if existing_tags.include?(tag) || tag.blank? + + t = Tag.find_by(name: tag) + unless t + t = Tag.new(name: tag) + saved = t.save + unless saved + failed << tag + next + end + end + + tagging = Tagging.new(tag: t, taggable: taggable) + saved = tagging.save + failed << tag unless saved + end + end end diff --git a/app/controllers/projects/student_preferences_controller.rb b/app/controllers/projects/student_preferences_controller.rb index 55ba9057c8639f60320257aebdc276c227c0dbbd..48d5259e31bb9ceb316384fbda5a115729f4d37f 100644 --- a/app/controllers/projects/student_preferences_controller.rb +++ b/app/controllers/projects/student_preferences_controller.rb @@ -5,7 +5,7 @@ module Projects before_action :check_modifiable def create - email = params[:email] + email = params[:email].downcase return unless email limit = @course_edition.configuration.student_preference_count @@ -37,7 +37,7 @@ module Projects def destroy # If there is no id and email is present, look up by email if params[:id] == '-1' && params[:email].present? - student = User.find_by(email: params[:email]) + student = User.find_by(email: params[:email].lower) # If the student does not exist, we expect an error, which is what we want. @student_preference = StudentPreference.find_by(user_id: current_user.id, student_id: student.id, course_edition_id: @course_edition.id) else diff --git a/app/controllers/projects_controller.rb b/app/controllers/projects_controller.rb index 0f49bc146e788614209a91e202c23b8ed41b9d2a..939b912ea25d2c5944c96d5556e0e08c0d83a0ad 100644 --- a/app/controllers/projects_controller.rb +++ b/app/controllers/projects_controller.rb @@ -332,7 +332,7 @@ class ProjectsController < ApplicationController def fill_role_assignments(role_hash, specific_params) specific_params[:course_specific_role_selection]&.each do |csr| csr_id = csr.second[:id] - csr_user_email = csr.second[:email] + csr_user_email = csr.second[:email].downcase csr_user_name = csr.second[:name] csr_user_email.strip! # trim spaces from the email if csr_id.nil? || csr_user_email.nil? || csr_user_name.nil? diff --git a/app/helpers/actable_helper.rb b/app/helpers/actable_helper.rb index 198b29b73d54fa6b4bb5b14a5198ce13954c77d9..af5bee21bc45c7ed49f2748bf7f6296ca0930cd6 100644 --- a/app/helpers/actable_helper.rb +++ b/app/helpers/actable_helper.rb @@ -20,12 +20,7 @@ module ActableHelper raise StandardError, "Unable to reroute project_path for project='#{project}', args='#{args}'" \ end - specific = project.specific - if specific.nil? - raise StandardError, "Invalid project with actable=nil: #{project}" - end - - send("#{specific.model_name.name.underscore}_path".to_s, specific, *args) + send("#{project.actable_type.underscore}_path", project.actable_id, *args) end def project_url(project, *args) @@ -33,12 +28,7 @@ module ActableHelper raise StandardError, "Unable to reroute project_url for project='#{project}', args='#{args}'" \ end - specific = project.specific - if specific.nil? - raise StandardError, "Invalid project with actable=nil: #{project}" - end - - send("#{specific.model_name.name.underscore}_url".to_s, specific, *args) + send("#{project.actable_type.underscore}_url", project.actable_id, *args) end def edit_project_path(project, *args) @@ -46,12 +36,7 @@ module ActableHelper raise StandardError, "Unable to reroute edit_project_path for project='#{project}', args='#{args}'" end - specific = project.specific - if specific.nil? - raise StandardError, "Invalid project with actable=nil: #{project}" - end - - send("edit_#{specific.model_name.name.underscore}_path".to_s, specific, *args) + send("edit_#{project.actable_type.underscore}_path", project.actable_id, *args) end def edit_project_url(project, *args) @@ -59,12 +44,7 @@ module ActableHelper raise StandardError, "Unable to reroute edit_project_url for project='#{project}', args='#{args}'" end - specific = project.specific - if specific.nil? - raise StandardError, "Invalid project with actable=nil: #{project}" - end - - send("edit_#{specific.model_name.name.underscore}_url".to_s, specific, *args) + send("edit_#{project.actable_type.underscore}_url", project.actable_id, *args) end def new_project_path(*args) @@ -85,12 +65,7 @@ module ActableHelper raise StandardError, "Unable to reroute course_edition_project_path for project='#{project}', args='#{args}'" \ end - specific = project.specific - if specific.nil? - raise StandardError, "Invalid project with actable=nil: #{project}" - end - - send("course_edition_#{specific.model_name.name.underscore}_path".to_s, course_edition, specific, *args) + send("course_edition_#{project.actable_type.underscore}_path", course_edition, project.actable_id, *args) end def course_edition_project_url(course_edition, project, *args) @@ -100,12 +75,7 @@ module ActableHelper raise StandardError, "Unable to reroute course_edition_project_url for project='#{project}', args='#{args}'" \ end - specific = project.specific - if specific.nil? - raise StandardError, "Invalid project with actable=nil: #{project}" - end - - send("course_edition_#{specific.model_name.name.underscore}_url".to_s, course_edition, specific, *args) + send("course_edition_#{project.actable_type.underscore}_url", course_edition, project.actable_id, *args) end # ----------------------------------------------------------------------------------------------- @@ -119,12 +89,7 @@ module ActableHelper raise StandardError, "Unable to reroute admin_project_path for project='#{project}', args='#{args}'" \ end - specific = project.specific - if specific.nil? - raise StandardError, "Invalid project with actable=nil: #{project}" - end - - send("admin_#{specific.model_name.name.underscore}_path".to_s, specific, *args) + send("admin_#{project.actable_type.underscore}_path", project.actable_id, *args) end def admin_project_url(project, *args) @@ -135,12 +100,7 @@ module ActableHelper raise StandardError, "Unable to reroute admin_project_url for project='#{project}', args='#{args}'" \ end - specific = project.specific - if specific.nil? - raise StandardError, "Invalid project with actable=nil: #{project}" - end - - send("admin_#{specific.model_name.name.underscore}_url".to_s, specific, *args) + send("admin_#{project.actable_type.underscore}_url", project.actable_id, *args) end def edit_admin_project_path(project, *args) @@ -150,12 +110,7 @@ module ActableHelper raise StandardError, "Unable to reroute edit_admin_project_path for project='#{project}', args='#{args}'" end - specific = project.specific - if specific.nil? - raise StandardError, "Invalid project with actable=nil: #{project}" - end - - send("edit_admin_#{specific.model_name.name.underscore}_path".to_s, specific, *args) + send("edit_admin_#{project.actable_type.underscore}_path", project.actable_id, *args) end def edit_admin_project_url(project, *args) @@ -165,12 +120,7 @@ module ActableHelper raise StandardError, "Unable to reroute edit_admin_project_url for project='#{project}', args='#{args}'" end - specific = project.specific - if specific.nil? - raise StandardError, "Invalid project with actable=nil: #{project}" - end - - send("edit_admin_#{specific.model_name.name.underscore}_url".to_s, specific, *args) + send("edit_admin_#{project.actable_type.underscore}_url", project.actable_id, *args) end def new_admin_project_path(*args) @@ -199,12 +149,7 @@ module ActableHelper raise StandardError, "Unable to reroute admin_offerer_path for offerer='#{offerer}', args='#{args}'" \ end - specific = offerer.specific - if specific.nil? - raise StandardError, "Invalid offerer with actable=nil: #{offerer}" - end - - send("admin_#{specific.model_name.name.underscore}_path".to_s, specific, *args) + send("admin_#{offerer.actable_type.underscore}_path", offerer.actable_id, *args) end def admin_offerer_url(offerer, *args) @@ -214,11 +159,6 @@ module ActableHelper raise StandardError, "Unable to reroute admin_offerer_url for offerer='#{offerer}', args='#{args}'" \ end - specific = offerer.specific - if specific.nil? - raise StandardError, "Invalid offerer with actable=nil: #{offerer}" - end - - send("admin_#{specific.model_name.name.underscore}_url".to_s, specific, *args) + send("admin_#{offerer.actable_type.underscore}_url", offerer.actable_id, *args) end end diff --git a/app/models/concerns/user_concerns/associatable.rb b/app/models/concerns/user_concerns/associatable.rb index 7bf2c293dc3e1ea60b4c42c2a65b388520ed6fd2..d70ab8a94f4d0cc279261957080b09c85aecc2be 100644 --- a/app/models/concerns/user_concerns/associatable.rb +++ b/app/models/concerns/user_concerns/associatable.rb @@ -318,19 +318,17 @@ module UserConcerns end def active_offerer_projects(offerer_type = nil) - Project.where(id: cliented_projects).or(Project.where(offerer_id: involved_offerers)) - .where(offerer_id: Offerer.with_type(offerer_type)) - .active - .joins(:course_edition) - .where(course_editions: { id: CourseEdition.active }) + offerer_projects(offerer_type) + .active + .joins(:course_edition) + .where(course_editions: { id: CourseEdition.active }) end def archived_offerer_projects(offerer_type = nil) - Project.where(id: cliented_projects).or(Project.where(offerer_id: involved_offerers)) - .where(offerer_id: Offerer.with_type(offerer_type)) - .active - .joins(:course_edition) - .where(course_editions: { id: CourseEdition.inactive }) + offerer_projects(offerer_type) + .joins(:course_edition) + .where(course_editions: { id: CourseEdition.inactive }) + .or(offerer_projects(offerer_type).deactivated) end def show_projects? diff --git a/app/models/tag.rb b/app/models/tag.rb index ff618b7c4a678450e6a9ea7c56a2396b00aed6b9..ffbede84f66dc2f0b7463fdb780e096c098e1a30 100644 --- a/app/models/tag.rb +++ b/app/models/tag.rb @@ -11,4 +11,8 @@ class Tag < ApplicationRecord def destroy_if_unassociated destroy if taggings.empty? end + + scope :regular, (lambda { + where('name NOT LIKE \'%:%\'') + }) end diff --git a/app/views/admin/projects/edit/_project_form.html.erb b/app/views/admin/projects/edit/_project_form.html.erb index 201e7252ee250a70604342985daf52acd3ef5d75..5ccadfc9ddbf857e2ca0f91090dbcc5c409c3221 100644 --- a/app/views/admin/projects/edit/_project_form.html.erb +++ b/app/views/admin/projects/edit/_project_form.html.erb @@ -38,14 +38,42 @@ <%# This code here may seem complex, but it had to be optimized due to ridiculous loading time of the edit page. %> <% types = [ResearchGroup.model_name, Company.model_name, User.model_name] %> <% human_types = types.map { |type| t("projects.form.offerer.types.#{type.param_key}.name") } %> - <% offerers = Offerer.sorted_for_collection(types: types.map(&:name), elements: %i[id name]) %> - <%= f.grouped_collection_select :offerer_id, - [0, 1, 2], - ->(type) { offerers[type] }, - ->(type) { human_types[type] }, - :first, :second, - { required: true, selected: f.object.offerer_id }, - class: 'selectize', placeholder: t('projects.form.offerer.types_placeholder') %> + <% offerers = Offerer.sorted_for_collection(types: types.map(&:name), elements: %i[id name email]) %> + <%= f.grouped_collection_select :offerer_id, + [0, 1, 2], + ->(type) { offerers[type] }, + ->(type) { human_types[type] }, + :first, ->(o) { [o.second, o.third] }, + { required: true, selected: f.object.offerer_id }, + placeholder: t('projects.form.offerer.types_placeholder') %> + + <script type="text/javascript"> + $(document).on('turbolinks:load', function () { + let renderFunction = function (data, escape) { + let u = JSON.parse(data.text); + return '<div class="option">' + + '<span>' + escape(u[0]) + '</span><br>' + + '<span class="text-muted">' + escape(u[1]) + '</span>' + + '</div>'; + }; + + $('#generic_project_offerer_id').selectize({ + sortField: 'text', + render: { + item: renderFunction, + option: renderFunction + } + }); + }); + + $(document).on('turbolinks:before-cache', function () { + $('#generic_project_offerer_id').each(function () { + if (this.selectize !== undefined) { + this.selectize.destroy(); + } + }); + }); + </script> </td> </tr> <tr> diff --git a/app/views/admin/projects/show/_information.html.erb b/app/views/admin/projects/show/_information.html.erb index 61b85b2245754a57354ed4e7e7715378b78f97f8..9c836fbc70c484df59bd511925969a3b0349dc86 100644 --- a/app/views/admin/projects/show/_information.html.erb +++ b/app/views/admin/projects/show/_information.html.erb @@ -166,7 +166,13 @@ <% end %> <tr> <td><strong> <%= Project.human_attribute_name :offerer %> </strong></td> - <td> <%= link_to @project.offerer.name, admin_offerer_path(@project.offerer) %></td> + <td> + <%= link_to @project.offerer.name, admin_offerer_path(@project.offerer) %> + <div class="text-muted"> + <%= @project.offerer.actable_type %>, + <%= @project.offerer.email %> + </div> + </td> </tr> <tr> <td><strong> <%= Project.human_attribute_name :course_edition %> </strong></td> diff --git a/app/views/admin/research_groups/_form.html.erb b/app/views/admin/research_groups/_form.html.erb index 9d33b8dd7acb81c85a2229f1ee87d5d618a82aa9..902af23180f80fa2e4c0d3febd95cf862d9b9d52 100644 --- a/app/views/admin/research_groups/_form.html.erb +++ b/app/views/admin/research_groups/_form.html.erb @@ -2,98 +2,90 @@ <%= f.text_field :name %> <%= f.text_field :sso_name, label: raw( - t('activerecord.attributes.research_group.sso_name') + ' ' + - popover('Used to automatically link users to the research group based on the information from the TU Delft single sign on.')) %> - <%= f.grouped_collection_select :department_id, - Faculty.sort_by_name, - ->(faculty) { faculty.departments.sort_by_name }, :name, - :id, :name, - { prompt: true, required: true }, - { class: 'selectize', placeholder: 'Select a department' } %> + t('activerecord.attributes.research_group.sso_name') + ' ' + + popover('Used to automatically link users to the research group based on the information from the TU Delft single sign on.')) %> + <%= f.grouped_collection_select :department_id, + Faculty.sort_by_name, + ->(faculty) { faculty.departments.sort_by_name }, :name, + :id, :name, + { prompt: true, required: true }, + { class: 'selectize', placeholder: 'Select a department' } %> <%= f.text_field :email %> - <%= f.text_area :description, required: true, class: 'toastui-editor-init', 'data-height': '400px' %> - - <div class="panel panel-default"> - <div class="panel-heading"> - <h3 class="panel-title"> - <%= icon :fas, :image %> <%= Image.model_name.human(count: 2) %> - </h3> - </div> - - <div class="list-group cocoon"> - - <%= f.fields_for :images do |image| %> - <%= render 'general/image_fields', f: image %> - <% end %> + <%= + f.collection_select( + :tags, + Tag.regular.sort_by_name, :name, :name, + { label: raw(Tag.model_name.human(count: 2) + ' ' + popover(t('admin.themes.tags.explanation'))), + selected: @research_group.tags.map(&:name) }, + { multiple: true, placeholder: 'Add relevant tags...' } + ) + %> + + <script> + $('#research_group_tags').selectize({ + plugins: ['remove_button'], + delimiter: ',', + persist: false, + create: function (input) { + return { + value: input, + text: input, + }; + } + }); + </script> - <%= link_to_add_association( - glyphicon_text('plus-sign', "Add #{Image.model_name.human}"), - f, - :images, - partial: 'general/image_fields', - class: 'list-group-item list-group-item--button', - 'data-association-insertion-node' => 'this' - ) %> + <%= f.text_area :description, required: true, class: 'toastui-editor-init', 'data-height': '400px' %> - </div> - </div> - <div class="row"> - <div class="col-sm-6"> - <div class="panel panel-default"> - <div class="panel-heading"> - <h3 class="panel-title" id="tags"> - <%= glyphicon :tags %> <%= Tag.model_name.human(count: 2) %> - </h3> - </div> + <div class="row"> + <div class="col-sm-6"> + <div class="panel panel-default"> + <div class="panel-heading"> + <h3 class="panel-title"> + <%= icon :fas, :image %> <%= Image.model_name.human(count: 2) %> + </h3> + </div> - <div class="list-group cocoon"> + <div class="list-group cocoon"> - <%= f.fields_for :tags do |f_tags| %> - <% @research_group.tags.each do |tag| %> - <%= f_tags.fields_for tag.id.to_s, tag do |f_tag| %> - <%= render 'admin/application/tag_fields', f: f_tag %> - <% end %> - <% end %> + <%= f.fields_for :images do |image| %> + <%= render 'general/image_fields', f: image %> + <% end %> - <a class="list-group-item list-group-item--button add_fields" data-association-insertion-node="this" - data-association="tag" data-associations="tags" id="tag_add" - data-association-insertion-template=" - <%= CGI.escapeHTML(render_association('new_tags', - f_tags, - Tag.new, - 'f', - { wrapper: 'inline' }, - 'admin/application/tag_fields_new').to_str).html_safe %> - " href="#"> - <%= glyphicon_text('plus-sign', "Add #{Tag.model_name.human}") %> - </a> - <% end %> + <%= link_to_add_association( + glyphicon_text('plus-sign', "Add #{Image.model_name.human}"), + f, + :images, + partial: 'general/image_fields', + class: 'list-group-item list-group-item--button', + 'data-association-insertion-node' => 'this' + ) %> - </div> </div> </div> - <div class="col-sm-6"> - <div class="panel panel-default"> - <div class="panel-heading"> - <h3 class="panel-title"> - <%= icon :fas, :university %> Associated Programmes - </h3> - </div> + </div> + <div class="col-sm-6"> + <div class="panel panel-default"> + <div class="panel-heading"> + <h3 class="panel-title"> + <%= icon :fas, :university %> Associated Programmes + </h3> + </div> - <div class="list-group cocoon"> + <div class="list-group cocoon"> - <%= f.fields_for :programmes do |f_programmes| %> - <% @research_group.programmes.each do |programme| %> - <%= f_programmes.fields_for programme.id.to_s, programme do |f_programme| %> - <%= render 'programme_fields', f: f_programme %> - <% end %> + <%= f.fields_for :programmes do |f_programmes| %> + <% @research_group.programmes.each do |programme| %> + <%= f_programmes.fields_for programme.id.to_s, programme do |f_programme| %> + <%= render 'programme_fields', f: f_programme %> <% end %> + <% end %> - <a class="list-group-item list-group-item--button add_fields" data-association-insertion-node="this" - data-association="programme" data-associations="programmes" id="programme_add" - data-association-insertion-template=" + <a class="list-group-item list-group-item--button add_fields" data-association-insertion-node="this" + data-association="programme" data-associations="programmes" id="programme_add" + data-association-insertion-template=" <%= CGI.escapeHTML(render_association('new_programmes', f_programmes, Programme.new, @@ -101,15 +93,15 @@ { wrapper: 'inline' }, 'programme_fields').to_str).html_safe %> " href="#"> - <%= glyphicon_text('plus-sign', 'Add Associated Programme') %> - </a> - <% end %> + <%= glyphicon_text('plus-sign', 'Add Associated Programme') %> + </a> + <% end %> - </div> </div> </div> </div> + </div> - <% cancel_path = @research_group.persisted? ? admin_research_group_path(@research_group) : admin_research_groups_path %> - <%= render 'admin/application/form_buttons', f: f, cancel_path: cancel_path %> + <% cancel_path = @research_group.persisted? ? admin_research_group_path(@research_group) : admin_research_groups_path %> + <%= render 'admin/application/form_buttons', f: f, cancel_path: cancel_path %> <% end %> diff --git a/app/views/admin/themes/_form.html.erb b/app/views/admin/themes/_form.html.erb index 154abc9e4b770334bfecad92b21b88b7406587c3..6097a731d45b46ac716a04c71821f65fc6ec8888 100644 --- a/app/views/admin/themes/_form.html.erb +++ b/app/views/admin/themes/_form.html.erb @@ -6,6 +6,30 @@ { required: true, prompt: true }, class: 'selectize' %> + <%= + f.collection_select( + :tags, + Tag.regular.sort_by_name, :name, :name, + { label: raw(Tag.model_name.human(count: 2) + ' ' + popover(t('admin.themes.tags.explanation'))), + selected: @theme.tags.map(&:name) }, + { multiple: true, placeholder: 'Add relevant tags...' } + ) + %> + + <script> + $('#theme_tags').selectize({ + plugins: ['remove_button'], + delimiter: ',', + persist: false, + create: function (input) { + return { + value: input, + text: input, + }; + } + }); + </script> + <%= f.text_area :description, required: true, class: 'toastui-editor-init', 'data-height': '400px' %> <div class="panel panel-default"> @@ -54,41 +78,6 @@ </div> </div> - <div class="panel panel-default"> - - <div class="panel-heading"> - <h3 class="panel-title" id="tags"> - <%= glyphicon :tags %> <%= Tag.model_name.human(count: 2) %> - <%= popover t('admin.themes.tags.explanation') %> - </h3> - </div> - - <div class="list-group cocoon"> - - <%= f.fields_for :tags do |f_tags| %> - <% @theme.tags.each do |tag| %> - <%= f_tags.fields_for tag.id.to_s, tag do |f_tag| %> - <%= render 'admin/application/tag_fields', f: f_tag %> - <% end %> - <% end %> - - <a class="list-group-item list-group-item--button add_fields" data-association-insertion-node="this" - data-association="tag" data-associations="tags" id="tag_add" - data-association-insertion-template=" - <%= CGI.escapeHTML(render_association('new_tags', - f_tags, - Tag.new, - 'f', - { wrapper: 'inline' }, - 'admin/application/tag_fields_new').to_str).html_safe %> - " href="#"> - <%= glyphicon_text('plus-sign', "Add #{Tag.model_name.human}") %> - </a> - <% end %> - - </div> - </div> - <% cancel_path = @theme.persisted? ? admin_theme_path(@theme) : admin_research_groups_path %> <%= render 'admin/application/form_buttons', f: f, cancel_path: cancel_path %> <% end %> diff --git a/app/views/admin/thesis_projects/_form.html.erb b/app/views/admin/thesis_projects/_form.html.erb index 8fdae4e063faf06bcdc742fe8eea1cadc8beb27d..f235c0d0c251706df2af2c5971ceb0168bfe51ca 100644 --- a/app/views/admin/thesis_projects/_form.html.erb +++ b/app/views/admin/thesis_projects/_form.html.erb @@ -14,6 +14,30 @@ { required: true, prompt: CourseEdition.supporting_thesis_projects.count > 1 }, { class: 'selectize', multiple: true } %> + <%= + f.collection_select( + :tags, + Tag.regular.sort_by_name, :name, :name, + { label: raw(Tag.model_name.human(count: 2) + ' ' + popover(t('admin.thesis_projects.tags.explanation'))), + selected: @thesis_project.tags.map(&:name) }, + { multiple: true, placeholder: 'Add relevant tags...' } + ) + %> + + <script> + $('#thesis_project_tags').selectize({ + plugins: ['remove_button'], + delimiter: ',', + persist: false, + create: function (input) { + return { + value: input, + text: input, + }; + } + }); + </script> + <%= f.text_area :description, required: true, class: 'toastui-editor-init' %> <div class="panel panel-default"> @@ -37,41 +61,6 @@ </div> </div> - <div class="panel panel-default"> - - <div class="panel-heading"> - <h3 class="panel-title" id="tags"> - <%= glyphicon :tags %> <%= Tag.model_name.human(count: 2) %> - <%= popover t('admin.thesis_projects.tags.explanation') %> - </h3> - </div> - - <div class="list-group cocoon"> - - <%= f.fields_for :tags do |f_tags| %> - <% @thesis_project.tags.each do |tag| %> - <%= f_tags.fields_for tag.id.to_s, tag do |f_tag| %> - <%= render 'admin/application/tag_fields', f: f_tag %> - <% end %> - <% end %> - - <a class="list-group-item list-group-item--button add_fields" data-association-insertion-node="this" - data-association="tag" data-associations="tags" id="tag_add" - data-association-insertion-template=" - <%= CGI.escapeHTML(render_association('new_tags', - f_tags, - Tag.new, - 'f', - { wrapper: 'inline' }, - 'admin/application/tag_fields_new').to_str).html_safe %> - " href="#"> - <%= glyphicon_text('plus-sign', "Add #{Tag.model_name.human}") %> - </a> - <% end %> - - </div> - </div> - <% cancel_path = @thesis_project.persisted? ? admin_thesis_project_path(@thesis_project) : admin_thesis_projects_path %> <%= render 'admin/application/form_buttons', f: f, cancel_path: cancel_path %> <% end %> diff --git a/app/views/admin/users/_user_selection_dropdown.erb b/app/views/admin/users/_user_selection_dropdown.erb index 2013ad825f46b5d6d5ce7cb9ea34be1c7963dfc3..9099448cd45e95d0f73e657432f7e95f73984aba 100644 --- a/app/views/admin/users/_user_selection_dropdown.erb +++ b/app/views/admin/users/_user_selection_dropdown.erb @@ -21,7 +21,7 @@ '</div>'; }; - let dropdown = $('#user_selection_dropdown_<%= unique_id %>').selectize({ + $('#user_selection_dropdown_<%= unique_id %>').selectize({ sortField: 'text', render: { 'option_create': function (data, escape) { @@ -36,10 +36,16 @@ $('#ldapModal_<%= unique_id %>').modal('show') return false } - })[0].selectize - - dropdown.refreshOptions(false) + }); }) + + $(document).on('turbolinks:before-cache', function () { + $('#user_selection_dropdown_<%= unique_id %>').each(function () { + if (this.selectize !== undefined) { + this.selectize.destroy(); + } + }); + }); </script> <%= form.grouped_collection_select field_id, diff --git a/app/views/companies/_form.html.erb b/app/views/companies/_form.html.erb index e2fa8d5422543de41c58e17c9c35a8e2061696ab..914ec68c4db3a0d9cc77760455311b4e31f42eb1 100644 --- a/app/views/companies/_form.html.erb +++ b/app/views/companies/_form.html.erb @@ -65,5 +65,5 @@ ) %> </div> <%= f.submit value: "#{f.object.new_record? ? 'Create' : 'Update'} #{company_name.capitalize}", class: 'btn btn-primary' %> - <%= link_to 'Cancel', url_for(company), class: 'btn btn-default' unless no_cancel %> + <%= link_to 'Cancel', f.object.new_record? ? companies_url : offerer_url(company.acting_as), class: 'btn btn-default' unless no_cancel %> <% end %> diff --git a/config/locales/views/en.yml b/config/locales/views/en.yml index 93452ba7d41cfbfbde16a8e3debaa9fb9f192857..63757b1e5f2c9c4a8334dd112675a1b233cdfd3a 100644 --- a/config/locales/views/en.yml +++ b/config/locales/views/en.yml @@ -45,7 +45,7 @@ Please have a look before submitting a proposal: filters: all: All %{projects_name} active: Current %{projects_name} - inactive: Archived %{projects_name} + inactive: Inactive and archived %{projects_name} supervisor: no_project_notice: There are no %{projects_name} where you are linked as a supervisor. project_explanation: These are all the %{projects_name} where you are linked as a supervisor. @@ -154,14 +154,14 @@ will be assigned to all members of the group on the 'students' sheet automatical explanation: Users listed here will receive emails from interested students and/OR will be listed on the theme. tags: label: Tags - explanation: Tags affect seaches by students and are used for auto completion. Add relevant keywords, courses, etc. as tags to improve searchability. + explanation: Tags affect searches by students and are used for auto completion. Add relevant keywords, courses, etc. as tags to improve searchability. You can also add tags that don't exist yet by typing. thesis_projects: associated_users: label: Associated Users explanation: Users listed here will receive emails from interested students and/OR will be listed on the thesis project. tags: label: Tags - explanation: Tags affect seaches by students and are used for auto completion. Add relevant keywords, courses, etc. as tags to improve searchability. + explanation: Tags affect searches by students and are used for auto completion. Add relevant keywords, courses, etc. as tags to improve searchability. You can also add tags that don't exist yet by typing. companies: show: employees: diff --git a/config/locales/views/nl.yml b/config/locales/views/nl.yml index b11b10fd1fb6863df7656f1b960419e19fe21654..e69c0bf5a5234f96555ab9cf411deaae537f6bc6 100644 --- a/config/locales/views/nl.yml +++ b/config/locales/views/nl.yml @@ -46,7 +46,7 @@ Zou u deze willen lezen voor u een voorstel indient: filters: all: Alle %{projects_name} active: Huidige %{projects_name} - inactive: Geärchiveerde %{projects_name} + inactive: Inactieve en geärchiveerde %{projects_name} supervisor: no_project_notice: Er zijn geen %{projects_name} waar u als begeleider bent gekoppeld. project_explanation: Dit zijn de %{projects_name} waar u als begeleider bent gekoppeld. @@ -161,14 +161,14 @@ worden dan automatisch toegekend aan alle leden van de groep op de 'students' sh explanation: Gebruikers in deze lijst ontvangen emails van geïnteresseerde studenten en/of worden genoemd als onderzoekers bij het thema. tags: label: Labels - explanation: Labels hebben effect op zoekopdrachten bij studenten en worden gebruikt voor automatisch aanvullen van zoektermen. Voeg relevante kernwoorden, vakken, etc. toe als labels om vindbaarheid te verbeteren. + explanation: Labels hebben effect op zoekopdrachten bij studenten en worden gebruikt voor automatisch aanvullen van zoektermen. Voeg relevante kernwoorden, vakken, etc. toe als labels om vindbaarheid te verbeteren. U kunt ook nieuwe labels maken door deze in te typen. thesis_projects: associated_users: label: Gekoppelde Gebruikers explanation: Gebruikers in deze lijst ontvangen emails van geïnteresseerde studenten en/of worden genoemd als onderzoekers bij het thesis project. tags: label: Labels - explanation: Labels hebben effect op zoekopdrachten bij studenten en worden gebruikt voor automatisch aanvullen van zoektermen. Voeg relevante kernwoorden, vakken, etc. toe als labels om vindbaarheid te verbeteren. + explanation: Labels hebben effect op zoekopdrachten bij studenten en worden gebruikt voor automatisch aanvullen van zoektermen. Voeg relevante kernwoorden, vakken, etc. toe als labels om vindbaarheid te verbeteren. U kunt nieuwe labels maken door deze in te typen. companies: show: employees: diff --git a/db/migrate/20220830133912_downcase_emails.rb b/db/migrate/20220830133912_downcase_emails.rb new file mode 100644 index 0000000000000000000000000000000000000000..d8cb600541fdb6d6f26ad4f9b6466faaee19548d --- /dev/null +++ b/db/migrate/20220830133912_downcase_emails.rb @@ -0,0 +1,35 @@ +class DowncaseEmails < ActiveRecord::Migration[6.1] + def up + UserCourseSpecificRole.where('1=1').each do |ucsr| + next unless ucsr.unregistered_email + + downcased = ucsr.unregistered_email.downcase + + next if downcased == ucsr.unregistered_email + + ucsr.unregistered_email = downcased + ucsr.save! + + User.find_by(email: downcased)&.send(:assign_to_course_specific_roles) + end + + RoleInvitation.where('1=1').each do |ri| + next unless ri.email + + downcased = ri.email.downcase + + next if downcased == ri.email + + ri.email = downcased + + u = User.find_by(email: downcased) + ri.user = u if u + + ri.save! + end + end + + def down + # reverting is impossible and unnecessary + end +end diff --git a/db/schema.rb b/db/schema.rb index cbac363cdceda61bd33b501c4ff91dc0748612f9..0f740f746a0ef11f247641b096512a7828d47ccb 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 2022_08_21_102031) do +ActiveRecord::Schema.define(version: 2022_08_30_133912) do create_table "active_storage_attachments", force: :cascade do |t| t.string "name", null: false