From 0e44a916e32a5cddd43406906253619d08b45f11 Mon Sep 17 00:00:00 2001 From: Josh Johnson Date: Tue, 29 Oct 2019 21:19:56 +0000 Subject: [PATCH] Fix constructor (#693) * breaking test * Remove ablity to pass multiple elements + tests * Update readme * Update README.md * :bookmark: Version 8.0.0 * Remove type definition hack * Update coverage command * Add some missing list tests * Remove .only * Update demo page to loop over elements * Update constructor to set initialised flag if already active * Make templates private * Throw type error once if element is invalid * Fix list children bug * Re-add generic examples to index.html * Housekeeping * Use typeof instead of isType where applicable * Remove isElement * Add test for isIE11 --- .eslintrc.json | 3 +- .github/workflows/publish.yml | 4 +- .github/workflows/unit-tests.yml | 2 +- README.md | 13 +- config/jsdom.js | 4 + package-lock.json | 2 +- package.json | 4 +- public/assets/scripts/choices.js | 860 ++++++++++++---------- public/assets/scripts/choices.min.js | 6 +- public/assets/styles/base.css | 3 +- public/assets/styles/base.min.css | 2 +- public/assets/styles/choices.css | 3 +- public/assets/styles/choices.min.css | 2 +- public/index.html | 9 + src/scripts/choices.js | 155 ++-- src/scripts/choices.test.js | 205 +++++- src/scripts/components/list.js | 29 +- src/scripts/components/list.test.js | 31 + src/scripts/components/wrapped-element.js | 4 +- src/scripts/lib/utils.js | 13 +- src/scripts/lib/utils.test.js | 22 +- types/index.d.ts | 10 - 22 files changed, 842 insertions(+), 544 deletions(-) diff --git a/.eslintrc.json b/.eslintrc.json index 4b6b5a0..e392363 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -64,7 +64,8 @@ }, "rules": { "no-restricted-syntax": "off", - "compat/compat": "off" + "compat/compat": "off", + "no-new": "off" } }, { diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 5367e2a..7175ac7 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -20,7 +20,7 @@ jobs: npm ci npm run build npx bundlesize - npm run coverage + npm run test:unit:coverage npm run test:e2e env: CI: true @@ -85,4 +85,4 @@ jobs: env: ACTIONS_DEPLOY_KEY: ${{ secrets.ACTIONS_DEPLOY_KEY }} PUBLISH_BRANCH: gh-pages - PUBLISH_DIR: ./public \ No newline at end of file + PUBLISH_DIR: ./public diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml index 2a2e380..e0136ca 100644 --- a/.github/workflows/unit-tests.yml +++ b/.github/workflows/unit-tests.yml @@ -25,7 +25,7 @@ jobs: CYPRESS_INSTALL_BINARY: 0 HUSKY_SKIP_INSTALL: true - - run: npm run coverage + - run: npm run test:unit:coverage env: FORCE_COLOR: 2 diff --git a/README.md b/README.md index a414ed1..3bce930 100644 --- a/README.md +++ b/README.md @@ -67,14 +67,11 @@ Or include Choices directly: ## Setup -If you pass a selector which targets multiple elements, an array of Choices instances -will be returned. If you target one element, that instance will be returned. +**Note:** If you pass a selector which targets multiple elements, the first matching element will be used. Versions prior to 8.x.x would return multiple Choices instances. ```js - // Pass multiple elements: - const [firstInstance, secondInstance] = new Choices(elements); - - // Pass single element: + // Pass single element + const element = document.querySelector('.js-choice'); const choices = new Choices(element); // Pass reference @@ -84,8 +81,8 @@ will be returned. If you target one element, that instance will be returned. // Pass jQuery element const choices = new Choices($('.js-choice')[0]); - // Passing options (with default options) - const choices = new Choices(elements, { + // Passing options (with default options) + const choices = new Choices(element, { silent: false, items: [], choices: [], diff --git a/config/jsdom.js b/config/jsdom.js index 30ef6ef..301e35c 100644 --- a/config/jsdom.js +++ b/config/jsdom.js @@ -1,3 +1,5 @@ +/* eslint-disable no-param-reassign */ + const { JSDOM } = require('jsdom'); const jsdom = new JSDOM( @@ -36,6 +38,8 @@ global.HTMLElement = window.HTMLElement; global.Option = window.Option; global.HTMLOptionElement = window.HTMLOptionElement; global.HTMLOptGroupElement = window.HTMLOptGroupElement; +global.HTMLSelectElement = window.HTMLSelectElement; +global.HTMLInputElement = window.HTMLInputElement; global.DocumentFragment = window.DocumentFragment; global.requestAnimationFrame = window.requestAnimationFrame; diff --git a/package-lock.json b/package-lock.json index 575cc4e..01af5f5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "choices.js", - "version": "7.1.5", + "version": "8.0.0", "lockfileVersion": 1, "requires": true, "dependencies": { diff --git a/package.json b/package.json index f9272ae..2154319 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "choices.js", - "version": "7.1.5", + "version": "8.0.0", "description": "A vanilla JS customisable text input/select box plugin", "main": "./public/assets/scripts/choices.js", "types": "./types/index.d.ts", @@ -8,7 +8,6 @@ "start": "run-p js:watch css:watch", "build": "run-p js:build css:build", "lint": "eslint src/scripts", - "coverage": "NODE_ENV=test nyc --reporter=lcov --reporter=text --reporter=text-summary mocha", "bundlesize": "bundlesize", "cypress:run": "$(npm bin)/cypress run", "cypress:open": "$(npm bin)/cypress open", @@ -16,6 +15,7 @@ "test": "run-s test:unit test:e2e", "test:unit": "NODE_ENV=test mocha", "test:unit:watch": "NODE_ENV=test mocha --watch --inspect=5556", + "test:unit:coverage": "NODE_ENV=test nyc --reporter=lcov --reporter=text --reporter=text-summary mocha", "test:e2e": "run-p --race start cypress:run", "js:watch": "NODE_ENV=development node server.js", "js:build": "webpack --config webpack.config.prod.js", diff --git a/public/assets/scripts/choices.js b/public/assets/scripts/choices.js index fa969aa..b748d0f 100644 --- a/public/assets/scripts/choices.js +++ b/public/assets/scripts/choices.js @@ -1,4 +1,4 @@ -/*! choices.js v7.1.5 | © 2019 Josh Johnson | https://github.com/jshjohnson/Choices#readme */ +/*! choices.js v8.0.0 | © 2019 Josh Johnson | https://github.com/jshjohnson/Choices#readme */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); @@ -257,7 +257,7 @@ if (typeof self !== 'undefined') { var result = Object(_ponyfill_js__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"])(root); /* harmony default export */ __webpack_exports__["a"] = (result); -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(6), __webpack_require__(7)(module))) +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(5), __webpack_require__(6)(module))) /***/ }), /* 2 */ @@ -302,65 +302,13 @@ function symbolObservablePonyfill(root) { /* 4 */ /***/ (function(module, exports, __webpack_require__) { -module.exports = __webpack_require__(8); +module.exports = __webpack_require__(7); /***/ }), /* 5 */ /***/ (function(module, exports) { -window.delegateEvent = function delegateEvent() { - var events; - var addedListenerTypes; - - if (typeof events === 'undefined') { - events = new Map(); - } - - if (typeof addedListenerTypes === 'undefined') { - addedListenerTypes = []; - } - - function _callback(event) { - var type = events.get(event.type); - if (!type) return; - type.forEach(function (fn) { - return fn(event); - }); - } - - return { - add: function add(type, fn) { - // Cache list of events. - if (events.has(type)) { - events.get(type).push(fn); - } else { - events.set(type, [fn]); - } // Setup events. - - - if (addedListenerTypes.indexOf(type) === -1) { - document.documentElement.addEventListener(type, _callback, true); - addedListenerTypes.push(type); - } - }, - remove: function remove(type, fn) { - if (!events.get(type)) return; - events.set(type, events.get(type).filter(function (item) { - return item !== fn; - })); - - if (!events.get(type).length) { - addedListenerTypes.splice(addedListenerTypes.indexOf(type), 1); - } - } - }; -}(); - -/***/ }), -/* 6 */ -/***/ (function(module, exports) { - var g; // This works in non-strict mode @@ -384,7 +332,7 @@ module.exports = g; /***/ }), -/* 7 */ +/* 6 */ /***/ (function(module, exports) { module.exports = function(originalModule) { @@ -414,7 +362,7 @@ module.exports = function(originalModule) { /***/ }), -/* 8 */ +/* 7 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -428,9 +376,6 @@ var fuse_default = /*#__PURE__*/__webpack_require__.n(dist_fuse); var cjs = __webpack_require__(0); var cjs_default = /*#__PURE__*/__webpack_require__.n(cjs); -// EXTERNAL MODULE: ./src/scripts/lib/delegate-events.js -var delegate_events = __webpack_require__(5); - // EXTERNAL MODULE: ./node_modules/symbol-observable/es/index.js var es = __webpack_require__(1); @@ -1362,18 +1307,13 @@ var utils_wrap = function wrap(element, wrapper) { return wrapper.appendChild(element); }; +/** + * @param {HTMLElement} el + * @param {string} attr + */ + var findAncestorByAttrName = function findAncestorByAttrName(el, attr) { - var target = el; - - while (target) { - if (target.hasAttribute(attr)) { - return target; - } - - target = target.parentElement; - } - - return null; + return el.closest("[" + attr + "]"); }; var getAdjacentEl = function getAdjacentEl(startEl, className, direction) { if (direction === void 0) { @@ -1432,19 +1372,24 @@ var strToEl = function () { return firldChild; }; }(); -var sortByAlpha = function sortByAlpha(a, b) { - var labelA = ("" + (a.label || a.value)).toLowerCase(); - var labelB = ("" + (b.label || b.value)).toLowerCase(); - - if (labelA < labelB) { - return -1; - } - - if (labelA > labelB) { - return 1; - } - - return 0; +var sortByAlpha = +/** + * @param {{ label?: string, value: string }} a + * @param {{ label?: string, value: string }} b + * @returns {number} + */ +function sortByAlpha(_ref, _ref2) { + var value = _ref.value, + _ref$label = _ref.label, + label = _ref$label === void 0 ? value : _ref$label; + var value2 = _ref2.value, + _ref2$label = _ref2.label, + label2 = _ref2$label === void 0 ? value2 : _ref2$label; + return label.localeCompare(label2, [], { + sensitivity: 'base', + ignorePunctuation: true, + numeric: true + }); }; var sortByScore = function sortByScore(a, b) { return a.score - b.score; @@ -1467,15 +1412,6 @@ var getWindowHeight = function getWindowHeight() { var html = document.documentElement; return Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight); }; -var fetchFromObject = function fetchFromObject(object, path) { - var index = path.indexOf('.'); - - if (index > -1) { - return fetchFromObject(object[path.substring(0, index)], path.substr(index + 1)); - } - - return object[path]; -}; var isIE11 = function isIE11() { return !!(navigator.userAgent.match(/Trident/) && navigator.userAgent.match(/rv[ :]11/)); }; @@ -2035,21 +1971,23 @@ function input_createClass(Constructor, protoProps, staticProps) { if (protoProp 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 + */ function Input(_ref) { var element = _ref.element, type = _ref.type, classNames = _ref.classNames, - placeholderValue = _ref.placeholderValue; - Object.assign(this, { - element: element, - type: type, - classNames: classNames, - placeholderValue: placeholderValue - }); + preventPaste = _ref.preventPaste; this.element = element; + this.type = type; this.classNames = classNames; + this.preventPaste = preventPaste; this.isFocussed = this.element === document.activeElement; - this.isDisabled = false; + this.isDisabled = element.disabled; this._onPaste = this._onPaste.bind(this); this._onInput = this._onInput.bind(this); this._onFocus = this._onFocus.bind(this); @@ -2059,25 +1997,29 @@ function () { var _proto = Input.prototype; _proto.addEventListeners = function addEventListeners() { - this.element.addEventListener('input', this._onInput); this.element.addEventListener('paste', this._onPaste); - this.element.addEventListener('focus', this._onFocus); - this.element.addEventListener('blur', this._onBlur); - - if (this.element.form) { - this.element.form.addEventListener('reset', this._onFormReset); - } + this.element.addEventListener('input', this._onInput, { + passive: true + }); + this.element.addEventListener('focus', this._onFocus, { + passive: true + }); + this.element.addEventListener('blur', this._onBlur, { + passive: true + }); }; _proto.removeEventListeners = function removeEventListeners() { - this.element.removeEventListener('input', this._onInput); + this.element.removeEventListener('input', this._onInput, { + passive: true + }); this.element.removeEventListener('paste', this._onPaste); - this.element.removeEventListener('focus', this._onFocus); - this.element.removeEventListener('blur', this._onBlur); - - if (this.element.form) { - this.element.form.removeEventListener('reset', this._onFormReset); - } + this.element.removeEventListener('focus', this._onFocus, { + passive: true + }); + this.element.removeEventListener('blur', this._onBlur, { + passive: true + }); }; _proto.enable = function enable() { @@ -2154,9 +2096,7 @@ function () { }; _proto._onPaste = function _onPaste(event) { - var target = event.target; - - if (target === this.element && this.preventPaste) { + if (this.preventPaste) { event.preventDefault(); } }; @@ -2176,11 +2116,11 @@ function () { } }, { key: "value", - set: function set(value) { - this.element.value = value; - }, get: function get() { return sanitise(this.element.value); + }, + set: function set(value) { + this.element.value = value; } }]); @@ -2224,7 +2164,7 @@ var DEFAULT_CONFIG = { renderChoiceLimit: -1, maxItemCount: -1, addItems: true, - addItemFilterFn: null, + addItemFilter: null, removeItems: true, removeItemButton: false, editItems: false, @@ -2316,7 +2256,6 @@ function () { }); this.scrollPos = this.element.scrollTop; this.height = this.element.offsetHeight; - this.hasChildren = !!this.element.children; } var _proto = List.prototype; @@ -2333,6 +2272,10 @@ function () { return this.element.querySelector(selector); }; + _proto.hasChildren = function hasChildren() { + return this.element.hasChildNodes(); + }; + _proto.scrollToTop = function scrollToTop() { this.element.scrollTop = 0; }; @@ -2351,25 +2294,25 @@ function () { var containerScrollPos = this.element.scrollTop + dropdownHeight; // Difference between the choice and scroll position - var endpoint = direction > 0 ? this.element.scrollTop + choicePos - containerScrollPos : choice.offsetTop; + var destination = direction > 0 ? this.element.scrollTop + choicePos - containerScrollPos : choice.offsetTop; requestAnimationFrame(function (time) { - _this._animateScroll(time, endpoint, direction); + _this._animateScroll(time, destination, direction); }); }; - _proto._scrollDown = function _scrollDown(scrollPos, strength, endpoint) { - var easing = (endpoint - scrollPos) / strength; + _proto._scrollDown = function _scrollDown(scrollPos, strength, destination) { + var easing = (destination - scrollPos) / strength; var distance = easing > 1 ? easing : 1; this.element.scrollTop = scrollPos + distance; }; - _proto._scrollUp = function _scrollUp(scrollPos, strength, endpoint) { - var easing = (scrollPos - endpoint) / strength; + _proto._scrollUp = function _scrollUp(scrollPos, strength, destination) { + var easing = (scrollPos - destination) / strength; var distance = easing > 1 ? easing : 1; this.element.scrollTop = scrollPos - distance; }; - _proto._animateScroll = function _animateScroll(time, endpoint, direction) { + _proto._animateScroll = function _animateScroll(time, destination, direction) { var _this2 = this; var strength = SCROLLING_SPEED; @@ -2377,22 +2320,22 @@ function () { var continueAnimation = false; if (direction > 0) { - this._scrollDown(choiceListScrollTop, strength, endpoint); + this._scrollDown(choiceListScrollTop, strength, destination); - if (choiceListScrollTop < endpoint) { + if (choiceListScrollTop < destination) { continueAnimation = true; } } else { - this._scrollUp(choiceListScrollTop, strength, endpoint); + this._scrollUp(choiceListScrollTop, strength, destination); - if (choiceListScrollTop > endpoint) { + if (choiceListScrollTop > destination) { continueAnimation = true; } } if (continueAnimation) { requestAnimationFrame(function () { - _this2._animateScroll(time, endpoint, direction); + _this2._animateScroll(time, destination, direction); }); } }; @@ -2460,8 +2403,9 @@ function () { } this.element.removeAttribute('data-choice'); // Re-assign values - this is weird, I know + // @todo Figure out why we need to do this - this.element.value = this.element.value; + this.element.value = this.element.value; // eslint-disable-line no-self-assign }; _proto.enable = function enable() { @@ -2525,6 +2469,9 @@ function (_WrappedElement) { wrapped_input_createClass(WrappedInput, [{ key: "value", + get: function get() { + return this.element.value; + }, set: function set(items) { var itemValues = items.map(function (_ref2) { var value = _ref2.value; @@ -2533,9 +2480,6 @@ function (_WrappedElement) { var joinedValues = itemValues.join(this.delimiter); this.element.setAttribute('value', joinedValues); this.element.value = joinedValues; - }, - get: function get() { - return this.element.value; } }]); @@ -2639,15 +2583,24 @@ var TEMPLATES = containerOuter: function containerOuter(_ref, dir, isSelectElement, isSelectOneElement, searchEnabled, passedElementType) { var _containerOuter = _ref.containerOuter; var div = Object.assign(document.createElement('div'), { - className: _containerOuter, - dir: dir + className: _containerOuter }); div.dataset.type = passedElementType; - if (isSelectOneElement) div.tabIndex = 0; + + if (dir) { + div.dir = dir; + } + + if (isSelectOneElement) { + div.tabIndex = 0; + } if (isSelectElement) { div.setAttribute('role', searchEnabled ? 'combobox' : 'listbox'); - if (searchEnabled) div.setAttribute('aria-autocomplete', 'list'); + + if (searchEnabled) { + div.setAttribute('aria-autocomplete', 'list'); + } } div.setAttribute('aria-haspopup', 'true'); @@ -2699,13 +2652,26 @@ var TEMPLATES = value: value, customProperties: customProperties }); - if (active) div.setAttribute('aria-selected', 'true'); - if (disabled) div.setAttribute('aria-disabled', 'true'); - if (isPlaceholder) div.classList.add(placeholder); + + if (active) { + div.setAttribute('aria-selected', 'true'); + } + + if (disabled) { + div.setAttribute('aria-disabled', 'true'); + } + + if (isPlaceholder) { + div.classList.add(placeholder); + } + div.classList.add(highlighted ? highlightedState : itemSelectable); if (removeItemButton) { - if (disabled) div.classList.remove(itemSelectable); + if (disabled) { + div.classList.remove(itemSelectable); + } + div.dataset.deletable = ''; /** @todo This MUST be localizable, not hardcoded! */ @@ -2725,10 +2691,13 @@ var TEMPLATES = choiceList: function choiceList(_ref7, isSelectOneElement) { var list = _ref7.list; var div = Object.assign(document.createElement('div'), { - className: list, - dir: 'ltr' + className: list }); - if (!isSelectOneElement) div.setAttribute('aria-multiselectable', 'true'); + + if (!isSelectOneElement) { + div.setAttribute('aria-multiselectable', 'true'); + } + div.setAttribute('role', 'listbox'); return div; }, @@ -2748,7 +2717,11 @@ var TEMPLATES = id: id, value: value }); - if (disabled) div.setAttribute('aria-disabled', 'true'); + + if (disabled) { + div.setAttribute('aria-disabled', 'true'); + } + div.appendChild(Object.assign(document.createElement('div'), { className: groupHeading, innerHTML: value @@ -2784,7 +2757,9 @@ var TEMPLATES = if (disabled) { div.dataset.choiceDisabled = ''; div.setAttribute('aria-disabled', 'true'); - } else div.dataset.choiceSelectable = ''; + } else { + div.dataset.choiceSelectable = ''; + } return div; }, @@ -2822,7 +2797,13 @@ var TEMPLATES = } var classes = [item, itemChoice]; - if (type === 'no-choices') classes.push(noChoices);else if (type === 'no-results') classes.push(noResults); + + if (type === 'no-choices') { + classes.push(noChoices); + } else if (type === 'no-results') { + classes.push(noResults); + } + return Object.assign(document.createElement('div'), { innerHTML: innerHTML, className: classes.join(' ') @@ -2835,7 +2816,11 @@ var TEMPLATES = active = _ref15.active, disabled = _ref15.disabled; var opt = new Option(label, value, false, active); - if (customProperties) opt.dataset.customProperties = customProperties; + + if (customProperties) { + opt.dataset.customProperties = customProperties; + } + opt.disabled = disabled; return opt; } @@ -2926,8 +2911,6 @@ var items_highlightItem = function highlightItem(id, highlighted) { }; // CONCATENATED MODULE: ./src/scripts/actions/groups.js -/* eslint-disable import/prefer-default-export */ - var groups_addGroup = function addGroup(value, id, active, disabled) { return { type: ACTION_TYPES.ADD_GROUP, @@ -2950,7 +2933,6 @@ var resetTo = function resetTo(state) { }; }; // CONCATENATED MODULE: ./src/scripts/actions/general.js -/* eslint-disable import/prefer-default-export */ var setIsLoading = function setIsLoading(isLoading) { return { type: 'SET_IS_LOADING', @@ -2958,6 +2940,9 @@ var setIsLoading = function setIsLoading(isLoading) { }; }; // CONCATENATED MODULE: ./src/scripts/choices.js +function choices_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function choices_createClass(Constructor, protoProps, staticProps) { if (protoProps) choices_defineProperties(Constructor.prototype, protoProps); if (staticProps) choices_defineProperties(Constructor, staticProps); return Constructor; } @@ -2971,14 +2956,42 @@ var setIsLoading = function setIsLoading(isLoading) { +var USER_DEFAULTS = +/** @type {Partial} */ +{}; /** * Choices * @author Josh Johnson */ +/** + * @typedef {import('../../types/index').Choices.Choice} Choice + */ + var choices_Choices = /*#__PURE__*/ function () { + choices_createClass(Choices, null, [{ + key: "defaults", + get: function get() { + return Object.preventExtensions({ + get options() { + return USER_DEFAULTS; + }, + + get templates() { + return TEMPLATES; + } + + }); + } + /** + * @param {string | HTMLInputElement | HTMLSelectElement} element + * @param {Partial} userConfig + */ + + }]); + function Choices(element, userConfig) { var _this = this; @@ -2990,22 +3003,19 @@ function () { userConfig = {}; } - if (isType('String', element)) { - var elements = Array.from(document.querySelectorAll(element)); // If there are multiple elements, create a new instance - // for each element besides the first one (as that already has an instance) - - if (elements.length > 1) { - return this._generateInstances(elements, userConfig); - } - } - - this.config = cjs_default.a.all([DEFAULT_CONFIG, Choices.userDefaults, userConfig], // When merging array configs, replace with a copy of the userConfig array, + 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) { return [].concat(sourceArray); } - }); + }); // Convert addItemFilter to function + + if (userConfig.addItemFilter && typeof userConfig.addItemFilter !== 'function') { + var re = userConfig.addItemFilter instanceof RegExp ? userConfig.addItemFilter : new RegExp(userConfig.addItemFilter); + this.config.addItemFilter = re.test.bind(re); + } + var invalidConfigOptions = diff(this.config, DEFAULT_CONFIG); if (invalidConfigOptions.length) { @@ -3014,17 +3024,12 @@ function () { if (!['auto', 'always'].includes(this.config.renderSelectedChoices)) { this.config.renderSelectedChoices = 'auto'; - } // Retrieve triggering element (i.e. element with 'data-choice' trigger) - + } var passedElement = isType('String', element) ? document.querySelector(element) : element; - if (!passedElement) { - if (!this.config.silent) { - console.error('Could not find passed element or passed element was of an invalid type'); - } - - return; + 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'; @@ -3038,22 +3043,18 @@ function () { classNames: this.config.classNames, delimiter: this.config.delimiter }); - } else if (this._isSelectElement) { + } else { this.passedElement = new WrappedSelect({ element: passedElement, classNames: this.config.classNames, template: function template(data) { - return _this.config.templates.option(data); + return _this._templates.option(data); } }); } - if (!this.passedElement) { - return console.error('Passed element was of an invalid type'); - } - this.initialised = false; - this._store = new store_Store(this.render); + this._store = new store_Store(); this._initialState = {}; this._currentState = {}; this._prevState = {}; @@ -3064,7 +3065,26 @@ function () { this._wasTap = true; this._placeholderValue = this._generatePlaceholderValue(); this._baseId = generateId(this.passedElement.element, 'choices-'); - this._direction = this.passedElement.element.getAttribute('dir') || 'ltr'; + /** + * setting direction in cases where it's explicitly set on passedElement + * or when calculated direction is different from the document + * @type {HTMLElement['dir']} + */ + + this._direction = this.passedElement.element.dir; + + if (!this._direction) { + var _window$getComputedSt = window.getComputedStyle(this.passedElement.element), + elementDirection = _window$getComputedSt.direction; + + var _window$getComputedSt2 = window.getComputedStyle(document.documentElement), + documentDirection = _window$getComputedSt2.direction; + + if (elementDirection !== documentDirection) { + this._direction = elementDirection; + } + } + this._idNames = { itemChoice: 'item-choice' }; // Assign preset choices from passed object @@ -3094,24 +3114,25 @@ function () { this._onDirectionKey = this._onDirectionKey.bind(this); this._onDeleteKey = this._onDeleteKey.bind(this); - if (!this.config.silent) { - if (this.config.shouldSortItems === true && this._isSelectOneElement) { + 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 element has already been initialised with Choices, fail silently - if (this.passedElement.element.getAttribute('data-choice') === 'active') { + if (this.passedElement.element.getAttribute('data-choice') === 'active') { + if (!this.config.silent) { console.warn('Trying to initialise Choices on element already initialised'); } + + this.initialised = true; + return; } // Let's go this.init(); } - /* ======================================== - = Public functions = - ======================================== */ - var _proto = Choices.prototype; @@ -3165,7 +3186,7 @@ function () { } this.clearStore(); - this.config.templates = null; + this._templates = null; this.initialised = false; }; @@ -3410,29 +3431,108 @@ function () { return _this10._findAndSelectChoiceByValue(val); }); return this; - }; + } + /** + * Set choices of select input via an array of objects (or function that returns array of object or promise of it), + * a value field name and a label field name. + * This behaves the same as passing items via the choices option but can be called after initialising Choices. + * This can also be used to add groups of choices (see example 2); Optionally pass a true `replaceChoices` value to remove any existing choices. + * Optionally pass a `customProperties` object to add additional data to your choices (useful when searching/filtering etc). + * + * **Input types affected:** select-one, select-multiple + * + * @template {object[] | ((instance: Choices) => object[] | Promise)} T + * @param {T} [choicesArrayOrFetcher] + * @param {string} [value = 'value'] - name of `value` field + * @param {string} [label = 'label'] - name of 'label' field + * @param {boolean} [replaceChoices = false] - whether to replace of add choices + * @returns {this | Promise} + * + * @example + * ```js + * const example = new Choices(element); + * + * example.setChoices([ + * {value: 'One', label: 'Label One', disabled: true}, + * {value: 'Two', label: 'Label Two', selected: true}, + * {value: 'Three', label: 'Label Three'}, + * ], 'value', 'label', false); + * ``` + * + * @example + * ```js + * const example = new Choices(element); + * + * example.setChoices(async () => { + * try { + * const items = await fetch('/items'); + * return items.json() + * } catch(err) { + * console.error(err) + * } + * }); + * ``` + * + * @example + * ```js + * const example = new Choices(element); + * + * example.setChoices([{ + * label: 'Group one', + * id: 1, + * disabled: false, + * choices: [ + * {value: 'Child One', label: 'Child One', selected: true}, + * {value: 'Child Two', label: 'Child Two', disabled: true}, + * {value: 'Child Three', label: 'Child Three'}, + * ] + * }, + * { + * label: 'Group two', + * id: 2, + * disabled: false, + * choices: [ + * {value: 'Child Four', label: 'Child Four', disabled: true}, + * {value: 'Child Five', label: 'Child Five'}, + * {value: 'Child Six', label: 'Child Six', customProperties: { + * description: 'Custom description about child six', + * random: 'Another random custom property' + * }}, + * ] + * }], 'value', 'label', false); + * ``` + */ + ; - _proto.setChoices = function setChoices(choices, value, label, replaceChoices) { + _proto.setChoices = function setChoices(choicesArrayOrFetcher, value, label, replaceChoices) { var _this11 = this; - if (choices === void 0) { - choices = []; + if (choicesArrayOrFetcher === void 0) { + choicesArrayOrFetcher = []; } if (value === void 0) { - value = ''; + value = 'value'; } if (label === void 0) { - label = ''; + label = 'label'; } if (replaceChoices === void 0) { replaceChoices = false; } - if (!this._isSelectElement || !value) { - return this; + if (!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 (typeof value !== 'string' || !value) { + throw new TypeError("value parameter must be a name of 'value' field in passed objects"); } // Clear choices if needed @@ -3440,6 +3540,41 @@ 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); + }); + var fetcher = choicesArrayOrFetcher(this); + + if (typeof fetcher === 'object' && typeof fetcher.then === 'function') { + // that's a promise + return fetcher.then(function (data) { + return _this11.setChoices(data, value, label, replaceChoices); + }).catch(function (err) { + if (!_this11.config.silent) { + console.error(err); + } + }).then(function () { + return _this11._handleLoadingState(false); + }).then(function () { + return _this11; + }); + } // function returned something else than promise, let's check if it's an array of choices + + + if (!Array.isArray(fetcher)) { + throw new TypeError(".setChoices first argument function must return either array of choices or Promise, got: " + typeof fetcher); + } // recursion with results, it's sync and choices were cleared already + + + return this.setChoices(fetcher, value, label, false); + } + this.containerOuter.removeLoadingState(); var addGroupsAndChoices = function addGroupsAndChoices(groupOrChoice) { @@ -3464,7 +3599,7 @@ function () { this._setLoading(true); - choices.forEach(addGroupsAndChoices); + choicesArrayOrFetcher.forEach(addGroupsAndChoices); this._setLoading(false); @@ -3473,6 +3608,8 @@ function () { _proto.clearChoices = function clearChoices() { this._store.dispatch(choices_clearChoices()); + + return this; }; _proto.clearStore = function clearStore() { @@ -3494,26 +3631,6 @@ function () { return this; }; - _proto.ajax = function ajax(fn) { - var _this12 = this; - - if (!this.initialised || !this._isSelectElement || !fn) { - return this; - } - - requestAnimationFrame(function () { - return _this12._handleLoadingState(true); - }); - fn(this._ajaxCallback()); - return this; - } - /* ===== End of Public functions ====== */ - - /* ============================================= - = Private functions = - ============================================= */ - ; - _proto._render = function _render() { if (this._store.isLoading()) { return; @@ -3540,7 +3657,7 @@ function () { }; _proto._renderChoices = function _renderChoices() { - var _this13 = this; + var _this12 = this; var _this$_store = this._store, activeGroups = _this$_store.activeGroups, @@ -3550,7 +3667,7 @@ function () { if (this.config.resetScrollPosition) { requestAnimationFrame(function () { - return _this13.choiceList.scrollToTop(); + return _this12.choiceList.scrollToTop(); }); } // If we have grouped options @@ -3617,7 +3734,7 @@ function () { }; _proto._createGroupsFragment = function _createGroupsFragment(groups, choices, fragment) { - var _this14 = this; + var _this13 = this; if (fragment === void 0) { fragment = document.createDocumentFragment(); @@ -3625,11 +3742,11 @@ function () { var getGroupChoices = function getGroupChoices(group) { return choices.filter(function (choice) { - if (_this14._isSelectOneElement) { + if (_this13._isSelectOneElement) { return choice.groupId === group.id; } - return choice.groupId === group.id && (_this14.config.renderSelectedChoices === 'always' || !choice.selected); + return choice.groupId === group.id && (_this13.config.renderSelectedChoices === 'always' || !choice.selected); }); }; // If sorting is enabled, filter groups @@ -3642,18 +3759,18 @@ function () { var groupChoices = getGroupChoices(group); if (groupChoices.length >= 1) { - var dropdownGroup = _this14._getTemplate('choiceGroup', group); + var dropdownGroup = _this13._getTemplate('choiceGroup', group); fragment.appendChild(dropdownGroup); - _this14._createChoicesFragment(groupChoices, fragment, true); + _this13._createChoicesFragment(groupChoices, fragment, true); } }); return fragment; }; _proto._createChoicesFragment = function _createChoicesFragment(choices, fragment, withinGroup) { - var _this15 = this; + var _this14 = this; if (fragment === void 0) { fragment = document.createDocumentFragment(); @@ -3671,10 +3788,10 @@ function () { var filter = this._isSearching ? sortByScore : this.config.sortFn; var appendChoice = function appendChoice(choice) { - var shouldRender = renderSelectedChoices === 'auto' ? _this15._isSelectOneElement || !choice.selected : true; + var shouldRender = renderSelectedChoices === 'auto' ? _this14._isSelectOneElement || !choice.selected : true; if (shouldRender) { - var dropdownItem = _this15._getTemplate('choice', choice, _this15.config.itemSelectText); + var dropdownItem = _this14._getTemplate('choice', choice, _this14.config.itemSelectText); fragment.appendChild(dropdownItem); } @@ -3730,7 +3847,7 @@ function () { }; _proto._createItemsFragment = function _createItemsFragment(items, fragment) { - var _this16 = this; + var _this15 = this; if (fragment === void 0) { fragment = document.createDocumentFragment(); @@ -3756,7 +3873,7 @@ function () { var addItemToFragment = function addItemToFragment(item) { // Create new list element - var listItem = _this16._getTemplate('item', item, removeItemButton); // Append it to list + var listItem = _this15._getTemplate('item', item, removeItemButton); // Append it to list fragment.appendChild(listItem); @@ -3815,7 +3932,7 @@ function () { }; _proto._handleItemAction = function _handleItemAction(activeItems, element, hasShiftKey) { - var _this17 = this; + var _this16 = this; if (hasShiftKey === void 0) { hasShiftKey = false; @@ -3831,9 +3948,9 @@ function () { activeItems.forEach(function (item) { if (item.id === parseInt(passedId, 10) && !item.highlighted) { - _this17.highlightItem(item); + _this16.highlightItem(item); } else if (!hasShiftKey && item.highlighted) { - _this17.unhighlightItem(item); + _this16.unhighlightItem(item); } }); // Focus input as without focus, a user cannot do anything with a // highlighted item @@ -3851,7 +3968,10 @@ function () { var choice = this._store.getChoiceById(id); - if (!choice) return; + if (!choice) { + return; + } + var passedKeyCode = activeItems[0] && activeItems[0].keyCode ? activeItems[0].keyCode : null; var hasActiveDropdown = this.dropdown.isActive; // Update choice keyCode @@ -3998,9 +4118,9 @@ function () { notice = isType('Function', this.config.uniqueItemText) ? this.config.uniqueItemText(value) : this.config.uniqueItemText; } - if (this._isTextElement && this.config.addItems && canAddItem && isType('Function', this.config.addItemFilterFn) && !this.config.addItemFilterFn(value)) { + if (this._isTextElement && this.config.addItems && canAddItem && typeof this.config.addItemFilter === 'function' && !this.config.addItemFilter(value)) { canAddItem = false; - notice = isType('Function', this.config.customAddItemText) ? this.config.customAddItemText(value) : this.config.customAddItemText; + notice = typeof this.config.customAddItemText === 'function' ? this.config.customAddItemText(value) : this.config.customAddItemText; } } @@ -4010,55 +4130,6 @@ function () { }; }; - _proto._ajaxCallback = function _ajaxCallback() { - var _this18 = this; - - return function (results, value, label) { - if (!results || !value) { - return; - } - - var parsedResults = isType('Object', results) ? [results] : results; - - if (parsedResults && isType('Array', parsedResults) && parsedResults.length) { - // Remove loading states/text - _this18._handleLoadingState(false); - - _this18._setLoading(true); // Add each result as a choice - - - parsedResults.forEach(function (result) { - if (result.choices) { - _this18._addGroup({ - group: result, - id: result.id || null, - valueKey: value, - labelKey: label - }); - } else { - _this18._addChoice({ - value: fetchFromObject(result, value), - label: fetchFromObject(result, label), - isSelected: result.selected, - isDisabled: result.disabled, - customProperties: result.customProperties, - placeholder: result.placeholder - }); - } - }); - - _this18._setLoading(false); - - if (_this18._isSelectOneElement) { - _this18._selectPlaceholderChoice(); - } - } else { - // No results, remove loading state - _this18._handleLoadingState(false); - } - }; - }; - _proto._searchChoices = function _searchChoices(value) { var newValue = isType('String', value) ? value.trim() : value; var currentValue = isType('String', this._currentValue) ? this._currentValue.trim() : this._currentValue; @@ -4086,48 +4157,90 @@ function () { }; _proto._addEventListeners = function _addEventListeners() { - window.delegateEvent.add('keyup', this._onKeyUp); - window.delegateEvent.add('keydown', this._onKeyDown); - window.delegateEvent.add('click', this._onClick); - window.delegateEvent.add('touchmove', this._onTouchMove); - window.delegateEvent.add('touchend', this._onTouchEnd); - window.delegateEvent.add('mousedown', this._onMouseDown); - window.delegateEvent.add('mouseover', this._onMouseOver); + var _document = document, + documentElement = _document.documentElement; // capture events - can cancel event processing or propagation + + documentElement.addEventListener('keydown', this._onKeyDown, true); + documentElement.addEventListener('touchend', this._onTouchEnd, true); + documentElement.addEventListener('mousedown', this._onMouseDown, true); // passive events - doesn't call `preventDefault` or `stopPropagation` + + documentElement.addEventListener('click', this._onClick, { + passive: true + }); + documentElement.addEventListener('touchmove', this._onTouchMove, { + passive: true + }); + documentElement.addEventListener('mouseover', this._onMouseOver, { + passive: true + }); if (this._isSelectOneElement) { - this.containerOuter.element.addEventListener('focus', this._onFocus); - this.containerOuter.element.addEventListener('blur', this._onBlur); + this.containerOuter.element.addEventListener('focus', this._onFocus, { + passive: true + }); + this.containerOuter.element.addEventListener('blur', this._onBlur, { + passive: true + }); } - this.input.element.addEventListener('focus', this._onFocus); - this.input.element.addEventListener('blur', this._onBlur); + this.input.element.addEventListener('keyup', this._onKeyUp, { + passive: true + }); + this.input.element.addEventListener('focus', this._onFocus, { + passive: true + }); + this.input.element.addEventListener('blur', this._onBlur, { + passive: true + }); if (this.input.element.form) { - this.input.element.form.addEventListener('reset', this._onFormReset); + this.input.element.form.addEventListener('reset', this._onFormReset, { + passive: true + }); } this.input.addEventListeners(); }; _proto._removeEventListeners = function _removeEventListeners() { - window.delegateEvent.remove('keyup', this._onKeyUp); - window.delegateEvent.remove('keydown', this._onKeyDown); - window.delegateEvent.remove('click', this._onClick); - window.delegateEvent.remove('touchmove', this._onTouchMove); - window.delegateEvent.remove('touchend', this._onTouchEnd); - window.delegateEvent.remove('mousedown', this._onMouseDown); - window.delegateEvent.remove('mouseover', this._onMouseOver); + var _document2 = document, + documentElement = _document2.documentElement; + documentElement.removeEventListener('keydown', this._onKeyDown, true); + documentElement.removeEventListener('touchend', this._onTouchEnd, true); + documentElement.removeEventListener('mousedown', this._onMouseDown, true); + documentElement.removeEventListener('keyup', this._onKeyUp, { + passive: true + }); + documentElement.removeEventListener('click', this._onClick, { + passive: true + }); + documentElement.removeEventListener('touchmove', this._onTouchMove, { + passive: true + }); + documentElement.removeEventListener('mouseover', this._onMouseOver, { + passive: true + }); if (this._isSelectOneElement) { - this.containerOuter.element.removeEventListener('focus', this._onFocus); - this.containerOuter.element.removeEventListener('blur', this._onBlur); + this.containerOuter.element.removeEventListener('focus', this._onFocus, { + passive: true + }); + this.containerOuter.element.removeEventListener('blur', this._onBlur, { + passive: true + }); } - this.input.element.removeEventListener('focus', this._onFocus); - this.input.element.removeEventListener('blur', this._onBlur); + this.input.element.removeEventListener('focus', this._onFocus, { + passive: true + }); + this.input.element.removeEventListener('blur', this._onBlur, { + passive: true + }); if (this.input.element.form) { - this.input.element.form.removeEventListener('reset', this._onFormReset); + this.input.element.form.removeEventListener('reset', this._onFormReset, { + passive: true + }); } this.input.removeEventListeners(); @@ -4148,7 +4261,7 @@ function () { var activeItems = this._store.activeItems; var hasFocusedInput = this.input.isFocussed; var hasActiveDropdown = this.dropdown.isActive; - var hasItems = this.itemList.hasChildren; + var hasItems = this.itemList.hasChildren(); var keyString = String.fromCharCode(keyCode); var BACK_KEY = KEY_CODES.BACK_KEY, DELETE_KEY = KEY_CODES.DELETE_KEY, @@ -4186,11 +4299,6 @@ function () { _proto._onKeyUp = function _onKeyUp(_ref2) { var target = _ref2.target, keyCode = _ref2.keyCode; - - if (target !== this.input.element) { - return; - } - var value = this.input.value; var activeItems = this._store.activeItems; @@ -4465,7 +4573,7 @@ function () { }; _proto._onFocus = function _onFocus(_ref11) { - var _this19 = this; + var _this17 = this; var target = _ref11.target; var focusWasWithinContainer = this.containerOuter.element.contains(target); @@ -4476,24 +4584,24 @@ function () { var focusActions = { text: function text() { - if (target === _this19.input.element) { - _this19.containerOuter.addFocusState(); + if (target === _this17.input.element) { + _this17.containerOuter.addFocusState(); } }, 'select-one': function selectOne() { - _this19.containerOuter.addFocusState(); + _this17.containerOuter.addFocusState(); - if (target === _this19.input.element) { - _this19.showDropdown(true); + if (target === _this17.input.element) { + _this17.showDropdown(true); } }, 'select-multiple': function selectMultiple() { - if (target === _this19.input.element) { - _this19.showDropdown(true); // If element is a select box, the focused element is the container and the dropdown + 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 - _this19.containerOuter.addFocusState(); + _this17.containerOuter.addFocusState(); } } }; @@ -4501,7 +4609,7 @@ function () { }; _proto._onBlur = function _onBlur(_ref12) { - var _this20 = this; + var _this18 = this; var target = _ref12.target; var blurWasWithinContainer = this.containerOuter.element.contains(target); @@ -4513,31 +4621,31 @@ function () { }); var blurActions = { text: function text() { - if (target === _this20.input.element) { - _this20.containerOuter.removeFocusState(); + if (target === _this18.input.element) { + _this18.containerOuter.removeFocusState(); if (hasHighlightedItems) { - _this20.unhighlightAll(); + _this18.unhighlightAll(); } - _this20.hideDropdown(true); + _this18.hideDropdown(true); } }, 'select-one': function selectOne() { - _this20.containerOuter.removeFocusState(); + _this18.containerOuter.removeFocusState(); - if (target === _this20.input.element || target === _this20.containerOuter.element && !_this20._canSearch) { - _this20.hideDropdown(true); + if (target === _this18.input.element || target === _this18.containerOuter.element && !_this18._canSearch) { + _this18.hideDropdown(true); } }, 'select-multiple': function selectMultiple() { - if (target === _this20.input.element) { - _this20.containerOuter.removeFocusState(); + if (target === _this18.input.element) { + _this18.containerOuter.removeFocusState(); - _this20.hideDropdown(true); + _this18.hideDropdown(true); if (hasHighlightedItems) { - _this20.unhighlightAll(); + _this18.unhighlightAll(); } } } @@ -4557,7 +4665,7 @@ function () { }; _proto._highlightChoice = function _highlightChoice(el) { - var _this21 = this; + var _this19 = this; if (el === void 0) { el = null; @@ -4573,7 +4681,7 @@ function () { var highlightedChoices = Array.from(this.dropdown.element.querySelectorAll("." + this.config.classNames.highlightedState)); // Remove any highlighted choices highlightedChoices.forEach(function (choice) { - choice.classList.remove(_this21.config.classNames.highlightedState); + choice.classList.remove(_this19.config.classNames.highlightedState); choice.setAttribute('aria-selected', 'false'); }); @@ -4751,7 +4859,7 @@ function () { }; _proto._addGroup = function _addGroup(_ref15) { - var _this22 = this; + var _this20 = this; var group = _ref15.group, id = _ref15.id, @@ -4769,7 +4877,7 @@ function () { var addGroupChoices = function addGroupChoices(choice) { var isOptDisabled = choice.disabled || choice.parentNode && choice.parentNode.disabled; - _this22._addChoice({ + _this20._addChoice({ value: choice[valueKey], label: isType('Object', choice) ? choice[labelKey] : choice.innerHTML, isSelected: choice.selected, @@ -4787,21 +4895,19 @@ function () { }; _proto._getTemplate = function _getTemplate(template) { - var _templates$template; + var _this$_templates$temp; if (!template) { return null; } - var _this$config4 = this.config, - templates = _this$config4.templates, - classNames = _this$config4.classNames; + var classNames = this.config.classNames; for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } - return (_templates$template = templates[template]).call.apply(_templates$template, [this, classNames].concat(args)); + return (_this$_templates$temp = this._templates[template]).call.apply(_this$_templates$temp, [this, classNames].concat(args)); }; _proto._createTemplates = function _createTemplates() { @@ -4812,7 +4918,7 @@ function () { userTemplates = callbackOnCreateTemplates.call(this, strToEl); } - this.config.templates = cjs_default()(TEMPLATES, userTemplates); + this._templates = cjs_default()(TEMPLATES, userTemplates); }; _proto._createElements = function _createElements() { @@ -4831,7 +4937,8 @@ function () { this.input = new input_Input({ element: this._getTemplate('input', this._placeholderValue), classNames: this.config.classNames, - type: this.passedElement.element.type + type: this.passedElement.element.type, + preventPaste: !this.config.paste }); this.choiceList = new list_List({ element: this._getTemplate('choiceList', this._isSelectOneElement) @@ -4883,7 +4990,7 @@ function () { }; _proto._addPredefinedChoices = function _addPredefinedChoices() { - var _this23 = this; + var _this21 = this; var passedGroups = this.passedElement.optionGroups; this._highlightPosition = 0; @@ -4906,7 +5013,7 @@ function () { } passedGroups.forEach(function (group) { - return _this23._addGroup({ + return _this21._addGroup({ group: group, id: group.id || null }); @@ -4927,7 +5034,10 @@ function () { }); }); // 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 + if (this.config.shouldSort) { + allChoices.sort(filter); + } // Determine whether there is a selected choice + var hasSelectedChoice = allChoices.some(function (choice) { return choice.selected; @@ -4939,10 +5049,10 @@ function () { customProperties = choice.customProperties, placeholder = choice.placeholder; - if (_this23._isSelectElement) { + if (_this21._isSelectElement) { // If the choice is actually a group if (choice.choices) { - _this23._addGroup({ + _this21._addGroup({ group: choice, id: choice.id || null }); @@ -4950,11 +5060,11 @@ function () { // 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 = _this23._isSelectOneElement && !hasSelectedChoice && index === 0; + var shouldPreselect = _this21._isSelectOneElement && !hasSelectedChoice && index === 0; var isSelected = shouldPreselect ? true : choice.selected; var isDisabled = shouldPreselect ? false : choice.disabled; - _this23._addChoice({ + _this21._addChoice({ value: value, label: label, isSelected: isSelected, @@ -4964,7 +5074,7 @@ function () { }); } } else { - _this23._addChoice({ + _this21._addChoice({ value: value, label: label, isSelected: choice.selected, @@ -4985,13 +5095,13 @@ function () { }; _proto._addPredefinedItems = function _addPredefinedItems() { - var _this24 = this; + var _this22 = this; var handlePresetItem = function handlePresetItem(item) { var itemType = getType(item); if (itemType === 'Object' && item.value) { - _this24._addItem({ + _this22._addItem({ value: item.value, label: item.label, choiceId: item.id, @@ -4999,7 +5109,7 @@ function () { placeholder: item.placeholder }); } else if (itemType === 'String') { - _this24._addItem({ + _this22._addItem({ value: item }); } @@ -5011,7 +5121,7 @@ function () { }; _proto._setChoiceOrItem = function _setChoiceOrItem(item) { - var _this25 = this; + var _this23 = this; var itemType = getType(item).toLowerCase(); var handleType = { @@ -5022,8 +5132,8 @@ function () { // that is then selected. For text inputs we can just add items normally. - if (!_this25._isTextElement) { - _this25._addChoice({ + if (!_this23._isTextElement) { + _this23._addChoice({ value: item.value, label: item.label, isSelected: true, @@ -5032,7 +5142,7 @@ function () { placeholder: item.placeholder }); } else { - _this25._addItem({ + _this23._addItem({ value: item.value, label: item.label, choiceId: item.id, @@ -5042,15 +5152,15 @@ function () { } }, string: function string() { - if (!_this25._isTextElement) { - _this25._addChoice({ + if (!_this23._isTextElement) { + _this23._addChoice({ value: item, label: item, isSelected: true, isDisabled: false }); } else { - _this25._addItem({ + _this23._addItem({ value: item }); } @@ -5060,12 +5170,12 @@ function () { }; _proto._findAndSelectChoiceByValue = function _findAndSelectChoiceByValue(val) { - var _this26 = this; + var _this24 = this; var choices = this._store.choices; // Check 'value' property exists and the choice isn't already selected var foundChoice = choices.find(function (choice) { - return _this26.config.itemComparer(choice.value, val); + return _this24.config.itemComparer(choice.value, val); }); if (foundChoice && !foundChoice.selected) { @@ -5081,13 +5191,6 @@ function () { } }; - _proto._generateInstances = function _generateInstances(elements, config) { - return elements.reduce(function (instances, element) { - instances.push(new Choices(element, config)); - return instances; - }, [this]); - }; - _proto._generatePlaceholderValue = function _generatePlaceholderValue() { if (this._isSelectOneElement) { return false; @@ -5101,7 +5204,6 @@ function () { return Choices; }(); -choices_Choices.userDefaults = {}; /* harmony default export */ var scripts_choices = __webpack_exports__["default"] = (choices_Choices); /***/ }) diff --git a/public/assets/scripts/choices.min.js b/public/assets/scripts/choices.min.js index ea9092b..4d98486 100644 --- a/public/assets/scripts/choices.min.js +++ b/public/assets/scripts/choices.min.js @@ -1,5 +1,5 @@ -/*! choices.js v7.1.5 | © 2019 Josh Johnson | https://github.com/jshjohnson/Choices#readme */ -window.Choices=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="/public/assets/scripts/",i(i.s=4)}([function(e,t,i){"use strict";var n=function(e){return function(e){return!!e&&"object"==typeof e}(e)&&!function(e){var t=Object.prototype.toString.call(e);return"[object RegExp]"===t||"[object Date]"===t||function(e){return e.$$typeof===s}(e)}(e)};var s="function"==typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function r(e,t){return!1!==t.clone&&t.isMergeableObject(e)?l((i=e,Array.isArray(i)?[]:{}),e,t):e;var i}function o(e,t,i){return e.concat(t).map((function(e){return r(e,i)}))}function a(e){return Object.keys(e).concat(function(e){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(e).filter((function(t){return e.propertyIsEnumerable(t)})):[]}(e))}function c(e,t,i){var n={};return i.isMergeableObject(e)&&a(e).forEach((function(t){n[t]=r(e[t],i)})),a(t).forEach((function(s){(function(e,t){try{return t in e&&!(Object.hasOwnProperty.call(e,t)&&Object.propertyIsEnumerable.call(e,t))}catch(e){return!1}})(e,s)||(i.isMergeableObject(t[s])&&e[s]?n[s]=function(e,t){if(!t.customMerge)return l;var i=t.customMerge(e);return"function"==typeof i?i:l}(s,i)(e[s],t[s],i):n[s]=r(t[s],i))})),n}function l(e,t,i){(i=i||{}).arrayMerge=i.arrayMerge||o,i.isMergeableObject=i.isMergeableObject||n,i.cloneUnlessOtherwiseSpecified=r;var s=Array.isArray(t);return s===Array.isArray(e)?s?i.arrayMerge(e,t,i):c(e,t,i):r(t,i)}l.all=function(e,t){if(!Array.isArray(e))throw new Error("first argument should be an array");return e.reduce((function(e,i){return l(e,i,t)}),{})};var h=l;e.exports=h},function(e,t,i){"use strict";(function(e,n){var s,r=i(3);s="undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==e?e:n;var o=Object(r.a)(s);t.a=o}).call(this,i(6),i(7)(e))},function(e,t,i){ +/*! choices.js v8.0.0 | © 2019 Josh Johnson | https://github.com/jshjohnson/Choices#readme */ +window.Choices=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="/public/assets/scripts/",i(i.s=4)}([function(e,t,i){"use strict";var n=function(e){return function(e){return!!e&&"object"==typeof e}(e)&&!function(e){var t=Object.prototype.toString.call(e);return"[object RegExp]"===t||"[object Date]"===t||function(e){return e.$$typeof===s}(e)}(e)};var s="function"==typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function r(e,t){return!1!==t.clone&&t.isMergeableObject(e)?l((i=e,Array.isArray(i)?[]:{}),e,t):e;var i}function o(e,t,i){return e.concat(t).map((function(e){return r(e,i)}))}function a(e){return Object.keys(e).concat(function(e){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(e).filter((function(t){return e.propertyIsEnumerable(t)})):[]}(e))}function c(e,t,i){var n={};return i.isMergeableObject(e)&&a(e).forEach((function(t){n[t]=r(e[t],i)})),a(t).forEach((function(s){(function(e,t){try{return t in e&&!(Object.hasOwnProperty.call(e,t)&&Object.propertyIsEnumerable.call(e,t))}catch(e){return!1}})(e,s)||(i.isMergeableObject(t[s])&&e[s]?n[s]=function(e,t){if(!t.customMerge)return l;var i=t.customMerge(e);return"function"==typeof i?i:l}(s,i)(e[s],t[s],i):n[s]=r(t[s],i))})),n}function l(e,t,i){(i=i||{}).arrayMerge=i.arrayMerge||o,i.isMergeableObject=i.isMergeableObject||n,i.cloneUnlessOtherwiseSpecified=r;var s=Array.isArray(t);return s===Array.isArray(e)?s?i.arrayMerge(e,t,i):c(e,t,i):r(t,i)}l.all=function(e,t){if(!Array.isArray(e))throw new Error("first argument should be an array");return e.reduce((function(e,i){return l(e,i,t)}),{})};var h=l;e.exports=h},function(e,t,i){"use strict";(function(e,n){var s,r=i(3);s="undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==e?e:n;var o=Object(r.a)(s);t.a=o}).call(this,i(5),i(6)(e))},function(e,t,i){ /*! * Fuse.js v3.4.5 - Lightweight fuzzy-search (http://fusejs.io) * @@ -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");m=m.name}else a[m]={weight:1};this._analyze({key:m,value:this.options.getFn(h,m),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,m=t.resultMap,p=void 0===m?{}:m,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),S=[],I=0;I-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=p[c];F?F.output.push({key:i,arrayIndex:s,value:r,score:D,matchedIndices:y.matchedIndices}):(p[c]={item:o,output:[{key:i,arrayIndex:s,value:r,score:D,matchedIndices:y.matchedIndices}]},v.push(p[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(t[i.substring(0,n)],i.substr(n+1)):t[i]},L=function(e){return JSON.parse(JSON.stringify(e))},x=function(e,t){var i=Object.keys(e).sort(),n=Object.keys(t).sort();return i.filter((function(e){return n.indexOf(e)<0}))},k=function(e){for(var t=Object.keys(e),i={},n=0;n-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:_}),D=function(e,t){var i=e;if("CLEAR_ALL"===t.type)i=void 0;else if("RESET_TO"===t.type)return L(t.state);return k(i,t)};function P(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 j(e,t){for(var i=0;in?1:0},placeholder:!0,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(e){return'Press Enter to add "'+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",B="hideDropdown",V="change",G="choice",q="search",U="addItem",z="removeItem",W="highlightItem",X="highlightChoice",Y="ADD_CHOICE",$="FILTER_CHOICES",J="ACTIVATE_CHOICES",Z="CLEAR_CHOICES",Q="ADD_GROUP",ee="ADD_ITEM",te="REMOVE_ITEM",ie="HIGHLIGHT_ITEM",ne=46,se=8,re=13,oe=65,ae=27,ce=38,le=40,he=33,ue=34,de=function(){function e(e){var t=e.element;Object.assign(this,{element:t}),this.scrollPos=this.element.scrollTop,this.height=this.element.offsetHeight,this.hasChildren=!!this.element.children}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.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 me(e,t){for(var i=0;i0?"treeitem":"option"),Object.assign(f.dataset,{choice:"",id:c,value:l,selectText:i}),m?(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}},ye=function(e){return void 0===e&&(e=!0),{type:J,active:e}},Ee=function(e,t){return{type:ie,id:e,highlighted:t}},Se=function(e,t,i,n){return{type:Q,value:e,id:t,active:i,disabled:n}},Ie=function(){function e(t,i){var n=this;if(void 0===t&&(t="[data-choice]"),void 0===i&&(i={}),S("String",t)){var s=Array.from(document.querySelectorAll(t));if(s.length>1)return this._generateInstances(s,i)}this.config=o.a.all([R,e.userDefaults,i],{arrayMerge:function(e,t){return[].concat(t)}});var r=x(this.config,R);r.length&&console.warn("Unknown config option(s) passed",r.join(", ")),["auto","always"].includes(this.config.renderSelectedChoices)||(this.config.renderSelectedChoices="auto");var a=S("String",t)?document.querySelector(t):t;if(a){if(this._isTextElement="text"===a.type,this._isSelectOneElement="select-one"===a.type,this._isSelectMultipleElement="select-multiple"===a.type,this._isSelectElement=this._isSelectOneElement||this._isSelectMultipleElement,this._isTextElement?this.passedElement=new ve({element:a,classNames:this.config.classNames,delimiter:this.config.delimiter}):this._isSelectElement&&(this.passedElement=new _e({element:a,classNames:this.config.classNames,template:function(e){return n.config.templates.option(e)}})),!this.passedElement)return console.error("Passed element was of an invalid type");this.initialised=!1,this._store=new F(this.render),this._initialState={},this._currentState={},this._prevState={},this._currentValue="",this._canSearch=this.config.searchEnabled,this._isScrollingOnIe=!1,this._highlightPosition=0,this._wasTap=!0,this._placeholderValue=this._generatePlaceholderValue(),this._baseId=y(this.passedElement.element,"choices-"),this._direction=this.passedElement.element.getAttribute("dir")||"ltr",this._idNames={itemChoice:"item-choice"},this._presetChoices=this.config.choices,this._presetItems=this.config.items,this.passedElement.value&&(this._presetItems=this._presetItems.concat(this.passedElement.value.split(this.config.delimiter))),this._render=this._render.bind(this),this._onFocus=this._onFocus.bind(this),this._onBlur=this._onBlur.bind(this),this._onKeyUp=this._onKeyUp.bind(this),this._onKeyDown=this._onKeyDown.bind(this),this._onClick=this._onClick.bind(this),this._onTouchMove=this._onTouchMove.bind(this),this._onTouchEnd=this._onTouchEnd.bind(this),this._onMouseDown=this._onMouseDown.bind(this),this._onMouseOver=this._onMouseOver.bind(this),this._onFormReset=this._onFormReset.bind(this),this._onAKey=this._onAKey.bind(this),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.config.silent||(!0===this.config.shouldSortItems&&this._isSelectOneElement&&console.warn("shouldSortElements: Type of passed element is 'select-one', falling back to false."),"active"===this.passedElement.element.getAttribute("data-choice")&&console.warn("Trying to initialise Choices on element already initialised")),this.init()}else this.config.silent||console.error("Could not find passed element or passed element was of an invalid type")}var t=e.prototype;return t.init=function(){if(!this.initialised){this._createTemplates(),this._createElements(),this._createStructure(),this._initialState=L(this._store.state),this._store.subscribe(this._render),this._render(),this._addEventListeners(),(!this.config.addItems||this.passedElement.element.hasAttribute("disabled"))&&this.disable(),this.initialised=!0;var e=this.config.callbackOnInit;e&&S("Function",e)&&e.call(this)}},t.destroy=function(){this.initialised&&(this._removeEventListeners(),this.passedElement.reveal(),this.containerOuter.unwrap(this.passedElement.element),this._isSelectElement&&(this.passedElement.options=this._presetChoices),this.clearStore(),this.config.templates=null,this.initialised=!1)},t.enable=function(){return this.passedElement.isDisabled&&this.passedElement.enable(),this.containerOuter.isDisabled&&(this._addEventListeners(),this.input.enable(),this.containerOuter.enable()),this},t.disable=function(){return this.passedElement.isDisabled||this.passedElement.disable(),this.containerOuter.isDisabled||(this._removeEventListeners(),this.input.disable(),this.containerOuter.disable()),this},t.highlightItem=function(e,t){if(void 0===t&&(t=!0),!e)return this;var i=e.id,n=e.groupId,s=void 0===n?-1:n,r=e.value,o=void 0===r?"":r,a=e.label,c=void 0===a?"":a,l=s>=0?this._store.getGroupById(s):null;return this._store.dispatch(Ee(i,!0)),t&&this.passedElement.triggerEvent(W,{id:i,value:o,label:c,groupValue:l&&l.value?l.value:null}),this},t.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(Ee(t,!1)),this.passedElement.triggerEvent(W,{id:t,value:r,label:a,groupValue:c&&c.value?c.value:null}),this},t.highlightAll=function(){var e=this;return this._store.items.forEach((function(t){return e.highlightItem(t)})),this},t.unhighlightAll=function(){var e=this;return this._store.items.forEach((function(t){return e.unhighlightItem(t)})),this},t.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},t.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},t.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},t.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)},t.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(B,{})})),this):this},t.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},t.setValue=function(e){var t=this;return this.initialised?(e.forEach((function(e){return t._setChoiceOrItem(e)})),this):this},t.setChoiceByValue=function(e){var t=this;return!this.initialised||this._isTextElement?this:((S("Array",e)?e:[e]).forEach((function(e){return t._findAndSelectChoiceByValue(e)})),this)},t.setChoices=function(e,t,i,n){var s=this;if(void 0===e&&(e=[]),void 0===t&&(t=""),void 0===i&&(i=""),void 0===n&&(n=!1),!this._isSelectElement||!t)return this;n&&this.clearChoices(),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},t.clearChoices=function(){this._store.dispatch({type:Z})},t.clearStore=function(){return this._store.dispatch({type:"CLEAR_ALL"}),this},t.clearInput=function(){var e=!this._isSelectOneElement;return this.input.clear(e),!this._isTextElement&&this._canSearch&&(this._isSearching=!1,this._store.dispatch(ye(!0))),this},t.ajax=function(e){var t=this;return this.initialised&&this._isSelectElement&&e?(requestAnimationFrame((function(){return t._handleLoadingState(!0)})),e(this._ajaxCallback()),this):this},t._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)}},t._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=S("Function",this.config.noResultsText)?this.config.noResultsText():this.config.noResultsText,c=this._getTemplate("notice",l,"no-results")):(l=S("Function",this.config.noChoicesText)?this.config.noChoicesText():this.config.noChoicesText,c=this._getTemplate("notice",l,"no-choices")),this.choiceList.append(c)}},t._renderItems=function(){var e=this._store.activeItems||[];this.itemList.clear();var t=this._createItemsFragment(e);t.childNodes&&this.itemList.append(t)},t._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},t._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,m=u.normalChoices;(this.config.shouldSort||this._isSearching)&&m.sort(c);var p=h.length,f=[].concat(d,m);this._isSearching?p=o:a>0&&!i&&(p=a);for(var v=0;v=n){var o=s?this._searchChoices(e):0;this.passedElement.triggerEvent(q,{value:e,resultCount:o})}else r&&(this._isSearching=!1,this._store.dispatch(ye(!0)))}},t._canAddItem=function(e,t){var i=!0,n=S("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 S("String",t)?e[i]===t.trim():e[i]===t}))}(e,t);this.config.maxItemCount>0&&this.config.maxItemCount<=e.length&&(i=!1,n=S("Function",this.config.maxItemText)?this.config.maxItemText(this.config.maxItemCount):this.config.maxItemText),!this.config.duplicateItemsAllowed&&s&&i&&(i=!1,n=S("Function",this.config.uniqueItemText)?this.config.uniqueItemText(t):this.config.uniqueItemText),this._isTextElement&&this.config.addItems&&i&&S("Function",this.config.addItemFilterFn)&&!this.config.addItemFilterFn(t)&&(i=!1,n=S("Function",this.config.customAddItemText)?this.config.customAddItemText(t):this.config.customAddItemText)}return{response:i,notice:n}},t._ajaxCallback=function(){var e=this;return function(t,i,n){if(t&&i){var s=S("Object",t)?[t]:t;s&&S("Array",s)&&s.length?(e._handleLoadingState(!1),e._setLoading(!0),s.forEach((function(t){t.choices?e._addGroup({group:t,id:t.id||null,valueKey:i,labelKey:n}):e._addChoice({value:T(t,i),label:T(t,n),isSelected:t.selected,isDisabled:t.disabled,customProperties:t.customProperties,placeholder:t.placeholder})})),e._setLoading(!1),e._isSelectOneElement&&e._selectPlaceholderChoice()):e._handleLoadingState(!1)}}},t._searchChoices=function(e){var t=S("String",e)?e.trim():e,i=S("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:$,results:e}}(c)),c.length},t._addEventListeners=function(){window.delegateEvent.add("keyup",this._onKeyUp),window.delegateEvent.add("keydown",this._onKeyDown),window.delegateEvent.add("click",this._onClick),window.delegateEvent.add("touchmove",this._onTouchMove),window.delegateEvent.add("touchend",this._onTouchEnd),window.delegateEvent.add("mousedown",this._onMouseDown),window.delegateEvent.add("mouseover",this._onMouseOver),this._isSelectOneElement&&(this.containerOuter.element.addEventListener("focus",this._onFocus),this.containerOuter.element.addEventListener("blur",this._onBlur)),this.input.element.addEventListener("focus",this._onFocus),this.input.element.addEventListener("blur",this._onBlur),this.input.element.form&&this.input.element.form.addEventListener("reset",this._onFormReset),this.input.addEventListeners()},t._removeEventListeners=function(){window.delegateEvent.remove("keyup",this._onKeyUp),window.delegateEvent.remove("keydown",this._onKeyDown),window.delegateEvent.remove("click",this._onClick),window.delegateEvent.remove("touchmove",this._onTouchMove),window.delegateEvent.remove("touchend",this._onTouchEnd),window.delegateEvent.remove("mousedown",this._onMouseDown),window.delegateEvent.remove("mouseover",this._onMouseOver),this._isSelectOneElement&&(this.containerOuter.element.removeEventListener("focus",this._onFocus),this.containerOuter.element.removeEventListener("blur",this._onBlur)),this.input.element.removeEventListener("focus",this._onFocus),this.input.element.removeEventListener("blur",this._onBlur),this.input.element.form&&this.input.element.form.removeEventListener("reset",this._onFormReset),this.input.removeEventListeners()},t._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=ne,d=se,m=re,p=oe,f=ae,v=ce,g=le,_=he,b=ue,y=s||r;!this._isTextElement&&/[a-zA-Z0-9-_ ]/.test(h)&&this.showDropdown();var E=((t={})[p]=this._onAKey,t[m]=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})}},t._onKeyUp=function(e){var t=e.target,i=e.keyCode;if(t===this.input.element){var n=this.input.value,s=this._store.activeItems,r=this._canAddItem(s,n),o=ne,a=se;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(ye(!0))):u&&this._handleSearch(this.input.value)}this._canSearch=this.config.searchEnabled}},t._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())},t._onEnterKey=function(e){var t=e.event,i=e.target,n=e.activeItems,s=e.hasActiveDropdown,r=re,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())},t._onEscapeKey=function(e){e.hasActiveDropdown&&(this.hideDropdown(!0),this.containerOuter.focus())},t._onDirectionKey=function(e){var t=e.event,i=e.hasActiveDropdown,n=e.keyCode,s=e.metaKey,r=le,o=he,a=ue;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()}},t._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())},t._onTouchMove=function(){this._wasTap&&(this._wasTap=!1)},t._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},t._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()}},t._onMouseOver=function(e){var t=e.target;(t===this.dropdown||this.dropdown.element.contains(t))&&t.hasAttribute("data-choice")&&this._highlightChoice(t)},t._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))},t._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]()},t._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()},t._onFormReset=function(){this._store.dispatch({type:"RESET_TO",state:this._initialState})},t._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(X,{el:n}),this.dropdown.isActive&&(this.input.setActiveDescendant(n.id),this.containerOuter.setActiveDescendant(n.id))}},t._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,m=void 0===d?null:d,p=S("String",t)?t.trim():t,f=m,v=l,g=this._store.items,_=n||p,b=parseInt(r,10)||-1,y=a>=0?this._store.getGroupById(a):null,E=g?g.length+1:1;return this.config.prependValue&&(p=this.config.prependValue+p.toString()),this.config.appendValue&&(p+=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:ee,value:t,label:i,id:n,choiceId:s,groupId:r,customProperties:o,placeholder:a,keyCode:c}}({value:p,label:_,id:E,choiceId:b,groupId:a,customProperties:l,placeholder:u,keyCode:f})),this._isSelectOneElement&&this.removeActiveItems(E),this.passedElement.triggerEvent(U,{id:E,value:p,label:_,customProperties:v,groupValue:y&&y.value?y.value:void 0,keyCode:f}),this},t._removeItem=function(e){if(!e||!S("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:te,id:e,choiceId:t}}(t,s)),o&&o.value?this.passedElement.triggerEvent(z,{id:t,value:i,label:n,groupValue:o.value}):this.passedElement.triggerEvent(z,{id:t,value:i,label:n}),this},t._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,m=void 0!==d&&d,p=e.keyCode,f=void 0===p?null:p;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:Y,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:m,keyCode:f})),r&&this._addItem({value:t,label:g,choiceId:_,customProperties:u,placeholder:m,keyCode:f})}},t._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=S("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(Se(i.label,l,!0,h));c.forEach((function(e){var i=e.disabled||e.parentNode&&e.parentNode.disabled;t._addChoice({value:e[r],label:S("Object",e)?e[a]:e.innerHTML,isSelected:e.selected,isDisabled:i,groupId:l,customProperties:e.customProperties,placeholder:e.placeholder})}))}else this._store.dispatch(Se(i.label,i.id,!1,i.disabled))},t._getTemplate=function(e){var t;if(!e)return null;for(var i=this.config,n=i.templates,s=i.classNames,r=arguments.length,o=new Array(r>1?r-1:0),a=1;a1&&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;r '; @@ -197,6 +189,18 @@ describe('utils', () => { }); }); + describe('isIE11', () => { + it('returns whether the given user agent string matches an IE11 user agent string', () => { + const IE11UserAgent = + 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko'; + const firefoxUserAgent = + 'Mozilla/5.0 (Android 4.4; Mobile; rv:41.0) Gecko/41.0 Firefox/41.0'; + + expect(isIE11(IE11UserAgent)).to.equal(true); + expect(isIE11(firefoxUserAgent)).to.equal(false); + }); + }); + describe('existsInArray', () => { it('determines whether a value exists within given array', () => { const values = [ diff --git a/types/index.d.ts b/types/index.d.ts index 0f64819..e20ef03 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -777,16 +777,6 @@ export default class Choices { userConfig?: Partial, ); - /** - * It's impossible to declare in TypeScript what Choices constructor is actually doing: - * @see {@link https://github.com/Microsoft/TypeScript/issues/27594} - * it returns array of Choices in case if selectorOrElement is string - * and one instance of Choices otherwise - * This little hack will at least allow to use it in Typescript - * - */ - [index: number]: this; - /** * Creates a new instance of Choices, adds event listeners, creates templates and renders a Choices element to the DOM. *