From ab22347d7be00977d46a1256a05a2b8fa1e6bb84 Mon Sep 17 00:00:00 2001 From: Josh Johnson Date: Sun, 3 Nov 2019 17:45:16 +0000 Subject: [PATCH] Code refactoring (#735) * Add placeholder options to demo page * Use constant types in components * Refactor adding predefined groups/items/choices * Add 'highlighted' flag to Item type * Fix dispatch param type * Build * Add jsdoc comments to utils * Remove unused file * Add default values to js doc comments * Use Redux Action type * Housekeeping * Increase utils coverage * Apply suggestions from code review * Add _getTemplate unit tests --- package-lock.json | 66 +- package.json | 1 + public/assets/scripts/choices.js | 1394 ++++++++++++++++---------- public/assets/scripts/choices.min.js | 2 +- public/index.html | 32 +- src/scripts/actions/choices.js | 9 +- src/scripts/actions/groups.js | 3 +- src/scripts/actions/items.js | 7 +- src/scripts/actions/misc.js | 10 +- src/scripts/choices.js | 213 ++-- src/scripts/choices.test.js | 33 +- src/scripts/components/container.js | 5 +- src/scripts/components/input.js | 3 +- src/scripts/components/list.js | 2 +- src/scripts/lib/delegate-events.js | 45 - src/scripts/lib/utils.js | 124 ++- src/scripts/lib/utils.test.js | 49 +- src/scripts/store/store.js | 2 +- types/index.d.ts | 5 +- 19 files changed, 1198 insertions(+), 807 deletions(-) delete mode 100644 src/scripts/lib/delegate-events.js diff --git a/package-lock.json b/package-lock.json index b23b218..d9683ae 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1944,7 +1944,7 @@ }, "browserify-aes": { "version": "1.2.0", - "resolved": "http://registry.npmjs.org/browserify-aes/-/browserify-aes-1.2.0.tgz", + "resolved": "https://registry.npmjs.org/browserify-aes/-/browserify-aes-1.2.0.tgz", "integrity": "sha512-+7CHXqGuspUn/Sl5aO7Ea0xWGAtETPXNSAjHo48JfLdPWcMng33Xe4znFvQweqc/uzk5zSOI3H52CYnjCfb5hA==", "dev": true, "requires": { @@ -1981,7 +1981,7 @@ }, "browserify-rsa": { "version": "4.0.1", - "resolved": "http://registry.npmjs.org/browserify-rsa/-/browserify-rsa-4.0.1.tgz", + "resolved": "https://registry.npmjs.org/browserify-rsa/-/browserify-rsa-4.0.1.tgz", "integrity": "sha1-IeCr+vbyApzy+vsTNWenAdQTVSQ=", "dev": true, "requires": { @@ -2026,7 +2026,7 @@ }, "buffer": { "version": "4.9.1", - "resolved": "http://registry.npmjs.org/buffer/-/buffer-4.9.1.tgz", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-4.9.1.tgz", "integrity": "sha1-bRu2AbB6TvztlwlBMgkwJ8lbwpg=", "dev": true, "requires": { @@ -2213,7 +2213,7 @@ }, "camelcase-keys": { "version": "2.1.0", - "resolved": "http://registry.npmjs.org/camelcase-keys/-/camelcase-keys-2.1.0.tgz", + "resolved": "https://registry.npmjs.org/camelcase-keys/-/camelcase-keys-2.1.0.tgz", "integrity": "sha1-MIvur/3ygRkFHvodkyITyRuPkuc=", "dev": true, "requires": { @@ -2807,7 +2807,7 @@ }, "create-hash": { "version": "1.2.0", - "resolved": "http://registry.npmjs.org/create-hash/-/create-hash-1.2.0.tgz", + "resolved": "https://registry.npmjs.org/create-hash/-/create-hash-1.2.0.tgz", "integrity": "sha512-z00bCGNHDG8mHAkP7CtT1qVu+bFQUPjYq/4Iv3C3kWjTFV10zIjfSoeqXo9Asws8gwSHDGj/hl2u4OGIjapeCg==", "dev": true, "requires": { @@ -2820,7 +2820,7 @@ }, "create-hmac": { "version": "1.1.7", - "resolved": "http://registry.npmjs.org/create-hmac/-/create-hmac-1.1.7.tgz", + "resolved": "https://registry.npmjs.org/create-hmac/-/create-hmac-1.1.7.tgz", "integrity": "sha512-MJG9liiZ+ogc4TzUwuvbER1JRdgvUFSB5+VR/g5h82fGaIRWMWddtKBHi7/sVhfjQZ6SehlyhvQYrcYkaUIpLg==", "dev": true, "requires": { @@ -3350,7 +3350,7 @@ }, "diffie-hellman": { "version": "5.0.3", - "resolved": "http://registry.npmjs.org/diffie-hellman/-/diffie-hellman-5.0.3.tgz", + "resolved": "https://registry.npmjs.org/diffie-hellman/-/diffie-hellman-5.0.3.tgz", "integrity": "sha512-kqag/Nl+f3GwyK25fhUMYj81BUOrZ9IuJsjIcDE5icNM9FJHAVm3VcUDxdLPoQtTuUylWm6ZIknYJwwaPxsUzg==", "dev": true, "requires": { @@ -3420,7 +3420,7 @@ }, "duplexer": { "version": "0.1.1", - "resolved": "http://registry.npmjs.org/duplexer/-/duplexer-0.1.1.tgz", + "resolved": "https://registry.npmjs.org/duplexer/-/duplexer-0.1.1.tgz", "integrity": "sha1-rOb/gIwc5mtX0ev5eXessCM0z8E=", "dev": true }, @@ -4092,7 +4092,7 @@ "dependencies": { "pify": { "version": "2.3.0", - "resolved": "http://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=", "dev": true } @@ -5873,7 +5873,7 @@ }, "get-stream": { "version": "3.0.0", - "resolved": "http://registry.npmjs.org/get-stream/-/get-stream-3.0.0.tgz", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-3.0.0.tgz", "integrity": "sha1-jpQ9E1jcN1VQVOy+LtsFqhdO3hQ=", "dev": true }, @@ -6038,7 +6038,7 @@ }, "got": { "version": "6.7.1", - "resolved": "http://registry.npmjs.org/got/-/got-6.7.1.tgz", + "resolved": "https://registry.npmjs.org/got/-/got-6.7.1.tgz", "integrity": "sha1-JAzQV4WpoY5WHcG0S0HHY+8ejbA=", "dev": true, "requires": { @@ -6903,7 +6903,7 @@ }, "is-obj": { "version": "1.0.1", - "resolved": "http://registry.npmjs.org/is-obj/-/is-obj-1.0.1.tgz", + "resolved": "https://registry.npmjs.org/is-obj/-/is-obj-1.0.1.tgz", "integrity": "sha1-PkcprB9f3gJc19g6iW2rn09n2w8=", "dev": true }, @@ -7866,7 +7866,7 @@ }, "load-json-file": { "version": "2.0.0", - "resolved": "http://registry.npmjs.org/load-json-file/-/load-json-file-2.0.0.tgz", + "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-2.0.0.tgz", "integrity": "sha1-eUfkIUmvgNaWy/eXvKq8/h/inKg=", "dev": true, "requires": { @@ -7887,7 +7887,7 @@ }, "pify": { "version": "2.3.0", - "resolved": "http://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=", "dev": true } @@ -8145,7 +8145,7 @@ }, "media-typer": { "version": "0.3.0", - "resolved": "http://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", "integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=", "dev": true }, @@ -8186,7 +8186,7 @@ }, "meow": { "version": "3.7.0", - "resolved": "http://registry.npmjs.org/meow/-/meow-3.7.0.tgz", + "resolved": "https://registry.npmjs.org/meow/-/meow-3.7.0.tgz", "integrity": "sha1-cstmi0JSKCkKu/qFaJJYcwioAfs=", "dev": true, "requires": { @@ -8214,7 +8214,7 @@ }, "load-json-file": { "version": "1.1.0", - "resolved": "http://registry.npmjs.org/load-json-file/-/load-json-file-1.1.0.tgz", + "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-1.1.0.tgz", "integrity": "sha1-lWkFcI1YtLq0wiYbBPWfMcmTdMA=", "dev": true, "requires": { @@ -8256,7 +8256,7 @@ }, "pify": { "version": "2.3.0", - "resolved": "http://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=", "dev": true }, @@ -8454,7 +8454,7 @@ }, "mkdirp": { "version": "0.5.1", - "resolved": "http://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", "dev": true, "requires": { @@ -8724,7 +8724,7 @@ "dependencies": { "semver": { "version": "5.3.0", - "resolved": "http://registry.npmjs.org/semver/-/semver-5.3.0.tgz", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.3.0.tgz", "integrity": "sha1-myzl094C0XxgEq0yaqa00M9U+U8=", "dev": true } @@ -9603,7 +9603,7 @@ }, "onetime": { "version": "1.1.0", - "resolved": "http://registry.npmjs.org/onetime/-/onetime-1.1.0.tgz", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-1.1.0.tgz", "integrity": "sha1-ofeDj4MUxRbwXs78vEzP4EtO14k=", "dev": true }, @@ -9653,7 +9653,7 @@ }, "ora": { "version": "0.2.3", - "resolved": "http://registry.npmjs.org/ora/-/ora-0.2.3.tgz", + "resolved": "https://registry.npmjs.org/ora/-/ora-0.2.3.tgz", "integrity": "sha1-N1J9Igrc1Tw5tzVx11QVbV22V6Q=", "dev": true, "requires": { @@ -9704,7 +9704,7 @@ }, "os-locale": { "version": "1.4.0", - "resolved": "http://registry.npmjs.org/os-locale/-/os-locale-1.4.0.tgz", + "resolved": "https://registry.npmjs.org/os-locale/-/os-locale-1.4.0.tgz", "integrity": "sha1-IPnxeuKe00XoveWDsT0gCYA8FNk=", "dev": true, "requires": { @@ -9940,7 +9940,7 @@ "dependencies": { "pify": { "version": "2.3.0", - "resolved": "http://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=", "dev": true } @@ -11770,7 +11770,7 @@ }, "safe-regex": { "version": "1.1.0", - "resolved": "http://registry.npmjs.org/safe-regex/-/safe-regex-1.1.0.tgz", + "resolved": "https://registry.npmjs.org/safe-regex/-/safe-regex-1.1.0.tgz", "integrity": "sha1-QKNmnzsHfR6UPURinhV91IAjvy4=", "dev": true, "requires": { @@ -12134,7 +12134,7 @@ }, "sha.js": { "version": "2.4.11", - "resolved": "http://registry.npmjs.org/sha.js/-/sha.js-2.4.11.tgz", + "resolved": "https://registry.npmjs.org/sha.js/-/sha.js-2.4.11.tgz", "integrity": "sha512-QMEp5B7cftE7APOjk5Y6xgrbWu+WkLVQwk8JNjZ8nKRciZaByEW6MubieAiToS7+dwvrjGhH8jRXz3MVd0AYqQ==", "dev": true, "requires": { @@ -12201,6 +12201,12 @@ "supports-color": "^5.5.0" } }, + "sinon-chai": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/sinon-chai/-/sinon-chai-3.3.0.tgz", + "integrity": "sha512-r2JhDY7gbbmh5z3Q62pNbrjxZdOAjpsqW/8yxAZRSqLZqowmfGZPGUZPFf3UX36NLis0cv8VEM5IJh9HgkSOAA==", + "dev": true + }, "slash": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", @@ -12209,7 +12215,7 @@ }, "slice-ansi": { "version": "0.0.4", - "resolved": "http://registry.npmjs.org/slice-ansi/-/slice-ansi-0.0.4.tgz", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-0.0.4.tgz", "integrity": "sha1-7b+JA/ZvfOL46v1s7tZeJkyDGzU=", "dev": true }, @@ -12629,7 +12635,7 @@ }, "strip-ansi": { "version": "3.0.1", - "resolved": "http://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", "dev": true, "requires": { @@ -12644,7 +12650,7 @@ }, "strip-eof": { "version": "1.0.0", - "resolved": "http://registry.npmjs.org/strip-eof/-/strip-eof-1.0.0.tgz", + "resolved": "https://registry.npmjs.org/strip-eof/-/strip-eof-1.0.0.tgz", "integrity": "sha1-u0P/VZim6wXYm1n80SnJgzE2Br8=", "dev": true }, @@ -12977,7 +12983,7 @@ }, "through": { "version": "2.3.8", - "resolved": "http://registry.npmjs.org/through/-/through-2.3.8.tgz", + "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", "integrity": "sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU=", "dev": true }, diff --git a/package.json b/package.json index b1abf12..20bc93d 100644 --- a/package.json +++ b/package.json @@ -84,6 +84,7 @@ "postcss-cli": "^6.1.3", "prettier": "^1.18.2", "sinon": "^7.5.0", + "sinon-chai": "^3.3.0", "webpack": "^4.41.2", "webpack-cli": "^3.3.9", "webpack-dev-middleware": "^3.7.2", diff --git a/public/assets/scripts/choices.js b/public/assets/scripts/choices.js index b748d0f..45dd55f 100644 --- a/public/assets/scripts/choices.js +++ b/public/assets/scripts/choices.js @@ -1266,34 +1266,61 @@ var general = function general(state, action) { /* harmony default export */ var reducers_general = (general); // CONCATENATED MODULE: ./src/scripts/lib/utils.js +/** + * @param {number} min + * @param {number} max + * @returns {number} + */ var getRandomNumber = function getRandomNumber(min, max) { return Math.floor(Math.random() * (max - min) + min); }; +/** + * @param {number} length + * @returns {string} + */ + var generateChars = function generateChars(length) { - var chars = ''; - - for (var i = 0; i < length; i++) { - var randomChar = getRandomNumber(0, 36); - chars += randomChar.toString(36); - } - - return chars; + return Array.from({ + length: length + }, function () { + return getRandomNumber(0, 36).toString(36); + }).join(''); }; +/** + * @param {HTMLInputElement | HTMLSelectElement} element + * @param {string} prefix + * @returns {string} + */ + var generateId = function generateId(element, prefix) { var id = element.id || element.name && element.name + "-" + generateChars(2) || generateChars(4); id = id.replace(/(:|\.|\[|\]|,)/g, ''); id = prefix + "-" + id; return id; }; +/** + * @param {any} obj + * @returns {string} + */ + var getType = function getType(obj) { return Object.prototype.toString.call(obj).slice(8, -1); }; +/** + * @param {string} type + * @param {any} obj + * @returns {boolean} + */ + var isType = function isType(type, obj) { return obj !== undefined && obj !== null && getType(obj) === type; }; -var isElement = function isElement(element) { - return element instanceof Element; -}; +/** + * @param {HTMLElement} element + * @param {HTMLElement} [wrapper={HTMLDivElement}] + * @returns {HTMLElement} + */ + var utils_wrap = function wrap(element, wrapper) { if (wrapper === void 0) { wrapper = document.createElement('div'); @@ -1315,49 +1342,79 @@ var utils_wrap = function wrap(element, wrapper) { var findAncestorByAttrName = function findAncestorByAttrName(el, attr) { return el.closest("[" + attr + "]"); }; -var getAdjacentEl = function getAdjacentEl(startEl, className, direction) { +/** + * @param {Element} startEl + * @param {string} selector + * @param {1 | -1} direction + * @returns {Element | undefined} + */ + +var getAdjacentEl = function getAdjacentEl(startEl, selector, direction) { if (direction === void 0) { direction = 1; } - if (!startEl || !className) { - return; + if (!(startEl instanceof Element) || typeof selector !== 'string') { + return undefined; } - var parent = startEl.parentNode.parentNode; - var children = Array.from(parent.querySelectorAll(className)); - var startPos = children.indexOf(startEl); - var operatorDirection = direction > 0 ? 1 : -1; - return children[startPos + operatorDirection]; + var prop = (direction > 0 ? 'next' : 'previous') + "ElementSibling"; + var sibling = startEl[prop]; + + while (sibling) { + if (sibling.matches(selector)) { + return sibling; + } + + sibling = sibling[prop]; + } + + return sibling; }; -var isScrolledIntoView = function isScrolledIntoView(el, parent, direction) { +/** + * @param {HTMLElement} element + * @param {HTMLElement} parent + * @param {-1 | 1} direction + * @returns {boolean} + */ + +var isScrolledIntoView = function isScrolledIntoView(element, parent, direction) { if (direction === void 0) { direction = 1; } - if (!el) { - return; + if (!element) { + return false; } var isVisible; if (direction > 0) { // In view from bottom - isVisible = parent.scrollTop + parent.offsetHeight >= el.offsetTop + el.offsetHeight; + isVisible = parent.scrollTop + parent.offsetHeight >= element.offsetTop + element.offsetHeight; } else { // In view from top - isVisible = el.offsetTop >= parent.scrollTop; + isVisible = element.offsetTop >= parent.scrollTop; } return isVisible; }; +/** + * @param {any} value + * @returns {any} + */ + var sanitise = function sanitise(value) { - if (!isType('String', value)) { + if (typeof value !== 'string') { return value; } return value.replace(/&/g, '&').replace(/>/g, '&rt;').replace(/\"" + sanitise(value) + "\""; + }, + maxItemText: function maxItemText(maxItemCount) { + return "Only " + maxItemCount + " values can be added"; + }, + valueComparer: function valueComparer(value1, value2) { + return value1 === value2; + }, + fuseOptions: { + includeScore: true + }, + callbackOnInit: null, + callbackOnCreateTemplates: null, + classNames: DEFAULT_CLASSNAMES +}; +var EVENTS = { + showDropdown: 'showDropdown', + hideDropdown: 'hideDropdown', + change: 'change', + choice: 'choice', + search: 'search', + addItem: 'addItem', + removeItem: 'removeItem', + highlightItem: 'highlightItem', + highlightChoice: 'highlightChoice' +}; +var ACTION_TYPES = { + ADD_CHOICE: 'ADD_CHOICE', + FILTER_CHOICES: 'FILTER_CHOICES', + ACTIVATE_CHOICES: 'ACTIVATE_CHOICES', + CLEAR_CHOICES: 'CLEAR_CHOICES', + ADD_GROUP: 'ADD_GROUP', + ADD_ITEM: 'ADD_ITEM', + REMOVE_ITEM: 'REMOVE_ITEM', + HIGHLIGHT_ITEM: 'HIGHLIGHT_ITEM', + CLEAR_ALL: 'CLEAR_ALL' +}; +var KEY_CODES = { + BACK_KEY: 46, + DELETE_KEY: 8, + ENTER_KEY: 13, + A_KEY: 65, + ESC_KEY: 27, + UP_KEY: 38, + DOWN_KEY: 40, + PAGE_UP_KEY: 33, + PAGE_DOWN_KEY: 34 +}; +var TEXT_TYPE = 'text'; +var SELECT_ONE_TYPE = 'select-one'; +var SELECT_MULTIPLE_TYPE = 'select-multiple'; +var SCROLLING_SPEED = 4; // CONCATENATED MODULE: ./src/scripts/components/container.js +/** + * @typedef {import('../../../types/index').Choices.passedElement} passedElement + * @typedef {import('../../../types/index').Choices.ClassNames} ClassNames + */ + var container_Container = /*#__PURE__*/ function () { + /** + * @param {{ + * element: HTMLElement, + * type: passedElement['type'], + * classNames: ClassNames, + * position + * }} args + */ function Container(_ref) { var element = _ref.element, type = _ref.type, classNames = _ref.classNames, position = _ref.position; - Object.assign(this, { - element: element, - classNames: classNames, - type: type, - position: position - }); + this.element = element; + this.classNames = classNames; + this.type = type; + this.position = position; this.isOpen = false; this.isFlipped = false; this.isFocussed = false; @@ -1774,42 +2006,28 @@ function () { this._onFocus = this._onFocus.bind(this); this._onBlur = this._onBlur.bind(this); } - /** - * Add event listeners - */ - var _proto = Container.prototype; _proto.addEventListeners = function addEventListeners() { this.element.addEventListener('focus', this._onFocus); this.element.addEventListener('blur', this._onBlur); - } - /** - * Remove event listeners - */ - - /** */ - ; + }; _proto.removeEventListeners = function removeEventListeners() { this.element.removeEventListener('focus', this._onFocus); this.element.removeEventListener('blur', this._onBlur); } /** - * Determine whether container should be flipped - * based on passed dropdown position - * @param {Number} dropdownPos - * @returns + * Determine whether container should be flipped based on passed + * dropdown position + * @param {number} dropdownPos + * @returns {boolean} */ ; - _proto.shouldFlip = function shouldFlip(dropdownPos, windowHeight) { - if (windowHeight === void 0) { - windowHeight = getWindowHeight(); - } - - if (dropdownPos === undefined) { + _proto.shouldFlip = function shouldFlip(dropdownPos) { + if (typeof dropdownPos !== 'number') { return false; } // If flip is enabled and the dropdown bottom position is // greater than the window height flip the dropdown. @@ -1818,7 +2036,7 @@ function () { var shouldFlip = false; if (this.position === 'auto') { - shouldFlip = dropdownPos >= windowHeight; + shouldFlip = !window.matchMedia("(min-height: " + (dropdownPos + 1) + "px)").matches; } else if (this.position === 'top') { shouldFlip = true; } @@ -1826,22 +2044,21 @@ function () { return shouldFlip; } /** - * Set active descendant attribute - * @param {Number} activeDescendant ID of active descendant + * @param {string} activeDescendantID */ ; _proto.setActiveDescendant = function setActiveDescendant(activeDescendantID) { this.element.setAttribute('aria-activedescendant', activeDescendantID); - } - /** - * Remove active descendant attribute - */ - ; + }; _proto.removeActiveDescendant = function removeActiveDescendant() { this.element.removeAttribute('aria-activedescendant'); - }; + } + /** + * @param {number} dropdownPos + */ + ; _proto.open = function open(dropdownPos) { this.element.classList.add(this.classNames.openState); @@ -1878,80 +2095,64 @@ function () { _proto.removeFocusState = function removeFocusState() { this.element.classList.remove(this.classNames.focusState); - } - /** - * Remove disabled state - */ - ; + }; _proto.enable = function enable() { this.element.classList.remove(this.classNames.disabledState); this.element.removeAttribute('aria-disabled'); - if (this.type === 'select-one') { + if (this.type === SELECT_ONE_TYPE) { this.element.setAttribute('tabindex', '0'); } this.isDisabled = false; - } - /** - * Set disabled state - */ - ; + }; _proto.disable = function disable() { this.element.classList.add(this.classNames.disabledState); this.element.setAttribute('aria-disabled', 'true'); - if (this.type === 'select-one') { + if (this.type === SELECT_ONE_TYPE) { this.element.setAttribute('tabindex', '-1'); } this.isDisabled = true; - }; + } + /** + * @param {HTMLElement} element + */ + ; _proto.wrap = function wrap(element) { utils_wrap(element, this.element); - }; + } + /** + * @param {Element} element + */ + ; _proto.unwrap = function unwrap(element) { // Move passed element outside this element this.element.parentNode.insertBefore(element, this.element); // Remove this element this.element.parentNode.removeChild(this.element); - } - /** - * Add loading state to element - */ - ; + }; _proto.addLoadingState = function addLoadingState() { this.element.classList.add(this.classNames.loadingState); this.element.setAttribute('aria-busy', 'true'); this.isLoading = true; - } - /** - * Remove loading state from element - */ - ; + }; _proto.removeLoadingState = function removeLoadingState() { this.element.classList.remove(this.classNames.loadingState); this.element.removeAttribute('aria-busy'); this.isLoading = false; - } - /** - * Set focussed state - */ - ; + }; _proto._onFocus = function _onFocus() { this.isFocussed = true; - } - /** - * Remove blurred state - */ - ; + }; _proto._onBlur = function _onBlur() { this.isFocussed = false; @@ -1968,14 +2169,21 @@ function input_createClass(Constructor, protoProps, staticProps) { if (protoProp +/** + * @typedef {import('../../../types/index').Choices.passedElement} passedElement + * @typedef {import('../../../types/index').Choices.ClassNames} ClassNames + */ + var input_Input = /*#__PURE__*/ function () { /** - * - * @typedef {import('../../../types/index').Choices.passedElement} passedElement - * @typedef {import('../../../types/index').Choices.ClassNames} ClassNames - * @param {{element: HTMLInputElement, type: passedElement['type'], classNames: ClassNames, preventPaste: boolean }} p + * @param {{ + * element: HTMLInputElement, + * type: passedElement['type'], + * classNames: ClassNames, + * preventPaste: boolean + * }} args */ function Input(_ref) { var element = _ref.element, @@ -1993,6 +2201,10 @@ function () { this._onFocus = this._onFocus.bind(this); this._onBlur = this._onBlur.bind(this); } + /** + * @param {string} placeholder + */ + var _proto = Input.prototype; @@ -2045,8 +2257,8 @@ function () { } /** * Set value of input to blank - * @return {Object} Class instance - * @public + * @param {boolean} setWidth + * @returns {this} */ ; @@ -2079,7 +2291,11 @@ function () { placeholder = _this$element.placeholder; style.minWidth = placeholder.length + 1 + "ch"; style.width = value.length + 1 + "ch"; - }; + } + /** + * @param {string} activeDescendantID + */ + ; _proto.setActiveDescendant = function setActiveDescendant(activeDescendantID) { this.element.setAttribute('aria-activedescendant', activeDescendantID); @@ -2090,10 +2306,14 @@ function () { }; _proto._onInput = function _onInput() { - if (this.type !== 'select-one') { + if (this.type !== SELECT_ONE_TYPE) { this.setWidth(); } - }; + } + /** + * @param {Event} event + */ + ; _proto._onPaste = function _onPaste(event) { if (this.preventPaste) { @@ -2114,11 +2334,19 @@ function () { set: function set(placeholder) { this.element.placeholder = placeholder; } + /** + * @returns {string} + */ + }, { key: "value", get: function get() { return sanitise(this.element.value); - }, + } + /** + * @param {string} value + */ + , set: function set(value) { this.element.value = value; } @@ -2128,132 +2356,21 @@ function () { }(); -// CONCATENATED MODULE: ./src/scripts/constants.js - -var DEFAULT_CLASSNAMES = { - containerOuter: 'choices', - containerInner: 'choices__inner', - input: 'choices__input', - inputCloned: 'choices__input--cloned', - list: 'choices__list', - listItems: 'choices__list--multiple', - listSingle: 'choices__list--single', - listDropdown: 'choices__list--dropdown', - item: 'choices__item', - itemSelectable: 'choices__item--selectable', - itemDisabled: 'choices__item--disabled', - itemChoice: 'choices__item--choice', - placeholder: 'choices__placeholder', - group: 'choices__group', - groupHeading: 'choices__heading', - button: 'choices__button', - activeState: 'is-active', - focusState: 'is-focused', - openState: 'is-open', - disabledState: 'is-disabled', - highlightedState: 'is-highlighted', - flippedState: 'is-flipped', - loadingState: 'is-loading', - noResults: 'has-no-results', - noChoices: 'has-no-choices' -}; -var DEFAULT_CONFIG = { - items: [], - choices: [], - silent: false, - renderChoiceLimit: -1, - maxItemCount: -1, - addItems: true, - addItemFilter: null, - removeItems: true, - removeItemButton: false, - editItems: false, - duplicateItemsAllowed: true, - delimiter: ',', - paste: true, - searchEnabled: true, - searchChoices: true, - searchFloor: 1, - searchResultLimit: 4, - searchFields: ['label', 'value'], - position: 'auto', - resetScrollPosition: true, - shouldSort: true, - shouldSortItems: false, - sortFn: sortByAlpha, - placeholder: true, - placeholderValue: null, - searchPlaceholderValue: null, - prependValue: null, - appendValue: null, - renderSelectedChoices: 'auto', - loadingText: 'Loading...', - noResultsText: 'No results found', - noChoicesText: 'No choices to choose from', - itemSelectText: 'Press to select', - uniqueItemText: 'Only unique values can be added', - customAddItemText: 'Only values matching specific conditions can be added', - addItemText: function addItemText(value) { - return "Press Enter to add \"" + sanitise(value) + "\""; - }, - maxItemText: function maxItemText(maxItemCount) { - return "Only " + maxItemCount + " values can be added"; - }, - itemComparer: function itemComparer(choice, item) { - return choice === item; - }, - fuseOptions: { - includeScore: true - }, - callbackOnInit: null, - callbackOnCreateTemplates: null, - classNames: DEFAULT_CLASSNAMES -}; -var EVENTS = { - showDropdown: 'showDropdown', - hideDropdown: 'hideDropdown', - change: 'change', - choice: 'choice', - search: 'search', - addItem: 'addItem', - removeItem: 'removeItem', - highlightItem: 'highlightItem', - highlightChoice: 'highlightChoice' -}; -var ACTION_TYPES = { - ADD_CHOICE: 'ADD_CHOICE', - FILTER_CHOICES: 'FILTER_CHOICES', - ACTIVATE_CHOICES: 'ACTIVATE_CHOICES', - CLEAR_CHOICES: 'CLEAR_CHOICES', - ADD_GROUP: 'ADD_GROUP', - ADD_ITEM: 'ADD_ITEM', - REMOVE_ITEM: 'REMOVE_ITEM', - HIGHLIGHT_ITEM: 'HIGHLIGHT_ITEM', - CLEAR_ALL: 'CLEAR_ALL' -}; -var KEY_CODES = { - BACK_KEY: 46, - DELETE_KEY: 8, - ENTER_KEY: 13, - A_KEY: 65, - ESC_KEY: 27, - UP_KEY: 38, - DOWN_KEY: 40, - PAGE_UP_KEY: 33, - PAGE_DOWN_KEY: 34 -}; -var SCROLLING_SPEED = 4; // CONCATENATED MODULE: ./src/scripts/components/list.js +/** + * @typedef {import('../../../types/index').Choices.Choice} Choice + */ var list_List = /*#__PURE__*/ function () { + /** + * @param {{ element: HTMLElement }} args + */ function List(_ref) { var element = _ref.element; - Object.assign(this, { - element: element - }); + this.element = element; this.scrollPos = this.element.scrollTop; this.height = this.element.offsetHeight; } @@ -2262,15 +2379,28 @@ function () { _proto.clear = function clear() { this.element.innerHTML = ''; - }; + } + /** + * @param {Element} node + */ + ; _proto.append = function append(node) { this.element.appendChild(node); - }; + } + /** + * @param {string} selector + * @returns {Element | null} + */ + ; _proto.getChild = function getChild(selector) { return this.element.querySelector(selector); - }; + } + /** + * @returns {boolean} + */ + ; _proto.hasChildren = function hasChildren() { return this.element.hasChildNodes(); @@ -2278,41 +2408,63 @@ function () { _proto.scrollToTop = function scrollToTop() { this.element.scrollTop = 0; - }; + } + /** + * @param {HTMLElement} element + * @param {1 | -1} direction + */ + ; - _proto.scrollToChoice = function scrollToChoice(choice, direction) { + _proto.scrollToChildElement = function scrollToChildElement(element, direction) { var _this = this; - if (!choice) { + if (!element) { return; } - var dropdownHeight = this.element.offsetHeight; - var choiceHeight = choice.offsetHeight; // Distance from bottom of element to top of parent + var listHeight = this.element.offsetHeight; // Scroll position of dropdown - var choicePos = choice.offsetTop + choiceHeight; // Scroll position of dropdown + var listScrollPosition = this.element.scrollTop + listHeight; + var elementHeight = element.offsetHeight; // Distance from bottom of element to top of parent - var containerScrollPos = this.element.scrollTop + dropdownHeight; // Difference between the choice and scroll position + var elementPos = element.offsetTop + elementHeight; // Difference between the element and scroll position - var destination = direction > 0 ? this.element.scrollTop + choicePos - containerScrollPos : choice.offsetTop; - requestAnimationFrame(function (time) { - _this._animateScroll(time, destination, direction); + var destination = direction > 0 ? this.element.scrollTop + elementPos - listScrollPosition : element.offsetTop; + requestAnimationFrame(function () { + _this._animateScroll(destination, direction); }); - }; + } + /** + * @param {number} scrollPos + * @param {number} strength + * @param {number} destination + */ + ; _proto._scrollDown = function _scrollDown(scrollPos, strength, destination) { var easing = (destination - scrollPos) / strength; var distance = easing > 1 ? easing : 1; this.element.scrollTop = scrollPos + distance; - }; + } + /** + * @param {number} scrollPos + * @param {number} strength + * @param {number} destination + */ + ; _proto._scrollUp = function _scrollUp(scrollPos, strength, destination) { var easing = (scrollPos - destination) / strength; var distance = easing > 1 ? easing : 1; this.element.scrollTop = scrollPos - distance; - }; + } + /** + * @param {*} destination + * @param {*} direction + */ + ; - _proto._animateScroll = function _animateScroll(time, destination, direction) { + _proto._animateScroll = function _animateScroll(destination, direction) { var _this2 = this; var strength = SCROLLING_SPEED; @@ -2335,7 +2487,7 @@ function () { if (continueAnimation) { requestAnimationFrame(function () { - _this2._animateScroll(time, destination, direction); + _this2._animateScroll(destination, direction); }); } }; @@ -2350,19 +2502,27 @@ function wrapped_element_defineProperties(target, props) { for (var i = 0; i < p function wrapped_element_createClass(Constructor, protoProps, staticProps) { if (protoProps) wrapped_element_defineProperties(Constructor.prototype, protoProps); if (staticProps) wrapped_element_defineProperties(Constructor, staticProps); return Constructor; } +/** + * @typedef {import('../../../types/index').Choices.passedElement} passedElement + * @typedef {import('../../../types/index').Choices.ClassNames} ClassNames + */ var wrapped_element_WrappedElement = /*#__PURE__*/ function () { + /** + * @param {{ + * element: HTMLInputElement | HTMLSelectElement, + * classNames: ClassNames, + * }} args + */ function WrappedElement(_ref) { var element = _ref.element, classNames = _ref.classNames; - Object.assign(this, { - element: element, - classNames: classNames - }); + this.element = element; + this.classNames = classNames; - if (!isElement(element)) { + if (!(element instanceof HTMLInputElement) && !(element instanceof HTMLSelectElement)) { throw new TypeError('Invalid element passed'); } @@ -2376,7 +2536,7 @@ function () { this.element.classList.add(this.classNames.input); this.element.hidden = true; // Remove element from tab index - this.element.tabIndex = '-1'; // Backup original styles if any + this.element.tabIndex = -1; // Backup original styles if any var origStyle = this.element.getAttribute('style'); @@ -2425,6 +2585,16 @@ function () { }; wrapped_element_createClass(WrappedElement, [{ + key: "isActive", + get: function get() { + return this.element.dataset.choice === 'active'; + } + }, { + key: "dir", + get: function get() { + return this.element.dir; + } + }, { key: "value", get: function get() { return this.element.value; @@ -2447,12 +2617,23 @@ function wrapped_input_createClass(Constructor, protoProps, staticProps) { if (p function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } +/** + * @typedef {import('../../../types/index').Choices.ClassNames} ClassNames + * @typedef {import('../../../types/index').Choices.Item} Item + */ var WrappedInput = /*#__PURE__*/ function (_WrappedElement) { _inheritsLoose(WrappedInput, _WrappedElement); + /** + * @param {{ + * element: HTMLInputElement, + * classNames: ClassNames, + * delimiter: string + * }} args + */ function WrappedInput(_ref) { var _this; @@ -2466,12 +2647,20 @@ function (_WrappedElement) { _this.delimiter = delimiter; return _this; } + /** + * @returns {string} + */ + wrapped_input_createClass(WrappedInput, [{ key: "value", get: function get() { return this.element.value; - }, + } + /** + * @param {Item[]} items + */ + , set: function set(items) { var itemValues = items.map(function (_ref2) { var value = _ref2.value; @@ -2495,12 +2684,25 @@ function wrapped_select_createClass(Constructor, protoProps, staticProps) { if ( function wrapped_select_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } +/** + * @typedef {import('../../../types/index').Choices.ClassNames} ClassNames + * @typedef {import('../../../types/index').Choices.Item} Item + * @typedef {import('../../../types/index').Choices.Choice} Choice + */ var WrappedSelect = /*#__PURE__*/ function (_WrappedElement) { wrapped_select_inheritsLoose(WrappedSelect, _WrappedElement); + /** + * @param {{ + * element: HTMLSelectElement, + * classNames: ClassNames, + * delimiter: string + * template: function + * }} args + */ function WrappedSelect(_ref) { var _this; @@ -2517,6 +2719,9 @@ function (_WrappedElement) { var _proto = WrappedSelect.prototype; + /** + * @param {DocumentFragment} fragment + */ _proto.appendDocFragment = function appendDocFragment(fragment) { this.element.innerHTML = ''; this.element.appendChild(fragment); @@ -2528,16 +2733,28 @@ function (_WrappedElement) { return this.element.querySelector('option[value=""]') || // Backward compatibility layer for the non-standard placeholder attribute supported in older versions. this.element.querySelector('option[placeholder]'); } + /** + * @returns {Element[]} + */ + }, { key: "optionGroups", get: function get() { return Array.from(this.element.getElementsByTagName('OPTGROUP')); } + /** + * @returns {Item[] | Choice[]} + */ + }, { key: "options", get: function get() { return Array.from(this.element.options); - }, + } + /** + * @param {Item[] | Choice[]} options + */ + , set: function set(options) { var _this2 = this; @@ -2827,6 +3044,14 @@ var TEMPLATES = }; /* harmony default export */ var templates = (TEMPLATES); // CONCATENATED MODULE: ./src/scripts/actions/choices.js +/** + * @typedef {import('../../../types/index').Choices.Choice} Choice + */ + +/** + * @argument {Choice} choice + * @returns {{ type: string } & Choice} + */ var choices_addChoice = function addChoice(_ref) { var value = _ref.value, @@ -2851,12 +3076,22 @@ var choices_addChoice = function addChoice(_ref) { keyCode: keyCode }; }; +/** + * @argument {Choice[]} results + * @returns {{ type: string, results: Choice[] }} + */ + var choices_filterChoices = function filterChoices(results) { return { type: ACTION_TYPES.FILTER_CHOICES, results: results }; }; +/** + * @argument {boolean} active + * @returns {{ type: string, active: boolean }} + */ + var choices_activateChoices = function activateChoices(active) { if (active === void 0) { active = true; @@ -2867,6 +3102,10 @@ var choices_activateChoices = function activateChoices(active) { active: active }; }; +/** + * @returns {{ type: string }} + */ + var choices_clearChoices = function clearChoices() { return { type: ACTION_TYPES.CLEAR_CHOICES @@ -2874,6 +3113,15 @@ var choices_clearChoices = function clearChoices() { }; // CONCATENATED MODULE: ./src/scripts/actions/items.js +/** + * @typedef {import('../../../types/index').Choices.Item} Item + */ + +/** + * @param {Item} item + * @returns {{ type: string } & Item} + */ + var items_addItem = function addItem(_ref) { var value = _ref.value, label = _ref.label, @@ -2895,6 +3143,12 @@ var items_addItem = function addItem(_ref) { keyCode: keyCode }; }; +/** + * @param {string} id + * @param {string} choiceId + * @returns {{ type: string, id: string, choiceId: string }} + */ + var items_removeItem = function removeItem(id, choiceId) { return { type: ACTION_TYPES.REMOVE_ITEM, @@ -2902,6 +3156,12 @@ var items_removeItem = function removeItem(id, choiceId) { choiceId: choiceId }; }; +/** + * @param {string} id + * @param {boolean} highlighted + * @returns {{ type: string, id: string, highlighted: boolean }} + */ + var items_highlightItem = function highlightItem(id, highlighted) { return { type: ACTION_TYPES.HIGHLIGHT_ITEM, @@ -2911,7 +3171,20 @@ var items_highlightItem = function highlightItem(id, highlighted) { }; // CONCATENATED MODULE: ./src/scripts/actions/groups.js -var groups_addGroup = function addGroup(value, id, active, disabled) { +/** + * @typedef {import('../../../types/index').Choices.Group} Group + */ + +/** + * @param {Group} group + * @returns {{ type: string } & Group} + */ + +var groups_addGroup = function addGroup(_ref) { + var value = _ref.value, + id = _ref.id, + active = _ref.active, + disabled = _ref.disabled; return { type: ACTION_TYPES.ADD_GROUP, value: value, @@ -2921,18 +3194,30 @@ var groups_addGroup = function addGroup(value, id, active, disabled) { }; }; // CONCATENATED MODULE: ./src/scripts/actions/misc.js +/** + * @returns {{ type: string }} + */ var clearAll = function clearAll() { return { type: 'CLEAR_ALL' }; }; +/** + * @param {any} state + * @returns {{ type: string, state: object }} + */ + var resetTo = function resetTo(state) { return { type: 'RESET_TO', state: state }; }; -// CONCATENATED MODULE: ./src/scripts/actions/general.js +/** + * @param {boolean} isLoading + * @returns {{ type: string, isLoading: boolean }} + */ + var setIsLoading = function setIsLoading(isLoading) { return { type: 'SET_IS_LOADING', @@ -2955,19 +3240,21 @@ function choices_createClass(Constructor, protoProps, staticProps) { if (protoPr +/** + * @typedef {import('../../types/index').Choices.Choice} Choice + * @typedef {import('../../types/index').Choices.Item} Item + * @typedef {import('../../types/index').Choices.Group} Group + * @typedef {import('../../types/index').Choices.Options} Options + */ -var USER_DEFAULTS = -/** @type {Partial} */ -{}; +/** @type {Partial} */ + +var USER_DEFAULTS = {}; /** * Choices * @author Josh Johnson */ -/** - * @typedef {import('../../types/index').Choices.Choice} Choice - */ - var choices_Choices = /*#__PURE__*/ function () { @@ -2987,7 +3274,7 @@ function () { } /** * @param {string | HTMLInputElement | HTMLSelectElement} element - * @param {Partial} userConfig + * @param {Partial} userConfig */ }]); @@ -3003,10 +3290,11 @@ function () { userConfig = {}; } + /** @type {Partial} */ this.config = cjs_default.a.all([DEFAULT_CONFIG, Choices.defaults.options, userConfig], // When merging array configs, replace with a copy of the userConfig array, // instead of concatenating with the default array { - arrayMerge: function arrayMerge(destinationArray, sourceArray) { + arrayMerge: function arrayMerge(_, sourceArray) { return [].concat(sourceArray); } }); // Convert addItemFilter to function @@ -3026,15 +3314,15 @@ function () { this.config.renderSelectedChoices = 'auto'; } - var passedElement = isType('String', element) ? document.querySelector(element) : element; + var passedElement = typeof element === 'string' ? document.querySelector(element) : element; if (!(passedElement instanceof HTMLInputElement || passedElement instanceof HTMLSelectElement)) { throw TypeError('Expected one of the following types text|select-one|select-multiple'); } - this._isTextElement = passedElement.type === 'text'; - this._isSelectOneElement = passedElement.type === 'select-one'; - this._isSelectMultipleElement = passedElement.type === 'select-multiple'; + this._isTextElement = passedElement.type === TEXT_TYPE; + this._isSelectOneElement = passedElement.type === SELECT_ONE_TYPE; + this._isSelectMultipleElement = passedElement.type === SELECT_MULTIPLE_TYPE; this._isSelectElement = this._isSelectOneElement || this._isSelectMultipleElement; if (this._isTextElement) { @@ -3071,7 +3359,7 @@ function () { * @type {HTMLElement['dir']} */ - this._direction = this.passedElement.element.dir; + this._direction = this.passedElement.dir; if (!this._direction) { var _window$getComputedSt = window.getComputedStyle(this.passedElement.element), @@ -3087,14 +3375,30 @@ function () { this._idNames = { itemChoice: 'item-choice' - }; // Assign preset choices from passed object + }; // Assign preset groups from passed element + + this._presetGroups = this.passedElement.optionGroups; // Assign preset choices from passed object this._presetChoices = this.config.choices; // Assign preset items from passed object first - this._presetItems = this.config.items; // Then add any values passed from attribute + this._presetItems = this.config.items; // Add any values passed from attribute if (this.passedElement.value) { this._presetItems = this._presetItems.concat(this.passedElement.value.split(this.config.delimiter)); + } // Create array of choices from option elements + + + if (this.passedElement.options) { + this.passedElement.options.forEach(function (o) { + _this._presetChoices.push({ + value: o.value, + label: o.innerHTML, + selected: o.selected, + disabled: o.disabled || o.parentNode.disabled, + placeholder: o.value === '' || o.hasAttribute('placeholder'), + customProperties: o.getAttribute('data-custom-properties') + }); + }); } this._render = this._render.bind(this); @@ -3112,16 +3416,9 @@ function () { this._onEnterKey = this._onEnterKey.bind(this); this._onEscapeKey = this._onEscapeKey.bind(this); this._onDirectionKey = this._onDirectionKey.bind(this); - this._onDeleteKey = this._onDeleteKey.bind(this); + this._onDeleteKey = this._onDeleteKey.bind(this); // If element has already been initialised with Choices, fail silently - if (this.config.shouldSortItems === true && this._isSelectOneElement) { - if (!this.config.silent) { - console.warn("shouldSortElements: Type of passed element is 'select-one', falling back to false."); - } - } // If element has already been initialised with Choices, fail silently - - - if (this.passedElement.element.getAttribute('data-choice') === 'active') { + if (this.passedElement.isActive) { if (!this.config.silent) { console.warn('Trying to initialise Choices on element already initialised'); } @@ -3166,7 +3463,7 @@ function () { this.initialised = true; var callbackOnInit = this.config.callbackOnInit; // Run callback if it is a function - if (callbackOnInit && isType('Function', callbackOnInit)) { + if (callbackOnInit && typeof callbackOnInit === 'function') { callbackOnInit.call(this); } }; @@ -3352,7 +3649,7 @@ function () { requestAnimationFrame(function () { _this7.dropdown.show(); - _this7.containerOuter.open(_this7.dropdown.distanceFromTopWindow()); + _this7.containerOuter.open(_this7.dropdown.distanceFromTopWindow); if (!preventInputFocus && _this7._canSearch) { _this7.input.focus(); @@ -3425,7 +3722,7 @@ function () { } // If only one value has been passed, convert to array - var choiceValue = isType('Array', value) ? value : [value]; // Loop through each value and + var choiceValue = Array.isArray(value) ? value : [value]; // Loop through each value and choiceValue.forEach(function (val) { return _this10._findAndSelectChoiceByValue(val); @@ -3441,7 +3738,7 @@ function () { * * **Input types affected:** select-one, select-multiple * - * @template {object[] | ((instance: Choices) => object[] | Promise)} T + * @template {Choice[] | ((instance: Choices) => object[] | Promise)} T * @param {T} [choicesArrayOrFetcher] * @param {string} [value = 'value'] - name of `value` field * @param {string} [label = 'label'] - name of 'label' field @@ -3540,20 +3837,20 @@ function () { this.clearChoices(); } - if (!Array.isArray(choicesArrayOrFetcher)) { - if (typeof choicesArrayOrFetcher !== 'function') { - throw new TypeError(".setChoices must be called either with array of choices with a function resulting into Promise of array of choices"); - } // it's a choices fetcher - - - requestAnimationFrame(function () { - return _this11._handleLoadingState(true); - }); + if (typeof choicesArrayOrFetcher === 'function') { + // it's a choices fetcher function var fetcher = choicesArrayOrFetcher(this); - if (typeof fetcher === 'object' && typeof fetcher.then === 'function') { + if (typeof Promise === 'function' && fetcher instanceof Promise) { // that's a promise - return fetcher.then(function (data) { + // eslint-disable-next-line compat/compat + return new Promise(function (resolve) { + return requestAnimationFrame(resolve); + }).then(function () { + return _this11._handleLoadingState(true); + }).then(function () { + return fetcher; + }).then(function (data) { return _this11.setChoices(data, value, label, replaceChoices); }).catch(function (err) { if (!_this11.config.silent) { @@ -3575,9 +3872,15 @@ function () { return this.setChoices(fetcher, value, label, false); } + if (!Array.isArray(choicesArrayOrFetcher)) { + throw new TypeError(".setChoices must be called either with array of choices with a function resulting into Promise of array of choices"); + } + this.containerOuter.removeLoadingState(); - var addGroupsAndChoices = function addGroupsAndChoices(groupOrChoice) { + this._setLoading(true); + + choicesArrayOrFetcher.forEach(function (groupOrChoice) { if (groupOrChoice.choices) { _this11._addGroup({ group: groupOrChoice, @@ -3595,11 +3898,7 @@ function () { placeholder: groupOrChoice.placeholder }); } - }; - - this._setLoading(true); - - choicesArrayOrFetcher.forEach(addGroupsAndChoices); + }); this._setLoading(false); @@ -3709,10 +4008,10 @@ function () { var notice; if (this._isSearching) { - notice = isType('Function', this.config.noResultsText) ? this.config.noResultsText() : this.config.noResultsText; + notice = typeof this.config.noResultsText === 'function' ? this.config.noResultsText() : this.config.noResultsText; dropdownItem = this._getTemplate('notice', notice, 'no-results'); } else { - notice = isType('Function', this.config.noChoicesText) ? this.config.noChoicesText() : this.config.noChoicesText; + notice = typeof this.config.noChoicesText === 'function' ? this.config.noChoicesText() : this.config.noChoicesText; dropdownItem = this._getTemplate('notice', notice, 'no-choices'); } @@ -3752,7 +4051,7 @@ function () { if (this.config.shouldSort) { - groups.sort(this.config.sortFn); + groups.sort(this.config.sorter); } groups.forEach(function (group) { @@ -3785,7 +4084,7 @@ function () { renderSelectedChoices = _this$config.renderSelectedChoices, searchResultLimit = _this$config.searchResultLimit, renderChoiceLimit = _this$config.renderChoiceLimit; - var filter = this._isSearching ? sortByScore : this.config.sortFn; + var filter = this._isSearching ? sortByScore : this.config.sorter; var appendChoice = function appendChoice(choice) { var shouldRender = renderSelectedChoices === 'auto' ? _this14._isSelectOneElement || !choice.selected : true; @@ -3828,11 +4127,11 @@ function () { var choiceLimit = rendererableChoices.length; // Prepend placeholeder - var sortedChoices = [].concat(placeholderChoices, normalChoices); + var sortedChoices = this._isSelectOneElement ? [].concat(placeholderChoices, normalChoices) : normalChoices; if (this._isSearching) { choiceLimit = searchResultLimit; - } else if (renderChoiceLimit > 0 && !withinGroup) { + } else if (renderChoiceLimit && renderChoiceLimit > 0 && !withinGroup) { choiceLimit = renderChoiceLimit; } // Add each choice to dropdown within range @@ -3856,11 +4155,11 @@ function () { // Create fragment to add elements to var _this$config2 = this.config, shouldSortItems = _this$config2.shouldSortItems, - sortFn = _this$config2.sortFn, + sorter = _this$config2.sorter, removeItemButton = _this$config2.removeItemButton; // If sorting is enabled, filter items if (shouldSortItems && !this._isSelectOneElement) { - items.sort(sortFn); + items.sort(sorter); } if (this._isTextElement) { @@ -3880,9 +4179,7 @@ function () { }; // Add each list item to list - items.forEach(function (item) { - return addItemToFragment(item); - }); + items.forEach(addItemToFragment); return fragment; }; @@ -4101,7 +4398,7 @@ function () { _proto._canAddItem = function _canAddItem(activeItems, value) { var canAddItem = true; - var notice = isType('Function', this.config.addItemText) ? this.config.addItemText(value) : this.config.addItemText; + var notice = typeof this.config.addItemText === 'function' ? this.config.addItemText(value) : this.config.addItemText; if (!this._isSelectOneElement) { var isDuplicateValue = existsInArray(activeItems, value); @@ -4110,12 +4407,12 @@ function () { // If there is a max entry limit and we have reached that limit // don't update canAddItem = false; - notice = isType('Function', this.config.maxItemText) ? this.config.maxItemText(this.config.maxItemCount) : this.config.maxItemText; + notice = typeof this.config.maxItemText === 'function' ? this.config.maxItemText(this.config.maxItemCount) : this.config.maxItemText; } if (!this.config.duplicateItemsAllowed && isDuplicateValue && canAddItem) { canAddItem = false; - notice = isType('Function', this.config.uniqueItemText) ? this.config.uniqueItemText(value) : this.config.uniqueItemText; + notice = typeof this.config.uniqueItemText === 'function' ? this.config.uniqueItemText(value) : this.config.uniqueItemText; } if (this._isTextElement && this.config.addItems && canAddItem && typeof this.config.addItemFilter === 'function' && !this.config.addItemFilter(value)) { @@ -4131,8 +4428,8 @@ function () { }; _proto._searchChoices = function _searchChoices(value) { - var newValue = isType('String', value) ? value.trim() : value; - var currentValue = isType('String', this._currentValue) ? this._currentValue.trim() : this._currentValue; + var newValue = typeof value === 'string' ? value.trim() : value; + var currentValue = typeof this._currentValue === 'string' ? this._currentValue.trim() : this._currentValue; if (newValue.length < 1 && newValue === currentValue + " ") { return 0; @@ -4430,7 +4727,7 @@ function () { if (skipKey) { if (directionInt > 0) { - nextEl = Array.from(this.dropdown.element.querySelectorAll(selectableChoiceIdentifier)).pop(); + nextEl = this.dropdown.element.querySelector(selectableChoiceIdentifier + ":last-of-type"); } else { nextEl = this.dropdown.element.querySelector(selectableChoiceIdentifier); } @@ -4448,7 +4745,7 @@ function () { // We prevent default to stop the cursor moving // when pressing the arrow if (!isScrolledIntoView(nextEl, this.choiceList.element, directionInt)) { - this.choiceList.scrollToChoice(nextEl, directionInt); + this.choiceList.scrollToChildElement(nextEl, directionInt); } this._highlightChoice(nextEl); @@ -4508,7 +4805,7 @@ function () { var target = event.target, shiftKey = event.shiftKey; // If we have our mouse down on the scrollbar and are on IE11... - if (this.choiceList.element.contains(target) && isIE11()) { + if (this.choiceList.element.contains(target) && isIE11(navigator.userAgent)) { this._isScrollingOnIe = true; } @@ -4573,7 +4870,8 @@ function () { }; _proto._onFocus = function _onFocus(_ref11) { - var _this17 = this; + var _this17 = this, + _focusActions; var target = _ref11.target; var focusWasWithinContainer = this.containerOuter.element.contains(target); @@ -4582,29 +4880,25 @@ function () { return; } - var focusActions = { - text: function text() { - if (target === _this17.input.element) { - _this17.containerOuter.addFocusState(); - } - }, - 'select-one': function selectOne() { + var focusActions = (_focusActions = {}, _focusActions[TEXT_TYPE] = function () { + if (target === _this17.input.element) { _this17.containerOuter.addFocusState(); - - if (target === _this17.input.element) { - _this17.showDropdown(true); - } - }, - 'select-multiple': function selectMultiple() { - if (target === _this17.input.element) { - _this17.showDropdown(true); // If element is a select box, the focused element is the container and the dropdown - // isn't already open, focus and show dropdown - - - _this17.containerOuter.addFocusState(); - } } - }; + }, _focusActions[SELECT_ONE_TYPE] = function () { + _this17.containerOuter.addFocusState(); + + if (target === _this17.input.element) { + _this17.showDropdown(true); + } + }, _focusActions[SELECT_MULTIPLE_TYPE] = function () { + if (target === _this17.input.element) { + _this17.showDropdown(true); // If element is a select box, the focused element is the container and the dropdown + // isn't already open, focus and show dropdown + + + _this17.containerOuter.addFocusState(); + } + }, _focusActions); focusActions[this.passedElement.element.type](); }; @@ -4615,41 +4909,39 @@ function () { var blurWasWithinContainer = this.containerOuter.element.contains(target); if (blurWasWithinContainer && !this._isScrollingOnIe) { + var _blurActions; + var activeItems = this._store.activeItems; var hasHighlightedItems = activeItems.some(function (item) { return item.highlighted; }); - var blurActions = { - text: function text() { - if (target === _this18.input.element) { - _this18.containerOuter.removeFocusState(); - - if (hasHighlightedItems) { - _this18.unhighlightAll(); - } - - _this18.hideDropdown(true); - } - }, - 'select-one': function selectOne() { + var blurActions = (_blurActions = {}, _blurActions[TEXT_TYPE] = function () { + if (target === _this18.input.element) { _this18.containerOuter.removeFocusState(); - if (target === _this18.input.element || target === _this18.containerOuter.element && !_this18._canSearch) { - _this18.hideDropdown(true); + if (hasHighlightedItems) { + _this18.unhighlightAll(); } - }, - 'select-multiple': function selectMultiple() { - if (target === _this18.input.element) { - _this18.containerOuter.removeFocusState(); - _this18.hideDropdown(true); + _this18.hideDropdown(true); + } + }, _blurActions[SELECT_ONE_TYPE] = function () { + _this18.containerOuter.removeFocusState(); - if (hasHighlightedItems) { - _this18.unhighlightAll(); - } + if (target === _this18.input.element || target === _this18.containerOuter.element && !_this18._canSearch) { + _this18.hideDropdown(true); + } + }, _blurActions[SELECT_MULTIPLE_TYPE] = function () { + if (target === _this18.input.element) { + _this18.containerOuter.removeFocusState(); + + _this18.hideDropdown(true); + + if (hasHighlightedItems) { + _this18.unhighlightAll(); } } - }; + }, _blurActions); blurActions[this.passedElement.element.type](); } else { // On IE11, clicking the scollbar blurs our input and thus @@ -4730,7 +5022,7 @@ function () { placeholder = _ref13$placeholder === void 0 ? false : _ref13$placeholder, _ref13$keyCode = _ref13.keyCode, keyCode = _ref13$keyCode === void 0 ? null : _ref13$keyCode; - var passedValue = isType('String', value) ? value.trim() : value; + var passedValue = typeof value === 'string' ? value.trim() : value; var passedKeyCode = keyCode; var passedCustomProperties = customProperties; var items = this._store.items; @@ -4872,7 +5164,12 @@ function () { var isDisabled = group.disabled ? group.disabled : false; if (groupChoices) { - this._store.dispatch(groups_addGroup(group.label, groupId, true, isDisabled)); + this._store.dispatch(groups_addGroup({ + value: group.label, + id: groupId, + active: true, + disabled: isDisabled + })); var addGroupChoices = function addGroupChoices(choice) { var isOptDisabled = choice.disabled || choice.parentNode && choice.parentNode.disabled; @@ -4890,7 +5187,12 @@ function () { groupChoices.forEach(addGroupChoices); } else { - this._store.dispatch(groups_addGroup(group.label, group.id, false, group.disabled)); + this._store.dispatch(groups_addGroup({ + value: group.label, + id: group.id, + active: false, + disabled: group.disabled + })); } }; @@ -4914,7 +5216,7 @@ function () { var callbackOnCreateTemplates = this.config.callbackOnCreateTemplates; var userTemplates = {}; - if (callbackOnCreateTemplates && isType('Function', callbackOnCreateTemplates)) { + if (callbackOnCreateTemplates && typeof callbackOnCreateTemplates === 'function') { userTemplates = callbackOnCreateTemplates.call(this, strToEl); } @@ -4965,7 +5267,7 @@ function () { this.input.placeholder = this.config.searchPlaceholderValue || ''; } else if (this._placeholderValue) { this.input.placeholder = this._placeholderValue; - this.input.setWidth(true); + this.input.setWidth(); } this.containerOuter.element.appendChild(this.containerInner.element); @@ -4983,145 +5285,133 @@ function () { } if (this._isSelectElement) { - this._addPredefinedChoices(); - } else if (this._isTextElement) { - this._addPredefinedItems(); + this._highlightPosition = 0; + this._isSearching = false; + + this._setLoading(true); + + if (this._presetGroups.length) { + this._addPredefinedGroups(this._presetGroups); + } else { + this._addPredefinedChoices(this._presetChoices); + } + + this._setLoading(false); + } + + if (this._isTextElement) { + this._addPredefinedItems(this._presetItems); } }; - _proto._addPredefinedChoices = function _addPredefinedChoices() { + _proto._addPredefinedGroups = function _addPredefinedGroups(groups) { var _this21 = this; - var passedGroups = this.passedElement.optionGroups; - this._highlightPosition = 0; - this._isSearching = false; + // If we have a placeholder option + var placeholderChoice = this.passedElement.placeholderOption; - this._setLoading(true); - - if (passedGroups && passedGroups.length) { - // If we have a placeholder option - var placeholderChoice = this.passedElement.placeholderOption; - - if (placeholderChoice && placeholderChoice.parentNode.tagName === 'SELECT') { - this._addChoice({ - value: placeholderChoice.value, - label: placeholderChoice.innerHTML, - isSelected: placeholderChoice.selected, - isDisabled: placeholderChoice.disabled, - placeholder: true - }); - } - - passedGroups.forEach(function (group) { - return _this21._addGroup({ - group: group, - id: group.id || null - }); + if (placeholderChoice && placeholderChoice.parentNode.tagName === 'SELECT') { + this._addChoice({ + value: placeholderChoice.value, + label: placeholderChoice.innerHTML, + isSelected: placeholderChoice.selected, + isDisabled: placeholderChoice.disabled, + placeholder: true }); - } else { - var passedOptions = this.passedElement.options; - var filter = this.config.sortFn; - var allChoices = this._presetChoices; // Create array of options from option elements + } - passedOptions.forEach(function (o) { - allChoices.push({ - value: o.value, - label: o.innerHTML, - selected: o.selected, - disabled: o.disabled || o.parentNode.disabled, - placeholder: o.hasAttribute('placeholder'), - customProperties: o.getAttribute('data-custom-properties') - }); - }); // If sorting is enabled or the user is searching, filter choices - - if (this.config.shouldSort) { - allChoices.sort(filter); - } // Determine whether there is a selected choice - - - var hasSelectedChoice = allChoices.some(function (choice) { - return choice.selected; + groups.forEach(function (group) { + return _this21._addGroup({ + group: group, + id: group.id || null }); + }); + }; - var handleChoice = function handleChoice(choice, index) { - var value = choice.value, - label = choice.label, - customProperties = choice.customProperties, - placeholder = choice.placeholder; + _proto._addPredefinedChoices = function _addPredefinedChoices(choices) { + var _this22 = this; - if (_this21._isSelectElement) { - // If the choice is actually a group - if (choice.choices) { - _this21._addGroup({ - group: choice, - id: choice.id || null - }); - } else { - // If there is a selected choice already or the choice is not - // the first in the array, add each choice normally - // Otherwise pre-select the first choice in the array if it's a single select - var shouldPreselect = _this21._isSelectOneElement && !hasSelectedChoice && index === 0; - var isSelected = shouldPreselect ? true : choice.selected; - var isDisabled = shouldPreselect ? false : choice.disabled; + // If sorting is enabled or the user is searching, filter choices + if (this.config.shouldSort) { + choices.sort(this.config.sorter); + } // Determine whether there is a selected choice - _this21._addChoice({ - value: value, - label: label, - isSelected: isSelected, - isDisabled: isDisabled, - customProperties: customProperties, - placeholder: placeholder - }); - } + + var hasSelectedChoice = choices.some(function (choice) { + return choice.selected; + }); // Add each choice + + choices.forEach(function (choice, index) { + var value = choice.value, + label = choice.label, + customProperties = choice.customProperties, + placeholder = choice.placeholder; + + if (_this22._isSelectElement) { + // If the choice is actually a group + if (choice.choices) { + _this22._addGroup({ + group: choice, + id: choice.id || null + }); } else { - _this21._addChoice({ + // If there is a selected choice already or the choice is not + // the first in the array, add each choice normally + // Otherwise pre-select the first choice in the array if it's a single select + var shouldPreselect = _this22._isSelectOneElement && !hasSelectedChoice && index === 0; + var isSelected = shouldPreselect ? true : choice.selected; + var isDisabled = shouldPreselect ? false : choice.disabled; + + _this22._addChoice({ value: value, label: label, - isSelected: choice.selected, - isDisabled: choice.disabled, + isSelected: isSelected, + isDisabled: isDisabled, customProperties: customProperties, placeholder: placeholder }); } - }; // Add each choice + } else { + _this22._addChoice({ + value: value, + label: label, + isSelected: choice.selected, + isDisabled: choice.disabled, + customProperties: customProperties, + placeholder: placeholder + }); + } + }); + } + /** + * @param {Item[]} items + */ + ; + _proto._addPredefinedItems = function _addPredefinedItems(items) { + var _this23 = this; - allChoices.forEach(function (choice, index) { - return handleChoice(choice, index); - }); - } - - this._setLoading(false); - }; - - _proto._addPredefinedItems = function _addPredefinedItems() { - var _this22 = this; - - var handlePresetItem = function handlePresetItem(item) { - var itemType = getType(item); - - if (itemType === 'Object' && item.value) { - _this22._addItem({ + items.forEach(function (item) { + if (typeof item === 'object' && item.value) { + _this23._addItem({ value: item.value, label: item.label, choiceId: item.id, customProperties: item.customProperties, placeholder: item.placeholder }); - } else if (itemType === 'String') { - _this22._addItem({ + } + + if (typeof item === 'string') { + _this23._addItem({ value: item }); } - }; - - this._presetItems.forEach(function (item) { - return handlePresetItem(item); }); }; _proto._setChoiceOrItem = function _setChoiceOrItem(item) { - var _this23 = this; + var _this24 = this; var itemType = getType(item).toLowerCase(); var handleType = { @@ -5132,8 +5422,8 @@ function () { // that is then selected. For text inputs we can just add items normally. - if (!_this23._isTextElement) { - _this23._addChoice({ + if (!_this24._isTextElement) { + _this24._addChoice({ value: item.value, label: item.label, isSelected: true, @@ -5142,7 +5432,7 @@ function () { placeholder: item.placeholder }); } else { - _this23._addItem({ + _this24._addItem({ value: item.value, label: item.label, choiceId: item.id, @@ -5152,15 +5442,15 @@ function () { } }, string: function string() { - if (!_this23._isTextElement) { - _this23._addChoice({ + if (!_this24._isTextElement) { + _this24._addChoice({ value: item, label: item, isSelected: true, isDisabled: false }); } else { - _this23._addItem({ + _this24._addItem({ value: item }); } @@ -5170,12 +5460,12 @@ function () { }; _proto._findAndSelectChoiceByValue = function _findAndSelectChoiceByValue(val) { - var _this24 = this; + var _this25 = this; var choices = this._store.choices; // Check 'value' property exists and the choice isn't already selected var foundChoice = choices.find(function (choice) { - return _this24.config.itemComparer(choice.value, val); + return _this25.config.valueComparer(choice.value, val); }); if (foundChoice && !foundChoice.selected) { @@ -5192,14 +5482,28 @@ function () { }; _proto._generatePlaceholderValue = function _generatePlaceholderValue() { - if (this._isSelectOneElement) { - return false; + if (this._isSelectElement) { + var placeholderOption = this.passedElement.placeholderOption; + return placeholderOption ? placeholderOption.text : false; } - return this.config.placeholder ? this.config.placeholderValue || this.passedElement.element.getAttribute('placeholder') : false; - } - /* ===== End of Private functions ====== */ - ; + var _this$config4 = this.config, + placeholder = _this$config4.placeholder, + placeholderValue = _this$config4.placeholderValue; + var dataset = this.passedElement.element.dataset; + + if (placeholder) { + if (placeholderValue) { + return placeholderValue; + } + + if (dataset.placeholder) { + return dataset.placeholder; + } + } + + return false; + }; return Choices; }(); diff --git a/public/assets/scripts/choices.min.js b/public/assets/scripts/choices.min.js index 4d98486..380b471 100644 --- a/public/assets/scripts/choices.min.js +++ b/public/assets/scripts/choices.min.js @@ -8,4 +8,4 @@ window.Choices=function(e){var t={};function i(n){if(t[n])return t[n].exports;va * * http://www.apache.org/licenses/LICENSE-2.0 */ -e.exports=function(e){var t={};function i(n){if(t[n])return t[n].exports;var s=t[n]={i:n,l:!1,exports:{}};return e[n].call(s.exports,s,s.exports,i),s.l=!0,s.exports}return i.m=e,i.c=t,i.d=function(e,t,n){i.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},i.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},i.t=function(e,t){if(1&t&&(e=i(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(i.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var s in e)i.d(n,s,function(t){return e[t]}.bind(null,s));return n},i.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return i.d(t,"a",t),t},i.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},i.p="",i(i.s=1)}([function(e,t){e.exports=function(e){return Array.isArray?Array.isArray(e):"[object Array]"===Object.prototype.toString.call(e)}},function(e,t,i){function n(e){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function s(e,t){for(var i=0;i1&&void 0!==arguments[1]?arguments[1]:{limit:!1};this._log('---------\nSearch pattern: "'.concat(e,'"'));var i=this._prepareSearchers(e),n=i.tokenSearchers,s=i.fullSearcher,r=this._search(n,s),o=r.weights,a=r.results;return this._computeScore(o,a),this.options.shouldSort&&this._sort(a),t.limit&&"number"==typeof t.limit&&(a=a.slice(0,t.limit)),this._format(a)}},{key:"_prepareSearchers",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",t=[];if(this.options.tokenize)for(var i=e.split(this.options.tokenSeparator),n=0,s=i.length;n0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1?arguments[1]:void 0,i=this.list,n={},s=[];if("string"==typeof i[0]){for(var r=0,o=i.length;r1)throw new Error("Key weight has to be > 0 and <= 1");p=p.name}else a[p]={weight:1};this._analyze({key:p,value:this.options.getFn(h,p),record:h,index:c},{resultMap:n,results:s,tokenSearchers:e,fullSearcher:t})}return{weights:a,results:s}}},{key:"_analyze",value:function(e,t){var i=e.key,n=e.arrayIndex,s=void 0===n?-1:n,r=e.value,o=e.record,c=e.index,l=t.tokenSearchers,h=void 0===l?[]:l,u=t.fullSearcher,d=void 0===u?[]:u,p=t.resultMap,m=void 0===p?{}:p,f=t.results,v=void 0===f?[]:f;if(null!=r){var g=!1,_=-1,b=0;if("string"==typeof r){this._log("\nKey: ".concat(""===i?"-":i));var y=d.search(r);if(this._log('Full text: "'.concat(r,'", score: ').concat(y.score)),this.options.tokenize){for(var E=r.split(this.options.tokenSeparator),I=[],S=0;S-1&&(D=(D+_)/2),this._log("Score average:",D);var P=!this.options.tokenize||!this.options.matchAllTokens||b>=h.length;if(this._log("\nCheck Matches: ".concat(P)),(g||y.isMatch)&&P){var F=m[c];F?F.output.push({key:i,arrayIndex:s,value:r,score:D,matchedIndices:y.matchedIndices}):(m[c]={item:o,output:[{key:i,arrayIndex:s,value:r,score:D,matchedIndices:y.matchedIndices}]},v.push(m[c]))}}else if(a(r))for(var M=0,N=r.length;M-1&&(o.arrayIndex=r.arrayIndex),t.matches.push(o)}}})),this.options.includeScore&&s.push((function(e,t){t.score=e.score}));for(var r=0,o=e.length;ri)return s(e,this.pattern,n);var o=this.options,a=o.location,c=o.distance,l=o.threshold,h=o.findAllMatches,u=o.minMatchCharLength;return r(e,this.pattern,this.patternAlphabet,{location:a,distance:c,threshold:l,findAllMatches:h,minMatchCharLength:u})}}])&&n(t.prototype,i),e}();e.exports=a},function(e,t){var i=/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g;e.exports=function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:/ +/g,s=new RegExp(t.replace(i,"\\$&").replace(n,"|")),r=e.match(s),o=!!r,a=[];if(o)for(var c=0,l=r.length;c=D;M-=1){var N=M-1,j=i[e.charAt(N)];if(j&&(E[N]=1),F[M]=(F[M+1]<<1|1)&j,0!==L&&(F[M]|=(O[M+1]|O[M])<<1|1|O[M+1]),F[M]&T&&(C=n(t,{errors:L,currentLocation:N,expectedLocation:v,distance:l}))<=_){if(_=C,(b=N)<=v)break;D=Math.max(1,2*v-b)}}if(n(t,{errors:L+1,currentLocation:v,expectedLocation:v,distance:l})>_)break;O=F}return{isMatch:b>=0,score:0===C?.001:C,matchedIndices:s(E,f)}}},function(e,t){e.exports=function(e,t){var i=t.errors,n=void 0===i?0:i,s=t.currentLocation,r=void 0===s?0:s,o=t.expectedLocation,a=void 0===o?0:o,c=t.distance,l=void 0===c?100:c,h=n/e.length,u=Math.abs(a-r);return l?h+u/l:u?1:h}},function(e,t){e.exports=function(){for(var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,i=[],n=-1,s=-1,r=0,o=e.length;r=t&&i.push([n,s]),n=-1)}return e[r-1]&&r-n>=t&&i.push([n,r-1]),i}},function(e,t){e.exports=function(e){for(var t={},i=e.length,n=0;n/g,"&rt;").replace(/-1?e.map((function(e){var i=e;return i.id===parseInt(t.choiceId,10)&&(i.selected=!0),i})):e;case"REMOVE_ITEM":return t.choiceId>-1?e.map((function(e){var i=e;return i.id===parseInt(t.choiceId,10)&&(i.selected=!1),i})):e;case"FILTER_CHOICES":return e.map((function(e){var i=e;return i.active=t.results.some((function(e){var t=e.item,n=e.score;return t.id===i.id&&(i.score=n,!0)})),i}));case"ACTIVATE_CHOICES":return e.map((function(e){var i=e;return i.active=t.active,i}));case"CLEAR_CHOICES":return f;default:return e}},general:_}),k=function(e,t){var i=e;if("CLEAR_ALL"===t.type)i=void 0;else if("RESET_TO"===t.type)return T(t.state);return x(i,t)};function D(e,t){for(var i=0;i=t:"top"===this.position&&(s=!0),s},t.setActiveDescendant=function(e){this.element.setAttribute("aria-activedescendant",e)},t.removeActiveDescendant=function(){this.element.removeAttribute("aria-activedescendant")},t.open=function(e){this.element.classList.add(this.classNames.openState),this.element.setAttribute("aria-expanded","true"),this.isOpen=!0,this.shouldFlip(e)&&(this.element.classList.add(this.classNames.flippedState),this.isFlipped=!0)},t.close=function(){this.element.classList.remove(this.classNames.openState),this.element.setAttribute("aria-expanded","false"),this.removeActiveDescendant(),this.isOpen=!1,this.isFlipped&&(this.element.classList.remove(this.classNames.flippedState),this.isFlipped=!1)},t.focus=function(){this.isFocussed||this.element.focus()},t.addFocusState=function(){this.element.classList.add(this.classNames.focusState)},t.removeFocusState=function(){this.element.classList.remove(this.classNames.focusState)},t.enable=function(){this.element.classList.remove(this.classNames.disabledState),this.element.removeAttribute("aria-disabled"),"select-one"===this.type&&this.element.setAttribute("tabindex","0"),this.isDisabled=!1},t.disable=function(){this.element.classList.add(this.classNames.disabledState),this.element.setAttribute("aria-disabled","true"),"select-one"===this.type&&this.element.setAttribute("tabindex","-1"),this.isDisabled=!0},t.wrap=function(e){!function(e,t){void 0===t&&(t=document.createElement("div")),e.nextSibling?e.parentNode.insertBefore(t,e.nextSibling):e.parentNode.appendChild(t),t.appendChild(e)}(e,this.element)},t.unwrap=function(e){this.element.parentNode.insertBefore(e,this.element),this.element.parentNode.removeChild(this.element)},t.addLoadingState=function(){this.element.classList.add(this.classNames.loadingState),this.element.setAttribute("aria-busy","true"),this.isLoading=!0},t.removeLoadingState=function(){this.element.classList.remove(this.classNames.loadingState),this.element.removeAttribute("aria-busy"),this.isLoading=!1},t._onFocus=function(){this.isFocussed=!0},t._onBlur=function(){this.isFocussed=!1},e}();function N(e,t){for(var i=0;i"'+O(e)+'"'},maxItemText:function(e){return"Only "+e+" values can be added"},itemComparer:function(e,t){return e===t},fuseOptions:{includeScore:!0},callbackOnInit:null,callbackOnCreateTemplates:null,classNames:{containerOuter:"choices",containerInner:"choices__inner",input:"choices__input",inputCloned:"choices__input--cloned",list:"choices__list",listItems:"choices__list--multiple",listSingle:"choices__list--single",listDropdown:"choices__list--dropdown",item:"choices__item",itemSelectable:"choices__item--selectable",itemDisabled:"choices__item--disabled",itemChoice:"choices__item--choice",placeholder:"choices__placeholder",group:"choices__group",groupHeading:"choices__heading",button:"choices__button",activeState:"is-active",focusState:"is-focused",openState:"is-open",disabledState:"is-disabled",highlightedState:"is-highlighted",flippedState:"is-flipped",loadingState:"is-loading",noResults:"has-no-results",noChoices:"has-no-choices"}},H="showDropdown",R="hideDropdown",B="change",V="choice",G="search",q="addItem",U="removeItem",z="highlightItem",W="highlightChoice",X="ADD_CHOICE",Y="FILTER_CHOICES",$="ACTIVATE_CHOICES",J="CLEAR_CHOICES",Z="ADD_GROUP",Q="ADD_ITEM",ee="REMOVE_ITEM",te="HIGHLIGHT_ITEM",ie=46,ne=8,se=13,re=65,oe=27,ae=38,ce=40,le=33,he=34,ue=function(){function e(e){var t=e.element;Object.assign(this,{element:t}),this.scrollPos=this.element.scrollTop,this.height=this.element.offsetHeight}var t=e.prototype;return t.clear=function(){this.element.innerHTML=""},t.append=function(e){this.element.appendChild(e)},t.getChild=function(e){return this.element.querySelector(e)},t.hasChildren=function(){return this.element.hasChildNodes()},t.scrollToTop=function(){this.element.scrollTop=0},t.scrollToChoice=function(e,t){var i=this;if(e){var n=this.element.offsetHeight,s=e.offsetHeight,r=e.offsetTop+s,o=this.element.scrollTop+n,a=t>0?this.element.scrollTop+r-o:e.offsetTop;requestAnimationFrame((function(e){i._animateScroll(e,a,t)}))}},t._scrollDown=function(e,t,i){var n=(i-e)/t,s=n>1?n:1;this.element.scrollTop=e+s},t._scrollUp=function(e,t,i){var n=(e-i)/t,s=n>1?n:1;this.element.scrollTop=e-s},t._animateScroll=function(e,t,i){var n=this,s=this.element.scrollTop,r=!1;i>0?(this._scrollDown(s,4,t),st&&(r=!0)),r&&requestAnimationFrame((function(){n._animateScroll(e,t,i)}))},e}();function de(e,t){for(var i=0;i0?"treeitem":"option"),Object.assign(f.dataset,{choice:"",id:c,value:l,selectText:i}),p?(f.dataset.choiceDisabled="",f.setAttribute("aria-disabled","true")):f.dataset.choiceSelectable="",f},input:function(e,t){var i=e.input,n=e.inputCloned,s=Object.assign(document.createElement("input"),{type:"text",className:i+" "+n,autocomplete:"off",autocapitalize:"off",spellcheck:!1});return s.setAttribute("role","textbox"),s.setAttribute("aria-autocomplete","list"),s.setAttribute("aria-label",t),s},dropdown:function(e){var t=e.list,i=e.listDropdown,n=document.createElement("div");return n.classList.add(t,i),n.setAttribute("aria-expanded","false"),n},notice:function(e,t,i){var n=e.item,s=e.itemChoice,r=e.noResults,o=e.noChoices;void 0===i&&(i="");var a=[n,s];return"no-choices"===i?a.push(o):"no-results"===i&&a.push(r),Object.assign(document.createElement("div"),{innerHTML:t,className:a.join(" ")})},option:function(e){var t=e.label,i=e.value,n=e.customProperties,s=e.active,r=e.disabled,o=new Option(t,i,!1,s);return n&&(o.dataset.customProperties=n),o.disabled=r,o}},be=function(e){return void 0===e&&(e=!0),{type:$,active:e}},ye=function(e,t){return{type:te,id:e,highlighted:t}},Ee=function(e,t,i,n){return{type:Z,value:e,id:t,active:i,disabled:n}};function Ie(e,t){for(var i=0;i=0?this._store.getGroupById(s):null;return this._store.dispatch(ye(i,!0)),t&&this.passedElement.triggerEvent(z,{id:i,value:o,label:c,groupValue:l&&l.value?l.value:null}),this},r.unhighlightItem=function(e){if(!e)return this;var t=e.id,i=e.groupId,n=void 0===i?-1:i,s=e.value,r=void 0===s?"":s,o=e.label,a=void 0===o?"":o,c=n>=0?this._store.getGroupById(n):null;return this._store.dispatch(ye(t,!1)),this.passedElement.triggerEvent(z,{id:t,value:r,label:a,groupValue:c&&c.value?c.value:null}),this},r.highlightAll=function(){var e=this;return this._store.items.forEach((function(t){return e.highlightItem(t)})),this},r.unhighlightAll=function(){var e=this;return this._store.items.forEach((function(t){return e.unhighlightItem(t)})),this},r.removeActiveItemsByValue=function(e){var t=this;return this._store.activeItems.filter((function(t){return t.value===e})).forEach((function(e){return t._removeItem(e)})),this},r.removeActiveItems=function(e){var t=this;return this._store.activeItems.filter((function(t){return t.id!==e})).forEach((function(e){return t._removeItem(e)})),this},r.removeHighlightedItems=function(e){var t=this;return void 0===e&&(e=!1),this._store.highlightedActiveItems.forEach((function(i){t._removeItem(i),e&&t._triggerChange(i.value)})),this},r.showDropdown=function(e){var t=this;return this.dropdown.isActive?this:(requestAnimationFrame((function(){t.dropdown.show(),t.containerOuter.open(t.dropdown.distanceFromTopWindow()),!e&&t._canSearch&&t.input.focus(),t.passedElement.triggerEvent(H,{})})),this)},r.hideDropdown=function(e){var t=this;return this.dropdown.isActive?(requestAnimationFrame((function(){t.dropdown.hide(),t.containerOuter.close(),!e&&t._canSearch&&(t.input.removeActiveDescendant(),t.input.blur()),t.passedElement.triggerEvent(R,{})})),this):this},r.getValue=function(e){void 0===e&&(e=!1);var t=this._store.activeItems.reduce((function(t,i){var n=e?i.value:i;return t.push(n),t}),[]);return this._isSelectOneElement?t[0]:t},r.setValue=function(e){var t=this;return this.initialised?(e.forEach((function(e){return t._setChoiceOrItem(e)})),this):this},r.setChoiceByValue=function(e){var t=this;return!this.initialised||this._isTextElement?this:((I("Array",e)?e:[e]).forEach((function(e){return t._findAndSelectChoiceByValue(e)})),this)},r.setChoices=function(e,t,i,n){var s=this;if(void 0===e&&(e=[]),void 0===t&&(t="value"),void 0===i&&(i="label"),void 0===n&&(n=!1),!this.initialised)throw new ReferenceError("setChoices was called on a non-initialized instance of Choices");if(!this._isSelectElement)throw new TypeError("setChoices can't be used with INPUT based Choices");if("string"!=typeof t||!t)throw new TypeError("value parameter must be a name of 'value' field in passed objects");if(n&&this.clearChoices(),!Array.isArray(e)){if("function"!=typeof e)throw new TypeError(".setChoices must be called either with array of choices with a function resulting into Promise of array of choices");requestAnimationFrame((function(){return s._handleLoadingState(!0)}));var r=e(this);if("object"==typeof r&&"function"==typeof r.then)return r.then((function(e){return s.setChoices(e,t,i,n)})).catch((function(e){s.config.silent||console.error(e)})).then((function(){return s._handleLoadingState(!1)})).then((function(){return s}));if(!Array.isArray(r))throw new TypeError(".setChoices first argument function must return either array of choices or Promise, got: "+typeof r);return this.setChoices(r,t,i,!1)}this.containerOuter.removeLoadingState();return this._setLoading(!0),e.forEach((function(e){e.choices?s._addGroup({group:e,id:e.id||null,valueKey:t,labelKey:i}):s._addChoice({value:e[t],label:e[i],isSelected:e.selected,isDisabled:e.disabled,customProperties:e.customProperties,placeholder:e.placeholder})})),this._setLoading(!1),this},r.clearChoices=function(){return this._store.dispatch({type:J}),this},r.clearStore=function(){return this._store.dispatch({type:"CLEAR_ALL"}),this},r.clearInput=function(){var e=!this._isSelectOneElement;return this.input.clear(e),!this._isTextElement&&this._canSearch&&(this._isSearching=!1,this._store.dispatch(be(!0))),this},r._render=function(){if(!this._store.isLoading()){this._currentState=this._store.state;var e=this._currentState.choices!==this._prevState.choices||this._currentState.groups!==this._prevState.groups||this._currentState.items!==this._prevState.items,t=this._isSelectElement,i=this._currentState.items!==this._prevState.items;e&&(t&&this._renderChoices(),i&&this._renderItems(),this._prevState=this._currentState)}},r._renderChoices=function(){var e=this,t=this._store,i=t.activeGroups,n=t.activeChoices,s=document.createDocumentFragment();if(this.choiceList.clear(),this.config.resetScrollPosition&&requestAnimationFrame((function(){return e.choiceList.scrollToTop()})),i.length>=1&&!this._isSearching){var r=n.filter((function(e){return!0===e.placeholder&&-1===e.groupId}));r.length>=1&&(s=this._createChoicesFragment(r,s)),s=this._createGroupsFragment(i,n,s)}else n.length>=1&&(s=this._createChoicesFragment(n,s));if(s.childNodes&&s.childNodes.length>0){var o=this._store.activeItems,a=this._canAddItem(o,this.input.value);a.response?(this.choiceList.append(s),this._highlightChoice()):this.choiceList.append(this._getTemplate("notice",a.notice))}else{var c,l;this._isSearching?(l=I("Function",this.config.noResultsText)?this.config.noResultsText():this.config.noResultsText,c=this._getTemplate("notice",l,"no-results")):(l=I("Function",this.config.noChoicesText)?this.config.noChoicesText():this.config.noChoicesText,c=this._getTemplate("notice",l,"no-choices")),this.choiceList.append(c)}},r._renderItems=function(){var e=this._store.activeItems||[];this.itemList.clear();var t=this._createItemsFragment(e);t.childNodes&&this.itemList.append(t)},r._createGroupsFragment=function(e,t,i){var n=this;void 0===i&&(i=document.createDocumentFragment());return this.config.shouldSort&&e.sort(this.config.sortFn),e.forEach((function(e){var s=function(e){return t.filter((function(t){return n._isSelectOneElement?t.groupId===e.id:t.groupId===e.id&&("always"===n.config.renderSelectedChoices||!t.selected)}))}(e);if(s.length>=1){var r=n._getTemplate("choiceGroup",e);i.appendChild(r),n._createChoicesFragment(s,i,!0)}})),i},r._createChoicesFragment=function(e,t,i){var n=this;void 0===t&&(t=document.createDocumentFragment()),void 0===i&&(i=!1);var s=this.config,r=s.renderSelectedChoices,o=s.searchResultLimit,a=s.renderChoiceLimit,c=this._isSearching?A:this.config.sortFn,l=function(e){if("auto"!==r||(n._isSelectOneElement||!e.selected)){var i=n._getTemplate("choice",e,n.config.itemSelectText);t.appendChild(i)}},h=e;"auto"!==r||this._isSelectOneElement||(h=e.filter((function(e){return!e.selected})));var u=h.reduce((function(e,t){return t.placeholder?e.placeholderChoices.push(t):e.normalChoices.push(t),e}),{placeholderChoices:[],normalChoices:[]}),d=u.placeholderChoices,p=u.normalChoices;(this.config.shouldSort||this._isSearching)&&p.sort(c);var m=h.length,f=[].concat(d,p);this._isSearching?m=o:a>0&&!i&&(m=a);for(var v=0;v=n){var o=s?this._searchChoices(e):0;this.passedElement.triggerEvent(G,{value:e,resultCount:o})}else r&&(this._isSearching=!1,this._store.dispatch(be(!0)))}},r._canAddItem=function(e,t){var i=!0,n=I("Function",this.config.addItemText)?this.config.addItemText(t):this.config.addItemText;if(!this._isSelectOneElement){var s=function(e,t,i){return void 0===i&&(i="value"),e.some((function(e){return I("String",t)?e[i]===t.trim():e[i]===t}))}(e,t);this.config.maxItemCount>0&&this.config.maxItemCount<=e.length&&(i=!1,n=I("Function",this.config.maxItemText)?this.config.maxItemText(this.config.maxItemCount):this.config.maxItemText),!this.config.duplicateItemsAllowed&&s&&i&&(i=!1,n=I("Function",this.config.uniqueItemText)?this.config.uniqueItemText(t):this.config.uniqueItemText),this._isTextElement&&this.config.addItems&&i&&"function"==typeof this.config.addItemFilter&&!this.config.addItemFilter(t)&&(i=!1,n="function"==typeof this.config.customAddItemText?this.config.customAddItemText(t):this.config.customAddItemText)}return{response:i,notice:n}},r._searchChoices=function(e){var t=I("String",e)?e.trim():e,i=I("String",this._currentValue)?this._currentValue.trim():this._currentValue;if(t.length<1&&t===i+" ")return 0;var n=this._store.searchableChoices,r=t,o=[].concat(this.config.searchFields),a=Object.assign(this.config.fuseOptions,{keys:o}),c=new s.a(n,a).search(r);return this._currentValue=t,this._highlightPosition=0,this._isSearching=!0,this._store.dispatch(function(e){return{type:Y,results:e}}(c)),c.length},r._addEventListeners=function(){var e=document.documentElement;e.addEventListener("keydown",this._onKeyDown,!0),e.addEventListener("touchend",this._onTouchEnd,!0),e.addEventListener("mousedown",this._onMouseDown,!0),e.addEventListener("click",this._onClick,{passive:!0}),e.addEventListener("touchmove",this._onTouchMove,{passive:!0}),e.addEventListener("mouseover",this._onMouseOver,{passive:!0}),this._isSelectOneElement&&(this.containerOuter.element.addEventListener("focus",this._onFocus,{passive:!0}),this.containerOuter.element.addEventListener("blur",this._onBlur,{passive:!0})),this.input.element.addEventListener("keyup",this._onKeyUp,{passive:!0}),this.input.element.addEventListener("focus",this._onFocus,{passive:!0}),this.input.element.addEventListener("blur",this._onBlur,{passive:!0}),this.input.element.form&&this.input.element.form.addEventListener("reset",this._onFormReset,{passive:!0}),this.input.addEventListeners()},r._removeEventListeners=function(){var e=document.documentElement;e.removeEventListener("keydown",this._onKeyDown,!0),e.removeEventListener("touchend",this._onTouchEnd,!0),e.removeEventListener("mousedown",this._onMouseDown,!0),e.removeEventListener("keyup",this._onKeyUp,{passive:!0}),e.removeEventListener("click",this._onClick,{passive:!0}),e.removeEventListener("touchmove",this._onTouchMove,{passive:!0}),e.removeEventListener("mouseover",this._onMouseOver,{passive:!0}),this._isSelectOneElement&&(this.containerOuter.element.removeEventListener("focus",this._onFocus,{passive:!0}),this.containerOuter.element.removeEventListener("blur",this._onBlur,{passive:!0})),this.input.element.removeEventListener("focus",this._onFocus,{passive:!0}),this.input.element.removeEventListener("blur",this._onBlur,{passive:!0}),this.input.element.form&&this.input.element.form.removeEventListener("reset",this._onFormReset,{passive:!0}),this.input.removeEventListeners()},r._onKeyDown=function(e){var t,i=e.target,n=e.keyCode,s=e.ctrlKey,r=e.metaKey;if(i===this.input.element||this.containerOuter.element.contains(i)){var o=this._store.activeItems,a=this.input.isFocussed,c=this.dropdown.isActive,l=this.itemList.hasChildren(),h=String.fromCharCode(n),u=ie,d=ne,p=se,m=re,f=oe,v=ae,g=ce,_=le,b=he,y=s||r;!this._isTextElement&&/[a-zA-Z0-9-_ ]/.test(h)&&this.showDropdown();var E=((t={})[m]=this._onAKey,t[p]=this._onEnterKey,t[f]=this._onEscapeKey,t[v]=this._onDirectionKey,t[_]=this._onDirectionKey,t[g]=this._onDirectionKey,t[b]=this._onDirectionKey,t[d]=this._onDeleteKey,t[u]=this._onDeleteKey,t);E[n]&&E[n]({event:e,target:i,keyCode:n,metaKey:r,activeItems:o,hasFocusedInput:a,hasActiveDropdown:c,hasItems:l,hasCtrlDownKeyPressed:y})}},r._onKeyUp=function(e){var t=e.target,i=e.keyCode,n=this.input.value,s=this._store.activeItems,r=this._canAddItem(s,n),o=ie,a=ne;if(this._isTextElement){if(r.notice&&n){var c=this._getTemplate("notice",r.notice);this.dropdown.element.innerHTML=c.outerHTML,this.showDropdown(!0)}else this.hideDropdown(!0)}else{var l=(i===o||i===a)&&!t.value,h=!this._isTextElement&&this._isSearching,u=this._canSearch&&r.response;l&&h?(this._isSearching=!1,this._store.dispatch(be(!0))):u&&this._handleSearch(this.input.value)}this._canSearch=this.config.searchEnabled},r._onAKey=function(e){var t=e.hasItems;e.hasCtrlDownKeyPressed&&t&&(this._canSearch=!1,this.config.removeItems&&!this.input.value&&this.input.element===document.activeElement&&this.highlightAll())},r._onEnterKey=function(e){var t=e.event,i=e.target,n=e.activeItems,s=e.hasActiveDropdown,r=se,o=i.hasAttribute("data-button");if(this._isTextElement&&i.value){var a=this.input.value;this._canAddItem(n,a).response&&(this.hideDropdown(!0),this._addItem({value:a}),this._triggerChange(a),this.clearInput())}if(o&&(this._handleButtonAction(n,i),t.preventDefault()),s){var c=this.dropdown.getChild("."+this.config.classNames.highlightedState);c&&(n[0]&&(n[0].keyCode=r),this._handleChoiceAction(n,c)),t.preventDefault()}else this._isSelectOneElement&&(this.showDropdown(),t.preventDefault())},r._onEscapeKey=function(e){e.hasActiveDropdown&&(this.hideDropdown(!0),this.containerOuter.focus())},r._onDirectionKey=function(e){var t=e.event,i=e.hasActiveDropdown,n=e.keyCode,s=e.metaKey,r=ce,o=le,a=he;if(i||this._isSelectOneElement){this.showDropdown(),this._canSearch=!1;var c,l=n===r||n===a?1:-1;if(s||n===a||n===o)c=l>0?Array.from(this.dropdown.element.querySelectorAll("[data-choice-selectable]")).pop():this.dropdown.element.querySelector("[data-choice-selectable]");else{var h=this.dropdown.element.querySelector("."+this.config.classNames.highlightedState);c=h?function(e,t,i){if(void 0===i&&(i=1),e&&t){var n=e.parentNode.parentNode,s=Array.from(n.querySelectorAll(t)),r=s.indexOf(e);return s[r+(i>0?1:-1)]}}(h,"[data-choice-selectable]",l):this.dropdown.element.querySelector("[data-choice-selectable]")}c&&(function(e,t,i){if(void 0===i&&(i=1),e)return i>0?t.scrollTop+t.offsetHeight>=e.offsetTop+e.offsetHeight:e.offsetTop>=t.scrollTop}(c,this.choiceList.element,l)||this.choiceList.scrollToChoice(c,l),this._highlightChoice(c)),t.preventDefault()}},r._onDeleteKey=function(e){var t=e.event,i=e.target,n=e.hasFocusedInput,s=e.activeItems;!n||i.value||this._isSelectOneElement||(this._handleBackspace(s),t.preventDefault())},r._onTouchMove=function(){this._wasTap&&(this._wasTap=!1)},r._onTouchEnd=function(e){var t=(e||e.touches[0]).target;this._wasTap&&this.containerOuter.element.contains(t)&&((t===this.containerOuter.element||t===this.containerInner.element)&&(this._isTextElement?this.input.focus():this._isSelectMultipleElement&&this.showDropdown()),e.stopPropagation());this._wasTap=!0},r._onMouseDown=function(e){var t=e.target,i=e.shiftKey;if(this.choiceList.element.contains(t)&&navigator.userAgent.match(/Trident/)&&navigator.userAgent.match(/rv[ :]11/)&&(this._isScrollingOnIe=!0),this.containerOuter.element.contains(t)&&t!==this.input.element){var n=this._store.activeItems,s=i,r=w(t,"data-button"),o=w(t,"data-item"),a=w(t,"data-choice");r?this._handleButtonAction(n,r):o?this._handleItemAction(n,o,s):a&&this._handleChoiceAction(n,a),e.preventDefault()}},r._onMouseOver=function(e){var t=e.target;(t===this.dropdown||this.dropdown.element.contains(t))&&t.hasAttribute("data-choice")&&this._highlightChoice(t)},r._onClick=function(e){var t=e.target;this.containerOuter.element.contains(t)?this.dropdown.isActive||this.containerOuter.isDisabled?this._isSelectOneElement&&t!==this.input.element&&!this.dropdown.element.contains(t)&&this.hideDropdown():this._isTextElement?document.activeElement!==this.input.element&&this.input.focus():(this.showDropdown(),this.containerOuter.focus()):(this._store.highlightedActiveItems.length>0&&this.unhighlightAll(),this.containerOuter.removeFocusState(),this.hideDropdown(!0))},r._onFocus=function(e){var t=this,i=e.target;this.containerOuter.element.contains(i)&&{text:function(){i===t.input.element&&t.containerOuter.addFocusState()},"select-one":function(){t.containerOuter.addFocusState(),i===t.input.element&&t.showDropdown(!0)},"select-multiple":function(){i===t.input.element&&(t.showDropdown(!0),t.containerOuter.addFocusState())}}[this.passedElement.element.type]()},r._onBlur=function(e){var t=this,i=e.target;if(this.containerOuter.element.contains(i)&&!this._isScrollingOnIe){var n=this._store.activeItems.some((function(e){return e.highlighted}));({text:function(){i===t.input.element&&(t.containerOuter.removeFocusState(),n&&t.unhighlightAll(),t.hideDropdown(!0))},"select-one":function(){t.containerOuter.removeFocusState(),(i===t.input.element||i===t.containerOuter.element&&!t._canSearch)&&t.hideDropdown(!0)},"select-multiple":function(){i===t.input.element&&(t.containerOuter.removeFocusState(),t.hideDropdown(!0),n&&t.unhighlightAll())}})[this.passedElement.element.type]()}else this._isScrollingOnIe=!1,this.input.element.focus()},r._onFormReset=function(){this._store.dispatch({type:"RESET_TO",state:this._initialState})},r._highlightChoice=function(e){var t=this;void 0===e&&(e=null);var i=Array.from(this.dropdown.element.querySelectorAll("[data-choice-selectable]"));if(i.length){var n=e;Array.from(this.dropdown.element.querySelectorAll("."+this.config.classNames.highlightedState)).forEach((function(e){e.classList.remove(t.config.classNames.highlightedState),e.setAttribute("aria-selected","false")})),n?this._highlightPosition=i.indexOf(n):(n=i.length>this._highlightPosition?i[this._highlightPosition]:i[i.length-1])||(n=i[0]),n.classList.add(this.config.classNames.highlightedState),n.setAttribute("aria-selected","true"),this.passedElement.triggerEvent(W,{el:n}),this.dropdown.isActive&&(this.input.setActiveDescendant(n.id),this.containerOuter.setActiveDescendant(n.id))}},r._addItem=function(e){var t=e.value,i=e.label,n=void 0===i?null:i,s=e.choiceId,r=void 0===s?-1:s,o=e.groupId,a=void 0===o?-1:o,c=e.customProperties,l=void 0===c?null:c,h=e.placeholder,u=void 0!==h&&h,d=e.keyCode,p=void 0===d?null:d,m=I("String",t)?t.trim():t,f=p,v=l,g=this._store.items,_=n||m,b=parseInt(r,10)||-1,y=a>=0?this._store.getGroupById(a):null,E=g?g.length+1:1;return this.config.prependValue&&(m=this.config.prependValue+m.toString()),this.config.appendValue&&(m+=this.config.appendValue.toString()),this._store.dispatch(function(e){var t=e.value,i=e.label,n=e.id,s=e.choiceId,r=e.groupId,o=e.customProperties,a=e.placeholder,c=e.keyCode;return{type:Q,value:t,label:i,id:n,choiceId:s,groupId:r,customProperties:o,placeholder:a,keyCode:c}}({value:m,label:_,id:E,choiceId:b,groupId:a,customProperties:l,placeholder:u,keyCode:f})),this._isSelectOneElement&&this.removeActiveItems(E),this.passedElement.triggerEvent(q,{id:E,value:m,label:_,customProperties:v,groupValue:y&&y.value?y.value:void 0,keyCode:f}),this},r._removeItem=function(e){if(!e||!I("Object",e))return this;var t=e.id,i=e.value,n=e.label,s=e.choiceId,r=e.groupId,o=r>=0?this._store.getGroupById(r):null;return this._store.dispatch(function(e,t){return{type:ee,id:e,choiceId:t}}(t,s)),o&&o.value?this.passedElement.triggerEvent(U,{id:t,value:i,label:n,groupValue:o.value}):this.passedElement.triggerEvent(U,{id:t,value:i,label:n}),this},r._addChoice=function(e){var t=e.value,i=e.label,n=void 0===i?null:i,s=e.isSelected,r=void 0!==s&&s,o=e.isDisabled,a=void 0!==o&&o,c=e.groupId,l=void 0===c?-1:c,h=e.customProperties,u=void 0===h?null:h,d=e.placeholder,p=void 0!==d&&d,m=e.keyCode,f=void 0===m?null:m;if(null!=t){var v=this._store.choices,g=n||t,_=v?v.length+1:1,b=this._baseId+"-"+this._idNames.itemChoice+"-"+_;this._store.dispatch(function(e){var t=e.value,i=e.label,n=e.id,s=e.groupId,r=e.disabled,o=e.elementId,a=e.customProperties,c=e.placeholder,l=e.keyCode;return{type:X,value:t,label:i,id:n,groupId:s,disabled:r,elementId:o,customProperties:a,placeholder:c,keyCode:l}}({value:t,label:g,id:_,groupId:l,disabled:a,elementId:b,customProperties:u,placeholder:p,keyCode:f})),r&&this._addItem({value:t,label:g,choiceId:_,customProperties:u,placeholder:p,keyCode:f})}},r._addGroup=function(e){var t=this,i=e.group,n=e.id,s=e.valueKey,r=void 0===s?"value":s,o=e.labelKey,a=void 0===o?"label":o,c=I("Object",i)?i.choices:Array.from(i.getElementsByTagName("OPTION")),l=n||Math.floor((new Date).valueOf()*Math.random()),h=!!i.disabled&&i.disabled;if(c){this._store.dispatch(Ee(i.label,l,!0,h));c.forEach((function(e){var i=e.disabled||e.parentNode&&e.parentNode.disabled;t._addChoice({value:e[r],label:I("Object",e)?e[a]:e.innerHTML,isSelected:e.selected,isDisabled:i,groupId:l,customProperties:e.customProperties,placeholder:e.placeholder})}))}else this._store.dispatch(Ee(i.label,i.id,!1,i.disabled))},r._getTemplate=function(e){var t;if(!e)return null;for(var i=this.config.classNames,n=arguments.length,s=new Array(n>1?n-1:0),r=1;r1&&void 0!==arguments[1]?arguments[1]:{limit:!1};this._log('---------\nSearch pattern: "'.concat(e,'"'));var i=this._prepareSearchers(e),n=i.tokenSearchers,s=i.fullSearcher,r=this._search(n,s),o=r.weights,a=r.results;return this._computeScore(o,a),this.options.shouldSort&&this._sort(a),t.limit&&"number"==typeof t.limit&&(a=a.slice(0,t.limit)),this._format(a)}},{key:"_prepareSearchers",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",t=[];if(this.options.tokenize)for(var i=e.split(this.options.tokenSeparator),n=0,s=i.length;n0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1?arguments[1]:void 0,i=this.list,n={},s=[];if("string"==typeof i[0]){for(var r=0,o=i.length;r1)throw new Error("Key weight has to be > 0 and <= 1");p=p.name}else a[p]={weight:1};this._analyze({key:p,value:this.options.getFn(h,p),record:h,index:c},{resultMap:n,results:s,tokenSearchers:e,fullSearcher:t})}return{weights:a,results:s}}},{key:"_analyze",value:function(e,t){var i=e.key,n=e.arrayIndex,s=void 0===n?-1:n,r=e.value,o=e.record,c=e.index,l=t.tokenSearchers,h=void 0===l?[]:l,u=t.fullSearcher,d=void 0===u?[]:u,p=t.resultMap,m=void 0===p?{}:p,f=t.results,v=void 0===f?[]:f;if(null!=r){var g=!1,_=-1,b=0;if("string"==typeof r){this._log("\nKey: ".concat(""===i?"-":i));var y=d.search(r);if(this._log('Full text: "'.concat(r,'", score: ').concat(y.score)),this.options.tokenize){for(var E=r.split(this.options.tokenSeparator),I=[],S=0;S-1&&(P=(P+_)/2),this._log("Score average:",P);var D=!this.options.tokenize||!this.options.matchAllTokens||b>=h.length;if(this._log("\nCheck Matches: ".concat(D)),(g||y.isMatch)&&D){var M=m[c];M?M.output.push({key:i,arrayIndex:s,value:r,score:P,matchedIndices:y.matchedIndices}):(m[c]={item:o,output:[{key:i,arrayIndex:s,value:r,score:P,matchedIndices:y.matchedIndices}]},v.push(m[c]))}}else if(a(r))for(var N=0,F=r.length;N-1&&(o.arrayIndex=r.arrayIndex),t.matches.push(o)}}})),this.options.includeScore&&s.push((function(e,t){t.score=e.score}));for(var r=0,o=e.length;ri)return s(e,this.pattern,n);var o=this.options,a=o.location,c=o.distance,l=o.threshold,h=o.findAllMatches,u=o.minMatchCharLength;return r(e,this.pattern,this.patternAlphabet,{location:a,distance:c,threshold:l,findAllMatches:h,minMatchCharLength:u})}}])&&n(t.prototype,i),e}();e.exports=a},function(e,t){var i=/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g;e.exports=function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:/ +/g,s=new RegExp(t.replace(i,"\\$&").replace(n,"|")),r=e.match(s),o=!!r,a=[];if(o)for(var c=0,l=r.length;c=P;N-=1){var F=N-1,j=i[e.charAt(F)];if(j&&(E[F]=1),M[N]=(M[N+1]<<1|1)&j,0!==L&&(M[N]|=(O[N+1]|O[N])<<1|1|O[N+1]),M[N]&T&&(C=n(t,{errors:L,currentLocation:F,expectedLocation:v,distance:l}))<=_){if(_=C,(b=F)<=v)break;P=Math.max(1,2*v-b)}}if(n(t,{errors:L+1,currentLocation:v,expectedLocation:v,distance:l})>_)break;O=M}return{isMatch:b>=0,score:0===C?.001:C,matchedIndices:s(E,f)}}},function(e,t){e.exports=function(e,t){var i=t.errors,n=void 0===i?0:i,s=t.currentLocation,r=void 0===s?0:s,o=t.expectedLocation,a=void 0===o?0:o,c=t.distance,l=void 0===c?100:c,h=n/e.length,u=Math.abs(a-r);return l?h+u/l:u?1:h}},function(e,t){e.exports=function(){for(var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,i=[],n=-1,s=-1,r=0,o=e.length;r=t&&i.push([n,s]),n=-1)}return e[r-1]&&r-n>=t&&i.push([n,r-1]),i}},function(e,t){e.exports=function(e){for(var t={},i=e.length,n=0;n/g,"&rt;").replace(/-1?e.map((function(e){var i=e;return i.id===parseInt(t.choiceId,10)&&(i.selected=!0),i})):e;case"REMOVE_ITEM":return t.choiceId>-1?e.map((function(e){var i=e;return i.id===parseInt(t.choiceId,10)&&(i.selected=!1),i})):e;case"FILTER_CHOICES":return e.map((function(e){var i=e;return i.active=t.results.some((function(e){var t=e.item,n=e.score;return t.id===i.id&&(i.score=n,!0)})),i}));case"ACTIVATE_CHOICES":return e.map((function(e){var i=e;return i.active=t.active,i}));case"CLEAR_CHOICES":return f;default:return e}},general:_}),x=function(e,t){var i=e;if("CLEAR_ALL"===t.type)i=void 0;else if("RESET_TO"===t.type)return A(t.state);return L(i,t)};function k(e,t){for(var i=0;i"'+w(e)+'"'},maxItemText:function(e){return"Only "+e+" values can be added"},valueComparer:function(e,t){return e===t},fuseOptions:{includeScore:!0},callbackOnInit:null,callbackOnCreateTemplates:null,classNames:{containerOuter:"choices",containerInner:"choices__inner",input:"choices__input",inputCloned:"choices__input--cloned",list:"choices__list",listItems:"choices__list--multiple",listSingle:"choices__list--single",listDropdown:"choices__list--dropdown",item:"choices__item",itemSelectable:"choices__item--selectable",itemDisabled:"choices__item--disabled",itemChoice:"choices__item--choice",placeholder:"choices__placeholder",group:"choices__group",groupHeading:"choices__heading",button:"choices__button",activeState:"is-active",focusState:"is-focused",openState:"is-open",disabledState:"is-disabled",highlightedState:"is-highlighted",flippedState:"is-flipped",loadingState:"is-loading",noResults:"has-no-results",noChoices:"has-no-choices"}},F="showDropdown",j="hideDropdown",K="change",R="choice",B="search",H="addItem",V="removeItem",G="highlightItem",q="highlightChoice",U="ADD_CHOICE",z="FILTER_CHOICES",W="ACTIVATE_CHOICES",X="CLEAR_CHOICES",$="ADD_GROUP",J="ADD_ITEM",Y="REMOVE_ITEM",Z="HIGHLIGHT_ITEM",Q=46,ee=8,te=13,ie=65,ne=27,se=38,re=40,oe=33,ae=34,ce="text",le="select-one",he="select-multiple",ue=function(){function e(e){var t=e.element,i=e.type,n=e.classNames,s=e.position;this.element=t,this.classNames=n,this.type=i,this.position=s,this.isOpen=!1,this.isFlipped=!1,this.isFocussed=!1,this.isDisabled=!1,this.isLoading=!1,this._onFocus=this._onFocus.bind(this),this._onBlur=this._onBlur.bind(this)}var t=e.prototype;return t.addEventListeners=function(){this.element.addEventListener("focus",this._onFocus),this.element.addEventListener("blur",this._onBlur)},t.removeEventListeners=function(){this.element.removeEventListener("focus",this._onFocus),this.element.removeEventListener("blur",this._onBlur)},t.shouldFlip=function(e){if("number"!=typeof e)return!1;var t=!1;return"auto"===this.position?t=!window.matchMedia("(min-height: "+(e+1)+"px)").matches:"top"===this.position&&(t=!0),t},t.setActiveDescendant=function(e){this.element.setAttribute("aria-activedescendant",e)},t.removeActiveDescendant=function(){this.element.removeAttribute("aria-activedescendant")},t.open=function(e){this.element.classList.add(this.classNames.openState),this.element.setAttribute("aria-expanded","true"),this.isOpen=!0,this.shouldFlip(e)&&(this.element.classList.add(this.classNames.flippedState),this.isFlipped=!0)},t.close=function(){this.element.classList.remove(this.classNames.openState),this.element.setAttribute("aria-expanded","false"),this.removeActiveDescendant(),this.isOpen=!1,this.isFlipped&&(this.element.classList.remove(this.classNames.flippedState),this.isFlipped=!1)},t.focus=function(){this.isFocussed||this.element.focus()},t.addFocusState=function(){this.element.classList.add(this.classNames.focusState)},t.removeFocusState=function(){this.element.classList.remove(this.classNames.focusState)},t.enable=function(){this.element.classList.remove(this.classNames.disabledState),this.element.removeAttribute("aria-disabled"),this.type===le&&this.element.setAttribute("tabindex","0"),this.isDisabled=!1},t.disable=function(){this.element.classList.add(this.classNames.disabledState),this.element.setAttribute("aria-disabled","true"),this.type===le&&this.element.setAttribute("tabindex","-1"),this.isDisabled=!0},t.wrap=function(e){!function(e,t){void 0===t&&(t=document.createElement("div")),e.nextSibling?e.parentNode.insertBefore(t,e.nextSibling):e.parentNode.appendChild(t),t.appendChild(e)}(e,this.element)},t.unwrap=function(e){this.element.parentNode.insertBefore(e,this.element),this.element.parentNode.removeChild(this.element)},t.addLoadingState=function(){this.element.classList.add(this.classNames.loadingState),this.element.setAttribute("aria-busy","true"),this.isLoading=!0},t.removeLoadingState=function(){this.element.classList.remove(this.classNames.loadingState),this.element.removeAttribute("aria-busy"),this.isLoading=!1},t._onFocus=function(){this.isFocussed=!0},t._onBlur=function(){this.isFocussed=!1},e}();function de(e,t){for(var i=0;i0?this.element.scrollTop+o-s:e.offsetTop;requestAnimationFrame((function(){i._animateScroll(a,t)}))}},t._scrollDown=function(e,t,i){var n=(i-e)/t,s=n>1?n:1;this.element.scrollTop=e+s},t._scrollUp=function(e,t,i){var n=(e-i)/t,s=n>1?n:1;this.element.scrollTop=e-s},t._animateScroll=function(e,t){var i=this,n=this.element.scrollTop,s=!1;t>0?(this._scrollDown(n,4,e),ne&&(s=!0)),s&&requestAnimationFrame((function(){i._animateScroll(e,t)}))},e}();function fe(e,t){for(var i=0;i0?"treeitem":"option"),Object.assign(f.dataset,{choice:"",id:c,value:l,selectText:i}),p?(f.dataset.choiceDisabled="",f.setAttribute("aria-disabled","true")):f.dataset.choiceSelectable="",f},input:function(e,t){var i=e.input,n=e.inputCloned,s=Object.assign(document.createElement("input"),{type:"text",className:i+" "+n,autocomplete:"off",autocapitalize:"off",spellcheck:!1});return s.setAttribute("role","textbox"),s.setAttribute("aria-autocomplete","list"),s.setAttribute("aria-label",t),s},dropdown:function(e){var t=e.list,i=e.listDropdown,n=document.createElement("div");return n.classList.add(t,i),n.setAttribute("aria-expanded","false"),n},notice:function(e,t,i){var n=e.item,s=e.itemChoice,r=e.noResults,o=e.noChoices;void 0===i&&(i="");var a=[n,s];return"no-choices"===i?a.push(o):"no-results"===i&&a.push(r),Object.assign(document.createElement("div"),{innerHTML:t,className:a.join(" ")})},option:function(e){var t=e.label,i=e.value,n=e.customProperties,s=e.active,r=e.disabled,o=new Option(t,i,!1,s);return n&&(o.dataset.customProperties=n),o.disabled=r,o}},Ie=function(e){return void 0===e&&(e=!0),{type:W,active:e}},Se=function(e,t){return{type:Z,id:e,highlighted:t}},we=function(e){var t=e.value,i=e.id,n=e.active,s=e.disabled;return{type:$,value:t,id:i,active:n,disabled:s}};function Oe(e,t){for(var i=0;i=0?this._store.getGroupById(s):null;return this._store.dispatch(Se(i,!0)),t&&this.passedElement.triggerEvent(G,{id:i,value:o,label:c,groupValue:l&&l.value?l.value:null}),this},r.unhighlightItem=function(e){if(!e)return this;var t=e.id,i=e.groupId,n=void 0===i?-1:i,s=e.value,r=void 0===s?"":s,o=e.label,a=void 0===o?"":o,c=n>=0?this._store.getGroupById(n):null;return this._store.dispatch(Se(t,!1)),this.passedElement.triggerEvent(G,{id:t,value:r,label:a,groupValue:c&&c.value?c.value:null}),this},r.highlightAll=function(){var e=this;return this._store.items.forEach((function(t){return e.highlightItem(t)})),this},r.unhighlightAll=function(){var e=this;return this._store.items.forEach((function(t){return e.unhighlightItem(t)})),this},r.removeActiveItemsByValue=function(e){var t=this;return this._store.activeItems.filter((function(t){return t.value===e})).forEach((function(e){return t._removeItem(e)})),this},r.removeActiveItems=function(e){var t=this;return this._store.activeItems.filter((function(t){return t.id!==e})).forEach((function(e){return t._removeItem(e)})),this},r.removeHighlightedItems=function(e){var t=this;return void 0===e&&(e=!1),this._store.highlightedActiveItems.forEach((function(i){t._removeItem(i),e&&t._triggerChange(i.value)})),this},r.showDropdown=function(e){var t=this;return this.dropdown.isActive?this:(requestAnimationFrame((function(){t.dropdown.show(),t.containerOuter.open(t.dropdown.distanceFromTopWindow),!e&&t._canSearch&&t.input.focus(),t.passedElement.triggerEvent(F,{})})),this)},r.hideDropdown=function(e){var t=this;return this.dropdown.isActive?(requestAnimationFrame((function(){t.dropdown.hide(),t.containerOuter.close(),!e&&t._canSearch&&(t.input.removeActiveDescendant(),t.input.blur()),t.passedElement.triggerEvent(j,{})})),this):this},r.getValue=function(e){void 0===e&&(e=!1);var t=this._store.activeItems.reduce((function(t,i){var n=e?i.value:i;return t.push(n),t}),[]);return this._isSelectOneElement?t[0]:t},r.setValue=function(e){var t=this;return this.initialised?(e.forEach((function(e){return t._setChoiceOrItem(e)})),this):this},r.setChoiceByValue=function(e){var t=this;return!this.initialised||this._isTextElement?this:((Array.isArray(e)?e:[e]).forEach((function(e){return t._findAndSelectChoiceByValue(e)})),this)},r.setChoices=function(e,t,i,n){var s=this;if(void 0===e&&(e=[]),void 0===t&&(t="value"),void 0===i&&(i="label"),void 0===n&&(n=!1),!this.initialised)throw new ReferenceError("setChoices was called on a non-initialized instance of Choices");if(!this._isSelectElement)throw new TypeError("setChoices can't be used with INPUT based Choices");if("string"!=typeof t||!t)throw new TypeError("value parameter must be a name of 'value' field in passed objects");if(n&&this.clearChoices(),"function"==typeof e){var r=e(this);if("function"==typeof Promise&&r instanceof Promise)return new Promise((function(e){return requestAnimationFrame(e)})).then((function(){return s._handleLoadingState(!0)})).then((function(){return r})).then((function(e){return s.setChoices(e,t,i,n)})).catch((function(e){s.config.silent||console.error(e)})).then((function(){return s._handleLoadingState(!1)})).then((function(){return s}));if(!Array.isArray(r))throw new TypeError(".setChoices first argument function must return either array of choices or Promise, got: "+typeof r);return this.setChoices(r,t,i,!1)}if(!Array.isArray(e))throw new TypeError(".setChoices must be called either with array of choices with a function resulting into Promise of array of choices");return this.containerOuter.removeLoadingState(),this._setLoading(!0),e.forEach((function(e){e.choices?s._addGroup({group:e,id:e.id||null,valueKey:t,labelKey:i}):s._addChoice({value:e[t],label:e[i],isSelected:e.selected,isDisabled:e.disabled,customProperties:e.customProperties,placeholder:e.placeholder})})),this._setLoading(!1),this},r.clearChoices=function(){return this._store.dispatch({type:X}),this},r.clearStore=function(){return this._store.dispatch({type:"CLEAR_ALL"}),this},r.clearInput=function(){var e=!this._isSelectOneElement;return this.input.clear(e),!this._isTextElement&&this._canSearch&&(this._isSearching=!1,this._store.dispatch(Ie(!0))),this},r._render=function(){if(!this._store.isLoading()){this._currentState=this._store.state;var e=this._currentState.choices!==this._prevState.choices||this._currentState.groups!==this._prevState.groups||this._currentState.items!==this._prevState.items,t=this._isSelectElement,i=this._currentState.items!==this._prevState.items;e&&(t&&this._renderChoices(),i&&this._renderItems(),this._prevState=this._currentState)}},r._renderChoices=function(){var e=this,t=this._store,i=t.activeGroups,n=t.activeChoices,s=document.createDocumentFragment();if(this.choiceList.clear(),this.config.resetScrollPosition&&requestAnimationFrame((function(){return e.choiceList.scrollToTop()})),i.length>=1&&!this._isSearching){var r=n.filter((function(e){return!0===e.placeholder&&-1===e.groupId}));r.length>=1&&(s=this._createChoicesFragment(r,s)),s=this._createGroupsFragment(i,n,s)}else n.length>=1&&(s=this._createChoicesFragment(n,s));if(s.childNodes&&s.childNodes.length>0){var o=this._store.activeItems,a=this._canAddItem(o,this.input.value);a.response?(this.choiceList.append(s),this._highlightChoice()):this.choiceList.append(this._getTemplate("notice",a.notice))}else{var c,l;this._isSearching?(l="function"==typeof this.config.noResultsText?this.config.noResultsText():this.config.noResultsText,c=this._getTemplate("notice",l,"no-results")):(l="function"==typeof this.config.noChoicesText?this.config.noChoicesText():this.config.noChoicesText,c=this._getTemplate("notice",l,"no-choices")),this.choiceList.append(c)}},r._renderItems=function(){var e=this._store.activeItems||[];this.itemList.clear();var t=this._createItemsFragment(e);t.childNodes&&this.itemList.append(t)},r._createGroupsFragment=function(e,t,i){var n=this;void 0===i&&(i=document.createDocumentFragment());return this.config.shouldSort&&e.sort(this.config.sorter),e.forEach((function(e){var s=function(e){return t.filter((function(t){return n._isSelectOneElement?t.groupId===e.id:t.groupId===e.id&&("always"===n.config.renderSelectedChoices||!t.selected)}))}(e);if(s.length>=1){var r=n._getTemplate("choiceGroup",e);i.appendChild(r),n._createChoicesFragment(s,i,!0)}})),i},r._createChoicesFragment=function(e,t,i){var n=this;void 0===t&&(t=document.createDocumentFragment()),void 0===i&&(i=!1);var s=this.config,r=s.renderSelectedChoices,o=s.searchResultLimit,a=s.renderChoiceLimit,c=this._isSearching?C:this.config.sorter,l=function(e){if("auto"!==r||(n._isSelectOneElement||!e.selected)){var i=n._getTemplate("choice",e,n.config.itemSelectText);t.appendChild(i)}},h=e;"auto"!==r||this._isSelectOneElement||(h=e.filter((function(e){return!e.selected})));var u=h.reduce((function(e,t){return t.placeholder?e.placeholderChoices.push(t):e.normalChoices.push(t),e}),{placeholderChoices:[],normalChoices:[]}),d=u.placeholderChoices,p=u.normalChoices;(this.config.shouldSort||this._isSearching)&&p.sort(c);var m=h.length,f=this._isSelectOneElement?[].concat(d,p):p;this._isSearching?m=o:a&&a>0&&!i&&(m=a);for(var v=0;v=n){var o=s?this._searchChoices(e):0;this.passedElement.triggerEvent(B,{value:e,resultCount:o})}else r&&(this._isSearching=!1,this._store.dispatch(Ie(!0)))}},r._canAddItem=function(e,t){var i=!0,n="function"==typeof this.config.addItemText?this.config.addItemText(t):this.config.addItemText;if(!this._isSelectOneElement){var s=function(e,t,i){return void 0===i&&(i="value"),e.some((function(e){return"string"==typeof t?e[i]===t.trim():e[i]===t}))}(e,t);this.config.maxItemCount>0&&this.config.maxItemCount<=e.length&&(i=!1,n="function"==typeof this.config.maxItemText?this.config.maxItemText(this.config.maxItemCount):this.config.maxItemText),!this.config.duplicateItemsAllowed&&s&&i&&(i=!1,n="function"==typeof this.config.uniqueItemText?this.config.uniqueItemText(t):this.config.uniqueItemText),this._isTextElement&&this.config.addItems&&i&&"function"==typeof this.config.addItemFilter&&!this.config.addItemFilter(t)&&(i=!1,n="function"==typeof this.config.customAddItemText?this.config.customAddItemText(t):this.config.customAddItemText)}return{response:i,notice:n}},r._searchChoices=function(e){var t="string"==typeof e?e.trim():e,i="string"==typeof this._currentValue?this._currentValue.trim():this._currentValue;if(t.length<1&&t===i+" ")return 0;var n=this._store.searchableChoices,r=t,o=[].concat(this.config.searchFields),a=Object.assign(this.config.fuseOptions,{keys:o}),c=new s.a(n,a).search(r);return this._currentValue=t,this._highlightPosition=0,this._isSearching=!0,this._store.dispatch(function(e){return{type:z,results:e}}(c)),c.length},r._addEventListeners=function(){var e=document.documentElement;e.addEventListener("keydown",this._onKeyDown,!0),e.addEventListener("touchend",this._onTouchEnd,!0),e.addEventListener("mousedown",this._onMouseDown,!0),e.addEventListener("click",this._onClick,{passive:!0}),e.addEventListener("touchmove",this._onTouchMove,{passive:!0}),e.addEventListener("mouseover",this._onMouseOver,{passive:!0}),this._isSelectOneElement&&(this.containerOuter.element.addEventListener("focus",this._onFocus,{passive:!0}),this.containerOuter.element.addEventListener("blur",this._onBlur,{passive:!0})),this.input.element.addEventListener("keyup",this._onKeyUp,{passive:!0}),this.input.element.addEventListener("focus",this._onFocus,{passive:!0}),this.input.element.addEventListener("blur",this._onBlur,{passive:!0}),this.input.element.form&&this.input.element.form.addEventListener("reset",this._onFormReset,{passive:!0}),this.input.addEventListeners()},r._removeEventListeners=function(){var e=document.documentElement;e.removeEventListener("keydown",this._onKeyDown,!0),e.removeEventListener("touchend",this._onTouchEnd,!0),e.removeEventListener("mousedown",this._onMouseDown,!0),e.removeEventListener("keyup",this._onKeyUp,{passive:!0}),e.removeEventListener("click",this._onClick,{passive:!0}),e.removeEventListener("touchmove",this._onTouchMove,{passive:!0}),e.removeEventListener("mouseover",this._onMouseOver,{passive:!0}),this._isSelectOneElement&&(this.containerOuter.element.removeEventListener("focus",this._onFocus,{passive:!0}),this.containerOuter.element.removeEventListener("blur",this._onBlur,{passive:!0})),this.input.element.removeEventListener("focus",this._onFocus,{passive:!0}),this.input.element.removeEventListener("blur",this._onBlur,{passive:!0}),this.input.element.form&&this.input.element.form.removeEventListener("reset",this._onFormReset,{passive:!0}),this.input.removeEventListeners()},r._onKeyDown=function(e){var t,i=e.target,n=e.keyCode,s=e.ctrlKey,r=e.metaKey;if(i===this.input.element||this.containerOuter.element.contains(i)){var o=this._store.activeItems,a=this.input.isFocussed,c=this.dropdown.isActive,l=this.itemList.hasChildren(),h=String.fromCharCode(n),u=Q,d=ee,p=te,m=ie,f=ne,v=se,g=re,_=oe,b=ae,y=s||r;!this._isTextElement&&/[a-zA-Z0-9-_ ]/.test(h)&&this.showDropdown();var E=((t={})[m]=this._onAKey,t[p]=this._onEnterKey,t[f]=this._onEscapeKey,t[v]=this._onDirectionKey,t[_]=this._onDirectionKey,t[g]=this._onDirectionKey,t[b]=this._onDirectionKey,t[d]=this._onDeleteKey,t[u]=this._onDeleteKey,t);E[n]&&E[n]({event:e,target:i,keyCode:n,metaKey:r,activeItems:o,hasFocusedInput:a,hasActiveDropdown:c,hasItems:l,hasCtrlDownKeyPressed:y})}},r._onKeyUp=function(e){var t=e.target,i=e.keyCode,n=this.input.value,s=this._store.activeItems,r=this._canAddItem(s,n),o=Q,a=ee;if(this._isTextElement){if(r.notice&&n){var c=this._getTemplate("notice",r.notice);this.dropdown.element.innerHTML=c.outerHTML,this.showDropdown(!0)}else this.hideDropdown(!0)}else{var l=(i===o||i===a)&&!t.value,h=!this._isTextElement&&this._isSearching,u=this._canSearch&&r.response;l&&h?(this._isSearching=!1,this._store.dispatch(Ie(!0))):u&&this._handleSearch(this.input.value)}this._canSearch=this.config.searchEnabled},r._onAKey=function(e){var t=e.hasItems;e.hasCtrlDownKeyPressed&&t&&(this._canSearch=!1,this.config.removeItems&&!this.input.value&&this.input.element===document.activeElement&&this.highlightAll())},r._onEnterKey=function(e){var t=e.event,i=e.target,n=e.activeItems,s=e.hasActiveDropdown,r=te,o=i.hasAttribute("data-button");if(this._isTextElement&&i.value){var a=this.input.value;this._canAddItem(n,a).response&&(this.hideDropdown(!0),this._addItem({value:a}),this._triggerChange(a),this.clearInput())}if(o&&(this._handleButtonAction(n,i),t.preventDefault()),s){var c=this.dropdown.getChild("."+this.config.classNames.highlightedState);c&&(n[0]&&(n[0].keyCode=r),this._handleChoiceAction(n,c)),t.preventDefault()}else this._isSelectOneElement&&(this.showDropdown(),t.preventDefault())},r._onEscapeKey=function(e){e.hasActiveDropdown&&(this.hideDropdown(!0),this.containerOuter.focus())},r._onDirectionKey=function(e){var t,i,n,s=e.event,r=e.hasActiveDropdown,o=e.keyCode,a=e.metaKey,c=re,l=oe,h=ae;if(r||this._isSelectOneElement){this.showDropdown(),this._canSearch=!1;var u,d=o===c||o===h?1:-1;if(a||o===h||o===l)u=d>0?this.dropdown.element.querySelector("[data-choice-selectable]:last-of-type"):this.dropdown.element.querySelector("[data-choice-selectable]");else{var p=this.dropdown.element.querySelector("."+this.config.classNames.highlightedState);u=p?function(e,t,i){if(void 0===i&&(i=1),e instanceof Element&&"string"==typeof t){for(var n=(i>0?"next":"previous")+"ElementSibling",s=e[n];s;){if(s.matches(t))return s;s=s[n]}return s}}(p,"[data-choice-selectable]",d):this.dropdown.element.querySelector("[data-choice-selectable]")}u&&(t=u,i=this.choiceList.element,void 0===(n=d)&&(n=1),t&&(n>0?i.scrollTop+i.offsetHeight>=t.offsetTop+t.offsetHeight:t.offsetTop>=i.scrollTop)||this.choiceList.scrollToChildElement(u,d),this._highlightChoice(u)),s.preventDefault()}},r._onDeleteKey=function(e){var t=e.event,i=e.target,n=e.hasFocusedInput,s=e.activeItems;!n||i.value||this._isSelectOneElement||(this._handleBackspace(s),t.preventDefault())},r._onTouchMove=function(){this._wasTap&&(this._wasTap=!1)},r._onTouchEnd=function(e){var t=(e||e.touches[0]).target;this._wasTap&&this.containerOuter.element.contains(t)&&((t===this.containerOuter.element||t===this.containerInner.element)&&(this._isTextElement?this.input.focus():this._isSelectMultipleElement&&this.showDropdown()),e.stopPropagation());this._wasTap=!0},r._onMouseDown=function(e){var t,i=e.target,n=e.shiftKey;if(this.choiceList.element.contains(i)&&((t=navigator.userAgent).match(/Trident/)&&t.match(/rv[ :]11/))&&(this._isScrollingOnIe=!0),this.containerOuter.element.contains(i)&&i!==this.input.element){var s=this._store.activeItems,r=n,o=S(i,"data-button"),a=S(i,"data-item"),c=S(i,"data-choice");o?this._handleButtonAction(s,o):a?this._handleItemAction(s,a,r):c&&this._handleChoiceAction(s,c),e.preventDefault()}},r._onMouseOver=function(e){var t=e.target;(t===this.dropdown||this.dropdown.element.contains(t))&&t.hasAttribute("data-choice")&&this._highlightChoice(t)},r._onClick=function(e){var t=e.target;this.containerOuter.element.contains(t)?this.dropdown.isActive||this.containerOuter.isDisabled?this._isSelectOneElement&&t!==this.input.element&&!this.dropdown.element.contains(t)&&this.hideDropdown():this._isTextElement?document.activeElement!==this.input.element&&this.input.focus():(this.showDropdown(),this.containerOuter.focus()):(this._store.highlightedActiveItems.length>0&&this.unhighlightAll(),this.containerOuter.removeFocusState(),this.hideDropdown(!0))},r._onFocus=function(e){var t,i=this,n=e.target;this.containerOuter.element.contains(n)&&((t={})[ce]=function(){n===i.input.element&&i.containerOuter.addFocusState()},t[le]=function(){i.containerOuter.addFocusState(),n===i.input.element&&i.showDropdown(!0)},t[he]=function(){n===i.input.element&&(i.showDropdown(!0),i.containerOuter.addFocusState())},t)[this.passedElement.element.type]()},r._onBlur=function(e){var t=this,i=e.target;if(this.containerOuter.element.contains(i)&&!this._isScrollingOnIe){var n,s=this._store.activeItems.some((function(e){return e.highlighted}));((n={})[ce]=function(){i===t.input.element&&(t.containerOuter.removeFocusState(),s&&t.unhighlightAll(),t.hideDropdown(!0))},n[le]=function(){t.containerOuter.removeFocusState(),(i===t.input.element||i===t.containerOuter.element&&!t._canSearch)&&t.hideDropdown(!0)},n[he]=function(){i===t.input.element&&(t.containerOuter.removeFocusState(),t.hideDropdown(!0),s&&t.unhighlightAll())},n)[this.passedElement.element.type]()}else this._isScrollingOnIe=!1,this.input.element.focus()},r._onFormReset=function(){this._store.dispatch({type:"RESET_TO",state:this._initialState})},r._highlightChoice=function(e){var t=this;void 0===e&&(e=null);var i=Array.from(this.dropdown.element.querySelectorAll("[data-choice-selectable]"));if(i.length){var n=e;Array.from(this.dropdown.element.querySelectorAll("."+this.config.classNames.highlightedState)).forEach((function(e){e.classList.remove(t.config.classNames.highlightedState),e.setAttribute("aria-selected","false")})),n?this._highlightPosition=i.indexOf(n):(n=i.length>this._highlightPosition?i[this._highlightPosition]:i[i.length-1])||(n=i[0]),n.classList.add(this.config.classNames.highlightedState),n.setAttribute("aria-selected","true"),this.passedElement.triggerEvent(q,{el:n}),this.dropdown.isActive&&(this.input.setActiveDescendant(n.id),this.containerOuter.setActiveDescendant(n.id))}},r._addItem=function(e){var t=e.value,i=e.label,n=void 0===i?null:i,s=e.choiceId,r=void 0===s?-1:s,o=e.groupId,a=void 0===o?-1:o,c=e.customProperties,l=void 0===c?null:c,h=e.placeholder,u=void 0!==h&&h,d=e.keyCode,p=void 0===d?null:d,m="string"==typeof t?t.trim():t,f=p,v=l,g=this._store.items,_=n||m,b=parseInt(r,10)||-1,y=a>=0?this._store.getGroupById(a):null,E=g?g.length+1:1;return this.config.prependValue&&(m=this.config.prependValue+m.toString()),this.config.appendValue&&(m+=this.config.appendValue.toString()),this._store.dispatch(function(e){var t=e.value,i=e.label,n=e.id,s=e.choiceId,r=e.groupId,o=e.customProperties,a=e.placeholder,c=e.keyCode;return{type:J,value:t,label:i,id:n,choiceId:s,groupId:r,customProperties:o,placeholder:a,keyCode:c}}({value:m,label:_,id:E,choiceId:b,groupId:a,customProperties:l,placeholder:u,keyCode:f})),this._isSelectOneElement&&this.removeActiveItems(E),this.passedElement.triggerEvent(H,{id:E,value:m,label:_,customProperties:v,groupValue:y&&y.value?y.value:void 0,keyCode:f}),this},r._removeItem=function(e){if(!e||!I("Object",e))return this;var t=e.id,i=e.value,n=e.label,s=e.choiceId,r=e.groupId,o=r>=0?this._store.getGroupById(r):null;return this._store.dispatch(function(e,t){return{type:Y,id:e,choiceId:t}}(t,s)),o&&o.value?this.passedElement.triggerEvent(V,{id:t,value:i,label:n,groupValue:o.value}):this.passedElement.triggerEvent(V,{id:t,value:i,label:n}),this},r._addChoice=function(e){var t=e.value,i=e.label,n=void 0===i?null:i,s=e.isSelected,r=void 0!==s&&s,o=e.isDisabled,a=void 0!==o&&o,c=e.groupId,l=void 0===c?-1:c,h=e.customProperties,u=void 0===h?null:h,d=e.placeholder,p=void 0!==d&&d,m=e.keyCode,f=void 0===m?null:m;if(null!=t){var v=this._store.choices,g=n||t,_=v?v.length+1:1,b=this._baseId+"-"+this._idNames.itemChoice+"-"+_;this._store.dispatch(function(e){var t=e.value,i=e.label,n=e.id,s=e.groupId,r=e.disabled,o=e.elementId,a=e.customProperties,c=e.placeholder,l=e.keyCode;return{type:U,value:t,label:i,id:n,groupId:s,disabled:r,elementId:o,customProperties:a,placeholder:c,keyCode:l}}({value:t,label:g,id:_,groupId:l,disabled:a,elementId:b,customProperties:u,placeholder:p,keyCode:f})),r&&this._addItem({value:t,label:g,choiceId:_,customProperties:u,placeholder:p,keyCode:f})}},r._addGroup=function(e){var t=this,i=e.group,n=e.id,s=e.valueKey,r=void 0===s?"value":s,o=e.labelKey,a=void 0===o?"label":o,c=I("Object",i)?i.choices:Array.from(i.getElementsByTagName("OPTION")),l=n||Math.floor((new Date).valueOf()*Math.random()),h=!!i.disabled&&i.disabled;if(c){this._store.dispatch(we({value:i.label,id:l,active:!0,disabled:h}));c.forEach((function(e){var i=e.disabled||e.parentNode&&e.parentNode.disabled;t._addChoice({value:e[r],label:I("Object",e)?e[a]:e.innerHTML,isSelected:e.selected,isDisabled:i,groupId:l,customProperties:e.customProperties,placeholder:e.placeholder})}))}else this._store.dispatch(we({value:i.label,id:i.id,active:!1,disabled:i.disabled}))},r._getTemplate=function(e){var t;if(!e)return null;for(var i=this.config.classNames,n=arguments.length,s=new Array(n>1?n-1:0),r=1;r + @@ -336,8 +337,8 @@ data-trigger name="choices-single-groups" id="choices-single-groups" - placeholder="This is a placeholder" > + @@ -376,7 +377,6 @@ data-trigger name="choices-single-rtl" id="choices-single-rtl" - placeholder="This is a placeholder" dir="rtl" > @@ -402,7 +402,6 @@ class="form-control" name="choices-single-preset-options" id="choices-single-preset-options" - placeholder="This is a placeholder" >